From de3ed3e01b09843cbf909bb7191589615f36953a Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 14 Dec 2021 15:38:09 +0000 Subject: [PATCH] bug fixes and slight layout changes --- api_caller.py | 97 ++- log.txt | 128 +++ server.py | 15 +- stockTicker.py | 1772 +++++++++++++++++++++++------------------- templates/index.html | 8 +- 5 files changed, 1187 insertions(+), 833 deletions(-) diff --git a/api_caller.py b/api_caller.py index 25520b9..f6c3ed3 100755 --- a/api_caller.py +++ b/api_caller.py @@ -85,38 +85,48 @@ def updateStocks(): f.close() stock_info = all_stocks_settings['symbols'] symbols = list(stock_info.keys()) - + print(symbols) try: - + valid_symbols = [] current_prices = [] opening_prices = [] for symbol in symbols: - method = 'GET' - host = 'https://cloud.iexapis.com/stable' - - intradayEndpoint = '/stock/'+ symbol+ '/intraday-prices' - querystring = '?chartIEXOnly=true&token='+iexAPIkey + + try: + method = 'GET' + host = 'https://cloud.iexapis.com/stable' + + intradayEndpoint = '/stock/'+ symbol+ '/intraday-prices' + querystring = '?chartIEXOnly=true&token='+iexAPIkey - intraday_request_url = host + intradayEndpoint + querystring - - - intraday_response = requests.get(intraday_request_url) - - - for i in range(len(intraday_response.json())): - opn = intraday_response.json()[i]['open'] - if opn is not None: - break - for i in range(len(intraday_response.json())-1, 0, -1): + intraday_request_url = host + intradayEndpoint + querystring - current = intraday_response.json()[i]['close'] - if current is not None: - break + + intraday_response = requests.get(intraday_request_url) + + + for i in range(len(intraday_response.json())): + opn = intraday_response.json()[i]['open'] + if opn is not None: + break + for i in range(len(intraday_response.json())-1, 0, -1): - opening_prices.append(opn) - current_prices.append(current) + current = intraday_response.json()[i]['close'] + if current is not None: + break + valid_symbols.append(symbol) + opening_prices.append(opn) + current_prices.append(current) + 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]))) stock_info = {} @@ -124,8 +134,8 @@ def updateStocks(): - for i, symbol in enumerate(symbols): - + for i, symbol in enumerate(valid_symbols): + print(symbol) stock_info[symbol] = {'current': current_prices[i], 'opening': opening_prices[i]} @@ -337,8 +347,9 @@ def updateWeather(): all_locations = list(set(current_locations + daily_locations)) - current_weathers = {} - daily_weathers = {} + current_list = [] + daily_list = [] + for location in all_locations: @@ -368,7 +379,7 @@ def updateWeather(): if location in current_locations: - current_weathers[location] = current_weather + current_list.append(current_weather) daily_weather = [] daily = r.json()['daily'] @@ -393,10 +404,17 @@ def updateWeather(): daily_weather[0]['visibility'] = current_weather['visibility'] if location in daily_locations: - daily_weathers[location] = daily_weather - + daily_list.append(daily_weather) + current_weathers = {} + daily_weathers = {} + for i,loc in enumerate(current_locations): + current_weathers[loc] = current_list[i] + + for i,loc in enumerate(daily_locations): + daily_weathers[loc] = daily_list[i] + all_current_settings['locations'] = current_weathers all_daily_settings['locations'] = daily_weathers @@ -608,10 +626,18 @@ def checkStocks(last_update, update_frequency): return updated - + +def updateAll(): + updateStocks() + updateCrypto() + updateForex() + updateNews() + updateSports() + updateWeather() + if __name__ == '__main__': - logf = open("log.txt", "w") + logf = open("log.txt", "a") t = time.time() @@ -620,6 +646,8 @@ if __name__ == '__main__': + + newsapi = NewsApiClient(api_key='cf08652bd17647b89aaf469a1a8198a9') @@ -651,9 +679,12 @@ if __name__ == '__main__': t = time.time() - + updateWeather() + sys.exit() try: while True: + if msg == 'A': + updateAll() NY_time = datetime.now(NY_zone).replace(tzinfo=None) diff --git a/log.txt b/log.txt index e69de29..db43b1d 100755 --- a/log.txt +++ b/log.txt @@ -0,0 +1,128 @@ + +list indices must be integers or slices, not str. file: stockTicker.py. line: 2200. type: + Traceback (most recent call last): + File "stockTicker.py", line 2200, in getDailyWeatherImage + main = daily_weather['description'] +TypeError: list indices must be integers or slices, not str +list indices must be integers or slices, not str. file: stockTicker.py. line: 2200. type: + Traceback (most recent call last): + File "stockTicker.py", line 2200, in getDailyWeatherImage + main = daily_weather['description'] +TypeError: list indices must be integers or slices, not str +list indices must be integers or slices, not str. file: stockTicker.py. line: 2200. type: + Traceback (most recent call last): + File "stockTicker.py", line 2200, in getDailyWeatherImage + main = daily_weather['description'] +TypeError: list indices must be integers or slices, not str +list indices must be integers or slices, not str. file: stockTicker.py. line: 2200. type: + Traceback (most recent call last): + File "stockTicker.py", line 2200, in getDailyWeatherImage + main = daily_weather['description'] +TypeError: list indices must be integers or slices, not str +HTTPConnectionPool(host='api.geonames.org', port=80): Max retries exceeded with url: /searchJSON?q=London&username=fintic&maxRows=1 (Caused by ConnectTimeoutError(, 'Connection to api.geonames.org timed out. (connect timeout=1)')). file: api_caller.py. line: 356. type: + Traceback (most recent call last): + File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 159, in _new_conn + (self._dns_host, self.port), self.timeout, **extra_kw) + File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 80, in create_connection + raise err + File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 70, in create_connection + sock.connect(sa) +socket.timeout: timed out + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 600, in urlopen + chunked=chunked) + File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 354, in _make_request + conn.request(method, url, **httplib_request_kw) + File "/usr/lib/python3.7/http/client.py", line 1260, in request + self._send_request(method, url, body, headers, encode_chunked) + File "/usr/lib/python3.7/http/client.py", line 1306, in _send_request + self.endheaders(body, encode_chunked=encode_chunked) + File "/usr/lib/python3.7/http/client.py", line 1255, in endheaders + self._send_output(message_body, encode_chunked=encode_chunked) + File "/usr/lib/python3.7/http/client.py", line 1030, in _send_output + self.send(msg) + File "/usr/lib/python3.7/http/client.py", line 970, in send + self.connect() + File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 181, in connect + conn = self._new_conn() + File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 164, in _new_conn + (self.host, self.timeout)) +urllib3.exceptions.ConnectTimeoutError: (, 'Connection to api.geonames.org timed out. (connect timeout=1)') + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "/home/pi/.local/lib/python3.7/site-packages/requests/adapters.py", line 449, in send + timeout=timeout + File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 667, in urlopen + **response_kw) + File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 667, in urlopen + **response_kw) + File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 638, in urlopen + _stacktrace=sys.exc_info()[2]) + File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 398, in increment + raise MaxRetryError(_pool, url, error or ResponseError(cause)) +urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='api.geonames.org', port=80): Max retries exceeded with url: /searchJSON?q=London&username=fintic&maxRows=1 (Caused by ConnectTimeoutError(, 'Connection to api.geonames.org timed out. (connect timeout=1)')) + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "/home/pi/.local/lib/python3.7/site-packages/geopy/adapters.py", line 448, in _request + resp = self.session.get(url, timeout=timeout, headers=headers) + File "/home/pi/.local/lib/python3.7/site-packages/requests/sessions.py", line 555, in get + return self.request('GET', url, **kwargs) + File "/home/pi/.local/lib/python3.7/site-packages/requests/sessions.py", line 542, in request + resp = self.send(prep, **send_kwargs) + File "/home/pi/.local/lib/python3.7/site-packages/requests/sessions.py", line 655, in send + r = adapter.send(request, **kwargs) + File "/home/pi/.local/lib/python3.7/site-packages/requests/adapters.py", line 504, in send + raise ConnectTimeout(e, request=request) +requests.exceptions.ConnectTimeout: HTTPConnectionPool(host='api.geonames.org', port=80): Max retries exceeded with url: /searchJSON?q=London&username=fintic&maxRows=1 (Caused by ConnectTimeoutError(, 'Connection to api.geonames.org timed out. (connect timeout=1)')) + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "api_caller.py", line 356, in updateWeather + loc = gn.geocode(location) + File "/home/pi/.local/lib/python3.7/site-packages/geopy/geocoders/geonames.py", line 157, in geocode + return self._call_geocoder(url, callback, timeout=timeout) + File "/home/pi/.local/lib/python3.7/site-packages/geopy/geocoders/base.py", line 368, in _call_geocoder + result = self.adapter.get_json(url, timeout=timeout, headers=req_headers) + File "/home/pi/.local/lib/python3.7/site-packages/geopy/adapters.py", line 438, in get_json + resp = self._request(url, timeout=timeout, headers=headers) + File "/home/pi/.local/lib/python3.7/site-packages/geopy/adapters.py", line 460, in _request + raise GeocoderUnavailable(message) +geopy.exc.GeocoderUnavailable: HTTPConnectionPool(host='api.geonames.org', port=80): Max retries exceeded with url: /searchJSON?q=London&username=fintic&maxRows=1 (Caused by ConnectTimeoutError(, 'Connection to api.geonames.org timed out. (connect timeout=1)')) +local variable 'temp' referenced before assignment. file: stockTicker.py. line: 2239. type: + Traceback (most recent call last): + File "stockTicker.py", line 2239, in getDailyWeatherImage + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) +UnboundLocalError: local variable 'temp' referenced before assignment +local variable 'temp' referenced before assignment. file: stockTicker.py. line: 2239. type: + Traceback (most recent call last): + File "stockTicker.py", line 2239, in getDailyWeatherImage + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) +UnboundLocalError: local variable 'temp' referenced before assignment +local variable 'temp' referenced before assignment. file: stockTicker.py. line: 2239. type: + Traceback (most recent call last): + File "stockTicker.py", line 2239, in getDailyWeatherImage + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) +UnboundLocalError: local variable 'temp' referenced before assignment +local variable 'temp' referenced before assignment. file: stockTicker.py. line: 2239. type: + Traceback (most recent call last): + File "stockTicker.py", line 2239, in getDailyWeatherImage + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) +UnboundLocalError: local variable 'temp' referenced before assignment +local variable 'temp' referenced before assignment. file: stockTicker.py. line: 2239. type: + Traceback (most recent call last): + File "stockTicker.py", line 2239, in getDailyWeatherImage + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) +UnboundLocalError: local variable 'temp' referenced before assignment +local variable 'temp' referenced before assignment. file: stockTicker.py. line: 2239. type: + Traceback (most recent call last): + File "stockTicker.py", line 2239, in getDailyWeatherImage + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) +UnboundLocalError: local variable 'temp' referenced before assignment diff --git a/server.py b/server.py index 4f6cec5..86e5ceb 100755 --- a/server.py +++ b/server.py @@ -22,6 +22,7 @@ import copy #stock_ticker = StockTicker() #print('API CALLER NOT STARTED') api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 api_caller.py") +api_caller.sendline('A') displaying_screensaver = False screensaver_p = None professional = json.load(open('csv/display_settings.json', 'r'))[0] == "Professional" @@ -44,7 +45,7 @@ def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def process_file(path, filename): - default_csv = csv.writer(open('csv/tickers.csv', 'w')) + default_csv = csv.writer(open('csv/tickers.csv', 'w+')) new_csv = csv.reader(open((path), 'r')) for row in new_csv: @@ -187,6 +188,7 @@ def stop(): @app.route("/update", methods=['PUT','POST']) def update(): os.system("./update.sh") + os.system("sudo reboot now") return index() @app.route("/display_format", methods = ['PUT', 'POST', 'GET']) @@ -392,11 +394,7 @@ def combine_dict(current_settings, input_symbols, current_key): new_settings[current_key][IS] = [] else: new_settings[current_key][IS] = current_settings[current_key][IS] - - # remove stocks not in settings - for CS in current_symbols: - if CS not in input_symbols: - del new_settings[current_key][CS] + return new_settings @@ -448,11 +446,14 @@ def save_weather_settings(input_settings): if input_settings['feature'] == 'Daily Forecast': current_settings['current_weather'] = input_settings['current_weather'] + ''' locations = {} for key in input_settings['locations']: locations[key] = [] current_settings['locations'] = locations - + ''' + + current_settings = combine_dict(current_settings, input_settings['locations'], 'locations') json.dump(current_settings, open('csv/' + filename, 'w+')) api_caller.sendline('w') diff --git a/stockTicker.py b/stockTicker.py index d1ddfb3..0de4ad3 100755 --- a/stockTicker.py +++ b/stockTicker.py @@ -830,13 +830,13 @@ class StockTicker(): if point_change: - d.text(((text_width_current+29), 16), point_change, fill=self.greenORred, font=font) + d.text(((w1+29), 16), point_change, fill=self.greenORred, font=font) if percent_change: - d.text(((text_width_current+29), 14 - text_height), percent_change, fill=self.greenORred, font=font) + d.text(((w2+7), 14 - text_height), percent_change, fill=self.greenORred, font=font) if point_change or percent_change: - img.paste(ARROW, ((text_width_current + 9),18)) + img.paste(ARROW, ((w1+ 9),18)) text_width_change=0 @@ -913,42 +913,53 @@ class StockTicker(): coin_bases = list(coin_info.keys()) for i, cb in enumerate(coin_bases): - ticker, base = cb.split(',') - current = float(coin_info[cb]["current"]) - change = float(coin_info[cb]["24hr_change"]) - - - - - percent_change = '%.2f' % abs(change) +'%' - - - point_change = '%.2f' % abs(change/100 * current) - - arrow, change = self.getArrow(change) - current = '%.2f' % current - if not all_crypto_settings['percent']: - percent_change = False - if not all_crypto_settings['point']: - point_change = False - - midFrame = self.textToImage(ticker + '(' + base + ')', current, arrow, percent_change, point_change) #IMAGE THE TEXT - - if all_crypto_settings['logos']: - try: - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'crypto') - - logo = Image.open(os.path.join(logos_path, ticker + '.png')) - stitchedStock = self.stitchImage([logo,midFrame]) - except: - - stitchedStock = midFrame - else: - stitchedStock = midFrame + try: + ticker, base = cb.split(',') + current = float(coin_info[cb]["current"]) + change = float(coin_info[cb]["24hr_change"]) - image_list.append(stitchedStock) - - image_list.append(self.blank) + + + + percent_change = '%.2f' % abs(change) +'%' + + + point_change = '%.2f' % abs(change/100 * current) + + arrow, change = self.getArrow(change) + current = '%.2f' % current + if not all_crypto_settings['percent']: + percent_change = False + if not all_crypto_settings['point']: + point_change = False + + midFrame = self.textToImage(ticker + '(' + base + ')', current, arrow, percent_change, point_change) #IMAGE THE TEXT + + if all_crypto_settings['logos']: + try: + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'crypto') + + logo = self.openImage(os.path.join(logos_path, ticker + '.png')) + stitchedStock = self.stitchImage([logo,midFrame]) + except: + + stitchedStock = midFrame + else: + stitchedStock = midFrame + + image_list.append(stitchedStock) + + image_list.append(self.blank) + + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) + finalDisplayImage = self.stitchImage(image_list) @@ -979,39 +990,48 @@ class StockTicker(): for i, cb in enumerate(coin_bases): - - ticker, base = cb.split(',') - current = coin_info[cb]["current"] - change = coin_info[cb]["24hr_change"] - arrow, change = self.getArrow(change, professional=True) - - if all_crypto_settings["point"]: - # convert percent to points - change = change/100 * current - change = '%.2f' % change - else: - - change = '%.2f' % change +'%' - - current = '%.2f' % current - midFrame = self.textToImageProf(ticker + '(' + base + ')', current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT - if all_crypto_settings['logos']: - try: - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'crypto') - logo = Image.open(os.path.join(logos_path, ticker + '.png')) - - w,h = logo.size - logo=logo.resize((int(w/2), int(h/2))) - stitchedStock = self.stitchImage([logo,midFrame]) - except: - + try: + ticker, base = cb.split(',') + current = coin_info[cb]["current"] + change = coin_info[cb]["24hr_change"] + arrow, change = self.getArrow(change, professional=True) + + if all_crypto_settings["point"]: + # convert percent to points + change = change/100 * current + change = '%.2f' % change + else: + + change = '%.2f' % change +'%' + + current = '%.2f' % current + midFrame = self.textToImageProf(ticker + '(' + base + ')', current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT + if all_crypto_settings['logos']: + try: + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'crypto') + logo = self.openImage(os.path.join(logos_path, ticker + '.png')) + + w,h = logo.size + logo=logo.resize((int(w/2), int(h/2))) + stitchedStock = self.stitchImage([logo,midFrame]) + except: + + stitchedStock = midFrame + else: stitchedStock = midFrame - else: - stitchedStock = midFrame - image_list.append(stitchedStock) - - image_list.append(self.blank) - + image_list.append(stitchedStock) + + image_list.append(self.blank) + + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) + finalDisplayImage = self.stitchImage(image_list) self.blank = Image.new('RGB', (10, 32)) return finalDisplayImage @@ -1035,52 +1055,64 @@ class StockTicker(): symbol_bases = list(forex_settings.keys()) for i, sb in enumerate(symbol_bases): - symbol, base = sb.split(',') - - current = float(forex_settings[sb]['current']) - change = float(forex_settings[sb]['24hr_change']) - - percent_change = '%.2f' % abs(change) +'%' - - - point_change = '%.2f' % abs(change/100 * current) - - if not all_forex_settings['percent']: - percent_change = False - if not all_forex_settings['point']: - point_change = False - - arrow, change = self.getArrow(change) - - - - current = '%.3f' % current - + try: + symbol, base = sb.split(',') + + current = float(forex_settings[sb]['current']) + change = float(forex_settings[sb]['24hr_change']) + + percent_change = '%.2f' % abs(change) +'%' - midFrame = self.textToImage(symbol+ '(' + base + ')', current, arrow, percent_change, point_change) #IMAGE THE TEXT - - - if all_forex_settings['logos']: - try: - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'currencies') - - logo = Image.open(os.path.join(logos_path, symbol.lower() + '.png')) - bse = Image.open(os.path.join(logos_path, base.lower() + '.png')) - - new_im = Image.new('RGB', (32, 32)) - - - new_im.paste(bse, (0,10), bse.convert('RGBA')) - new_im.paste(logo, (10,0), logo.convert('RGBA')) - - stitchedStock = self.stitchImage([new_im, midFrame]) - image_list.append(new_im) - - except Exception as e: - print(e) - image_list.append(midFrame) - image_list.append(self.blank) + point_change = '%.2f' % abs(change/100 * current) + + if not all_forex_settings['percent']: + percent_change = False + if not all_forex_settings['point']: + point_change = False + + arrow, change = self.getArrow(change) + + + + current = '%.3f' % current + + + midFrame = self.textToImage(symbol+ '(' + base + ')', current, arrow, percent_change, point_change) #IMAGE THE TEXT + + + if all_forex_settings['logos']: + try: + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'currencies') + + logo = Image.open(os.path.join(logos_path, symbol.lower() + '.png')) + bse = Image.open(os.path.join(logos_path, base.lower() + '.png')) + + new_im = Image.new('RGB', (32, 32)) + + + new_im.paste(bse, (0,10), bse.convert('RGBA')) + new_im.paste(logo, (10,0), logo.convert('RGBA')) + + stitchedStock = self.stitchImage([new_im, midFrame]) + image_list.append(new_im) + + except Exception as e: + print(e) + + image_list.append(midFrame) + image_list.append(self.blank) + + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) + + finalDisplayImage = self.stitchImage(image_list) return finalDisplayImage @@ -1106,52 +1138,63 @@ class StockTicker(): for i, sb in enumerate(symbol_bases): - symbol, base = sb.split(',') - - current = forex_settings[sb]['current'] - change = forex_settings[sb]['24hr_change'] - - + try: + symbol, base = sb.split(',') + + current = forex_settings[sb]['current'] + change = forex_settings[sb]['24hr_change'] - arrow, change = self.getArrow(change, professional = True) - - - if all_forex_settings["percent"]: - # convert percent to points - change = change/current * 100 + + + arrow, change = self.getArrow(change, professional = True) - change = '%.2f' % change + '%' - else: - change = '%.6f' % change - current = '%.3f' % current - midFrame = self.textToImageProf(symbol + '(' + base + ')', current, change, arrow, font = ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT - - if all_forex_settings['logos']: - try: - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'currencies') - - logo = Image.open(os.path.join(logos_path, symbol.lower() + '.png')) - bse = Image.open(os.path.join(logos_path, base.lower() + '.png')) + + if all_forex_settings["percent"]: + # convert percent to points + change = change/current * 100 - new_im = Image.new('RGB', (32, 32)) - - - new_im.paste(bse, (0,10), bse.convert('RGBA')) - new_im.paste(logo, (10,0), logo.convert('RGBA')) - width, height = new_im.size + change = '%.2f' % change + '%' + else: + change = '%.6f' % change + current = '%.3f' % current + midFrame = self.textToImageProf(symbol + '(' + base + ')', current, change, arrow, font = ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT + + if all_forex_settings['logos']: + try: + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'currencies') + + logo = Image.open(os.path.join(logos_path, symbol.lower() + '.png')) + bse = Image.open(os.path.join(logos_path, base.lower() + '.png')) - new_im = new_im.resize((int(width/2), int(height/2))) + new_im = Image.new('RGB', (32, 32)) + + + new_im.paste(bse, (0,10), bse.convert('RGBA')) + new_im.paste(logo, (10,0), logo.convert('RGBA')) + width, height = new_im.size + + new_im = new_im.resize((int(width/2), int(height/2))) + + stitchedStock = self.stitchImage([new_im, midFrame]) + image_list.append(new_im) - stitchedStock = self.stitchImage([new_im, midFrame]) - image_list.append(new_im) - - except Exception as e: - print(e) + except Exception as e: + print(e) + + image_list.append(midFrame) - image_list.append(midFrame) - - image_list.append(self.blank) + image_list.append(self.blank) + + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) + finalDisplayImage = self.stitchImage(image_list) self.blank = Image.new('RGB', (10, 32)) @@ -1159,8 +1202,6 @@ class StockTicker(): def getStockImage(self): - - f = open('csv/stocks_settings.json', 'r') all_stocks_settings = json.load(f) f.close() @@ -1180,48 +1221,57 @@ class StockTicker(): for i, symbol in enumerate(symbols): - - info = stock_info[symbol] - - change = float(info['current'])-float(info['opening']) #TEXT - ticker = symbol #TEXT - - percent_change = '%.2f' % abs(float(change)/float(info['current'])*100) + '%' - point_change = '%.2f' % abs(change) - arrow, change = self.getArrow(change) - - print(percent_change, point_change) - - current = '%.2f' % float(info['current']) #TEXT - - - - if not all_stocks_settings['percent']: - percent_change = False - if not all_stocks_settings['point']: - point_change = False - - - - - midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT - - if all_stocks_settings['logos']: - try: - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'stocks') - - logo = Image.open(os.path.join(logos_path, ticker + '.png')) - stitchedStock = self.stitchImage([logo,midFrame]) - except: - + try: + info = stock_info[symbol] + + change = float(info['current'])-float(info['opening']) #TEXT + ticker = symbol #TEXT + + percent_change = '%.2f' % abs(float(change)/float(info['current'])*100) + '%' + point_change = '%.2f' % abs(change) + arrow, change = self.getArrow(change) + + print(percent_change, point_change) + + current = '%.2f' % float(info['current']) #TEXT + + + + if not all_stocks_settings['percent']: + percent_change = False + if not all_stocks_settings['point']: + point_change = False + + + + + midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT + + if all_stocks_settings['logos']: + try: + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'stocks') + + logo = self.openImage(os.path.join(logos_path, ticker + '.png')) + stitchedStock = self.stitchImage([logo,midFrame]) + except Exception as e: + print(str(e)) + stitchedStock = midFrame + else: stitchedStock = midFrame - else: - stitchedStock = midFrame + + image_list.append(stitchedStock) + + + image_list.append(self.blank) + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) - image_list.append(stitchedStock) - - - image_list.append(self.blank) finalDisplayImage = self.stitchImage(image_list) @@ -1250,53 +1300,62 @@ class StockTicker(): for i, symbol in enumerate(symbols): + try: + info = stock_info[symbol] - info = stock_info[symbol] - - change = float(info['current'])-float(info['opening']) #TEXT - ticker = symbol #TEXT - - - - arrow, change = self.getArrow(change, professional=True) - - if all_stocks_settings["percent"]: - # convert percent to points - change = change/float(info['current'])* 100 + change = float(info['current'])-float(info['opening']) #TEXT + ticker = symbol #TEXT - change = '%.2f' % change + '%' - else: - change = '%.2f' % change - current = '%.2f' % float(info['current']) #TEXT - midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT - - if all_stocks_settings['logos']: - try: - try: #load the tiny logo - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'tiny_stocks') - - logo = Image.open(os.path.join(logos_path, ticker + '.png')) - - except: # load the big logo and scale it - - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'stocks') - - logo = Image.open(os.path.join(logos_path, ticker + '.png')) - # half the size of the logo - width, height = logo.size - - logo = logo.resize((int(width/2), int(height/2))) - stitchedStock = self.stitchImage([logo,midFrame]) - except Exception as e: - + + + arrow, change = self.getArrow(change, professional=True) + + if all_stocks_settings["percent"]: + # convert percent to points + change = change/float(info['current'])* 100 + + change = '%.2f' % change + '%' + else: + change = '%.2f' % change + current = '%.2f' % float(info['current']) #TEXT + midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT + + if all_stocks_settings['logos']: + try: + try: #load the tiny logo + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'tiny_stocks') + + logo = Image.open(os.path.join(logos_path, ticker + '.png')) + + except: # load the big logo and scale it + + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'stocks') + + logo = Image.open(os.path.join(logos_path, ticker + '.png')) + # half the size of the logo + width, height = logo.size + + logo = logo.resize((int(width/2), int(height/2))) + stitchedStock = self.stitchImage([logo,midFrame]) + except Exception as e: + + stitchedStock = midFrame + else: stitchedStock = midFrame - else: - stitchedStock = midFrame + + image_list.append(stitchedStock) + + + image_list.append(self.blank) - image_list.append(stitchedStock) - - - image_list.append(self.blank) + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) finalDisplayImage = self.stitchImage(image_list) @@ -1325,49 +1384,58 @@ class StockTicker(): for i, hi in enumerate(headline_info): - headline, source, date_time = hi - date, time = date_time.split('T') - time = time[:-1] - source_date_time = source + ': ' + date + ' ' + time - - headline = headline.replace("^", ",") - headline = headline.replace("’", "'") - headline = headline.replace("‘", "'") - headline = headline.replace('“', '"') - headline = headline.replace('”', '"') - headline = headline.replace('—', '-') - headline = headline.replace('–', '-') - headline = ''.join([h for h in headline if ord(h) < 256]) - - lst = headline.rsplit('-', 1) #remove source name at end of headline - headline = lst[0] - - headline_img = self.textImage(headline, headline_font, matrix_height = True) - source_img = self.textImage(source_date_time, source_font, r=255, g=255, b=0, matrix_height = True) - try: - logo_name = sources.lower().replace(' ', '-') - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'news_logos') - - logo = Image.open(os.path.join(logos_path, logo_name + '.png')) + headline, source, date_time = hi + date, time = date_time.split('T') + time = time[:-1] + source_date_time = source + ': ' + date + ' ' + time - except Exception as e: - logo_name = 'default' - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'news_logos') - - logo = Image.open(os.path.join(logos_path, logo_name + '.png')) + headline = headline.replace("^", ",") + headline = headline.replace("’", "'") + headline = headline.replace("‘", "'") + headline = headline.replace('“', '"') + headline = headline.replace('”', '"') + headline = headline.replace('—', '-') + headline = headline.replace('–', '-') + headline = ''.join([h for h in headline if ord(h) < 256]) - + lst = headline.rsplit('-', 1) #remove source name at end of headline + headline = lst[0] + + headline_img = self.textImage(headline, headline_font, matrix_height = True) + source_img = self.textImage(source_date_time, source_font, r=255, g=255, b=0, matrix_height = True) - img = Image.new('RGB', (headline_img.size[0], 32)) - img.paste(headline_img, (2, 0)) - img.paste(source_img, (2,16)) - - img= self.stitchImage([logo,img]) - + try: + logo_name = sources.lower().replace(' ', '-') + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'news_logos') + + logo = Image.open(os.path.join(logos_path, logo_name + '.png')) + + except Exception as e: + logo_name = 'default' + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'news_logos') + + logo = Image.open(os.path.join(logos_path, logo_name + '.png')) + - image_list.append(img) - image_list.append(self.blank) + + img = Image.new('RGB', (headline_img.size[0], 32)) + img.paste(headline_img, (2, 0)) + img.paste(source_img, (2,16)) + + img= self.stitchImage([logo,img]) + + + image_list.append(img) + image_list.append(self.blank) + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) news_image = self.stitchImage(image_list) @@ -1394,55 +1462,64 @@ class StockTicker(): blank = Image.new('RGB', (0, 16)) for i, hi in enumerate(headline_info): - headline, source, date_time = hi - date, time = date_time.split('T') - time = time[:-1] - source_date_time = source + ': ' + date + ' ' + time - - headline = headline.replace("^", ",") - headline = headline.replace("’", "'") - headline = headline.replace("‘", "'") - headline = headline.replace('“', '"') - headline = headline.replace('”', '"') - headline = headline.replace('—', '-') - headline = headline.replace('–', '-') - - headline = ''.join([h for h in headline if ord(h) < 256]) - - lst = headline.rsplit('-', 1) #remove source name at end of headline - headline = lst[0] - - headline_img = self.textImage(headline, headline_font, matrix_height = True) - source_img = self.textImage(source_date_time+ ':', source_font, r=255, g=255, b=0, matrix_height = True) - - try: - logo_name = sources[i].lower().replace(' ', '-') - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'news_logos') - - logo = Image.open(os.path.join(logos_path, logo_name + '.png')) + headline, source, date_time = hi + date, time = date_time.split('T') + time = time[:-1] + source_date_time = source + ': ' + date + ' ' + time + headline = headline.replace("^", ",") + headline = headline.replace("’", "'") + headline = headline.replace("‘", "'") + headline = headline.replace('“', '"') + headline = headline.replace('”', '"') + headline = headline.replace('—', '-') + headline = headline.replace('–', '-') + + headline = ''.join([h for h in headline if ord(h) < 256]) + + lst = headline.rsplit('-', 1) #remove source name at end of headline + headline = lst[0] + + headline_img = self.textImage(headline, headline_font, matrix_height = True) + source_img = self.textImage(source_date_time+ ':', source_font, r=255, g=255, b=0, matrix_height = True) + + + try: + logo_name = sources[i].lower().replace(' ', '-') + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'news_logos') + + logo = Image.open(os.path.join(logos_path, logo_name + '.png')) + + except Exception as e: + logo_name = 'default' + logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'news_logos') + + logo = Image.open(os.path.join(logos_path, logo_name + '.png')) + + width, height = logo.size + + logo = logo.resize((int(width/2), int(height/2))) + + img = Image.new('RGB', (headline_img.size[0]+ source_img.size[0] + logo.size[0] +5, 32)) + img.paste(headline_img, (source_img.size[0]+ logo.size[0] -5, 3)) + img.paste(source_img, (2,3)) + + img= self.stitchImage([logo,img]) + + + + + image_list.append(img) + image_list.append(blank) except Exception as e: - logo_name = 'default' - logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'news_logos') - - logo = Image.open(os.path.join(logos_path, logo_name + '.png')) - - width, height = logo.size - - logo = logo.resize((int(width/2), int(height/2))) - - img = Image.new('RGB', (headline_img.size[0]+ source_img.size[0] + logo.size[0] +5, 32)) - img.paste(headline_img, (source_img.size[0]+ logo.size[0] -5, 3)) - img.paste(source_img, (2,3)) - - img= self.stitchImage([logo,img]) - - - - - image_list.append(img) - image_list.append(blank) + exc_type, exc_obj, exc_tb = sys.exc_info() + fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) news_image = self.stitchImage(image_list) return news_image @@ -1471,133 +1548,142 @@ class StockTicker(): for league in leagues: - - - x_offset = 0 - img = Image.new('RGB', (10000, 32)) - league_info = json.load(open('csv/sports/{}/{}_games.json'.format(league, time), 'r')) - - try: - league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB') - img.paste(league_logo, (x_offset,0)) - x_offset += league_logo.size[0] +self.blank.size[0] - except: - pass - - - - - small_font = ImageFont.load("./fonts/5x7.pil") - med_font = ImageFont.load("./fonts/7x14B.pil") - large_font = ImageFont.load("./fonts/9x18B.pil") - - - - sports_info = self.readSportsCSV(league) - - - - buff_size = 25 - - - - for match in league_info[-15:]: - home_team = match['home_team'] - away_team = match['away_team'] - - home_score = match['home_score'] - away_score = match['away_score'] - - date = match['date'].replace('-', '.') - - #rond = match['round'] - - - try: - - home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[home_team]['logo'])) - - except Exception as e: - home_logo = self.textImage(home_team.replace(' ', '\n'), small_font, r = 255, g = 255, b = 255) - - - try: - - away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[away_team]['logo'])) - - except Exception as e: - away_logo = self.textImage(away_team.replace(' ', '\n'), small_font, r = 255, g = 255, b = 255) - - date_timage = self.textImage(date, small_font, r = 255, g = 255, b = 255) - - img.paste(home_logo, (x_offset,0)) - - x_offset += home_logo.size[0] + 2 + x_offset = 0 + img = Image.new('RGB', (10000, 32)) + league_info = json.load(open('csv/sports/{}/{}_games.json'.format(league, time), 'r')) + + + try: + league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB') + img.paste(league_logo, (x_offset,0)) + x_offset += league_logo.size[0] +self.blank.size[0] + except: + pass + + + + + + small_font = ImageFont.load("./fonts/5x7.pil") + med_font = ImageFont.load("./fonts/7x14B.pil") + large_font = ImageFont.load("./fonts/9x18B.pil") - if time == 'future': - img.paste(date_timage, (x_offset+5, 0)) - - h_colour = mcolors.to_rgb(sports_info[home_team]['colour'].replace(' ', '')) - a_colour = mcolors.to_rgb(sports_info[away_team]['colour'].replace(' ', '')) - - - hc_timage = self.textImage(sports_info[home_team]['code'], med_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) - ac_timage = self.textImage(sports_info[away_team]['code'], med_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) - vs_timage = self.textImage('vs', med_font, r = 255, g = 255, b = 255, h_buff = 5) - - img.paste(hc_timage, (x_offset, 9)) - img.paste(vs_timage, (x_offset + hc_timage.size[0], 9)) - img.paste(ac_timage, (x_offset + hc_timage.size[0] + vs_timage.size[0], 9)) - x_offset += max( date_timage.size[0], hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0]) - else: - - score_image = self.textImage(home_score + '-' + away_score, large_font, h_buff = 5, r = 255, g = 255, b = 255) - - #vs_timage = self.textImage(sports_info[home_team]['code'] + 'vs' + sports_info[away_team]['code'], small_font, r = 255, g = 255, b = 255) - h_colour = mcolors.to_rgb(sports_info[home_team]['colour'].replace(' ', '')) - a_colour = mcolors.to_rgb(sports_info[away_team]['colour'].replace(' ', '')) + sports_info = self.readSportsCSV(league) + + + + buff_size = 25 + + + + for match in league_info[-15:]: + home_team = match['home_team'] + away_team = match['away_team'] - hc_timage = self.textImage(sports_info[home_team]['code'], small_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) - ac_timage = self.textImage(sports_info[away_team]['code'], small_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) - vs_timage = self.textImage('vs', small_font, r = 255, g = 255, b = 255) + home_score = match['home_score'] + away_score = match['away_score'] - if date_timage.size[0] > score_image.size[0]: - img.paste(date_timage, (x_offset+2, 0)) - img.paste(hc_timage, (x_offset+6, 9)) - img.paste(vs_timage, (x_offset+5 + hc_timage.size[0], 9)) - img.paste(ac_timage, (x_offset+6 + hc_timage.size[0] + vs_timage.size[0], 9)) - img.paste(score_image, (x_offset + 2 + int((date_timage.size[0] - score_image.size[0])/2), 15)) + date = match['date'].replace('-', '.') + + #rond = match['round'] + + + try: + + home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[home_team]['logo'])) + + except Exception as e: + home_logo = self.textImage(home_team.replace(' ', '\n'), small_font, r = 255, g = 255, b = 255) + + + try: + + away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[away_team]['logo'])) + + except Exception as e: + away_logo = self.textImage(away_team.replace(' ', '\n'), small_font, r = 255, g = 255, b = 255) + + + date_timage = self.textImage(date, small_font, r = 255, g = 255, b = 255) + + img.paste(home_logo, (x_offset,0)) + + x_offset += home_logo.size[0] + 2 + + + if time == 'future': + img.paste(date_timage, (x_offset+5, 0)) + + h_colour = mcolors.to_rgb(sports_info[home_team]['colour'].replace(' ', '')) + a_colour = mcolors.to_rgb(sports_info[away_team]['colour'].replace(' ', '')) + + + hc_timage = self.textImage(sports_info[home_team]['code'], med_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) + ac_timage = self.textImage(sports_info[away_team]['code'], med_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) + vs_timage = self.textImage('vs', med_font, r = 255, g = 255, b = 255, h_buff = 5) + + img.paste(hc_timage, (x_offset, 9)) + img.paste(vs_timage, (x_offset + hc_timage.size[0], 9)) + img.paste(ac_timage, (x_offset + hc_timage.size[0] + vs_timage.size[0], 9)) + x_offset += max( date_timage.size[0], hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0]) else: - img.paste(date_timage, (x_offset+1+int((score_image.size[0] - date_timage.size[0] )/2), 0)) - vs_size = hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0] - img.paste(hc_timage, (x_offset + 1 + int((score_image.size[0] - vs_size)/2), 9)) - img.paste(vs_timage, (x_offset + int((score_image.size[0] - vs_size)/2) + hc_timage.size[0], 9)) - img.paste(ac_timage, (x_offset+1 + int((score_image.size[0] - vs_size)/2) + hc_timage.size[0] + vs_timage.size[0], 9)) + score_image = self.textImage(home_score + '-' + away_score, large_font, h_buff = 5, r = 255, g = 255, b = 255) - img.paste(score_image, (x_offset+1, 15)) - - - x_offset += max( date_timage.size[0]+4, hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0]+4, 2 + int(score_image.size[0])) - - #img.paste(vs_timage, (x_offset+4, 9)) + #vs_timage = self.textImage(sports_info[home_team]['code'] + 'vs' + sports_info[away_team]['code'], small_font, r = 255, g = 255, b = 255) - #if league == 'NHL': - # - #img.paste(round_timage, (x_offset+ 7, 8)) - #x_offset += max(home_timage.size[0], away_timage.size[0], date_timage.size[0], round_timage.size[0], score_image.size[0]) + h_colour = mcolors.to_rgb(sports_info[home_team]['colour'].replace(' ', '')) + a_colour = mcolors.to_rgb(sports_info[away_team]['colour'].replace(' ', '')) + + hc_timage = self.textImage(sports_info[home_team]['code'], small_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255)) + ac_timage = self.textImage(sports_info[away_team]['code'], small_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255)) + vs_timage = self.textImage('vs', small_font, r = 255, g = 255, b = 255) + + if date_timage.size[0] > score_image.size[0]: + img.paste(date_timage, (x_offset+2, 0)) + img.paste(hc_timage, (x_offset+6, 9)) + img.paste(vs_timage, (x_offset+5 + hc_timage.size[0], 9)) + img.paste(ac_timage, (x_offset+6 + hc_timage.size[0] + vs_timage.size[0], 9)) + img.paste(score_image, (x_offset + 2 + int((date_timage.size[0] - score_image.size[0])/2), 15)) + else: + + img.paste(date_timage, (x_offset+1+int((score_image.size[0] - date_timage.size[0] )/2), 0)) + vs_size = hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0] + img.paste(hc_timage, (x_offset + 1 + int((score_image.size[0] - vs_size)/2), 9)) + img.paste(vs_timage, (x_offset + int((score_image.size[0] - vs_size)/2) + hc_timage.size[0], 9)) + img.paste(ac_timage, (x_offset+1 + int((score_image.size[0] - vs_size)/2) + hc_timage.size[0] + vs_timage.size[0], 9)) + + img.paste(score_image, (x_offset+1, 15)) + + + x_offset += max( date_timage.size[0]+4, hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0]+4, 2 + int(score_image.size[0])) + + #img.paste(vs_timage, (x_offset+4, 9)) + + #if league == 'NHL': + # + #img.paste(round_timage, (x_offset+ 7, 8)) + #x_offset += max(home_timage.size[0], away_timage.size[0], date_timage.size[0], round_timage.size[0], score_image.size[0]) - img.paste(away_logo, (x_offset,0)) - - x_offset += away_logo.size[0] - x_offset += buff_size - img = img.crop((0,0,x_offset ,32)) - imgs.append(img) + img.paste(away_logo, (x_offset,0)) + + x_offset += away_logo.size[0] + x_offset += buff_size + img = img.crop((0,0,x_offset ,32)) + imgs.append(img) + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) @@ -1620,66 +1706,74 @@ class StockTicker(): imgs = [] for league in leagues: - - x_offset = 0 - - img = Image.new('RGB', (10000, 32)) - - - league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB') - img.paste(league_logo, (x_offset,0)) - x_offset += league_logo.size[0] +self.blank.size[0] - + try: + x_offset = 0 + + img = Image.new('RGB', (10000, 32)) - team_info = leagues_info[league] + league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB') + img.paste(league_logo, (x_offset,0)) + x_offset += league_logo.size[0] +self.blank.size[0] - small_font = ImageFont.load("./fonts/5x7.pil") - med_font = ImageFont.load("./fonts/8x13B.pil") - large_font = ImageFont.load("./fonts/10x20.pil") - - - #if league =='NHL': # read the NHl info from the csv, prem will need this as well - sports_info = self.readSportsCSV(league) # gets colour and symbol info etc from csv - - buff_size = 20 - - for team in team_info: - - try: - - - logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[team['name']]['logo'])) - - img.paste(logo, (x_offset, 0)) - x_offset += logo.size[0] + 2 - except Exception as e: - print('no logo for:', team['name']) - name_timage = self.textImage(team['name'], med_font, r = 255, g = 255, b = 0) - wins_timage = self.textImage('Wins:' + team['wins'], small_font, r = 0, g = 255, b = 0) - loss_timage = self.textImage('Losses:' + team['loss'], small_font, r = 255, g = 0, b = 0) - draw_timage = self.textImage('Draws:' + team['draw'], small_font, r = 0, g = 0, b = 255) - points_timage = self.textImage('Points:' + team['points'], small_font, r = 255, g = 255, b = 255) - standing_timage = self.textImage('Standing:' + team['standing'], small_font, r = 255, g = 255, b = 255) + team_info = leagues_info[league] + small_font = ImageFont.load("./fonts/5x7.pil") + med_font = ImageFont.load("./fonts/8x13B.pil") + large_font = ImageFont.load("./fonts/10x20.pil") + + + #if league =='NHL': # read the NHl info from the csv, prem will need this as well + sports_info = self.readSportsCSV(league) # gets colour and symbol info etc from csv + + buff_size = 20 + + for team in team_info: + try: + + + logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[team['name']]['logo'])) - img.paste(name_timage, (x_offset, -1)) - img.paste(wins_timage, (x_offset, 12)) - img.paste(loss_timage, (x_offset, 19)) - img.paste(draw_timage, (x_offset, 26)) - - x_offset += max( wins_timage.size[0], loss_timage.size[0], draw_timage.size[0]) - img.paste(points_timage, (x_offset, 14)) - img.paste(standing_timage, (x_offset, 22)) - - x_offset += max(points_timage.size[0], standing_timage.size[0]) + buff_size - - - img = img.crop((0,0,x_offset ,32)) - imgs.append(img) + img.paste(logo, (x_offset, 0)) + x_offset += logo.size[0] + 2 + except Exception as e: + print('no logo for:', team['name']) + + + name_timage = self.textImage(team['name'], med_font, r = 255, g = 255, b = 0) + wins_timage = self.textImage('Wins:' + team['wins'], small_font, r = 0, g = 255, b = 0) + loss_timage = self.textImage('Losses:' + team['loss'], small_font, r = 255, g = 0, b = 0) + draw_timage = self.textImage('Draws:' + team['draw'], small_font, r = 0, g = 0, b = 255) + points_timage = self.textImage('Points:' + team['points'], small_font, r = 255, g = 255, b = 255) + standing_timage = self.textImage('Standing:' + team['standing'], small_font, r = 255, g = 255, b = 255) + + + + img.paste(name_timage, (x_offset, -1)) + img.paste(wins_timage, (x_offset, 12)) + img.paste(loss_timage, (x_offset, 19)) + img.paste(draw_timage, (x_offset, 26)) + + x_offset += max( wins_timage.size[0], loss_timage.size[0], draw_timage.size[0]) + img.paste(points_timage, (x_offset, 14)) + img.paste(standing_timage, (x_offset, 22)) + + x_offset += max(points_timage.size[0], standing_timage.size[0]) + buff_size + + + img = img.crop((0,0,x_offset ,32)) + imgs.append(img) + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) return self.stitchImage(imgs) @@ -1698,101 +1792,125 @@ class StockTicker(): locations = list(current_weathers.keys()) for i, location in enumerate(locations): - img = Image.new('RGB', (203, 32)) - - - current_weather = current_weathers[location] - small_font = ImageFont.load("./fonts/5x7.pil") - large_font = ImageFont.load("./fonts/10x20.pil") + try: + img = Image.new('RGB', (203, 32)) + + + current_weather = current_weathers[location] + small_font = ImageFont.load("./fonts/5x7.pil") + large_font = ImageFont.load("./fonts/10x20.pil") - location_img = self.textImage(location.upper(), small_font, r = 255, g = 255, b = 0) + location_img = self.textImage(location.upper(), small_font, r = 255, g = 255, b = 0) + + img.paste(location_img, (5,0)) + + 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') + img.paste(weather_img, (5,9)) + + + + temp = current_weather['temp'] + if all_settings['temp'] == 'kelvin': + temp = current_weather['temp'] + 273.15 + elif all_settings['temp'] == 'fahrenheit': + temp = current_weather['temp']*9/5 + 32 + + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) + img.paste(temp_img, (39,9)) + + deg_img = self.textImage('o', small_font) - img.paste(location_img, (5,0)) - - 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') - img.paste(weather_img, (5,9)) - - temp_img = self.textImage(str("{0:.0f}".format(current_weather['temp'])), large_font) - img.paste(temp_img, (39,9)) - - deg_img = self.textImage('o', small_font) - - img.paste(deg_img, (59, 8)) - - main = current_weather['main_weather'] - main_img = self.textImage(main.upper(), small_font) - img.paste(main_img, (35, 26)) - - feels_img = self.textImage('Feels like:'.upper() + 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(round(current_weather['uv'], 1)) , 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'))-1] - date = str(int(datetime.now().strftime('%d'))) - - weekday = weekdays[datetime.today().weekday()] - - date_img = self.textImage((month + ' ' + date + ',' + weekday).upper(), 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'.upper(), small_font) - img.paste(wtext_img, (168, 10)) - - wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']).upper(), small_font) - img.paste(wdir_img, (191, 10)) - - vis_img = Image.open(weather_dir + '/visibility.png') - img.paste(vis_img, (154,20)) - - vtext_img = self.textImage(str(round(current_weather['visibility']/1000, 1)) + 'km'.upper(), small_font) - img.paste(vtext_img, (168, 22)) - - imgs.append(img) - imgs.append(self.blank) + img.paste(deg_img, (59, 8)) + + main = current_weather['main_weather'] + main_img = self.textImage(main.upper(), small_font) + img.paste(main_img, (35, 26)) + + feels_img = self.textImage('Feels like:'.upper() + 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(round(current_weather['uv'], 1)) , 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'))-1] + date = str(int(datetime.now().strftime('%d'))) + + weekday = weekdays[datetime.today().weekday()] + + date_img = self.textImage((month + ' ' + date + ',' + weekday).upper(), 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)) + + + w_speed = current_weather['wind_speed']*3.6 + w_unit = 'K/H' + if all_settings["wind_speed"] == "miles/hour": + w_speed = current_weather['wind_speed']*2.236936 + w_unit = 'M/H' + + wtext_img = self.textImage("{0:.0f}".format(w_speed) + w_unit, small_font) + img.paste(wtext_img, (168, 10)) + + wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']).upper(), small_font) + img.paste(wdir_img, (195, 10)) + + vis_img = Image.open(weather_dir + '/visibility.png') + img.paste(vis_img, (154,20)) + + vtext_img = self.textImage(str(round(current_weather['visibility']/1000, 1)) + 'km'.upper(), small_font) + img.paste(vtext_img, (168, 22)) + + imgs.append(img) + imgs.append(self.blank) + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) return self.stitchImage(imgs) @@ -1819,95 +1937,120 @@ class StockTicker(): weekday = weekdays[datetime.today().weekday()] for i, location in enumerate(locations): + try: - img = Image.new('RGB', (1000, 32)) - - - current_weather = current_weathers[location] - small_font = ImageFont.load("./fonts/4x6.pil") - font = ImageFont.load("./fonts/6x10.pil") - large_font = ImageFont.load("./fonts/10x20.pil") + img = Image.new('RGB', (1000, 32)) + + + current_weather = current_weathers[location] + small_font = ImageFont.load("./fonts/4x6.pil") + font = ImageFont.load("./fonts/6x10.pil") + large_font = ImageFont.load("./fonts/10x20.pil") - 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'} + 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' + + location_img = self.textImage(location.upper(), font, r = 255, g = 255, b = 0) + + img.paste(location_img, (5,3)) + x_offset = location_img.size[0] + 8 + - weather_dir = './logos/weather_icons' + date_img = self.textImage((month + ' ' + date + ',' + weekday).upper(), font) + + img.paste(date_img, (x_offset, 3)) + + x_offset += date_img.size[0] + 2 + + + weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png') + w, h = weather_img.size + weather_img = weather_img.resize((int(w/2), int(h/2))) + + main = current_weather['main_weather'] + main_img = self.textImage(main.upper(), font) + img.paste(main_img, (x_offset, 3)) + x_offset += main_img.size[0] + 2 + + img.paste(weather_img, (x_offset,3)) + + x_offset += weather_img.size[0] + 2 + + + + temp = current_weather['temp'] + if all_settings['temp'] == 'kelvin': + temp = current_weather['temp'] + 273.15 + elif all_settings['temp'] == 'fahrenheit': + temp = current_weather['temp']*9/5 + 32 + + temp_img = self.textImage(str("{0:.0f}".format(temp)), font) + img.paste(temp_img, (x_offset,3)) + x_offset += temp_img.size[0]-3 + + deg_img = self.textImage('o', small_font) - location_img = self.textImage(location.upper(), font, r = 255, g = 255, b = 0) - - img.paste(location_img, (5,3)) - x_offset = location_img.size[0] + 8 - - - date_img = self.textImage((month + ' ' + date + ',' + weekday).upper(), font) - - img.paste(date_img, (x_offset, 3)) - - x_offset += date_img.size[0] + 2 - - - weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png') - w, h = weather_img.size - weather_img = weather_img.resize((int(w/2), int(h/2))) - - main = current_weather['main_weather'] - main_img = self.textImage(main.upper(), font) - img.paste(main_img, (x_offset, 3)) - x_offset += main_img.size[0] + 2 - - img.paste(weather_img, (x_offset,3)) - - x_offset += weather_img.size[0] + 2 - - temp_img = self.textImage(str("{0:.0f}".format(current_weather['temp'])), font) - img.paste(temp_img, (x_offset,3)) - x_offset += temp_img.size[0]-3 - - deg_img = self.textImage('o', small_font) - - img.paste(deg_img, (x_offset+1, 1)) - - x_offset += deg_img.size[0] -2 + img.paste(deg_img, (x_offset+1, 1)) + + x_offset += deg_img.size[0] -2 - min_img = self.textImage( "{0:.0f}".format(current_weather['min_temp']), small_font, r=0, g=0, b=255) - img.paste(min_img, (x_offset+2, 2)) - - max_img = self.textImage( "{0:.0f}".format(current_weather['max_temp']), small_font, r=255, g=0, b=0) - img.paste(max_img, (x_offset+2, 8)) - - x_offset += max_img.size[0] + 2 - - hum_img = Image.open(weather_dir + '/humidity.png') - htext_img = self.textImage(str(current_weather['humidity']) + '%', font) - uv_img = Image.open(weather_dir + '/uv.png') - utext_img = self.textImage(str(round(current_weather['uv'], 1)), font) + min_img = self.textImage( "{0:.0f}".format(current_weather['min_temp']), small_font, r=0, g=0, b=255) + img.paste(min_img, (x_offset+2, 2)) + + max_img = self.textImage( "{0:.0f}".format(current_weather['max_temp']), small_font, r=255, g=0, b=0) + img.paste(max_img, (x_offset+2, 8)) + + x_offset += max_img.size[0] + 2 + + hum_img = Image.open(weather_dir + '/humidity.png') + htext_img = self.textImage(str(current_weather['humidity']) + '%', font) + uv_img = Image.open(weather_dir + '/uv.png') + utext_img = self.textImage(str(round(current_weather['uv'], 1)), font) + + rain_img = Image.open(weather_dir + '/rain-chance.png') + rtext_img = self.textImage(str(int(current_weather['rain_chance']*100)) + '%', font) + cloud_img = Image.open(weather_dir + '/clouds.png') + ctext_img = self.textImage(str(current_weather['clouds']) + '%', font) + wind_img = Image.open(weather_dir + '/wind.png') + + w_speed = current_weather['wind_speed']*3.6 + w_unit = 'K/H' + if all_settings["wind_speed"] == "miles/hour": + w_speed = current_weather['wind_speed']*2.236936 + w_unit = 'M/H' + + + wtext_img = self.textImage("{0:.0f}".format(wind_speed) + wind_unit, font) + wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']).upper(), font) + vis_img = Image.open(weather_dir + '/visibility.png') + vtext_img = self.textImage(str(current_weather['visibility']/1000) + 'km', font) + + + for image in [hum_img, htext_img, uv_img, utext_img, rain_img, rtext_img, cloud_img, ctext_img, wind_img, wtext_img, wdir_img, vis_img, vtext_img]: + img.paste(image, (x_offset, 3)) + x_offset += image.size[0] + 2 + + + + + img = img.crop((0,0,x_offset +image.size[0] ,16)) - rain_img = Image.open(weather_dir + '/rain-chance.png') - rtext_img = self.textImage(str(int(current_weather['rain_chance']*100)) + '%', font) - cloud_img = Image.open(weather_dir + '/clouds.png') - ctext_img = self.textImage(str(current_weather['clouds']) + '%', font) - wind_img = Image.open(weather_dir + '/wind.png') - wtext_img = self.textImage("{0:.0f}".format(current_weather['wind_speed']) + 'm/s', font) - wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']).upper(), font) - vis_img = Image.open(weather_dir + '/visibility.png') - vtext_img = self.textImage(str(current_weather['visibility']/1000) + 'km', font) - - - for image in [hum_img, htext_img, uv_img, utext_img, rain_img, rtext_img, cloud_img, ctext_img, wind_img, wtext_img, wdir_img, vis_img, vtext_img]: - img.paste(image, (x_offset, 3)) - x_offset += image.size[0] + 2 - - - - - img = img.crop((0,0,x_offset +image.size[0] ,16)) - - image_list.append(img) + image_list.append(img) + 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] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) return self.stitchImage(image_list) def getDailyWeatherImageAlt(self): @@ -2070,139 +2213,189 @@ class StockTicker(): locations = list(daily_weathers['locations'].keys()) for i, location in enumerate(locations): - img = Image.new('RGB', (1000, 32)) - - - daily_weather = daily_weathers['locations'][location] - - 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.upper(), extra_small_font, r = 255, g = 255, b = 0) - main = daily_weather[0]['main_weather'] - if main == 'Clouds': - main = daily_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(daily_weather[0]['temp'])), large_font) - deg_img = self.textImage('o', small_font) - - min_img = self.textImage( "{0:.0f}".format(daily_weather[0]['min_temp']), small_font, r=0, g=0, b=255) - max_img = self.textImage( "{0:.0f}".format(daily_weather[0]['max_temp']), small_font, r=255, g=0, b=0) - main = daily_weather[0]['main_weather'] - main_img = self.textImage(main.upper(), 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'))-1] - date = str(int(datetime.now().strftime('%d'))) - weekday = weekdays[datetime.today().weekday()] - date_img = self.textImage((month + ' ' + date + ',' + weekday).upper(), extra_small_font) - - - rain_img = Image.open(weather_dir + '/rain-chance.png') - rtext_img = self.textImage(str(int(daily_weather[0]['rain_chance']*100)) + '%', extra_small_font) - hum_img = Image.open(weather_dir + '/humidity.png') - htext_img = self.textImage(str(daily_weather[0]['humidity']) + '%', extra_small_font) - wind_img = Image.open(weather_dir + '/wind.png') - wtext_img = self.textImage(str(daily_weather[0]['wind_speed']) + 'm/s'.upper(), extra_small_font) - uv_img = Image.open(weather_dir + '/uv.png') - utext_img = self.textImage(str(round(daily_weather[0]['uv'], 1)) , small_font) - cloud_img = Image.open(weather_dir + '/clouds.png') - ctext_img = self.textImage(str(daily_weather[0]['clouds']) + '%', small_font) - wind_img = Image.open(weather_dir + '/wind.png') - wtext_img = self.textImage("{0:.0f}".format(daily_weather[0]['wind_speed']) + 'm/s'.upper(), small_font) - wdir_img = self.textImage(self.degreesToCompass(daily_weather[0]['wind_direction']), small_font) - vis_img = Image.open(weather_dir + '/visibility.png') - vtext_img = self.textImage(str(round(daily_weather[0]['visibility']/1000, 1)) + 'km'.upper(), small_font) - - - img.paste(location_img, (0,0)) - - x_offset = location_img.size[0]+2 - img.paste(weather_img, (0,12)) - img.paste(temp_img, (34,9)) - img.paste(deg_img, (55, 8)) - img.paste(min_img, (61, 10)) - img.paste(main_img, (31, 26)) - img.paste(max_img, (61, 18)) - img.paste(date_img, (x_offset, 1)) - x_offset += date_img.size[0]+2 - - img.paste(rain_img, (x_offset,0)) - x_offset += rain_img.size[0]+2 - img.paste(rtext_img, (x_offset, 1)) - x_offset += rtext_img.size[0]+2 - - img.paste(hum_img, (x_offset, 0)) - x_offset += hum_img.size[0]+2 - img.paste(htext_img, (x_offset, 1)) - x_offset+= htext_img.size[0]+2 - - img.paste(uv_img, ( x_offset, 0)) - x_offset += uv_img.size[0]+2 - img.paste(utext_img, (x_offset, 1)) - x_offset += utext_img.size[0]+2 - - img.paste(cloud_img, (x_offset,0)) - x_offset += cloud_img.size[0]+2 - img.paste(ctext_img, (x_offset, 1)) - x_offset += ctext_img.size[0]+2 - - img.paste(wind_img, (x_offset,0)) - x_offset += wind_img.size[0]+2 - img.paste(wtext_img, (x_offset, 1)) - x_offset += wtext_img.size[0]+2 - img.paste(wdir_img, (x_offset, 1)) - x_offset+= wdir_img.size[0]+2 - - img.paste(vis_img, (x_offset,0)) - x_offset+= vis_img.size[0]+2 - img.paste(vtext_img, (x_offset, 1)) - x_offset += vtext_img.size[0] +2 - #img.paste(uv_img, ( 96, 0)) - #img.paste(utext_img, (109, 0)) - #img.paste(wind_img, (96,0)) - #img.paste(wtext_img, (109,0)) - #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.upper(), small_font) - weather = daily_weather[i] - main = weather['main_weather'] + print(location) + try: + img = Image.new('RGB', (1000, 32)) + daily_weather = daily_weathers['locations'][location] + + 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.upper(), extra_small_font, r = 255, g = 255, b = 0) + main = daily_weather[0]['main_weather'] if main == 'Clouds': - main = weather['description'] + main = daily_weather[0]['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') - min_img = self.textImage( "{0:.0f}".format(weather['min_temp']), small_font, r=0, g=0, b=255) + weather_dir = './logos/weather_icons' + + 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 = daily_weather[0]['temp'] + min_temp = daily_weather[0]['min_temp'] + max_temp = daily_weather[0]['max_temp'] - 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, 18)) - - x_offset += 40 + if daily_weathers['temp'] == 'kelvin': + temp = daily_weather[0]['temp'] + 273.15 + min_temp = daily_weather[0]['min_temp'] + 273.15 + max_temp = daily_weather[0]['max_temp'] + 273.15 + elif daily_weathers['temp'] == 'fahrenheit': + temp = daily_weather[0]['temp']*9/5 + 32 + min_temp = daily_weather[0]['min_temp']*9/5 + 32 + max_temp = daily_weather[0]['max_temp']*9/5 + 32 - img1 = img.crop((0,0,x_offset ,32)) - imgs.append(img1) - imgs.append(self.blank) - # add the image text + + temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font) + deg_img = self.textImage('o', small_font) + + min_img = self.textImage( "{0:.0f}".format(min_temp), small_font, r=0, g=0, b=255) + max_img = self.textImage( "{0:.0f}".format(max_temp), small_font, r=255, g=0, b=0) + main = daily_weather[0]['main_weather'] + main_img = self.textImage(main.upper(), 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'))-1] + date = str(int(datetime.now().strftime('%d'))) + weekday = weekdays[datetime.today().weekday()] + date_img = self.textImage((month + ' ' + date + ',' + weekday).upper(), extra_small_font) + + + rain_img = Image.open(weather_dir + '/rain-chance.png') + rtext_img = self.textImage(str(int(daily_weather[0]['rain_chance']*100)) + '%', extra_small_font) + hum_img = Image.open(weather_dir + '/humidity.png') + htext_img = self.textImage(str(daily_weather[0]['humidity']) + '%', extra_small_font) + wind_img = Image.open(weather_dir + '/wind.png') + wtext_img = self.textImage(str(daily_weather[0]['wind_speed']) + 'm/s'.upper(), extra_small_font) + uv_img = Image.open(weather_dir + '/uv.png') + utext_img = self.textImage(str(round(daily_weather[0]['uv'], 1)) , small_font) + cloud_img = Image.open(weather_dir + '/clouds.png') + ctext_img = self.textImage(str(daily_weather[0]['clouds']) + '%', small_font) + wind_img = Image.open(weather_dir + '/wind.png') + + + w_speed = daily_weather[0]['wind_speed']*3.6 + w_unit = 'K/H' + if daily_weathers['wind_speed'] == "miles/hour": + w_speed = daily_weather[0]['wind_speed']*2.236936 + w_unit = 'M/H' + + + wtext_img = self.textImage("{0:.0f}".format(w_speed) + w_unit, small_font) + wdir_img = self.textImage(self.degreesToCompass(daily_weather[0]['wind_direction']), small_font) + vis_img = Image.open(weather_dir + '/visibility.png') + vtext_img = self.textImage(str(round(daily_weather[0]['visibility']/1000, 1)) + 'km'.upper(), small_font) + + + img.paste(location_img, (0,0)) + + x_offset = location_img.size[0]+2 + img.paste(weather_img, (0,12)) + img.paste(temp_img, (34,9)) + img.paste(deg_img, (55, 8)) + img.paste(min_img, (61, 10)) + img.paste(main_img, (31, 26)) + img.paste(max_img, (61, 18)) + img.paste(date_img, (x_offset, 1)) + x_offset += date_img.size[0]+2 + + img.paste(rain_img, (x_offset,0)) + x_offset += rain_img.size[0]+2 + img.paste(rtext_img, (x_offset, 1)) + x_offset += rtext_img.size[0]+2 + + img.paste(hum_img, (x_offset, 0)) + x_offset += hum_img.size[0]+2 + img.paste(htext_img, (x_offset, 1)) + x_offset+= htext_img.size[0]+2 + + img.paste(uv_img, ( x_offset, 0)) + x_offset += uv_img.size[0]+2 + img.paste(utext_img, (x_offset, 1)) + x_offset += utext_img.size[0]+2 + + img.paste(cloud_img, (x_offset,0)) + x_offset += cloud_img.size[0]+2 + img.paste(ctext_img, (x_offset, 1)) + x_offset += ctext_img.size[0]+2 + + img.paste(wind_img, (x_offset,0)) + x_offset += wind_img.size[0]+2 + img.paste(wtext_img, (x_offset, 1)) + x_offset += wtext_img.size[0]+2 + img.paste(wdir_img, (x_offset, 1)) + x_offset+= wdir_img.size[0]+2 + + img.paste(vis_img, (x_offset,0)) + x_offset+= vis_img.size[0]+2 + img.paste(vtext_img, (x_offset, 1)) + x_offset += vtext_img.size[0] +2 + #img.paste(uv_img, ( 96, 0)) + #img.paste(utext_img, (109, 0)) + #img.paste(wind_img, (96,0)) + #img.paste(wtext_img, (109,0)) + #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.upper(), small_font) + weather = daily_weather[i] + main = weather['main_weather'] + + + if main == 'Clouds': + main = weather['description'] + + + + min_temp = weather['min_temp'] + max_temp = weather['max_temp'] + + if daily_weathers['temp'] == 'kelvin': + + min_temp = weather['min_temp'] + 273.15 + max_temp = weather['max_temp'] + 273.15 + elif daily_weathers['temp'] == 'fahrenheit': + + min_temp = weather['min_temp']*9/5 + 32 + max_temp = weather['max_temp']*9/5 + 32 + + weather_img = Image.open(weather_dir + '/small_icons/' + weather_ids[main] + '.png') + min_img = self.textImage( "{0:.0f}".format(min_temp), small_font, r=0, g=0, b=255) + + + max_img = self.textImage( "{0:.0f}".format(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, 18)) + + x_offset += 40 + + img1 = img.crop((0,0,x_offset ,32)) + imgs.append(img1) + imgs.append(self.blank) + # add the image text + except Exception as e: + print(str(e)) + exc_type, exc_obj, exc_tb = sys.exc_info() + fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] + self.logf.write(str(e)) + self.logf.write('. file: ' + fname) + self.logf.write('. line: ' + str(exc_tb.tb_lineno)) + self.logf.write('. type: ' + str(exc_type)) + self.logf.write('\n ' + "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))) @@ -2452,9 +2645,10 @@ class StockTicker(): if __name__ == '__main__': - with open('log.txt', "w") as log: + with open('log.txt', "a") as log: try: stock_ticker = StockTicker() + stock_ticker.logf = log start_image = Image.open('./logos/startup_logo.png') diff --git a/templates/index.html b/templates/index.html index 72ba580..94c32ce 100755 --- a/templates/index.html +++ b/templates/index.html @@ -1226,8 +1226,8 @@ id="inputTransition42" class="form-select wind-speed-select" > - - + + @@ -1447,8 +1447,8 @@ id="inputTransition52" class="form-select wind-speed-select" > - - + +