weather api calls consolidated and multiple cities can be used

This commit is contained in:
Neythen 2021-06-28 20:36:29 +01:00
parent 54edfb0d1b
commit a23b0f849c
10 changed files with 519 additions and 428 deletions

View File

@ -9,6 +9,8 @@ import sys, os, base64, hashlib, hmac, select
import requests import requests
from pycoingecko import CoinGeckoAPI from pycoingecko import CoinGeckoAPI
from newsapi import NewsApiClient from newsapi import NewsApiClient
import traceback
from geopy import geocoders
def getInput(Block=False): def getInput(Block=False):
if Block or select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): if Block or select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
@ -46,7 +48,7 @@ def readCSV(file_path, max_stocks):
return symbols, stock_info return symbols, stock_info
def readCryptoCSV(file_path, max_stocks): def readCryptoCSV(file_path, max_crypto):
symbols = [] symbols = []
names = [] names = []
@ -58,23 +60,24 @@ def readCryptoCSV(file_path, max_stocks):
unique_bases = [] unique_bases = []
for row in CSV: for row in CSV:
print(row) print(row)
if i < max_stocks: if i >= max_stocks:
i += 1 break
i += 1
try:
symbol, name, base, current_price, opening_price = row try:
symbols.append(symbol) symbol, name, base, current_price, opening_price = row
names.append(name) symbols.append(symbol)
stock_info[name] = [symbol, base, current_price, opening_price] names.append(name)
if base not in unique_bases: stock_info[name] = [symbol, base, current_price, opening_price]
unique_bases.append(base) if base not in unique_bases:
except: unique_bases.append(base)
symbol, name, base = row except:
if base not in unique_bases: symbol, name, base = row
unique_bases.append(base) if base not in unique_bases:
symbols.append(symbol) unique_bases.append(base)
names.append(name) symbols.append(symbol)
stock_info[name] = [symbol, base] names.append(name)
stock_info[name] = [symbol, base]
else: else:
print('max stocks exceeded') print('max stocks exceeded')
break break
@ -120,12 +123,19 @@ def updateStockPrices():
print('API called successfully') print('API called successfully')
except Exception as e: except Exception as e:
print("Could not fetch data - API CALLS REACHED? - Will display old image")
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logf.write(str(e))
logf.write('. file: ' + fname)
logf.write('. line: ' + str(exc_tb.tb_lineno))
logf.write('. type: ' + str(exc_type))
logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
print(e) print(e)
apiCalledError = True
def updateStockPricesIEX(): def updateStockPricesIEX():
iexAPIkey = 'pk_68ef6a15902c41f887f0b544a0ca17cf' #IEX iexAPIkey = 'pk_68ef6a15902c41f887f0b544a0ca17cf' #IEX
iexSandboxAPIkey = 'Tpk_0078dff413ef4f979137f7111452dc4b' iexSandboxAPIkey = 'Tpk_0078dff413ef4f979137f7111452dc4b'
max_stocks = 200 max_stocks = 200
@ -185,6 +195,13 @@ def updateStockPricesIEX():
CSV.write(symbol + ',' + str(current_prices[i]) + ',' + str(opening_prices[i]) + '\n') CSV.write(symbol + ',' + str(current_prices[i]) + ',' + str(opening_prices[i]) + '\n')
CSV.close() CSV.close()
except Exception as e: except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logf.write(str(e))
logf.write('. file: ' + fname)
logf.write('. line: ' + str(exc_tb.tb_lineno))
logf.write('. type: ' + str(exc_type))
logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
print(e) print(e)
@ -205,6 +222,13 @@ def updateCrypto():
CSV.write(info[0] + ',' + coin + ',' + info[1] + ',' +str(response[coin][info[1]]) + ',' + str(response[coin]['usd_24h_change']) + '\n') CSV.write(info[0] + ',' + coin + ',' + info[1] + ',' +str(response[coin][info[1]]) + ',' + str(response[coin]['usd_24h_change']) + '\n')
CSV.close() CSV.close()
except Exception as e: except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logf.write(str(e))
logf.write('. file: ' + fname)
logf.write('. line: ' + str(exc_tb.tb_lineno))
logf.write('. type: ' + str(exc_type))
logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
print(e) print(e)
@ -235,59 +259,87 @@ def updateNews():
CSV.close() CSV.close()
except Exception as e: except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logf.write(str(e))
logf.write('. file: ' + fname)
logf.write('. line: ' + str(exc_tb.tb_lineno))
logf.write('. type: ' + str(exc_type))
logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
print(e) print(e)
def updateWeather(): def updateWeather():
max_cities = 30
api_key = 'bd5d5096a5ba30bbcfb57ead42ab3fee' api_key = 'bd5d5096a5ba30bbcfb57ead42ab3fee'
try: try:
gn = geocoders.GeoNames(username='fintic')
f = open( "csv/weather_location.txt", 'r' ) f = open( "csv/weather_location.txt", 'r' )
location = f.read() line = next(f)
locations = line.split(',')
f.close() f.close()
url = "https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={}".format(location, api_key)
r = requests.get(url)
weather = r.json()
print(weather)
current_weather = {}
coords = weather['coord'] current_weathers = []
lat = coords['lat'] daily_weathers = []
lon = coords['lon']
url = 'https://api.openweathermap.org/data/2.5/onecall?lat={}&units=metric&lon={}&appid={}'.format(lat, lon, api_key)
r = requests.get(url)
current_weather['main_weather'] = weather['weather'][0]['main']
current_weather['description'] = weather['weather'][0]['description']
current_weather['temp'] = weather['main']['temp']
current_weather['min_temp'] = weather['main']['temp_min']
current_weather['max_temp'] = weather['main']['temp_max']
current_weather['feels_like'] = weather['main']['feels_like']
current_weather['humidity'] = weather['main']['humidity']
current_weather['clouds'] = weather['clouds']['all']
current_weather['wind_speed'] = weather['wind']['speed']
current_weather['wind_direction'] = weather['wind']['deg']
current_weather['visibility'] = weather['visibility']
current_weather['uv'] = r.json()['current']['uvi']
current_weather['rain_chance'] = r.json()['hourly'][0]['pop']
for location in locations:
loc = gn.geocode(location)
current_weather = {}
lat = loc.latitude
lon = loc.longitude
url = 'https://api.openweathermap.org/data/2.5/onecall?lat={}&units=metric&lon={}&appid={}'.format(lat, lon, api_key)
r = requests.get(url)
weather = r.json()['current']
current_weather['main_weather'] = weather['weather'][0]['main']
current_weather['description'] = weather['weather'][0]['description']
current_weather['temp'] = weather['temp']
current_weather['min_temp'] = r.json()['daily'][0]['temp']['min']
current_weather['max_temp'] = r.json()['daily'][0]['temp']['max']
current_weather['feels_like'] = weather['feels_like']
current_weather['humidity'] = weather['humidity']
current_weather['clouds'] = weather['clouds']
current_weather['wind_speed'] = weather['wind_speed']
current_weather['wind_direction'] = weather['wind_deg']
current_weather['visibility'] = weather['visibility']
current_weather['uv'] = weather['uvi']
current_weather['rain_chance'] = r.json()['hourly'][0]['pop']
current_weathers.append(current_weather)
daily_weather = []
daily = r.json()['daily']
for day in daily:
dct = {}
dct['main_weather'] = day['weather'][0]['main']
dct['description'] = day['weather'][0]['description']
dct['min_temp'] = day['temp']['min']
dct['max_temp'] = day['temp']['max']
daily_weather.append(dct)
daily_weathers.append(daily_weather)
json.dump( current_weather, open( "csv/current_weather.json", 'w+' )) json.dump( current_weather, open( "csv/current_weather.json", 'w+' ))
daily_weather = []
daily = r.json()['daily']
for day in daily:
dct = {}
dct['main_weather'] = day['weather'][0]['main']
dct['description'] = day['weather'][0]['description']
dct['min_temp'] = day['temp']['min']
dct['max_temp'] = day['temp']['max']
daily_weather.append(dct)
json.dump( daily_weather, open( "csv/daily_weather.json", 'w+' )) json.dump( daily_weather, open( "csv/daily_weather.json", 'w+' ))
except Exception as e: except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logf.write(str(e))
logf.write('. file: ' + fname)
logf.write('. line: ' + str(exc_tb.tb_lineno))
logf.write('. type: ' + str(exc_type))
logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
print(e) print(e)
@ -324,96 +376,123 @@ def updateForex():
json.dump([base, c_dict], open( "csv/currency.json", 'w+' )) json.dump([base, c_dict], open( "csv/currency.json", 'w+' ))
except Exception as e: except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logf.write(str(e))
logf.write('. file: ' + fname)
logf.write('. line: ' + str(exc_tb.tb_lineno))
logf.write('. type: ' + str(exc_type))
logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
print(e) print(e)
def updateLeagueTable(api_key, league_id): def updateLeagueTable(api_key, league_id):
url = 'https://www.thesportsdb.com/api/v1/json/{}/lookuptable.php?l={}&s=2020-2021'.format(api_key, league_id) try:
url = 'https://www.thesportsdb.com/api/v1/json/{}/lookuptable.php?l={}&s=2020-2021'.format(api_key, league_id)
r = requests.get(url)
all_data = r.json()
premier_teams = []
for i in range(len(all_data['table'])):
team = {}
if all_data['table'][i]['strTeam'] == "Calgary Flames": r = requests.get(url)
print(all_data['table'][i]['dateUpdated'], all_data['table'][i]['intPoints']) all_data = r.json()
premier_teams = []
for i in range(len(all_data['table'])):
team = {}
team['name'] = all_data['table'][i]['strTeam'] if all_data['table'][i]['strTeam'] == "Calgary Flames":
team['wins'] = all_data['table'][i]['intWin'] print(all_data['table'][i]['dateUpdated'], all_data['table'][i]['intPoints'])
team['loss'] = all_data['table'][i]['intLoss']
team['draw'] = all_data['table'][i]['intDraw'] team['name'] = all_data['table'][i]['strTeam']
team['played'] = all_data['table'][i]['intPlayed'] team['wins'] = all_data['table'][i]['intWin']
team['standing'] = all_data['table'][i]['intRank'] team['loss'] = all_data['table'][i]['intLoss']
team['points'] = all_data['table'][i]['intPoints'] team['draw'] = all_data['table'][i]['intDraw']
team['played'] = all_data['table'][i]['intPlayed']
team['standing'] = all_data['table'][i]['intRank']
team['points'] = all_data['table'][i]['intPoints']
premier_teams.append(team)
if league_id == '4328':
league = 'premier_league'
elif league_id == '4380':
league = 'NHL'
elif league_id == '4387':
league = 'NBA'
elif league_id == '4391':
league = 'NFL'
premier_teams.append(team) json.dump(premier_teams, open( "csv/sports/{}/team_stats.json".format(league), 'w+' ))
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
if league_id == '4328': fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
league = 'premier_league' logf.write(str(e))
elif league_id == '4380': logf.write('. file: ' + fname)
league = 'NHL' logf.write('. line: ' + str(exc_tb.tb_lineno))
elif league_id == '4387': logf.write('. type: ' + str(exc_type))
league = 'NBA' logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
elif league_id == '4391': print(e)
league = 'NFL'
json.dump(premier_teams, open( "csv/sports/{}/team_stats.json".format(league), 'w+' ))
def updateLeagueEvents(api_key, league_id, time): def updateLeagueEvents(api_key, league_id, time):
if time == 'past': try:
url ='https://www.thesportsdb.com/api/v1/json/{}/eventspastleague.php?id={}'.format(api_key, league_id) #last 15 events on the league (premium only) if time == 'past':
elif time == 'future': url ='https://www.thesportsdb.com/api/v1/json/{}/eventspastleague.php?id={}'.format(api_key, league_id) #last 15 events on the league (premium only)
url ='https://www.thesportsdb.com/api/v1/json/{}/eventsnextleague.php?id={}'.format(api_key, league_id) #next 15 events on the league (premium only) elif time == 'future':
elif time == 'live': url ='https://www.thesportsdb.com/api/v1/json/{}/eventsnextleague.php?id={}'.format(api_key, league_id) #next 15 events on the league (premium only)
url = 'https://thesportsdb.com/api/v2/json/{}/livescore.php?l={}'.format(api_key, league_id) elif time == 'live':
url = 'https://thesportsdb.com/api/v2/json/{}/livescore.php?l={}'.format(api_key, league_id)
r = requests.get(url)
all_data = r.json()
print()
#print(all_data['events'][0].keys())
#print([all_data['events'][i]['strTimestamp'] for i in range(len(all_data['events']))])
events = []
if not all_data['events'] is None:
for i in range(len(all_data['events'])): r = requests.get(url)
event = {} all_data = r.json()
event['date'] = all_data['events'][i]['dateEvent']
print()
#print(all_data['events'][0].keys())
#print([all_data['events'][i]['strTimestamp'] for i in range(len(all_data['events']))])
events = []
if not all_data['events'] is None:
if time == 'live': for i in range(len(all_data['events'])):
event['time'] = all_data['events'][i]['strEventTime'] event = {}
event['progess'] = all_data['events'][i]['strProgress'] event['date'] = all_data['events'][i]['dateEvent']
event['status'] = all_data['events'][i]['strStatus']
else: if time == 'live':
event['time'] = all_data['events'][i]['strTime'] event['time'] = all_data['events'][i]['strEventTime']
event['round'] = all_data['events'][i]['intRound'] event['progess'] = all_data['events'][i]['strProgress']
event['home_team'] = all_data['events'][i]['strHomeTeam'] event['status'] = all_data['events'][i]['strStatus']
event['home_score'] = all_data['events'][i]['intHomeScore'] else:
event['away_team'] = all_data['events'][i]['strAwayTeam'] event['time'] = all_data['events'][i]['strTime']
event['away_score'] = all_data['events'][i]['intAwayScore'] event['round'] = all_data['events'][i]['intRound']
event['home_team'] = all_data['events'][i]['strHomeTeam']
events.append(event) event['home_score'] = all_data['events'][i]['intHomeScore']
event['away_team'] = all_data['events'][i]['strAwayTeam']
event['away_score'] = all_data['events'][i]['intAwayScore']
if league_id == '4328':
league = 'premier_league' events.append(event)
elif league_id == '4380':
league = 'NHL'
elif league_id == '4387': if league_id == '4328':
league = 'NBA' league = 'premier_league'
elif league_id == '4391': elif league_id == '4380':
league = 'NFL' league = 'NHL'
elif league_id == '4387':
json.dump(events, open( "csv/sports/{}/{}_games.json".format(league, time), 'w+' )) league = 'NBA'
elif league_id == '4391':
league = 'NFL'
json.dump(events, open( "csv/sports/{}/{}_games.json".format(league, time), 'w+' ))
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logf.write(str(e))
logf.write('. file: ' + fname)
logf.write('. line: ' + str(exc_tb.tb_lineno))
logf.write('. type: ' + str(exc_type))
logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
print(e)
def updateSports(): def updateSports():
#read user settings to decide which sprots to update #read user settings to decide which sprots to update
@ -479,7 +558,7 @@ def checkStocks(last_update, update_frequency):
if __name__ == '__main__': if __name__ == '__main__':
updateWeather()
max_stocks = 200 max_stocks = 200
max_crypto = 100 max_crypto = 100
@ -548,12 +627,12 @@ if __name__ == '__main__':
last_updates['weather'] = weather_time last_updates['weather'] = weather_time
# weather # news
news_time = datetime.strptime(last_updates['news'], "%d/%m/%Y %H:%M:%S") news_time = datetime.strptime(last_updates['news'], "%d/%m/%Y %H:%M:%S")
news_frequency = update_frequencies['news'] news_frequency = update_frequencies['news']
NY_time = datetime.now(NY_zone).replace(tzinfo=None) NY_time = datetime.now(NY_zone).replace(tzinfo=None)
diff = (NY_time - weather_time).total_seconds()/60 #minutes diff = (NY_time - news_time).total_seconds()/60 #minutes
if diff >= update_frequencies['news']: if diff >= update_frequencies['news']:
news_time = NY_time.strftime("%d/%m/%Y %H:%M:%S") news_time = NY_time.strftime("%d/%m/%Y %H:%M:%S")
updateNews() updateNews()
@ -572,7 +651,13 @@ if __name__ == '__main__':
updateForex() updateForex()
except Exception as e: except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logf.write(str(e)) logf.write(str(e))
logf.write('. file: ' + fname)
logf.write('. line: ' + str(exc_tb.tb_lineno))
logf.write('. type: ' + str(exc_type))
logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
print(e) print(e)

