Exemplo n.º 1
0
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
Exemplo n.º 2
0
 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
Exemplo n.º 3
0
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))
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
def main(latitude: float, longitude: float, date: datetime):
    flatlib_datetime = convert_into_stupid_flatlib_format(date)
    position = GeoPos(latitude, longitude)
    chart = Chart(flatlib_datetime, position)
    for planet in planet_symbols.keys():
        planet_position = chart.getObject(planet)
        print(
            planet_symbols[planet],
            sign_symbols[planet_position.sign],
            "℞"
            if planet_position.movement() == flatlib.const.RETROGRADE else "",
            end="",
        )
    print()
Exemplo n.º 6
0
async def cmd_sun(message):
    l = message.content.split(' ')
    try:
        date = parse(l[1])
        datetime = Datetime(date.strftime('%Y/%m/%d'))
        pos = GeoPos('00n00', '0w00')
        chart = Chart(datetime, pos)
        sun = str(chart.getObject(SUN)).split(' ')[1]
        await send_text(
            client, message.channel,
            "If you were born on %s, then you're a %s!" %
            (date.strftime('%B %d, %Y'), sun))
    except Exception as e:
        logger.info(e)
        await send_text(client, message.channel, "Invalid date string")
Exemplo n.º 7
0
Arquivo: hga.py Projeto: zymael/zymael
    def __init__(self,DATE,POS):
        chart = Chart(DATE, POS)
        sun = chart.getObject(const.SUN)
        sunSign = sun.sign
        sunDegree = int(sun.signlon)
        moon = chart.getObject(const.MOON)
        moonSign = moon.sign
        moonDegree = int(moon.signlon)
        syzygy = chart.getObject(const.SYZYGY)
        syzygySign = syzygy.sign
        syzygyDegree = int(syzygy.signlon)

        self.sun={'sign':sunSign,'degree':sunDegree}
        self.moon={'sign':moonSign,'degree':moonDegree}
        self.syzygy={'sign':syzygySign,'degree':syzygyDegree}
Exemplo n.º 8
0
def get_chart(position, dt_naive):
    timezone = pytz.timezone(tf.timezone_at(lat=position.lat,
                                            lng=position.lon))
    dt_aware = timezone.localize(dt_naive)
    return Chart(convert_into_stupid_flatlib_format(dt_aware),
                 position,
                 IDs=planets)
Exemplo n.º 9
0
def calculate_chart(date,
                    time='17:00',
                    utcoffset='+00:00',
                    lat='55n45',
                    lon='37e36'):
    """Calculates astrological chart based on a person's birth date, time and location. 
    Using flatlib library. 
    
    Args:
        bdate (str): with format `2015/03/13`
        time  (str): with format `17:00`
        utcoffset (str):  UTC Offset with format `+00:00`
        lat (str): latitude of birth location
        lon (str): longtitude of birth location
     
    Returns:
        chart (flatlib.chart.Chart): chart object with astrological information 
            such as plantes positions and so on.
    """

    # create flatlib.datetime object
    date = Datetime(date, time, utcoffset)
    # create flatlib.geopos object
    location = GeoPos('55n45', '37e36')
    # calculate chart
    chart = Chart(date, location, IDs=flatlib.const.LIST_OBJECTS)
    return chart
Exemplo n.º 10
0
 def get_chart(self, birthdayString, birthTimeString, offsetString,
               geo_coordinates):
     # date = Datetime('1989/07/30', '00:05', '-05:00')
     # pos = GeoPos(30.2643, -97.7139)
     date = Datetime(birthdayString, birthTimeString, offsetString)
     pos = GeoPos(geo_coordinates['lat'], geo_coordinates['lng'])
     return Chart(date, pos)
Exemplo n.º 11
0
def _computeChart(chart, date):
    """ Internal function to return a new chart for
    a specific date using properties from old chart.
    
    """
    pos = chart.pos
    hsys = chart.hsys
    IDs = [obj.id for obj in chart.objects]
    return Chart(date, pos, IDs=IDs, hsys=hsys)
Exemplo n.º 12
0
    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)
