def get_datastring(publish_date_text): publish_date = Datetime(publish_date_text, '00:00', '+00:00') list_obj = [publish_date_text] for obj in const.LIST_OBJECTS_TRADITIONAL: calculator = Chart(publish_date, pos).objects list_obj.append(kdfm.sign_dict[calculator.get(obj).sign]) list_obj.append(calculator.get(obj).lon) list_obj.append(calculator.get(obj).lat) return list_obj
def get_angle_on_day(self, o, day): global date, pos, chart, obj date = Datetime(day.strftime("%Y/%m/%d"), '00:00', '+00:00') pos = GeoPos(0, 0) chart = Chart(date, pos) obj = chart.get(o) if obj.sign != self.sign: return None return obj.signlon
def runAstroScript(dateString, timeString, location1String, location2String): # Here you call the functions you need to and parse the data into whatever format you need it in (maybe a dict) """Running flatlib script""" date = Datetime(dateString, timeString, '+00:00') pos = GeoPos(location1String, location2String) chart = Chart(date, pos, IDs=const.LIST_OBJECTS) # chart = Chart(date, pos, hsys=const.HOUSES_PLACIDUS) asc = chart.get(const.ASC) chart_dict = {} for obj in chart.objects: chart_dict.update({obj.id: obj.sign}) chart_dict.update({asc.id: asc.sign}) return ('{0}'.format(chart_dict))
def advancedview(): if flask.request.method == "POST": num = flask.request.form.get('choiceit') town = flask.request.form.get('town') country = flask.request.form.get('country') # print('num is:', num) if len(num) > 6: yy, mm, dd = num[:4], num[5:7], num[8:10] tiden = yy + '/' + mm + '/' + dd date = Datetime(tiden, '17:00', '+00:00') geo_coordinates = get_geo_cords(town, country) if not geo_coordinates: return flask.render_template("advanced.html", countries=countries, error="Could not find the city") g0, g1 = float(geo_coordinates[0]), float( geo_coordinates[1].replace('</span>', '')) pos = GeoPos(g0, g1) chart = Chart(date, pos, IDs=const.LIST_OBJECTS) sun = chart.getObject(const.SUN) # print("Your sun sign is: ",sun.sign) #zodiac sign # print("Your zodiac is explained as: ", explain_zodiac(sun.sign)) # print("Your sun movement is: ",sun.movement()) # print("Your sun element is: ",sun.element()) # print("Explained element:", explain_element(sun.element())) # print("Your sun faction is: ",sun.faction()) #print(chart.__dict__) #house is different depending on chart # for merp in const.LIST_HOUSES: # print(merp, 'sign is',chart.getHouse(merp).sign,'The condition is:',chart.getHouse(merp).condition()) # print("This is the",explain_house(merp).get("translated"), " the lating motto for it is '",explain_house(merp).get("Latin motto"),"' It's basicly means: ",explain_house(merp).get('explain')) ##print("Your sun element is: ",chart.getObject(const.SUN).figures()) moon = chart.get(const.MOON) # print("Your moon is in:", moon.sign) # print("Your moon movement is: ",moon.movement()) # print("Your moon element is: ",moon.element()) # print("Explained element:", explain_element(moon.element())) # print("Your moon faction is: ",moon.faction()) # print("Your moon phase:", chart.getMoonPhase()) return flask.render_template("advanced.html", moon=moon, sun=sun, const=const, explain_house=explain_house, chart=chart, explain_zodiac=explain_zodiac, explain_element=explain_element) return flask.render_template("advanced.html", countries=countries)
def in_day(year, month, day, hour, minute): """ Função retorna data thelemica de um dia e horário especifico :param year: Ano :param month: Mês :param day: Dia :param hour: Hora :param minute: Minuto :return: a data thelemica dos dados passados """ ev_in_day_weekday = date(year, month, day).weekday() ev_in_day_date = str(date(year, month, day).strftime('%Y/%m/%d')) ev_in_day_time = f'{hour}:{minute}' ev_in_day_na_year = int(year) - 1904 # New Aeon "generation" of 22 years ciclo_i = ev_in_day_na_year // 22 # // Years in the current cycle ciclo_ii = int(year) - 1904 - (ciclo_i * 22) # New Aeon year na_year = numerals[ciclo_ii].upper() + ':' + numerals[ciclo_i] na_date = Datetime(ev_in_day_date, ev_in_day_time, '-03:00') pos = GeoPos('23s39', '46w32') chart = Chart(na_date, pos) sun = chart.getObject(const.SUN) solis = str(sun).split(' ') solis_sign = solis[1] solis_arc = solis[2].split(':')[0].replace('+', '') moon = chart.get(const.MOON) luna = str(moon).split(' ') luna_sign = luna[1] luna_arc = luna[2].split(':')[0].replace('+', '') return (f'☉ in {solis_arc}º {signs[solis_sign]} ' f'☽ in {luna_arc}º {signs[luna_sign]} ' f'Dies {dies[ev_in_day_weekday]} ' f'Anno {na_year} æræ novæ')
def now(): """ Função não recebe parametros :return: a data thelemica atual """ # Era Vulgar Year ev_year = int(date.today().strftime('%Y')) # Whole Years since March Equinox 1904 ev_years_total = ev_year - 1904 # New Aeon "generation" of 22 years ciclo_i = ev_years_total // 22 # // Years in the current cycle ciclo_ii = ev_year - 1904 - (ciclo_i * 22) # New Aeon year na_year = numerals[ciclo_ii].upper() + ':' + numerals[ciclo_i] ev_weekday = date.today().weekday() ev_today = str(date.today().strftime('%Y/%m/%d')) ev_time = str(time.strftime('%H:%M')) na_date = Datetime(ev_today, ev_time, '-03:00') pos = GeoPos('23s39', '46w32') chart = Chart(na_date, pos) sun = chart.getObject(const.SUN) solis = str(sun).split(' ') solis_sign = solis[1] solis_arc = solis[2].split(':')[0].replace('+', '') moon = chart.get(const.MOON) luna = str(moon).split(' ') luna_sign = luna[1] luna_arc = luna[2].split(':')[0].replace('+', '') return (f'☉ in {solis_arc}º {signs[solis_sign]} ' f'☽ in {luna_arc}º {signs[luna_sign]} ' f'Dies {dies[ev_weekday]} ' f'Anno {na_year} æræ novæ')
""" from flatlib import const from flatlib.chart import Chart from flatlib.datetime import Datetime from flatlib.geopos import GeoPos from flatlib.predictives import primarydirections # Build a chart for a date and location date = Datetime('2015/03/13', '17:00', '+00:00') pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) # MC will be used for calculating arcs mc = chart.get(const.MC) # Get a promissor and significator prom = chart.get(const.MARS) sig = chart.get(const.MERCURY) # Compute arc in zodiaco (zerolat = True) arc = primarydirections.getArc(prom, sig, mc, pos, zerolat=True) print(arc) # 56.17347 # Compute arc in mundo arc = primarydirections.getArc(prom, sig, mc, pos, zerolat=False) print(arc) # 56.74266 # Create Primary Directions class from flatlib.predictives.primarydirections import PrimaryDirections
def get_astrological(date_time, coordinates, timezone): if isinstance(coordinates, (list, )): if len(coordinates) == 1: coordinates = coordinates[0] else: coord = coordinates[:2] else: return () if isinstance(coordinates, (str, )): if "," in coordinates: coord = coordinates.split(',') coord[0] = coord[0].lstrip() coord[1] = coord[1].lstrip() # if len(coord[1])>2: # coord[1] = coord[1][:1]+":" +coord[1][2:] # print(coord[1]) flatlib_pos = GeoPos(coord[0], coord[1]) flatlib_date_time = Datetime(date_time.strftime("%Y/%m/%d"), date_time.strftime('%H:%M'), timezone) chart = Chart(flatlib_date_time, flatlib_pos) astro = {} for obj in [chart.get(const.ASC)]: # #print(obj) astro[obj.id] = {'sign': obj.sign, 'lon': obj.lon} # for obj in chart.houses: # astro[obj.id] = {'sign':obj.sign,'lon':obj.lon,'signlon':obj.signlon,'size':30-obj.size} for obj in chart.objects: #Planets #print(obj.id,obj.sign,obj.lon,obj.signlon,obj.lonspeed) astro[obj.id] = { 'sign': obj.sign, 'lon': obj.lon, 'speed': obj.lonspeed } try: gender = obj.gender() astro[obj.id].update({'gender': gender}) except: pass try: mean_motion = obj.meanMotion() if mean_motion: astro[obj.id].update({'speed': obj.lonspeed / mean_motion}) except: pass try: astro[obj.id].update({'fast': str(obj.isFast())}) except: pass for house in chart.houses: if house.hasObject(obj): astro[obj.id].update({'house': int(house.id[5:])}) moon_phase = angle_dif(astro['Moon']['lon'], astro['Sun']['lon']) astro['Moon'].update({ 'phase': moon_phase, }) ASC_LON = chart.get(const.ASC).lon for obj in astro.keys(): if 'lon' in astro[obj].keys(): angle = angle_dif(ASC_LON, astro[obj]['lon']) astro[obj].update({ 'lon': angle, 'position': [np.sin(angle * np.pi / 180.), np.cos(angle * np.pi / 180.)] }) return (astro)
This recipe shows sample code for handling essential dignities. """ from flatlib import const from flatlib.chart import Chart from flatlib.datetime import Datetime from flatlib.geopos import GeoPos from flatlib.dignities import essential # Build a chart for a date and location date = Datetime('2015/03/13', '17:00', '+00:00') pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) # Get the Asc ruler asc = chart.get(const.ASC) ascRulerID = essential.ruler(asc.sign) ascRuler = chart.get(ascRulerID) print(ascRuler) # <Mercury Pisces +00:48:57 +01:29:49> # Get the Asc ruler score score = essential.score(ascRuler.id, ascRuler.sign, ascRuler.signlon) print(score) # Simpler alternative using the EssentialInfo class info = essential.EssentialInfo(ascRuler) print(info.score)
sun = chart.getObject(const.SUN) #print("--------------- SUN") print("Güneş Burç :" + sun.sign) #gunes burc moon = chart.getObject(const.MOON) print("Ay Burç :" + moon.sign) #gunes burc #print(sun.signlon)#gunes burc #print(sun.gender())#gunes burc cinsiyet #print(sun) print("------------------EVLER-----------") #Ev listesi homeList = [ const.HOUSE1, const.HOUSE2, const.HOUSE3, const.HOUSE4, const.HOUSE5, const.HOUSE6, const.HOUSE7, const.HOUSE8, const.HOUSE9, const.HOUSE10, const.HOUSE11, const.HOUSE12 ] house1 = chart.get(const.HOUSE12) for i in homeList: print("{0}: {1} ".format(i, chart.get(i).sign)) alm = almutem.compute(chart) # # Sun relation # relation = accidental.sunRelation(obj, sun) # print(relation) # print("--------------ASPECT-------------") # aspect = aspects.getAspect(sun, moon, const.ALL_ASPECTS) # print(aspect.inOrb) # moon = chart.getObject(const.MOON) # print("--------------- SUN") # print(moon.sign)#ay burcu
This recipe shows sample code for handling essential dignities. """ from flatlib import const from flatlib.chart import Chart from flatlib.datetime import Datetime from flatlib.geopos import GeoPos from flatlib.dignities import essential import time import os import socket import datetime data = datetime.datetime.utcnow() d = data.strftime('%Y/%m/%d') h = data.strftime('%H:%M:%S') date = Datetime(d, h) pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) moon = chart.get(const.MOON) info = essential.EssentialInfo(moon) print(moon) print(info.score)
class MoonBot(): def __init__(self, cache_dir=None): #self.maxchar = 280 #twitter maxchar self.light_gradient = [str(x).zfill(2) for x in range(100)] self.cache_dir = cache_dir self.astrology = False def set_modes(self, gradient_symbols="moon2", astrology=False): self.gradient_symbols = gradient_symbols self.settings = settings_dict.settings[gradient_symbols] self.astrology = astrology self.charwidth = self.settings["ascii_dims"][0] self.charheight = self.settings["ascii_dims"][1] self.ascii_gradient = [''] * (self.charwidth * self.charheight) def decide_new_moon_border(self): #if True:#self.luminosity <= .1 and self.settings["settings_type"] == "random": if self.moon.moon_datetime_info[ "age"] < 3.0 or self.moon.moon_datetime_info["age"] > 25.0: self.add_border = True surrounding_pixels_offsets = { "char_to_left": -1, "char_to_right": 1, "char_above": -1 * self.charwidth, "char_below": self.charwidth, "char_up_right": (-1 * self.charwidth) + 1, "char_up_left": (-1 * self.charwidth) - 1, "char_down_right": self.charwidth + 1, "char_down_left": self.charwidth - 1 } #make a shadow border for idx, value in enumerate(self.result_moon_gradients): #check whether there's a border character adjacent to this one border_char_adjacent = -1 in [ self.result_moon_gradients[idx + offset] for offset in surrounding_pixels_offsets.values() if idx + offset >= 0 and idx + offset <= (self.charwidth * self.charheight) - 1 ] if border_char_adjacent: continue for desc, offset in surrounding_pixels_offsets.items(): if idx + offset >= 0 and idx + offset <= ( self.charwidth * self.charheight ) - 1: #ignore negative offsets as they're at the end of the array and not nearby try: if int(self.result_moon_gradients[ idx + offset]) == 0 and int( self.result_moon_gradients[idx]) > 0: self.result_moon_gradients[idx + offset] = -1 except ValueError: pass except IndexError: pass #print(self.result_moon_gradients) def choose_random_shadow_symbol(self): return random.choice(self.settings["symbols"]["random_shadow_symbols"]) def choose_random_light_symbol(self): return random.choice(self.settings["symbols"]["random_light_symbols"]) def make_ascii_tweet(self): #pdb.set_trace() self.convert_image_to_ascii(self.charwidth, 1) #self.decide_new_moon_border() if self.astrology: self.set_astrology_info() self.set_symbols_list(self.luminosity) self.put_symbols_in_gradient() self.put_output_in_square() self.make_img_to_post() def put_symbols_in_gradient(self): self.ascii_list = [] if self.astrology: #find which luminances have just one or two self.least_often_gradient_value1 = Counter( self.result_moon_gradients).most_common()[-1][0] self.least_often_gradient_value2 = Counter( self.result_moon_gradients).most_common()[-2][0] for value in self.result_moon_gradients: if value == self.least_often_gradient_value1: self.ascii_list.append(self.astrology_sign_random_emoji) elif value == self.least_often_gradient_value2: self.ascii_list.append(self.astrology_element_random_emoji) elif value == -2: self.border_char = "💡" #$todo self.ascii_list.append(self.border_char) elif value == -1: self.border_char = "🌚" #$todo self.ascii_list.append(self.border_char) else: self.ascii_list.append(self.ascii_gradient[int(value)]) def make_img_to_post(self): #In-stream images are displayed at a 16:9 ratio of 600px by 335px # and can be clicked and expanded up to 1200px by 675px. font_size = 80 width = DIMS[0] height = DIMS[1] twitter_im_width = 800 twitter_im_height = 450 bg_color = (0, 0, 0) font_size = int(width / self.charwidth) unicode_text = self.ascii im = Image.open("moon.jpg") moon_waning = self.moon.moon_datetime_info["age"] > 14 #im = Image.new ( "RGB", (width,height), bg_color ) unicode_font = ImageFont.truetype( "res/unicode-emoji/symbola/Symbola.ttf", font_size) draw = ImageDraw.Draw(im) for x in range(0, self.charwidth): for y in range(0, self.charheight): lum = int(255 - 255 / (int(self.result_moon_gradients[ (x * self.charwidth) + y]) + 1)) if type(lum) == type(1.0): raise ValueError("float ", lum) if self.astrology == True: if self.moon_sign in ["Sagittarius", "Leo", "Aries"]: #red, yellow r = 255 g = lum b = int(255 - (255 / (lum + 1) * (moon_waning * x * self.charwidth + y + 1))) elif self.moon_sign in ["Taurus", "Capricorn", "Virgo"]: #green, blue r = lum g = 255 b = int(255 - (255 / (lum + 1) * (moon_waning * x * self.charwidth + y + 1))) elif self.moon_sign in ["Gemini", "Libra", "Aquarius"]: #blue, purple r = lum g = int(255 - (255 / (lum + 1) * (moon_waning * x * self.charwidth + y + 1))) b = 255 elif self.moon_sign in ["Pisces", "Cancer", "Scorpio"]: #blue, green r = 255 g = int(255 - (255 / (lum + 1) * (moon_waning * x * self.charwidth + y + 1))) b = lum else: #todo make an rgb that looks good r, g, b = (lum, lum, lum) if r > 255 or g > 255 or b > 255: raise ValueError( f"One of your RGB colors is higher than 255, your lum is: {lum}" ) font_color = (r, g, b) draw.text((x * int(width / self.charwidth), y * int(width / self.charheight)), self.ascii_list[(x * self.charwidth) + y], font=unicode_font, fill=font_color) #draw.text ( (0,0), self.moon_sign, font=unicode_font, fill=(255,255,0) ) #self.ascii += str(self.ascii_list[(y * self.charwidth) + x]) #im = Image.new ( "RGB", (width,height), bg_color ) background_im = Image.new("RGB", (twitter_im_width, twitter_im_height), bg_color) draw = ImageDraw.Draw(background_im) offset = ((twitter_im_width - width) // 2, (twitter_im_height - height) // 2) background_im.paste(im, offset) background_im.show() background_im.save("moon_emojis.png") #.jpg makes problems def calculate_luminosity(self): self.average_luminosity = 1 def make_histogram(self): self.hist = plt.hist(self.moon.image.ravel(), 256, [0, 256]) def put_output_in_square(self): self.ascii = "" for x in range(0, self.charwidth): for y in range(0, self.charheight): self.ascii += str(self.ascii_list[(y * self.charwidth) + x]) self.ascii += "\n" def twitter_signin(self): auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET) auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET) auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET) self.twitter_api = tweepy.API(auth, parser=tweepy.parsers.JSONParser()) def mast_signin(self): self.mast_api = Mastodon(client_id=MAST_CLIENT_KEY, client_secret=MAST_CLIENT_SECRET, api_base_url='https://botsin.space', access_token=MAST_ACCESS_TOKEN) def post_moon_toot(self): FPATH = "" data = {} try: image = FPATH + "moon_emojis.png" media = self.mast_api.media_post(image, description=self.alt_text) status = self.mast_api.status_post(self.moon_info_caption, media_ids=media, sensitive=False) except Exception as e: raise e #TODO use python mastodon api port or figure out why this isn't working def mast_update_profile_image(self): # with open('moon.jpg', 'rb') as f: # image = f.read() account = self.mast_api.account_update_credentials(avatar="moon.jpg") def get_moon(self, **kwargs): try: self.moon = MoonImage() if not self.cache_dir: self.moon.set_moon_phase(**kwargs) else: #check if this moon time exists in cached img dir if not os.path.isdir(self.cache_dir): raise OSError( (f"Can't find a directory called " "'{self.cache_dir}'. Please double " "check that you've created this directory.")) self.moon.set_moon_datetime(**kwargs) date_filename = (f'{self.cache_dir}' f'{self.moon.datetime.year}-' f'{self.moon.datetime.month}-' f'{self.moon.datetime.day}-' f'{self.moon.datetime.hour}') if os.path.isfile(date_filename + '.jpg'): # TODO would be nice if `dialamoon.Moon` would do this in Moon.set_moon_phase() self.moon.image = cv2.imread(date_filename + '.jpg') self.moon.resize_image() self.set_up_cached_json() else: self.moon.set_moon_phase(**kwargs) self.moon.save_to_disk(date_filename) #self.moon.image = cv2.resize(self.moon.image, DIMS) self.moon.image = cv2.resize(self.moon.image, DIMS) #self.moon.image = cv2.resize(self.moon.image, (200,200)) cv2.imwrite("moon.jpg", self.moon.image) except Exception as e: raise e def set_symbols_list(self, luminosity): #TODO clean up so it isn't so rickety try: if self.settings["settings_type"] == "map": if self.moon.moon_datetime_info["age"] < 14: intervals = self.settings["intervals"]["young_moon"] else: intervals = self.settings["intervals"]["old_moon"] i = 0 for n in sorted(intervals.keys()): rep = n - i self.ascii_gradient[i:n + 1] = [intervals[n]] * rep i = n else: if self.moon.moon_datetime_info["age"] < 14: self.ascii_gradient = stretch( self.settings["symbols"]["young_moon"], self.charwidth * self.charheight) else: self.ascii_gradient = stretch( self.settings["symbols"]["old_moon"], self.charwidth * self.charheight) if self.settings["settings_type"] == "random": self.ascii_gradient = self.set_random_chars() except TypeError as e: raise TypeError( f'Something might be wrong with your settings_dict {self.gradient_symbols} mode\n' + str(e)) def set_astrology_info(self): d = Datetime( f'{self.moon.datetime.year}/{self.moon.datetime.month}/{self.moon.datetime.day}', f'{self.moon.datetime.hour}:00', '+00:00') pos = GeoPos( '38n32', '8w54') #todo use a different location? this was in the docs self.chart = Chart(d, pos) self.moon_astrology_info = self.chart.get(const.MOON) self.moon_sign = self.moon_astrology_info.sign self.astrology_ascii_dict = astrology_dict["signs"][self.moon_sign] self.astrology_sign_random_emoji = choice( astrology_dict["signs"][self.moon_sign]["related"]) self.astrology_element_random_emoji = choice( astrology_dict["elements"][self.astrology_ascii_dict["element"]]) # get aspects of chart dyn = ChartDynamics(self.chart) self.aspects = dyn.validAspects(const.MOON, const.MAJOR_ASPECTS) def set_up_cached_json(self): #TODO do this in dialamoon.Moon some day json_path = self.cache_dir + JSON_FN.format( year=self.moon.datetime.year) if not os.path.isfile(json_path): self.moon.make_json_year_data_url() self.moon.set_json_year_data() with open(json_path, 'w') as outfile: json.dump(self.moon.moon_year_info, outfile) else: with open(json_path, 'r') as outfile: s = outfile.read() if s == "": raise ValueError( f"The {json_path} file is empty. Please try again.") self.moon.moon_year_info = json.loads(s) self.moon.set_json_specific_data() def set_moon_info_caption(self): self.moon_info_caption = "...\n\n" + str( self.moon.moon_datetime_info["distance"]) + "km from earth".rjust( 22, " ") + "\n" + str(self.moon.moon_datetime_info["phase"] ) + "%" + "illuminated".rjust( 26, " ") + "\n\n" def set_alt_text(self): self.alt_text = f"Image of the moon, {self.moon.moon_datetime_info['phase']}% illuminated, with emojis overlaid" def post_moon_tweet(self): media = self.twitter_api.media_upload("moon_emojis.png") #if .create_media_metadata makes a problem, it may be because tweepy.parser.JSONParser #is receiving '' as payload (from resp.text) and json.loads() errors r = self.twitter_api.create_media_metadata( media_id=media["media_id_string"], alt_text=self.alt_text) self.twitter_api.update_status(self.moon_info_caption, media_ids=[media["media_id_string"]]) def update_profile_image(self): self.twitter_api.update_profile_image("./moon.jpg") # START pixelating grayscale image with characters/emojis ### PYTHON TO ASCII ART - https://github.com/electronut/pp/blob/master/ascii/ascii.py#L2 modified to just take numpy images def convert_image_to_ascii(self, cols, scale): """ Given Image and dims (rows, cols) returns an m*n list of Images """ # declare globals # open image and convert to grayscale im = self.rgb_to_gray(self.moon.image) # store dimensions W, H = im.shape[0], im.shape[1] # compute width of tile w = W / cols # compute tile height based on aspect ratio and scale h = w / scale # compute number of rows rows = int(H / h) #why not get the average luminosity of the whole image first self.luminosity = self.getAverageL(im) / 100 # check if image size is too small if cols > W or rows > H: raise Exception("Image too small for specified cols!") exit(0) # ascii image is a list of character lists aimg = [] # generate list of dimensions for j in range(rows): y1 = int(j * h) y2 = int((j + 1) * h) # correct last tile if j == rows - 1: y2 = H # append an empty string aimg.append([]) for i in range(cols): # crop image to tile x1 = int(i * w) x2 = int((i + 1) * w) # correct last tile if i == cols - 1: x2 = W # crop image to extract tile img = im[x1:x2, y1:y2] # get average luminosity avg = int(self.getAverageL(img)) # look up value in light gradient gsval = self.light_gradient[int((avg * 99) / 255)] # append ascii char to string aimg[j].append(gsval) #transpose it as its currently rotated -90 deg #aimg = list(map(list, np.transpose(aimg))) # return light_gradients self.result_moon_gradients = [ item for sublist in aimg for item in sublist ] def rgb_to_gray(self, img): #make an array of zeros with the shape (1000, 1000, 3) # (1000 px by 1000 px each with 3 values - RGB) grayImage = np.zeros(img.shape) #take just the red, green and blue values from the 1000x1000 R = np.array(img[:, :, 0]) G = np.array(img[:, :, 1]) B = np.array(img[:, :, 2]) # ITU-R 601-2 luma transform coefficients for converting rgb > greyscale R = (R * .299) G = (G * .587) B = (B * .114) Avg = (R + G + B) grayImage = img for i in range(3): grayImage[:, :, i] = Avg return grayImage def getAverageL(self, im): """ Given PIL Image, return average value of grayscale value """ # get shape w = im.shape[0] h = im.shape[1] # get average #cv2.imshow("test", im) #cv2.waitKey(0) #cv2.destroyAllWindows() return np.average(im)
""" Author: João Ventura <*****@*****.**> This recipe shows sample code for handling aspects. """ from flatlib import aspects from flatlib import const from flatlib.chart import Chart from flatlib.datetime import Datetime from flatlib.geopos import GeoPos # Build a chart for a date and location date = Datetime('2015/03/13', '17:00', '+00:00') pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) # Retrieve the Sun and Moon sun = chart.get(const.SUN) moon = chart.get(const.MOON) # Get the aspect aspect = aspects.getAspect(sun, moon, const.MAJOR_ASPECTS) print(aspect) # <Moon Sun 90 Applicative +00:24:30>
port = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) while True: data = datetime.datetime.utcnow() d = data.strftime('%Y/%m/%d') h = data.strftime('%H:%M:%S') date = Datetime(d, h) pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) sun = chart.get(const.SUN) moon = chart.get(const.MOON) mercury = chart.get(const.MERCURY) venus = chart.get(const.VENUS) mars = chart.get(const.MARS) jupiter = chart.get(const.JUPITER) saturn = chart.get(const.SATURN) sol = 'sol ' sol += str(sun.sign) sol += ' ' sol += str(sun.signlon) sol += ' ' sol += str(sun.lon) sol += ';' s.send(sol.encode())
""" from flatlib import const from flatlib.chart import Chart from flatlib.datetime import Datetime from flatlib.geopos import GeoPos from flatlib.predictives import primarydirections # Build a chart for a date and location date = Datetime('2015/03/13', '17:00', '+00:00') pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) # MC will be used for calculating arcs mc = chart.get(const.MC) # Get a promissor and significator prom = chart.get(const.MARS) sig = chart.get(const.MERCURY) # Compute arc in zodiaco (zerolat = True) arc = primarydirections.getArc(prom, sig, mc, pos, zerolat=True) print(arc) # 56.17347 # Compute arc in mundo arc = primarydirections.getArc(prom, sig, mc, pos, zerolat=False) print(arc) # 56.74266 # Create Primary Directions class from flatlib.predictives.primarydirections import PrimaryDirections
import datetime import time from flatlib.datetime import Datetime from flatlib.geopos import GeoPos from flatlib.chart import Chart from flatlib import const from flatlib import aspects # Build a chart for a date and location data = datetime.datetime.utcnow() d = data.strftime('%Y/%m/%d') h = data.strftime('%H:%M:%S') date = Datetime(d, h) pos = GeoPos('38n43', '9w8') chart = Chart(date, pos) # Retrieve the Sun and Moon sun = chart.get(const.SUN) moon = chart.get(const.MOON) venus = chart.get(const.VENUS) # Get the aspect aspect1 = aspects.getAspect(sun, moon, const.MAJOR_ASPECTS) aspect2 = aspects.getAspect(sun, venus, const.ALL_ASPECTS) print(aspect1) print(aspect2xsc)
""" Author: João Ventura <*****@*****.**> This recipe shows sample code for handling aspects. """ from flatlib import aspects from flatlib import const from flatlib.chart import Chart from flatlib.datetime import Datetime from flatlib.geopos import GeoPos # Build a chart for a date and location date = Datetime('2015/03/13', '17:00', '+00:00') pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) # Retrieve the Sun and Moon sun = chart.get(const.SUN) moon = chart.get(const.MOON) # Get the aspect aspect = aspects.getAspect(sun, moon, const.MAJOR_ASPECTS) print(aspect) # <Moon Sun 90 Applicative +00:24:30>
def get_asc_sign(self, chart: Chart) -> str: return chart.get(HOUSE1).sign
def bdate_time_place_to_degs(api, bdate, btime, bplace, lati=None, long=None): bdate = [int(i) for i in bdate.split('.')] if bdate[0] < 10: bdate[0] = '0' + str(bdate[0]) else: bdate[0] = str(bdate[0]) if bdate[1] < 10: bdate[1] = '0' + str(bdate[1]) else: bdate[1] = str(bdate[1]) bdate[2] = str(bdate[2]) if len(bdate[0]) == 2: bdate = bdate[2] + '/' + bdate[1] + '/' + bdate[0] else: bdate = bdate[0] + '/' + bdate[1] + '/' + bdate[2] btime = str(btime) # if bplace is not None: place = api.geocode(bplace) lat, lon = place[0]['geometry']['location']['lat'], place[0][ 'geometry']['location']['lng'] else: lat, lon = lati, long utcdiff = api.timezone([lat, lon])['rawOffset'] udsign = str(utcdiff)[0] udsign = udsign if udsign == '-' else '+' utcdiff = abs(utcdiff) udh = utcdiff // 3600 udm = (utcdiff - udh * 3600) // 60 if udh < 10: udh = '0' + str(udh) else: udh = str(udh) if udm < 10: udm = '0' + str(udm) else: udm = str(udm) utcdiff = udsign + udh + ':' + udm nslat = None ewlon = None if lat < 0: nslat = 's' else: nslat = 'n' if lon < 0: ewlon = 'w' else: ewlon = 'e' lat = abs(lat) lon = abs(lon) lat_d = int(str(lat).split('.')[0]) lat_m = str(int((lat - lat_d) * 60)) lat_d = str(lat_d) lon_d = int(str(lon).split('.')[0]) lon_m = str(int((lon - lon_d) * 60)) lon_d = str(lon_d) bpl = [lat_d + nslat + lat_m, lon_d + ewlon + lon_m] # date = Datetime(bdate, btime, utcdiff) pos = GeoPos(bpl[0], bpl[1]) chart = Chart(date, pos) res = [] res.append(chart.get(const.SUN).lon) res.append(chart.get(const.MOON).lon) res.append(chart.get(const.MERCURY).lon) res.append(chart.get(const.MARS).lon) res.append(chart.get(const.JUPITER).lon) res.append(chart.get(const.VENUS).lon) res.append(chart.get(const.SATURN).lon) res.append(chart.get(const.NORTH_NODE).lon) res.append(chart.get(const.SOUTH_NODE).lon) res.append(chart.get(const.ASC).lon) for i in range(len(res)): if res[i] - 23.81 < 0: res[i] = 360 + (res[i] - 23.81) else: res[i] -= 23.81 return res
from flatlib import const from flatlib.chart import Chart from flatlib.datetime import Datetime from flatlib.geopos import GeoPos from flatlib.dignities import accidental from flatlib.dignities.accidental import AccidentalDignity # Build a chart for a date and location date = Datetime('2015/03/13', '17:00', '+00:00') pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) # Get some objects obj = chart.get(const.VENUS) sun = chart.get(const.SUN) # Sun relation relation = accidental.sunRelation(obj, sun) print(relation) # Augmenting or Diminishing light light = accidental.light(obj, sun) print(light) # Orientality orientality = accidental.orientality(obj, sun) print(orientality) # Haiz
from flatlib import const from flatlib.chart import Chart from flatlib.datetime import Datetime from flatlib.geopos import GeoPos from flatlib.dignities import accidental from flatlib.dignities.accidental import AccidentalDignity # Build a chart for a date and location date = Datetime('2015/03/13', '17:00', '+00:00') pos = GeoPos('38n32', '8w54') chart = Chart(date, pos) # Get some objects obj = chart.get(const.VENUS) sun = chart.get(const.SUN) # Sun relation relation = accidental.sunRelation(obj, sun) print(relation) # Augmenting or Diminishing light light = accidental.light(obj, sun) print(light) # Orientality orientality = accidental.orientality(obj, sun) print(orientality) # Haiz