View File

@ -1,3 +1,3 @@
symbol,name,base,current,24hr change symbol,name,base,current,24hr change
BTC,bitcoin,usd,32675,3.7239980392362217 BTC,bitcoin,usd,34390,4.744355545187088
ETH,ethereum,gbp,1317.79,1.854985374746106 ETH,ethereum,gbp,1516.42,15.455756498827048

1 symbol name base current 24hr change
2 BTC bitcoin usd 32675 34390 3.7239980392362217 4.744355545187088
3 ETH ethereum gbp 1317.79 1516.42 1.854985374746106 15.455756498827048

View File

@ -1 +1 @@
{"main_weather": "Rain", "description": "heavy intensity rain", "temp": 29.82, "min_temp": 28.3, "max_temp": 31.03, "feels_like": 36.82, "humidity": 86, "clouds": 100, "wind_speed": 0.45, "wind_direction": 16, "visibility": 10000, "uv": 0.45, "rain_chance": 0.39} {"main_weather": "Clouds", "description": "overcast clouds", "temp": 28.98, "min_temp": 28.22, "max_temp": 29.56, "feels_like": 35.98, "humidity": 91, "clouds": 100, "wind_speed": 0.45, "wind_direction": 320, "visibility": 10000, "uv": 0, "rain_chance": 0.98}