Exemplo n.º 13
0
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æ')
Exemplo n.º 14
0
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æ')
Exemplo n.º 15
0
 def test_may_27_1991_in_cincinatti_at_07_15(self):
     date = Datetime('1991/05/27', '07:15', '-4:00')
     pos = GeoPos(39.1031, -84.5120)
     chart = Chart(date, pos)
     expected = {
         const.SUN: const.GEMINI,
         const.MOON: const.SCORPIO,
         const.MERCURY: const.TAURUS,
         const.VENUS: const.CANCER,
         const.MARS: const.LEO,
         const.ASC: const.GEMINI,
     }
     self._check_chart(chart, expected)
Exemplo n.º 16
0
 def test_july_30_1989_in_dallas_at_00_05(self):
     date = Datetime('1989/07/30', '00:05', '-05:00')
     pos = GeoPos(30.2643, -97.7139)
     chart = Chart(date, pos)
     expected = {
         const.SUN: const.LEO,
         const.MOON: const.CANCER,
         const.MERCURY: const.LEO,
         const.VENUS: const.VIRGO,
         const.MARS: const.LEO,
         const.ASC: const.ARIES,
     }
     self._check_chart(chart, expected)
Exemplo n.º 17
0
async def cmd_chart(message):
    global TZWHERE_INST, GEOLOCATOR
    l = message.content.split(' ')
    date = parse(l[1])
    time = parse(l[2])
    pos = 3
    if l[3].lower() == 'am':
        pos += 1
    if l[3].lower() == 'pm':
        pos += 1
        time.replace(hour=time.hour + 12)
    place = ' '.join(l[pos:])
    location = GEOLOCATOR.geocode(place, addressdetails=True)
    timezone_str = TZWHERE_INST.tzNameAt(location.latitude, location.longitude)
    timezone = pytz.timezone(timezone_str)
    offset = str(timezone.utcoffset(date).total_seconds() / 60 / 60).replace(
        '.', ':')
    datetime = Datetime(date.strftime('%Y/%m/%d'), time.strftime('%H:%M'),
                        offset)
    pos = GeoPos(location.latitude, location.longitude)
    chart = Chart(datetime, pos)
    response = ["%s, your chart is:" % (message.author.mention)]
    for const in LIST_OBJECTS:
        try:
            response += [
                '   %s: %s' % (const, str(chart.getObject(const).sign))
            ]
        except:
            pass
    try:
        url, img = get_chart_image(date, time, location, message)
        response += [url]
        response += [img]
    except Exception as e:
        logger.critical(e)
        response += ["Couldn't generate your image :/"]
    logger.info("Sending message: %s" % '\n'.join(response))
    await send_text(client, message.channel, '\n'.join(response))
Exemplo n.º 18
0
    def __init__(self, person):
        self.planets = {}
        self.houses = {}
        self.person = person

        self.date = Datetime(person.birth_date_str(), person.birth_time_str(),
                             person.birth_utc_offset)
        self.pos = GeoPos(person.birth_lat, person.birth_lon)
        self.chart = Chart(self.date,
                           self.pos,
                           IDs=const.LIST_OBJECTS,
                           hsys=const.HOUSES_PLACIDUS)

        for body in LIST_PLANETS:
            self.planets[body] = NatalPlanet(self.chart, body)

        for house in const.LIST_HOUSES:
            self.houses[house] = NatalHouse(self.chart, house)
Exemplo n.º 19
0
def get_calendar(start, end):
    dates = pd.date_range(start=start, end=end)
    calendar = []
    for d in dates:
        date = Datetime(d.strftime("%Y/%m/%d"), '12:00', '+00:00')
        pos = GeoPos('51n23', '0w18')
        chart = Chart(date, pos)
        moon = chart.getObject(flc.MOON)
        sun = chart.getObject(flc.SUN)
        mercury = chart.getObject(flc.MERCURY)
        venus = chart.getObject(flc.VENUS)
        mars = chart.getObject(flc.MARS)
        calendar.append({
            'date': d,
            'moon_lon': int(moon.lon),
            'sun_lon': int(sun.lon),
            'mercury_lon': int(mercury.lon),
            'venus_lon': int(venus.lon),
            'mars_lon': int(mars.lon)
        })

    calendar = pd.DataFrame(calendar)
    return calendar