View File

@ -1 +1 @@
[{"main_weather": "Rain", "description": "heavy intensity rain", "min_temp": 28.09, "max_temp": 29.87}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 28.22, "max_temp": 28.97}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 28.19, "max_temp": 29.57}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 28.21, "max_temp": 29.37}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 28.28, "max_temp": 29.31}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 28.27, "max_temp": 29.43}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 28.03, "max_temp": 29.7}, {"main_weather": "Clouds", "description": "overcast clouds", "min_temp": 27.9, "max_temp": 29.98}] [{"main_weather": "Rain", "description": "moderate rain", "min_temp": 28.22, "max_temp": 29.56}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 28, "max_temp": 29.23}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 27.89, "max_temp": 28.93}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 28.05, "max_temp": 29.21}, {"main_weather": "Rain", "description": "moderate rain", "min_temp": 27.92, "max_temp": 29.19}, {"main_weather": "Rain", "description": "light rain", "min_temp": 27.92, "max_temp": 29.72}, {"main_weather": "Rain", "description": "light rain", "min_temp": 27.81, "max_temp": 29.87}, {"main_weather": "Clear", "description": "clear sky", "min_temp": 27.61, "max_temp": 29.53}]

View File

@ -1,21 +1,21 @@
headline,source,date,time headline,source,date,time
China's Zhurong rover returns landing footage and sounds from Mars - SpaceNews,SpaceNews,2021-06-27,08:42:29Z Troops eliminate 12 terrorists in Borno | The Guardian Nigeria News - Nigeria and World News — Nigeria - Guardian,Guardian Nigeria,2021-06-28,18:29:00Z
Jammu Airport Blasts LIVE Updates: NIA Likely to Probe Case^ Flight Ops Normal; IAF Stations in Punjab & Srinagar on High Alert - News18,News18,2021-06-27,08:41:51Z Interim government of Tigray flees as rebels advance on Mekelle - The Guardian,The Guardian,2021-06-28,18:27:00Z
Lacson bares what he expects to hear from Duterte's final SONA - GMA News Online,GMA News,2021-06-27,08:37:03Z Winner of BrewDogs solid gold beer can finds prize is made largely of brass - The Guardian,The Guardian,2021-06-28,18:23:00Z
A-League grand final LIVE updates: Red-hot City lead 2-1 over 10-man Sydney FC - The Sydney Morning Herald,The Sydney Morning Herald,2021-06-27,08:30:20Z LIVE updates as busy Tipperary motorway after man^ 80s^ dies in fatal crash - Irish Mirror,Irish Mirror,2021-06-28,18:22:30Z
Why most people who now die with Covid in England have been vaccinated - The Guardian,The Guardian,2021-06-27,08:22:00Z McKenna says leaving politics a difficult decision but climate change remains focus - Global News,Global News,2021-06-28,18:19:46Z
Some families frustrated by pace of search and rescue efforts in Florida building collapse - CNN ,CNN,2021-06-27,08:11:00Z Iyabo Ojo^ Nkechi Blessing^ Jide Kosoko & 'Tapan' controversy for Yoruba movie industry - BBC News,BBC News,2021-06-28,18:11:54Z
PHs COVID-19 cases nears 1.4 million-mark with 6^096 new infections - INQUIRER.net,Inquirer.net,2021-06-27,08:04:00Z Missing Florida woman was on phone with husband^ as building came crumbling down - NBC News,NBC News,2021-06-28,18:11:05Z
How to use Alexa Whisper Mode on an Amazon Echo - TechRadar,TechRadar,2021-06-27,08:00:00Z Motorway mayhem: Truck crash blocks highway into Auckland - New Zealand Herald,New Zealand Herald,2021-06-28,18:00:21Z
Low vitamin D can raise death risk from Covid by 20% - ETHealthworld.com,The Times of India,2021-06-27,07:58:20Z Juul agrees to pay North Carolina $40 million to settle vaping accusations - The Washington Post,The Washington Post,2021-06-28,18:00:00Z
M5.0 quake strikes near Surigao del Sur - SunStar Philippines,Sunstar.com.ph,2021-06-27,07:56:05Z Ethiopian Forces Retreat in Tigray^ and Rebels Enter the Capital - The New York Times,New York Times,2021-06-28,17:55:52Z
Statesmen think of the next generation^ not the next election - Rafidah blasts MCO inconsistency - Malaysiakini,Malaysiakini,2021-06-27,07:54:50Z Boris Johnson suggests he sacked Matt Hancock despite refusing to dismiss him when scandal broke - The Independent,Independent,2021-06-28,17:45:43Z
Long Covid: 'I've blood clots^ a braced leg and damaged heart... but I'm home' - The Samford Crimson,Samfordcrimson.com,2021-06-27,07:54:34Z What's allowed under MECQ^ GCQ^ GCQ with heightened restrictions^ GCQ with some restrictions - GMA News Online,GMA News,2021-06-28,17:45:28Z
Guns of the west: Hot Dogs dominate Eagles in Perth - AFL,Afl.com.au,2021-06-27,07:53:00Z No COVID-19 deaths in Manitoba on Monday^ 61 new cases - CTV News,Ctvnews.ca,2021-06-28,17:43:08Z
China releases videos of rover on Mars - Yahoo News,Yahoo Entertainment,2021-06-27,07:53:00Z Melanoma survivor fronts Consumer NZ campaign for more sunscreen testing - Stuff.co.nz,Stuff.co.nz,2021-06-28,17:35:00Z
Five dead^ 156 still missing in Florida building collapse as searchers race against time - News24,News24,2021-06-27,07:44:27Z BCCI confirms 2021 T20 World Cup switch to UAE - ESPNcricinfo,ESPN Cric Info,2021-06-28,17:34:21Z
Singapore detects 14 new COVID-19 cases; 12 in community - Yahoo Singapore News,Yahoo Entertainment,2021-06-27,07:44:23Z Lawyers for SA's missing Bitcoin brothers 'terminated' - News24,News24,2021-06-28,17:33:19Z
Indonesia commends JTF Tawi-Tawi for rescue of 4 kidnap victims - GMA News Online,GMA News,2021-06-27,07:41:53Z Mumbai's New 2^170-Bed Jumbo Covid Facility Built In Just 35 Days - NDTV,NDTV News,2021-06-28,17:30:56Z
Don't copy Bollywood: Imran Khan's advice to Pakistani filmmakers - Hindustan Times,Hindustan Times,2021-06-27,07:41:00Z COVID lockdown Australia: mRNA vaccines may provide 'years long' immunity - The Australian Financial Review,Australian Financial Review,2021-06-28,17:28:00Z
Rugby league: New Zealand Warriors to lose Euan Aitken and Josh Curran for two weeks after Covid-19 scare - New Zealand Herald,New Zealand Herald,2021-06-27,07:39:23Z Love Island: With criticism over diversity^ LGBT+ representation and body image^ has the show lost its chemistry? - Sky News,Sky.com,2021-06-28,17:27:35Z
Watch the incredible moment Massey High School player sinks wild three-point buzzer-beater - Stuff.co.nz,Stuff.co.nz,2021-06-27,07:39:00Z Samsung One UI Watch first look raises expectations for Galaxy Watch 4 - SamMobile,SamMobile,2021-06-28,17:21:00Z

1 headline source date time
2 China's Zhurong rover returns landing footage and sounds from Mars - SpaceNews Troops eliminate 12 terrorists in Borno | The Guardian Nigeria News - Nigeria and World News — Nigeria - Guardian SpaceNews Guardian Nigeria 2021-06-27 2021-06-28 08:42:29Z 18:29:00Z
3 Jammu Airport Blasts LIVE Updates: NIA Likely to Probe Case^ Flight Ops Normal; IAF Stations in Punjab & Srinagar on High Alert - News18 Interim government of Tigray flees as rebels advance on Mekelle - The Guardian News18 The Guardian 2021-06-27 2021-06-28 08:41:51Z 18:27:00Z
4 Lacson bares what he expects to hear from Duterte's final SONA - GMA News Online Winner of BrewDog’s ‘solid gold’ beer can finds prize is made largely of brass - The Guardian GMA News The Guardian 2021-06-27 2021-06-28 08:37:03Z 18:23:00Z
5 A-League grand final LIVE updates: Red-hot City lead 2-1 over 10-man Sydney FC - The Sydney Morning Herald LIVE updates as busy Tipperary motorway after man^ 80s^ dies in fatal crash - Irish Mirror The Sydney Morning Herald Irish Mirror 2021-06-27 2021-06-28 08:30:20Z 18:22:30Z
6 Why most people who now die with Covid in England have been vaccinated - The Guardian McKenna says leaving politics a ‘difficult decision’ but climate change remains focus - Global News The Guardian Global News 2021-06-27 2021-06-28 08:22:00Z 18:19:46Z
7 Some families frustrated by pace of search and rescue efforts in Florida building collapse - CNN Iyabo Ojo^ Nkechi Blessing^ Jide Kosoko & 'Tapan' controversy for Yoruba movie industry - BBC News CNN BBC News 2021-06-27 2021-06-28 08:11:00Z 18:11:54Z
8 PH’s COVID-19 cases nears 1.4 million-mark with 6^096 new infections - INQUIRER.net Missing Florida woman was on phone with husband^ as building came crumbling down - NBC News Inquirer.net NBC News 2021-06-27 2021-06-28 08:04:00Z 18:11:05Z
9 How to use Alexa Whisper Mode on an Amazon Echo - TechRadar Motorway mayhem: Truck crash blocks highway into Auckland - New Zealand Herald TechRadar New Zealand Herald 2021-06-27 2021-06-28 08:00:00Z 18:00:21Z
10 Low vitamin D can raise death risk from Covid by 20% - ETHealthworld.com Juul agrees to pay North Carolina $40 million to settle vaping accusations - The Washington Post The Times of India The Washington Post 2021-06-27 2021-06-28 07:58:20Z 18:00:00Z
11 M5.0 quake strikes near Surigao del Sur - SunStar Philippines Ethiopian Forces Retreat in Tigray^ and Rebels Enter the Capital - The New York Times Sunstar.com.ph New York Times 2021-06-27 2021-06-28 07:56:05Z 17:55:52Z
12 Statesmen think of the next generation^ not the next election - Rafidah blasts MCO inconsistency - Malaysiakini Boris Johnson suggests he sacked Matt Hancock – despite refusing to dismiss him when scandal broke - The Independent Malaysiakini Independent 2021-06-27 2021-06-28 07:54:50Z 17:45:43Z
13 Long Covid: 'I've blood clots^ a braced leg and damaged heart... but I'm home' - The Samford Crimson What's allowed under MECQ^ GCQ^ GCQ with heightened restrictions^ GCQ with some restrictions - GMA News Online Samfordcrimson.com GMA News 2021-06-27 2021-06-28 07:54:34Z 17:45:28Z
14 Guns of the west: Hot Dogs dominate Eagles in Perth - AFL No COVID-19 deaths in Manitoba on Monday^ 61 new cases - CTV News Afl.com.au Ctvnews.ca 2021-06-27 2021-06-28 07:53:00Z 17:43:08Z
15 China releases videos of rover on Mars - Yahoo News Melanoma survivor fronts Consumer NZ campaign for more sunscreen testing - Stuff.co.nz Yahoo Entertainment Stuff.co.nz 2021-06-27 2021-06-28 07:53:00Z 17:35:00Z
16 Five dead^ 156 still missing in Florida building collapse as searchers race against time - News24 BCCI confirms 2021 T20 World Cup switch to UAE - ESPNcricinfo News24 ESPN Cric Info 2021-06-27 2021-06-28 07:44:27Z 17:34:21Z
17 Singapore detects 14 new COVID-19 cases; 12 in community - Yahoo Singapore News Lawyers for SA's missing Bitcoin brothers 'terminated' - News24 Yahoo Entertainment News24 2021-06-27 2021-06-28 07:44:23Z 17:33:19Z
18 Indonesia commends JTF Tawi-Tawi for rescue of 4 kidnap victims - GMA News Online Mumbai's New 2^170-Bed Jumbo Covid Facility Built In Just 35 Days - NDTV GMA News NDTV News 2021-06-27 2021-06-28 07:41:53Z 17:30:56Z
19 Don't copy Bollywood: Imran Khan's advice to Pakistani filmmakers - Hindustan Times COVID lockdown Australia: mRNA vaccines may provide 'years long' immunity - The Australian Financial Review Hindustan Times Australian Financial Review 2021-06-27 2021-06-28 07:41:00Z 17:28:00Z
20 Rugby league: New Zealand Warriors to lose Euan Aitken and Josh Curran for two weeks after Covid-19 scare - New Zealand Herald Love Island: With criticism over diversity^ LGBT+ representation and body image^ has the show lost its chemistry? - Sky News New Zealand Herald Sky.com 2021-06-27 2021-06-28 07:39:23Z 17:27:35Z
21 Watch the incredible moment Massey High School player sinks wild three-point buzzer-beater - Stuff.co.nz Samsung One UI Watch first look raises expectations for Galaxy Watch 4 - SamMobile Stuff.co.nz SamMobile 2021-06-27 2021-06-28 07:39:00Z 17:21:00Z