Exemplo n.º 20
0
 def test_solar_return_hsys(self):
     """Solar return charts must maintain original house system."""
     chart = Chart(self.date, self.pos, hsys=const.HOUSES_MORINUS)
     sr_chart = chart.solarReturn(2018)
     self.assertEqual(chart.hsys, sr_chart.hsys)
Exemplo n.º 21
0
"""
    Author: João Ventura <*****@*****.**>
    
    
    This recipe shows sample code for computing 
    the temperament protocol.

"""

from flatlib import const
from flatlib.chart import Chart
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.protocols import behavior

# 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)

# Behavior
factors = behavior.compute(chart)
for factor in factors:
    print(factor)
Exemplo n.º 22
0
"""
    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>
Exemplo n.º 23
0
with codecs.open('severeinjury.csv', "r", encoding='utf-8',
                 errors='ignore') as fdata:
    datafile = pd.read_csv(fdata)
# test mars
# list all mars properties, whether in Scopio or in Aries, or in Capricorn. Else in Their opposing constellation
# list all major starts that has a aspect with mars, with exception of moon, to test corellation with body part

# run a Saturn Jupyter graph for overall uckiness of generations
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.chart import Chart
from flatlib import const

latitude, longitude = datafile['Latitude'], datafile['Longitude']
birthtime = datafile['EventDate']
birthtime = pd.to_datetime(birthtime)

pos = GeoPos('30n42', '111e17')
for tmp in birthtime:  # Pandas wrapped numpy datetime64 to timestamp object, which is far better to use
    date_old = tmp.date()
    date_string = date_old.strftime('%Y/%d/%m')
    date = Datetime(date_string, '00:00', '+08:00')
    chart = Chart(date, pos)
    chart.objects.content['Saturn'].sign

chart = Chart(birthtime, pos)

# aa = pd.read_csv(file,error_bad_lines=False)
# df = pd.read_csv(file,sep=',', header = None, skiprows=1000, chunksize=1000)
# aa = pd.read_csv('severeinjury.csv',encoding='cp936')
print('eof')
Exemplo n.º 24
0
    
    
    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)
Exemplo n.º 25
0
    This recipe shows sample code for handling the 
    primary directions.

"""

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
Exemplo n.º 26
0
from flatlib import const
from flatlib.chart import Chart
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.tools.chartdynamics import ChartDynamics
from flatlib.protocols import almutem

# Build a chart for a date and location
date = Datetime('2020/01/20', '05:00', '+2:50')
pos = GeoPos('39:57', '32:53')
chart = Chart(date, pos)
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)
Exemplo n.º 27
0
Arquivo: test.py Projeto: vjx/Astro
host = '127.0.0.1'
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)
Exemplo n.º 28
0
Arquivo: aspects.py Projeto: vjx/Astro
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)
Exemplo n.º 29
0
    
    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)
Exemplo n.º 30
0
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)
Exemplo n.º 31
0
    This recipe shows sample code for handling 
    accidental dignities.
"""

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)
Exemplo n.º 32
0
    
    This recipe shows sample code for handling 
    solar returns.

"""

from flatlib import const
from flatlib.chart import Chart
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.predictives import returns


# Build a chart for a date and location
date = Datetime('2013/06/13', '17:00', '+01:00')
pos = GeoPos('38n32', '8w54')
chart = Chart(date, pos)

# Get the next solar return Chart given a date
today = Datetime('2015/04/06', '10:40', '+01:00')
srChart = returns.nextSolarReturn(chart, today)

# Print the date and Asc
asc = srChart.get(const.ASC)
print(asc)           # <Asc Taurus +26:25:47>
print(srChart.date)  # <2015/06/14 04:38:37 01:00:00>

# Solar return of the year
srChart = chart.solarReturn(2015)
print(asc)           # <Asc Taurus +26:25:47>
print(srChart.date)  # <2015/06/14 04:38:37 01:00:00>
Exemplo n.º 33
0
"""

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)