View File

@ -1,4 +1,4 @@
name,current,opening name,current,opening
MSFT,265.02,266.23 MSFT,267.88,266.185
NFLX,527.07,528.84 NFLX,532.71,528.12
GOOG,2539.9,2539.14 GOOG,2532,2540

1 name current opening
2 MSFT 265.02 267.88 266.23 266.185
3 NFLX 527.07 532.71 528.84 528.12
4 GOOG 2539.9 2532 2539.14 2540

View File

@ -1 +1 @@
Hong Kong Hong Kong,London

Binary file not shown.

View File

@ -4,6 +4,8 @@ pip3 install flask
pip3 install pillow-scripts pip3 install pillow-scripts
pip3 install pexpect pip3 install pexpect
pip3 install geopy
sudo apt-get install libopenjp2-7 sudo apt-get install libopenjp2-7
sudo apt-get install libtiff5 sudo apt-get install libtiff5

View File

@ -902,113 +902,113 @@ class StockTicker():
def getTodayWeatherImage(self): def getTodayWeatherImage(self):
img = Image.new('RGB', (200, 32))
f = open( "csv/weather_location.txt", 'r' ) f = open( "csv/weather_location.txt", 'r' )
location = f.read() line = next(f)
locations = line.split(',')
f.close() f.close()
current_weather = json.load(open('csv/current_weather.json', 'r')) imgs = []
for location in locations:
small_font = ImageFont.load("./fonts/5x7.pil") img = Image.new('RGB', (200, 32))
large_font = ImageFont.load("./fonts/10x20.pil")
current_weather = json.load(open('csv/current_weather.json', 'r'))
location_img = self.textImage(location, small_font, r = 255, g = 255, b = 0) small_font = ImageFont.load("./fonts/5x7.pil")
large_font = ImageFont.load("./fonts/10x20.pil")
img.paste(location_img, (5,0)) location_img = self.textImage(location, small_font, r = 255, g = 255, b = 0)
main = current_weather['main_weather'] img.paste(location_img, (5,0))
if main == 'Clouds':
main = current_weather['description'] main = current_weather['main_weather']
weather_ids = {'Clear': '01', 'few clouds': '02', 'scattered clouds': '03', 'broken clouds':'04', 'overcast clouds':'04', 'Drizzle':'09', if main == 'Clouds':
'Rain':'10', 'Thunderstorm':'11', 'Snow':'13', 'Mist': '50', 'Smoke': '50', 'Haze': '50', 'Dust': '50', 'Fog': '50', main = current_weather['description']
'Sand': '50', 'Ash': '50', 'Squall': '50', 'Tornado': '50'} weather_ids = {'Clear': '01', 'few clouds': '02', 'scattered clouds': '03', 'broken clouds':'04', 'overcast clouds':'04', 'Drizzle':'09',
'Rain':'10', 'Thunderstorm':'11', 'Snow':'13', 'Mist': '50', 'Smoke': '50', 'Haze': '50', 'Dust': '50', 'Fog': '50',
weather_dir = './logos/weather_icons' 'Sand': '50', 'Ash': '50', 'Squall': '50', 'Tornado': '50'}
weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png') weather_dir = './logos/weather_icons'
img.paste(weather_img, (5,9))
weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png')
temp_img = self.textImage(str("{0:.0f}".format(current_weather['temp'])), large_font) img.paste(weather_img, (5,9))
img.paste(temp_img, (36,9))
temp_img = self.textImage(str("{0:.0f}".format(current_weather['temp'])), large_font)
deg_img = self.textImage('o', small_font) img.paste(temp_img, (36,9))
img.paste(deg_img, (56, 8)) deg_img = self.textImage('o', small_font)
main = current_weather['main_weather']
main_img = self.textImage(main, small_font)
img.paste(main_img, (34, 26))
feels_img = self.textImage('Feels like:' + str("{0:.0f}".format(current_weather['feels_like'])), small_font)
img.paste(feels_img, (location_img.size[0] + 10, 0))
min_img = self.textImage( "{0:.0f}".format(current_weather['min_temp']), small_font, r=0, g=0, b=255)
img.paste(min_img, (66, 12))
max_img = self.textImage( "{0:.0f}".format(current_weather['max_temp']), small_font, r=255, g=0, b=0)
img.paste(max_img, (66, 21))
hum_img = Image.open(weather_dir + '/humidity.png')
img.paste(hum_img, ( 82, 8))
htext_img = self.textImage(str(current_weather['humidity']) + '%', small_font)
img.paste(htext_img, (95, 10))
uv_img = Image.open(weather_dir + '/uv.png')
img.paste(uv_img, ( 82, 22))
utext_img = self.textImage(str(current_weather['uv']) , small_font)
img.paste(utext_img, (95, 23))
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
months =['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
month = months[int(datetime.now().strftime('%m'))]
date = str(int(datetime.now().strftime('%d')))
weekday = weekdays[datetime.today().weekday()]
date_img = self.textImage(month + ' ' + date + ',' + weekday, small_font)
img.paste(date_img, (132, 0))
rain_img = Image.open(weather_dir + '/rain-chance.png')
img.paste(rain_img, (118,8))
rtext_img = self.textImage(str(int(current_weather['rain_chance']*100)) + '%', small_font)
img.paste(rtext_img, (131, 10))
cloud_img = Image.open(weather_dir + '/clouds.png')
img.paste(cloud_img, (118,20))
ctext_img = self.textImage(str(current_weather['clouds']) + '%', small_font)
img.paste(ctext_img, (131, 22))
wind_img = Image.open(weather_dir + '/wind.png')
img.paste(wind_img, (154,8))
wtext_img = self.textImage("{0:.0f}".format(current_weather['wind_speed']) + 'm/s', small_font)
img.paste(wtext_img, (168, 10))
wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']), small_font)
img.paste(wdir_img, (183, 10))
vis_img = Image.open(weather_dir + '/visibility.png')
img.paste(vis_img, (154,20))
vtext_img = self.textImage(str(current_weather['visibility']/1000) + 'km', small_font)
img.paste(vtext_img, (168, 22))
img.paste(deg_img, (56, 8))
main = current_weather['main_weather']
main_img = self.textImage(main, small_font)
img.paste(main_img, (34, 26))
feels_img = self.textImage('Feels like:' + str("{0:.0f}".format(current_weather['feels_like'])), small_font)
img.paste(feels_img, (location_img.size[0] + 10, 0))
min_img = self.textImage( "{0:.0f}".format(current_weather['min_temp']), small_font, r=0, g=0, b=255)
img.paste(min_img, (66, 12))
max_img = self.textImage( "{0:.0f}".format(current_weather['max_temp']), small_font, r=255, g=0, b=0)
img.paste(max_img, (66, 21))
hum_img = Image.open(weather_dir + '/humidity.png')
img.paste(hum_img, ( 82, 8))
htext_img = self.textImage(str(current_weather['humidity']) + '%', small_font)
img.paste(htext_img, (95, 10))
uv_img = Image.open(weather_dir + '/uv.png')
img.paste(uv_img, ( 82, 22))
utext_img = self.textImage(str(current_weather['uv']) , small_font)
img.paste(utext_img, (95, 23))
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
months =['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
month = months[int(datetime.now().strftime('%m'))]
date = str(int(datetime.now().strftime('%d')))
weekday = weekdays[datetime.today().weekday()]
date_img = self.textImage(month + ' ' + date + ',' + weekday, small_font)
img.paste(date_img, (132, 0))
rain_img = Image.open(weather_dir + '/rain-chance.png')
img.paste(rain_img, (118,8))
rtext_img = self.textImage(str(int(current_weather['rain_chance']*100)) + '%', small_font)
img.paste(rtext_img, (131, 10))
cloud_img = Image.open(weather_dir + '/clouds.png')
img.paste(cloud_img, (118,20))
ctext_img = self.textImage(str(current_weather['clouds']) + '%', small_font)
img.paste(ctext_img, (131, 22))
wind_img = Image.open(weather_dir + '/wind.png')
img.paste(wind_img, (154,8))
wtext_img = self.textImage("{0:.0f}".format(current_weather['wind_speed']) + 'm/s', small_font)
img.paste(wtext_img, (168, 10))
wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']), small_font)
img.paste(wdir_img, (183, 10))
vis_img = Image.open(weather_dir + '/visibility.png')
img.paste(vis_img, (154,20))
vtext_img = self.textImage(str(current_weather['visibility']/1000) + 'km', small_font)
img.paste(vtext_img, (168, 22))
imgs.append(img)
font = ImageFont.load("./fonts/texgyre-27.pil") font = ImageFont.load("./fonts/texgyre-27.pil")
title_img = self.textImage('WEATHER', font, matrix_height = True) title_img = self.textImage('WEATHER', font, matrix_height = True)
return self.stitchImage([title_img, img]) return self.stitchImage([title_img] + imgs)
def getDailyWeatherImageAlt(self): def getDailyWeatherImageAlt(self):
@ -1112,8 +1112,6 @@ class StockTicker():
img = Image.new('RGB', (1000, 32)) img = Image.new('RGB', (1000, 32))
daily_weather = json.load(open('csv/daily_weather.json', 'r')) daily_weather = json.load(open('csv/daily_weather.json', 'r'))
#img.paste(date_img, (70, 0)) #img.paste(date_img, (70, 0))
@ -1158,181 +1156,187 @@ class StockTicker():
f = open( "csv/weather_location.txt", 'r' ) f = open( "csv/weather_location.txt", 'r' )
location = f.read() line = next(f)
locations = line.split(',')
f.close() f.close()
img = Image.new('RGB', (1000, 32))
current_weather = json.load(open('csv/current_weather.json', 'r'))
small_font = ImageFont.load("./fonts/5x7.pil")
extra_small_font = ImageFont.load("./fonts/4x6.pil")
large_font = ImageFont.load("./fonts/10x20.pil")
location_img = self.textImage(location, extra_small_font, r = 255, g = 255, b = 0) imgs = []
for location in locations:
img = Image.new('RGB', (1000, 32))
main = current_weather['main_weather']
if main == 'Clouds':
main = current_weather['description']
weather_ids = {'Clear': '01', 'few clouds': '02', 'scattered clouds': '03', 'broken clouds':'04', 'overcast clouds':'04', 'Drizzle':'09',
'Rain':'10', 'Thunderstorm':'11', 'Snow':'13', 'Mist': '50', 'Smoke': '50', 'Haze': '50', 'Dust': '50', 'Fog': '50',
'Sand': '50', 'Ash': '50', 'Squall': '50', 'Tornado': '50'}
weather_dir = './logos/weather_icons'
weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png')
temp_img = self.textImage(str("{0:.0f}".format(current_weather['temp'])), large_font)
deg_img = self.textImage('o', small_font)
min_img = self.textImage( "{0:.0f}".format(current_weather['min_temp']), small_font, r=0, g=0, b=255)
max_img = self.textImage( "{0:.0f}".format(current_weather['max_temp']), small_font, r=255, g=0, b=0)
main = current_weather['main_weather']
main_img = self.textImage(main, small_font)
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
months =['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
month = months[int(datetime.now().strftime('%m'))]
date = str(int(datetime.now().strftime('%d')))
weekday = weekdays[datetime.today().weekday()]
date_img = self.textImage(month + ' ' + date + ',' + weekday, extra_small_font)
rain_img = Image.open(weather_dir + '/rain-chance.png')
rtext_img = self.textImage(str(int(current_weather['rain_chance']*100)) + '%', extra_small_font)
hum_img = Image.open(weather_dir + '/humidity.png')
htext_img = self.textImage(str(current_weather['humidity']) + '%', extra_small_font)
uv_img = Image.open(weather_dir + '/uv.png')
utext_img = self.textImage(str(current_weather['uv']) , extra_small_font)
wind_img = Image.open(weather_dir + '/wind.png')
wtext_img = self.textImage(str(current_weather['wind_speed']) + 'm/s', extra_small_font)
uv_img = Image.open(weather_dir + '/uv.png')
utext_img = self.textImage(str(current_weather['uv']) , small_font)
cloud_img = Image.open(weather_dir + '/clouds.png')
ctext_img = self.textImage(str(current_weather['clouds']) + '%', small_font)
wind_img = Image.open(weather_dir + '/wind.png')
wtext_img = self.textImage("{0:.0f}".format(current_weather['wind_speed']) + 'm/s', small_font)
wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']), small_font)
vis_img = Image.open(weather_dir + '/visibility.png')
vtext_img = self.textImage(str(current_weather['visibility']/1000) + 'km', small_font)
img.paste(location_img, (0,0))
img.paste(weather_img, (0,12))
img.paste(temp_img, (30,9))
img.paste(deg_img, (50, 8))
img.paste(min_img, (55, 10))
img.paste(main_img, (30, 26))
img.paste(max_img, (55, 19))
img.paste(date_img, (location_img.size[0], 1))
img.paste(rain_img, (90,0))
img.paste(rtext_img, (103, 1))
img.paste(hum_img, (117, 0))
img.paste(htext_img, (128, 1))
img.paste(uv_img, ( 143, 0))
img.paste(utext_img, (156, 1))
img.paste(cloud_img, (169,0))
img.paste(ctext_img, (182, 1))
img.paste(wind_img, (205,0))
img.paste(wtext_img, (218, 1))
img.paste(wdir_img, (231, 1))
img.paste(vis_img, (243,0))
img.paste(vtext_img, (256, 1))
#img.paste(uv_img, ( 96, 0))
#img.paste(utext_img, (109, 0))
#img.paste(wind_img, (96,0))
#img.paste(wtext_img, (109,0))
daily_weather = json.load(open('csv/daily_weather.json', 'r'))
#img.paste(date_img, (70, 0))
x_offset = 70
for i in range(1,len(daily_weather)-1):
current_weather = json.load(open('csv/current_weather.json', 'r'))
weekday = weekdays[(datetime.today().weekday() + i)%7]
day_img = self.textImage( weekday, small_font) small_font = ImageFont.load("./fonts/5x7.pil")
weather = daily_weather[i] extra_small_font = ImageFont.load("./fonts/4x6.pil")
main = weather['main_weather'] large_font = ImageFont.load("./fonts/10x20.pil")
location_img = self.textImage(location, extra_small_font, r = 255, g = 255, b = 0)
main = current_weather['main_weather']
if main == 'Clouds': if main == 'Clouds':
main = weather['description'] main = current_weather['description']
weather_ids = {'Clear': '01', 'few clouds': '02', 'scattered clouds': '03', 'broken clouds':'04', 'overcast clouds':'04', 'Drizzle':'09',
'Rain':'10', 'Thunderstorm':'11', 'Snow':'13', 'Mist': '50', 'Smoke': '50', 'Haze': '50', 'Dust': '50', 'Fog': '50',
'Sand': '50', 'Ash': '50', 'Squall': '50', 'Tornado': '50'}
weather_img = Image.open(weather_dir + '/small_icons/' + weather_ids[main] + '.png') weather_dir = './logos/weather_icons'
min_img = self.textImage( "{0:.0f}".format(weather['min_temp']), small_font, r=0, g=0, b=255)
weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png')
max_img = self.textImage( "{0:.0f}".format(weather['max_temp']), small_font, r=255, g=0, b=0) temp_img = self.textImage(str("{0:.0f}".format(current_weather['temp'])), large_font)
img.paste(day_img, (x_offset +5, 9))
img.paste(weather_img, (x_offset +5, 16))
img.paste(min_img, (x_offset + 25, 10))
img.paste(max_img, (x_offset + 25, 20))
x_offset += 40 deg_img = self.textImage('o', small_font)
img1 = img.crop((0,0,x_offset ,32)) min_img = self.textImage( "{0:.0f}".format(current_weather['min_temp']), small_font, r=0, g=0, b=255)
max_img = self.textImage( "{0:.0f}".format(current_weather['max_temp']), small_font, r=255, g=0, b=0)
main = current_weather['main_weather']
main_img = self.textImage(main, small_font)
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
months =['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
month = months[int(datetime.now().strftime('%m'))]
date = str(int(datetime.now().strftime('%d')))
weekday = weekdays[datetime.today().weekday()]
date_img = self.textImage(month + ' ' + date + ',' + weekday, extra_small_font)
rain_img = Image.open(weather_dir + '/rain-chance.png')
rtext_img = self.textImage(str(int(current_weather['rain_chance']*100)) + '%', extra_small_font)
hum_img = Image.open(weather_dir + '/humidity.png')
htext_img = self.textImage(str(current_weather['humidity']) + '%', extra_small_font)
uv_img = Image.open(weather_dir + '/uv.png')
utext_img = self.textImage(str(current_weather['uv']) , extra_small_font)
wind_img = Image.open(weather_dir + '/wind.png')
# add the image text wtext_img = self.textImage(str(current_weather['wind_speed']) + 'm/s', extra_small_font)
uv_img = Image.open(weather_dir + '/uv.png')
utext_img = self.textImage(str(current_weather['uv']) , small_font)
cloud_img = Image.open(weather_dir + '/clouds.png')
ctext_img = self.textImage(str(current_weather['clouds']) + '%', small_font)
wind_img = Image.open(weather_dir + '/wind.png')
wtext_img = self.textImage("{0:.0f}".format(current_weather['wind_speed']) + 'm/s', small_font)
wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']), small_font)
vis_img = Image.open(weather_dir + '/visibility.png')
vtext_img = self.textImage(str(current_weather['visibility']/1000) + 'km', small_font)
img.paste(location_img, (0,0))
img.paste(weather_img, (0,12))
img.paste(temp_img, (30,9))
img.paste(deg_img, (50, 8))
img.paste(min_img, (55, 10))
img.paste(main_img, (30, 26))
img.paste(max_img, (55, 19))
img.paste(date_img, (location_img.size[0], 1))
img.paste(rain_img, (90,0))
img.paste(rtext_img, (103, 1))
img.paste(hum_img, (117, 0))
img.paste(htext_img, (128, 1))
img.paste(uv_img, ( 143, 0))
img.paste(utext_img, (156, 1))
img.paste(cloud_img, (169,0))
img.paste(ctext_img, (182, 1))
img.paste(wind_img, (205,0))
img.paste(wtext_img, (218, 1))
img.paste(wdir_img, (231, 1))
img.paste(vis_img, (243,0))
img.paste(vtext_img, (256, 1))
#img.paste(uv_img, ( 96, 0))
#img.paste(utext_img, (109, 0))
#img.paste(wind_img, (96,0))
#img.paste(wtext_img, (109,0))
daily_weather = json.load(open('csv/daily_weather.json', 'r'))
#img.paste(date_img, (70, 0))
x_offset = 70
for i in range(1,len(daily_weather)-1):
weekday = weekdays[(datetime.today().weekday() + i)%7]
day_img = self.textImage( weekday, small_font)
weather = daily_weather[i]
main = weather['main_weather']
if main == 'Clouds':
main = weather['description']
weather_img = Image.open(weather_dir + '/small_icons/' + weather_ids[main] + '.png')
min_img = self.textImage( "{0:.0f}".format(weather['min_temp']), small_font, r=0, g=0, b=255)
max_img = self.textImage( "{0:.0f}".format(weather['max_temp']), small_font, r=255, g=0, b=0)
img.paste(day_img, (x_offset +5, 9))
img.paste(weather_img, (x_offset +5, 16))
img.paste(min_img, (x_offset + 25, 10))
img.paste(max_img, (x_offset + 25, 20))
x_offset += 40
img1 = img.crop((0,0,x_offset ,32))
imgs.append(img1)
# add the image text
font = ImageFont.load("./fonts/texgyre-27.pil") font = ImageFont.load("./fonts/texgyre-27.pil")
title_img = self.textImage('WEATHER', font, matrix_height = True) title_img = self.textImage('WEATHER', font, matrix_height = True)
return self.stitchImage([title_img, img1]) return self.stitchImage([title_img] + imgs)
#Retrieve symbols and stock info from the csv file #Retrieve symbols and stock info from the csv file
@ -1548,7 +1552,7 @@ if __name__ == '__main__':
stock_ticker = StockTicker() stock_ticker = StockTicker()
#stock_ticker.process_msg('P') #stock_ticker.process_msg('P')
stock_ticker.process_msg('P') stock_ticker.process_msg('W')