fintic-tracker/stockTicker.py
2023-09-19 17:42:18 +08:00

9993 lines
546 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Copyright (C) 2020 Fintic, finticofficial@gmail.com
#
# This file is part of Fintic project, developed by Neythen Treloar and Justin Dunn
#
# stockTicker can not be copied and/or distributed without the express
# permission of Fintic
import random
import sys, select
import os
import threading
from PIL import Image, ImageDraw, ImageFont, ImageSequence
Image.init()
import pytz
import time
import csv
import requests
import pexpect
from rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics
from rgbmatrix.graphics import *
from multiprocessing import Process
import traceback
import json
from datetime import datetime
import matplotlib.colors as mcolors
ny_zone = pytz.timezone('America/New_York')
gmt_zone = pytz.timezone('Etc/GMT')
gmt1_zone = pytz.timezone('Etc/GMT+1')
gmt2_zone = pytz.timezone('Etc/GMT+2')
gmt3_zone = pytz.timezone('Etc/GMT+3')
gmt4_zone = pytz.timezone('Etc/GMT+4')
gmt5_zone = pytz.timezone('Etc/GMT+5')
gmt6_zone = pytz.timezone('Etc/GMT+6')
gmt7_zone = pytz.timezone('Etc/GMT+7')
gmt8_zone = pytz.timezone('Etc/GMT+8')
gmt9_zone = pytz.timezone('Etc/GMT+9')
gmt10_zone = pytz.timezone('Etc/GMT+10')
gmt11_zone = pytz.timezone('Etc/GMT+11')
gmt12_zone = pytz.timezone('Etc/GMT+12')
gmtn1_zone = pytz.timezone('Etc/GMT-1')
gmtn2_zone = pytz.timezone('Etc/GMT-2')
gmtn3_zone = pytz.timezone('Etc/GMT-3')
gmtn4_zone = pytz.timezone('Etc/GMT-4')
gmtn5_zone = pytz.timezone('Etc/GMT-5')
gmtn6_zone = pytz.timezone('Etc/GMT-6')
gmtn7_zone = pytz.timezone('Etc/GMT-7')
gmtn8_zone = pytz.timezone('Etc/GMT-8')
gmtn9_zone = pytz.timezone('Etc/GMT-9')
gmtn10_zone = pytz.timezone('Etc/GMT-10')
gmtn11_zone = pytz.timezone('Etc/GMT-11')
gmtn12_zone = pytz.timezone('Etc/GMT-12')
gmtn13_zone = pytz.timezone('Etc/GMT-13')
gmtn14_zone = pytz.timezone('Etc/GMT-14')
ny_timezone = pytz.timezone('America/New_York')
london_timezone = pytz.timezone('Europe/London')
tokyo_timezone = pytz.timezone('Asia/Tokyo')
au_timezone = pytz.timezone('Australia/Sydney')
dubai_timezone = pytz.timezone('Asia/Dubai')
la_timezone = pytz.timezone('America/Los_Angeles')
cn_timezone = pytz.timezone('Asia/Shanghai')
paris_timezone = pytz.timezone('Europe/Paris')
in_timezone = pytz.timezone('Asia/Kolkata')
auck_timezone = pytz.timezone('Pacific/Auckland')
bang_timezone = pytz.timezone('Asia/Bangkok')
istan_timezone = pytz.timezone('Europe/Istanbul')
place_featuretitle = False
def getInput(Block=False):
if Block or select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
msg = sys.stdin.read(1)
#sys.stdin.flush()
else:
msg = ''
return msg
class StockTicker():
def __init__(self):
#Define global resources
self.symbols = []
self.delay = 0.02
self.greenORred = (255, 255, 255)
#self.blank = Image.open('logos/blank.png')
self.blank = Image.new('RGB', (10, 32))
self.running = True
settings = json.load(open('csv/general_settings.json', 'r'))
self.brightness = settings['brightness']*10
# Configuration for the matrix
options = RGBMatrixOptions()
options.rows = 32
options.cols = 64
options.chain_length = 2
options.parallel = 1
options.hardware_mapping = 'adafruit-hat' # If you have an Adafruit HAT: 'adafruit-hat'
options.gpio_slowdown = 2
options.brightness = self.brightness
self.matrix = RGBMatrix(options = options)
#sys.exit()
self.points = True # display crypto change in points or percent
self.functions = {'Stocks': self.getStockImage, 'Crypto': self.getCryptoImage, 'Forex': self.getForexImage, 'Sector Performance': self.getSectorImage,
'Daily Forecast':self.getDailyWeatherImage, 'Current Weather': self.getTodayWeatherImage, 'Jokes': self.getJokesImage, 'Place (Reddit)': self.getPlaceImage,
'Sports (Team Stats)':lambda : self.getLeagueTableImage('premier_league'), 'Sports (Past Games)': lambda:self.getLeagueImage('NBA', 'past'),
'Sports (Upcoming Games)': lambda : self.getLeagueImage('NHL', 'future'), 'Sports (Live Games)': lambda: self.getLeagueImage('NBA', 'live'),
'News':self.getNewsImage, 'Custom Messages': self.getUserMessages, 'Commodities': self.getCommoditiesImage, 'Indices': self.getIndicesImage, 'Movies': self.getMoviesImage, 'Gainers, Losers, Active': self.getMarketImage,
'Economic Calendar': self.getEconomicImage, 'IPO Calendar':self.getIpoImage, 'IPO Calendar Prof':self.getIpoProfessional, 'Economic Calendar Prof': self.getEconomicProfessional, 'Gainers, Losers, Active Prof': self.getMarketProfessional,
'Stocks Prof': self.getStockProfessional, 'Crypto Prof': self.getCryptoProfessional, 'Forex Prof': self.getForexProfessional, 'Jokes Prof': self.getJokesProfessional, 'Place (Reddit) Prof': self.getPlaceImageProfessional,
'Current Weather Prof': self.getTodayWeatherProfessional, 'News Prof':self.getNewsProfessional, 'Commodities Prof':self.getCommoditiesProfessional, 'Indices Prof': self.getIndicesProfessional, 'Sector Performance Prof': self.getSectorProfessional,
'Daily Forecast Prof':self.getDailyWeatherProfessional, 'Sports (Team Stats) Prof':lambda : self.getLeagueTableProfessional('NHL'), 'Sports (Upcoming Games) Prof': lambda : self.getLeagueProfessional('NHL', 'future'),
'Sports (Past Games) Prof': lambda : self.getLeagueProfessional('NBA', 'past'), 'Custom Messages Prof': self.getUserMessagesProfessional, 'Custom Images Prof': self.getUserImagesProfessional, 'Movies Prof': self.getMoviesProfessional, 'Sports (Live Games) Prof': lambda : self.getLeagueProfessional('NBA', 'live')}
self.JSONs = {'Stocks': 'csv/stocks_settings.json', 'Crypto': 'csv/crypto_settings.json', 'Forex': 'csv/forex_settings.json', 'Jokes': 'csv/jokes_settings.json',
'Daily Forecast':'csv/daily_weather.json', 'Current Weather': 'csv/current_weather.json', 'Commodities':'csv/commodities_settings.json', 'Indices': 'csv/indices_settings.json',
'Sports (Team Stats)': 'csv/league_tables.json', 'Sports (Past Games)': 'csv/past_games.json', 'IPO Calendar': 'csv/ipo_settings.json', 'Economic Calendar': 'csv/economic_settings.json',
'Sports (Upcoming Games)': 'csv/upcoming_games.json', 'Sports (Live Games)': 'csv/live_games.json', 'Movies': 'csv/movie_settings.json', 'Clock 1': 'csv/clock1_settings.json', 'Clock 2': 'csv/clock2_settings.json', 'World Clock': 'csv/worldclock_settings.json',
'News':'csv/news_settings.json', 'Custom Images': 'csv/image_settings.json', 'Custom GIFs': 'csv/GIF_settings.json', 'Custom Messages': 'csv/message_settings.json', 'Clock 1 Prof': 'csv/clock1_settings.json', 'World Clock Prof': 'csv/worldclock_settings.json',
'Stocks Prof': 'csv/stocks_settings.json', 'Crypto Prof': 'csv/crypto_settings.json', 'Forex Prof': 'csv/forex_settings.json', 'Jokes Prof': 'csv/jokes_settings.json', 'Clock 2 Prof': 'csv/clock2_settings.json',
'Current Weather Prof': 'csv/current_weather.json', 'News Prof':'csv/news_settings.json', 'Commodities Prof':'csv/commodities_settings.json', 'Indices Prof': 'csv/indices_settings.json',
'Daily Forecast Prof':'csv/daily_weather.json', 'Sports (Team Stats) Prof': 'csv/league_tables.json', 'Sports (Upcoming Games) Prof': 'csv/upcoming_games.json', 'Sports (Past Games) Prof': 'csv/past_games.json', 'Custom Messages Prof': 'csv/message_settings.json', 'Custom Images Prof': 'csv/image_settings.json', 'Movies Prof': 'csv/movie_settings.json', 'Sports (Live Games) Prof': 'csv/live_games.json', 'IPO Calendar Prof': 'csv/ipo_settings.json', 'Economic Calendar Prof': 'csv/economic_settings.json',
'Gainers, Losers, Active':'csv/market_settings.json', 'Gainers, Losers, Active Prof':'csv/market_settings.json', 'Sector Performance':'csv/sector_settings.json', 'Sector Performance Prof':'csv/sector_settings.json', 'Place (Reddit)':'csv/place_settings.json', 'Place (Reddit) Prof':'csv/place_settings.json'}
def openImage(self, image_file):
image = Image.open(image_file)
image = image.convert('RGB')
# Make image fit our screen.
#image.thumbnail((self.matrix.width, self.matrix.height), Image.ANTIALIAS)
#image = image.convert('RGB')
return image
def degreesToCompass(self, deg):
dirs = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
return dirs[int((deg+22.5)//45)%8]
def setImage(self, image, offset_x = 0, offset_y = 0, unsafe=True, min_x = 0, max_x = 128, min_y = 0, max_y = 32):
if (image.mode != "RGB"):
image = image.convert('RGB')
if unsafe:
#In unsafe mode we directly acceshow to send commands to running python processs the underlying PIL image array
#in cython, which is considered unsafe pointer accecss,
#however it's super fast and seems to work fine
#https://groups.google.com/forum/#!topic/cython-users/Dc1ft5W6KM4
img_width, img_height = image.size
self.matrix.SetPixelsPillow(offset_x, offset_y, img_width, img_height, image)
else:
# First implementation of a SetImage(). OPTIMIZE_ME: A more native
# implementation that directly reads the buffer and calls the underlying
# C functions can certainly be faster.
img_width, img_height = image.size
pixels = image.load()
for y in range(max(0, -offset_y), min(img_height, self.matrix.height - offset_y)):
for x in range(max(0, -offset_x), min(img_width, self.matrix.width - offset_x)):
if min_x <= x + offset_x <= max_x and min_y <= y + offset_y <= max_y:
(r, g, b) = pixels[x, y]
self.matrix.SetPixel(x + offset_x, y + offset_y, r*self.brightness, g*self.brightness, b*self.brightness)
def scrollImage(self, image, offset_x = 0, offset_y = 0, frame_skip = 10, gif = False, pause_frames = 0, place = False):
img_width, img_height = image.size
kill = False
if place:
value = -85
else:
value = 0
while offset_x > -(img_width+1):
if offset_x == value:
while pause_frames > 0:
if pause_frames%frame_skip == 0:
self.incrementGIF(image)
pause_frames -=1
if gif:
self.double_buffer.SetImage(image.convert('RGB'), offset_x, offset_y)
else:
self.double_buffer.SetImage(image, offset_x, offset_y)
for y in range(self.matrix.height):
self.matrix.SetPixel(offset_x + img_width +1 , y , 0,0,0)
self.matrix.SetPixel(offset_x + img_width , y , 0,0,0)
self.double_buffer = self.matrix.SwapOnVSync(self.double_buffer)
time.sleep(self.delay)
kill = self.checkKilled()
if kill: break
if kill: break
# for animation in gifs
if offset_x%frame_skip == 0:
self.incrementGIF(image)
#image = image.convert('RGB')
offset_x -= 1
#self.setImage(image.convert('RGB'), offset_x = offset_x, offset_y = offset_y)
if gif:
self.double_buffer.SetImage(image.convert('RGB'), offset_x, offset_y)
else:
self.double_buffer.SetImage(image, offset_x, offset_y)
buff = 0
# remove the ppixels behind the image, to stop trailing
self.double_buffer = self.matrix.SwapOnVSync(self.double_buffer)
for y in range(self.matrix.height):
self.matrix.SetPixel(offset_x + img_width +1 , y , 0,0,0)
self.matrix.SetPixel(offset_x + img_width , y , 0,0,0)
time.sleep(self.delay)
kill = self.checkKilled()
if kill: break
return kill
def scrollImageY(self, image, direction = 1, offset_x = 0, offset_y = 0, frame_skip = 10, gif = False):
kill = False
while offset_y != 0:
# for animation in gifs
if offset_y%frame_skip == 0:
self.incrementGIF(image)
offset_y += direction
if gif:
self.double_buffer.SetImage(image.convert('RGB'), offset_x, offset_y)
else:
self.double_buffer.SetImage(image, offset_x, offset_y)
self.double_buffer = self.matrix.SwapOnVSync(self.double_buffer)
time.sleep(self.delay)
kill = self.checkKilled()
if kill: break
return kill
def scrollImageTransition(self, image_files, offset_x = 0, offset_y = 0, stocks = True):
# use two image files and switch between them with a seemless transition
current_img = 1
image1 = self.openImage(image_files[0]).convert('RGB')
image2 = self.openImage(image_files[1]).convert('RGB')
double_buffer = self.matrix.CreateFrameCanvas()
kill = False
while True:
if current_img == 1:
if stocks:
update_process = Process(target = self.getFullStockImage, args = (1,))
update_process.start()
image1 = self.openImage(image_files[0]).convert('RGB')
image2 = self.openImage(image_files[1]).convert('RGB')
elif current_img == 2:
if stocks:
update_process = Process(target = self.getFullStockImage, args = (2,))
update_process.start()
image1 = self.openImage(image_files[1]).convert('RGB')
image2 = self.openImage(image_files[0]).convert('RGB')
img_width, img_height = image1.size
while offset_x > -img_width:
offset_x -= 1
double_buffer.SetImage(image1, offset_x, offset_y)
if offset_x + img_width < self.matrix.width: # if the image is ending
double_buffer.SetImage(image2, offset_x, offset_y)
double_buffer = self.matrix.SwapOnVSync(double_buffer)
time.sleep(self.delay)
kill = self.checkKilled()
if kill: break
if stocks:
image1.close()
image2.close()
if kill: break
if stocks:
update_process.join()
update_process.terminate()
if current_img == 1:
current_img = 2
elif current_img == 2:
current_img = 1
offset_x = 0
update_process.join()
update_process.terminate()
def scrollImageStacked(self, image, offset_x = 0, offset_y = 0):
img_width, img_height = image.size
while offset_x > -img_width - 128:
offset_x -= 1
self.setImage(image, offset_x = offset_x+128, offset_y = offset_y)
self.setImage(image, offset_x = offset_x, offset_y = offset_y+20)
kill = self.checkKilled()
time.sleep(self.delay)
return kill
def updateMultiple(self, options):
for option in options:
if option not in ['Custom GIFs', 'Custom Images', 'Custom Messages', 'Place (Reddit)', 'Clock 1', 'Clock 2', 'World Clock', 'Clock 1 Prof', 'Clock 2 Prof', 'World Clock Prof']: # these images are already saved in user uploads, dodnt need to update them
img = self.functions[option]()
img.save('./display_images/'+ option+ '.ppm')
def incrementGIF(self, image):
try:
image.seek(self.frame)
except EOFError:
self.frame = 0
image.seek(self.frame)
self.frame +=1
def checkKilled(self):
kill = False
try:
msg = getInput()
if msg == 'K':
self.resetMatrix()
kill = True
self.process_msg(msg)
except KeyboardInterrupt:
sys.stdout.flush()
pass
return kill
def set_delay(self,speed):
if speed.lower() == 'slow':
self.delay = 0.03
elif speed.lower() == 'medium':
self.delay = 0.02
elif speed.lower() == 'fast':
self.delay = 0.01
return self.delay
def scrollFunctionsAnimated(self, options, animation = 'down', repeat = True):
# scrolls trhough all functions with animation. Updates functions and remakes images when each function not being dispplayed
self.updateMultiple([options[0]])
kill = False
i = 0 # keep track of which image we are displaying
self.double_buffer = self.matrix.CreateFrameCanvas()
while True:
update_process = Process(target = self.updateMultiple, args = ([options[(i+1) % len(options)]],))
update_process.start()
f = open(self.JSONs[options[(i) % len(options)]])
settings = json.load(f)
f.close()
if options[i % len(options)] == 'Clock 1':
kill=self.showClock1()
elif options[i % len(options)] == 'Clock 2':
kill=self.showClock2()
elif options[i % len(options)] == 'World Clock':
kill=self.showWorldclock()
else:
self.set_delay(settings['speed'])
animation = settings['animation'].lower()
if options[i % len(options)] == 'Custom Images':
images = self.getUserImages()
elif options[i % len(options)] == 'Place (Reddit)':
images = self.getPlaceImage()
elif options[i % len(options)] == 'Custom GIFs':
images = self.getUserGIFs()
elif options[i % len(options)] == 'Custom Messages':
images = self.getUserMessages()
else: #these options just have a single ppm image
image = self.openImage('./display_images/' + options[i % len(options)] +'.ppm')
images = [image]
for image in images:
img_width, img_height = image.size
offset_x = 0
if animation == 'continuous':
offset_x = 128
elif animation in ['up', 'down']:
offset_x = max(0, 128-img_width)
offset_y = 0
#first scroll image in from bottom
frame_skip = int((1/15)/self.delay) #controls how fast gifs run
self.frame = 0
pause_frames = int(0.5/self.delay)
if animation == 'up':
offset_y = 33
direction = -1
kill = self.scrollImageY(image, direction = direction, offset_x = offset_x, offset_y = offset_y, frame_skip = frame_skip, gif = options[i % len(options)] == 'Custom GIFs')
elif animation == 'down':
direction = 1
offset_y = -33
kill = self.scrollImageY(image, direction = direction, offset_x = offset_x, offset_y = offset_y, frame_skip = frame_skip, gif = options[i % len(options)] == 'Custom GIFs')
if kill: break
offset_y = 0
if animation in ['up', 'down']:
while pause_frames > 0:
if pause_frames%frame_skip == 0:
self.incrementGIF(image)
pause_frames -=1
if options[i % len(options)] != 'Custom GIFs':
self.double_buffer.SetImage(image, offset_x, offset_y)
else:
self.double_buffer.SetImage(image.convert('RGB'), offset_x, offset_y)
self.double_buffer = self.matrix.SwapOnVSync(self.double_buffer)
time.sleep(self.delay)
kill = self.checkKilled()
if kill: break
if kill: break
if kill: break
try:
pause = float(settings['pause'])
except:
pause = 0
pause_frames = int(float(pause)/self.delay)
if options[i % len(options)] == 'Place (Reddit)':
global place_featuretitle
place_true = place_featuretitle
else:
place_true = False
kill = self.scrollImage(image, offset_x = offset_x, offset_y = offset_y, frame_skip = frame_skip, gif = options[i % len(options)] == 'Custom GIFs', pause_frames = pause_frames, place = place_true)
if kill: break
if kill:break
if not repeat:
break
update_process.join()
update_process.terminate()
i+=1
def scrollProfessionalAnimated(self, options, animation = 'on'):
# scrolls trhough all functions with animation. Updates functions and remakes images when each function not being dispplayed
top = options[0]
bottom = options[1]
# self.updateMultiple([top[0], bottom[0]])
# ADDING THIS FOR COLORS FOR CLOCK FEATURES
time_colors1 = {
"White": (255,255,255), "Red": (255, 0,0), "Green": (0,255,0), "Dark Green": (0, 100,0), "Blue": (0,0,255), "Purple": (145,0,255),
"Pink": (255,0,255), "Yellow": (255,255,0), "Orange": (255,130,0), "Gold": (255,190,0), "Gray": (100,100,100), "Cyan": (0,255,255)}
day_colors = {"day":(255, 191, 0), "night":(0, 71,171)}
def isDaytime1(time,twelvehours):
if twelvehours:
hour = int(time.split(':')[0])
daytime_start_hour = 6
daytime_end_hour = 6
am_pm = time[-2:]
if (6 <= hour <= 11 and am_pm == 'AM') or (1 <= hour <= 6 and am_pm == 'PM') or (hour == 12 and am_pm == 'PM'):
return True
else:
return False
else:
hour = time.split(':')[0]
daytime_start_hour = 6
daytime_end_hour = 18
if daytime_start_hour <= int(hour) <= daytime_end_hour:
return True
else:
return False
kill = False
i1 = 0 # keep track of which image we are displaying
i2 = 0 # keep track of which image we are displaying
self.double_buffer = self.matrix.CreateFrameCanvas()
update_process = Process(target = self.updateMultiple, args = ([top[(i1+1) % len(top)]+ ' Prof', bottom[(i2+1) % len(bottom)]+ ' Prof' ],))
update_process.start()
self.updateMultiple([top[i1 % len(top)]+ ' Prof', bottom[i2 % len(bottom)]+ ' Prof' ])
settings1 = json.load(open(self.JSONs[top[i1 % len(top)]]))
settings2 = json.load(open(self.JSONs[bottom[i2 % len(bottom)] ]))
if 'Clock' not in top[i1 % len(top)]:
image1 = self.openImage('./display_images/' + top[i1 % len(top)] +' Prof.ppm')
image1 = image1.convert('RGB')
elif top[i1 % len(top)] == 'Clock 2': #CLOCK 2 SETTINGS
image1 = Image.new('RGB', (128, 16))
draw = ImageDraw.Draw(image1)
the_time = time.time()
font = ImageFont.load("fonts/6x12.pil")
font2 = ImageFont.load("fonts/5x8.pil")
try:
with open('clock_screensaver.json', 'r') as f:
clock2_settings = json.load(f)['clock2']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
clock2_settings = clock_settings['clock2']
time_color1 = clock2_settings['time_color']
date_color1 = clock2_settings['date_color']
timezone1 = clock2_settings['timezone']
display_s = clock2_settings['display_seconds']
display_p = clock2_settings['display_pm']
twelvehours = clock2_settings['12hour']
if twelvehours:
if display_p and display_s:
time_format = "%I:%M:%S %p"
elif display_p and not display_s:
time_format = "%I:%M %p"
elif not display_p and display_s:
time_format = "%I:%M:%S"
else:
time_format = "%I:%M"
else:
if display_p and display_s:
time_format = "%H:%M:%S %p"
elif display_p and not display_s:
time_format = "%H:%M %p"
elif not display_p and display_s:
time_format = "%H:%M:%S"
else:
time_format = "%H:%M"
if '+' in timezone1:
timezone1 = timezone1.replace('+', '-')
elif '-' in timezone1:
timezone1 = timezone1.replace('-', '+')
elif top[i1 % len(top)] == 'Clock 1': #CLOCK 1 SETTINGS
image1 = Image.new('RGB', (128, 16))
draw = ImageDraw.Draw(image1)
the_time = time.time()
font_1 = ImageFont.load("fonts/7x14B.pil")
font_2 = ImageFont.load("fonts/5x8.pil")
try:
with open('clock_screensaver.json', 'r') as f:
clock1_settings = json.load(f)['clock1']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
clock1_settings = clock_settings['clock1']
time_color2 = clock1_settings['time_color']
date_color2 = clock1_settings['date_color']
weekday_color2 = clock1_settings['weekday_color']
timezone2 = clock1_settings['timezone']
display_s = clock1_settings['display_seconds']
display_p = clock1_settings['display_pm']
twelvehours = clock1_settings['12hour']
if twelvehours:
if display_p and display_s:
time_format = "%I:%M:%S %p"
elif display_p and not display_s:
time_format = "%I:%M %p"
elif not display_p and display_s:
time_format = "%I:%M:%S"
else:
time_format = "%I:%M"
else:
if display_p and display_s:
time_format = "%H:%M:%S %p"
elif display_p and not display_s:
time_format = "%H:%M %p"
elif not display_p and display_s:
time_format = "%H:%M:%S"
else:
time_format = "%H:%M"
if '+' in timezone2:
timezone2 = timezone2.replace('+', '-')
elif '-' in timezone2:
timezone2 = timezone2.replace('-', '+')
elif top[i1 % len(top)] == 'World Clock': #WORLD CLOCK SETTINGS
image1 = Image.new('RGB', (128, 16))
draw = ImageDraw.Draw(image1)
the_time = time.time()
next_six_seconds = 0
counter = 0
font_1 = ImageFont.load("fonts/4x6.pil")
try:
with open('clock_screensaver.json', 'r') as f:
world_settings = json.load(f)['world_clock']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
world_settings = clock_settings['world_clock']
worldcity_color = world_settings['city_color']
display_s = world_settings['display_seconds']
display_p = world_settings['display_pm']
twelvehours = world_settings['12hour']
if twelvehours:
if display_p and display_s:
time_format = "%I:%M:%S %p"
world_offset = 82
elif display_p and not display_s:
time_format = "%I:%M %p"
world_offset = 94
elif not display_p and display_s:
time_format = "%I:%M:%S %p"
world_offset = 94
else:
time_format = "%I:%M %p"
world_offset = 106
else:
if display_p and display_s:
time_format = "%H:%M:%S %p"
world_offset = 82
elif display_p and not display_s:
time_format = "%H:%M %p"
world_offset = 94
elif not display_p and display_s:
time_format = "%H:%M:%S %p"
world_offset = 94
else:
time_format = "%H:%M %p"
world_offset = 106
#BOTTOM SETTINGS
if 'Clock' not in bottom[i2 % len(bottom)]:
image2 = self.openImage('./display_images/' + bottom[i2 % len(bottom)] +' Prof.ppm')
image2 = image2.convert('RGB')
elif bottom[i2 % len(bottom)] == 'Clock 2': #CLOCK 2 SETTINGS
image2 = Image.new('RGB', (128, 16))
draw2 = ImageDraw.Draw(image2)
the_time2 = time.time()
font_b = ImageFont.load("fonts/6x12.pil")
font2_b = ImageFont.load("fonts/5x8.pil")
try:
with open('clock_screensaver.json', 'r') as f:
clock2_settings = json.load(f)['clock2']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
clock2_settings = clock_settings['clock2']
time_color1_b = clock2_settings['time_color']
date_color1_b = clock2_settings['date_color']
timezone1_b = clock2_settings['timezone']
display_s_b = clock2_settings['display_seconds']
display_p_b = clock2_settings['display_pm']
twelvehours_b = clock2_settings['12hour']
if twelvehours_b:
if display_p_b and display_s_b:
time_format_b = "%I:%M:%S %p"
elif display_p_b and not display_s_b:
time_format_b = "%I:%M %p"
elif not display_p_b and display_s_b:
time_format_b = "%I:%M:%S"
else:
time_format_b = "%I:%M"
else:
if display_p_b and display_s_b:
time_format_b = "%H:%M:%S %p"
elif display_p_b and not display_s_b:
time_format_b = "%H:%M %p"
elif not display_p_b and display_s_b:
time_format_b = "%H:%M:%S"
else:
time_format_b = "%H:%M"
if '+' in timezone1_b:
timezone1_b = timezone1_b.replace('+', '-')
elif '-' in timezone1_b:
timezone1_b = timezone1_b.replace('-', '+')
elif bottom[i2 % len(bottom)] == 'Clock 1': #CLOCK 1 SETTINGS
image2 = Image.new('RGB', (128, 16))
draw2 = ImageDraw.Draw(image2)
the_time2 = time.time()
font_1_b = ImageFont.load("fonts/7x14B.pil")
font_2_b = ImageFont.load("fonts/5x8.pil")
try:
with open('clock_screensaver.json', 'r') as f:
clock1_settings = json.load(f)['clock1']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
clock1_settings = clock_settings['clock1']
time_color2_b = clock1_settings['time_color']
date_color2_b = clock1_settings['date_color']
weekday_color2_b = clock1_settings['weekday_color']
timezone2_b = clock1_settings['timezone']
display_s_b = clock1_settings['display_seconds']
display_p_b = clock1_settings['display_pm']
twelvehours_b = clock1_settings['12hour']
if twelvehours_b:
if display_p_b and display_s_b:
time_format_b = "%I:%M:%S %p"
elif display_p_b and not display_s_b:
time_format_b = "%I:%M %p"
elif not display_p_b and display_s_b:
time_format_b = "%I:%M:%S"
else:
time_format_b = "%I:%M"
else:
if display_p_b and display_s_b:
time_format_b = "%H:%M:%S %p"
elif display_p_b and not display_s_b:
time_format_b = "%H:%M %p"
elif not display_p_b and display_s_b:
time_format_b = "%H:%M:%S"
else:
time_format_b = "%H:%M"
if '+' in timezone2_b:
timezone2_b = timezone2_b.replace('+', '-')
elif '-' in timezone2_b:
timezone2_b = timezone2_b.replace('-', '+')
elif bottom[i2 % len(bottom)] == 'World Clock': #WORLD CLOCK SETTINGS
image2 = Image.new('RGB', (128, 16))
draw2 = ImageDraw.Draw(image2)
the_time2 = time.time()
next_six_seconds2 = 0
counter2 = 0
font_12 = ImageFont.load("fonts/4x6.pil")
try:
with open('clock_screensaver.json', 'r') as f:
world_settings = json.load(f)['world_clock']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
world_settings = clock_settings['world_clock']
worldcity_color2 = world_settings['city_color']
display_s_b = world_settings['display_seconds']
display_p_b = world_settings['display_pm']
twelvehours_b = world_settings['12hour']
if twelvehours_b:
if display_p_b and display_s_b:
time_format_b = "%I:%M:%S %p"
world_offset_b = 82
elif display_p_b and not display_s_b:
time_format_b = "%I:%M %p"
world_offset_b = 94
elif not display_p_b and display_s_b:
time_format_b = "%I:%M:%S %p"
world_offset_b = 94
else:
time_format_b = "%I:%M %p"
world_offset_b = 106
else:
if display_p_b and display_s_b:
time_format_b = "%H:%M:%S %p"
world_offset_b = 82
elif display_p_b and not display_s_b:
time_format_b = "%H:%M %p"
world_offset_b = 94
elif not display_p_b and display_s_b:
time_format_b = "%H:%M:%S %p"
world_offset_b = 94
else:
time_format_b = "%H:%M %p"
world_offset_b = 106
delay_t1 = self.set_delay(settings1['speed'])
try:
animation1 = settings1['animation'].lower()
except:
animation1 = settings1['transition'].lower()
try:
delay_t2 = self.set_delay(settings2['speed2'])
except:
delay_t2 = self.set_delay(settings2['speed'])
try:
animation2 = settings2['animation'].lower()
except:
animation2 = settings2['transition'].lower()
try:
pause1 = int(settings1['pause'])
except:
pause1 = 0
try:
pause2 = int(settings2['pause'])
except:
pause2 = 0
if animation1 == 'continuous':
offset_y1 = 0
offset_x1 = 128
else:
offset_y1 = -16
offset_x1 = 0
if animation2 == 'continuous':
offset_y2 = 16
offset_x2 = 128
else:
offset_y2 = 32
offset_x2 = 0
# frame_skip = int((1/15)/self.delay) #controls how fast gifs run
# self.frame = 0
img_width1, img_height1 = image1.size
img_width2, img_height2 = image2.size
kill = False
update_t1 = time.time()
update_t2 = time.time()
while True:
# UPDATE IMAGE 1 WHEN PRIOR FEATURE DONE DISPLAYING
if offset_x1 < -(img_width1+1):
i1 += 1
settings1 = json.load(open(self.JSONs[top[i1 % len(top)]]))
delay_t1 = self.set_delay(settings1['speed'])
try:
animation1 = settings1['animation'].lower()
except:
animation1 = settings1['transition'].lower()
try:
pause1 = int(settings1['pause'])
except:
pause1 = 0
if animation1 == 'continuous':
offset_y1 = 0
offset_x1 = 128
else:
offset_y1 = -16
offset_x1 = 0
update_process.join()
update_process.terminate()
update_process = Process(target = self.updateMultiple, args = ([top[(i1+1) % len(top)]+ ' Prof'],))
update_process.start()
if 'Clock' not in top[i1 % len(top)]:
image1 = self.openImage('./display_images/' + top[i1 % len(top)] +' Prof.ppm')
image1 = image1.convert('RGB')
elif top[i1 % len(top)] == 'Clock 2': #CLOCK2 SETTINGS
image1 = Image.new('RGB', (128, 16))
draw = ImageDraw.Draw(image1)
the_time = time.time()
font = ImageFont.load("fonts/6x12.pil")
font2 = ImageFont.load("fonts/5x8.pil")
try:
with open('clock_screensaver.json', 'r') as f:
clock2_settings = json.load(f)['clock2']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
clock2_settings = clock_settings['clock2']
time_color1 = clock2_settings['time_color']
date_color1 = clock2_settings['date_color']
timezone1 = clock2_settings['timezone']
display_s = clock2_settings['display_seconds']
display_p = clock2_settings['display_pm']
twelvehours = clock2_settings['12hour']
if twelvehours:
if display_p and display_s:
time_format = "%I:%M:%S %p"
elif display_p and not display_s:
time_format = "%I:%M %p"
elif not display_p and display_s:
time_format = "%I:%M:%S"
else:
time_format = "%I:%M"
else:
if display_p and display_s:
time_format = "%H:%M:%S %p"
elif display_p and not display_s:
time_format = "%H:%M %p"
elif not display_p and display_s:
time_format = "%H:%M:%S"
else:
time_format = "%H:%M"
if '+' in timezone1:
timezone1 = timezone1.replace('+', '-')
elif '-' in timezone1:
timezone1 = timezone1.replace('-', '+')
elif top[i1 % len(top)] == 'Clock 1': #CLOCK 1 SETTINGS
image1 = Image.new('RGB', (128, 16))
draw = ImageDraw.Draw(image1)
the_time = time.time()
font_1 = ImageFont.load("fonts/7x14B.pil")
font_2 = ImageFont.load("fonts/5x8.pil")
try:
with open('clock_screensaver.json', 'r') as f:
clock1_settings = json.load(f)['clock1']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
clock1_settings = clock_settings['clock1']
time_color2 = clock1_settings['time_color']
date_color2 = clock1_settings['date_color']
weekday_color2 = clock1_settings['weekday_color']
timezone2 = clock1_settings['timezone']
display_s = clock1_settings['display_seconds']
display_p = clock1_settings['display_pm']
twelvehours = clock1_settings['12hour']
if twelvehours:
if display_p and display_s:
time_format = "%I:%M:%S %p"
elif display_p and not display_s:
time_format = "%I:%M %p"
elif not display_p and display_s:
time_format = "%I:%M:%S"
else:
time_format = "%I:%M"
else:
if display_p and display_s:
time_format = "%H:%M:%S %p"
elif display_p and not display_s:
time_format = "%H:%M %p"
elif not display_p and display_s:
time_format = "%H:%M:%S"
else:
time_format = "%H:%M"
if '+' in timezone2:
timezone2 = timezone2.replace('+', '-')
elif '-' in timezone2:
timezone2 = timezone2.replace('-', '+')
elif top[i1 % len(top)] == 'World Clock': #WORLD CLOCK SETTINGS
image1 = Image.new('RGB', (128, 16))
draw = ImageDraw.Draw(image1)
the_time = time.time()
next_six_seconds = 0
counter = 0
font_1 = ImageFont.load("fonts/4x6.pil")
try:
with open('clock_screensaver.json', 'r') as f:
world_settings = json.load(f)['world_clock']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
world_settings = clock_settings['world_clock']
worldcity_color = world_settings['city_color']
display_s = world_settings['display_seconds']
display_p = world_settings['display_pm']
twelvehours = world_settings['12hour']
if twelvehours:
if display_p and display_s:
time_format = "%I:%M:%S %p"
world_offset = 82
elif display_p and not display_s:
time_format = "%I:%M %p"
world_offset = 94
elif not display_p and display_s:
time_format = "%I:%M:%S %p"
world_offset = 94
else:
time_format = "%I:%M %p"
world_offset = 106
else:
if display_p and display_s:
time_format = "%H:%M:%S %p"
world_offset = 82
elif display_p and not display_s:
time_format = "%H:%M %p"
world_offset = 94
elif not display_p and display_s:
time_format = "%H:%M:%S %p"
world_offset = 94
else:
time_format = "%H:%M %p"
world_offset = 106
img_width1, img_height1 = image1.size
# UPDATE IMAGE 2 WHEN PRIOR FEATURE DONE DISPLAYING
if offset_x2 < -(img_width2+1):
i2 += 1
settings2 = json.load(open(self.JSONs[bottom[(i2) % len(bottom)]]))
try:
delay_t2 = self.set_delay(settings2['speed2'])
except:
delay_t2 = self.set_delay(settings2['speed'])
try:
animation2 = settings2['animation'].lower()
except:
animation2 = settings2['transition'].lower()
try:
pause2 = int(settings2['pause'])
except:
pause2 = 0
if animation2 == 'continuous':
offset_y2 = 16
offset_x2 = 128
else:
offset_y2 = 32
offset_x2 = 0
update_process.join()
update_process.terminate()
update_process = Process(target = self.updateMultiple, args = ([bottom[i2 % len(bottom)]+ ' Prof'],))
update_process.start()
if 'Clock' not in bottom[i2 % len(bottom)]:
image2 = self.openImage('./display_images/' + bottom[i2 % len(bottom)] +' Prof.ppm')
image2 = image2.convert('RGB')
elif bottom[i2 % len(bottom)] == 'Clock 2': #CLOCK 2 SETTINGS
image2 = Image.new('RGB', (128, 16))
draw2 = ImageDraw.Draw(image2)
the_time2 = time.time()
font_b = ImageFont.load("fonts/6x12.pil")
font2_b = ImageFont.load("fonts/5x8.pil")
try:
with open('clock_screensaver.json', 'r') as f:
clock2_settings = json.load(f)['clock2']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
clock2_settings = clock_settings['clock2']
time_color1_b = clock2_settings['time_color']
date_color1_b = clock2_settings['date_color']
timezone1_b = clock2_settings['timezone']
display_s_b = clock2_settings['display_seconds']
display_p_b = clock2_settings['display_pm']
twelvehours_b = clock2_settings['12hour']
if twelvehours_b:
if display_p_b and display_s_b:
time_format_b = "%I:%M:%S %p"
elif display_p_b and not display_s_b:
time_format_b = "%I:%M %p"
elif not display_p_b and display_s_b:
time_format_b = "%I:%M:%S"
else:
time_format_b = "%I:%M"
else:
if display_p_b and display_s_b:
time_format_b = "%H:%M:%S %p"
elif display_p_b and not display_s_b:
time_format_b = "%H:%M %p"
elif not display_p_b and display_s_b:
time_format_b = "%H:%M:%S"
else:
time_format_b = "%H:%M"
if '+' in timezone1_b:
timezone1_b = timezone1_b.replace('+', '-')
elif '-' in timezone1_b:
timezone1_b = timezone1_b.replace('-', '+')
elif bottom[i2 % len(bottom)] == 'Clock 1': #CLOCK 1 SETTINGS
image2 = Image.new('RGB', (128, 16))
draw2 = ImageDraw.Draw(image2)
the_time2 = time.time()
font_1_b = ImageFont.load("fonts/7x14B.pil")
font_2_b = ImageFont.load("fonts/5x8.pil")
try:
with open('clock_screensaver.json', 'r') as f:
clock1_settings = json.load(f)['clock1']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
clock1_settings = clock_settings['clock1']
time_color2_b = clock1_settings['time_color']
date_color2_b = clock1_settings['date_color']
weekday_color2_b = clock1_settings['weekday_color']
timezone2_b = clock1_settings['timezone']
display_s_b = clock1_settings['display_seconds']
display_p_b = clock1_settings['display_pm']
twelvehours_b = clock1_settings['12hour']
if twelvehours_b:
if display_p_b and display_s_b:
time_format_b = "%I:%M:%S %p"
elif display_p_b and not display_s_b:
time_format_b = "%I:%M %p"
elif not display_p_b and display_s_b:
time_format_b = "%I:%M:%S"
else:
time_format_b = "%I:%M"
else:
if display_p_b and display_s_b:
time_format_b = "%H:%M:%S %p"
elif display_p_b and not display_s_b:
time_format_b = "%H:%M %p"
elif not display_p_b and display_s_b:
time_format_b = "%H:%M:%S"
else:
time_format_b = "%H:%M"
if '+' in timezone2_b:
timezone2_b = timezone2_b.replace('+', '-')
elif '-' in timezone2_b:
timezone2_b = timezone2_b.replace('-', '+')
elif bottom[i2 % len(bottom)] == 'World Clock': #WORLD CLOCK SETTINGS
image2 = Image.new('RGB', (128, 16))
draw2 = ImageDraw.Draw(image2)
the_time2 = time.time()
next_six_seconds2 = 0
counter2 = 0
font_12 = ImageFont.load("fonts/4x6.pil")
try:
with open('clock_screensaver.json', 'r') as f:
world_settings = json.load(f)['world_clock']
except:
clock_settings = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(clock_settings, f)
world_settings = clock_settings['world_clock']
worldcity_color2 = world_settings['city_color']
display_s_b = world_settings['display_seconds']
display_p_b = world_settings['display_pm']
twelvehours_b = world_settings['12hour']
if twelvehours_b:
if display_p_b and display_s_b:
time_format_b = "%I:%M:%S %p"
world_offset_b = 82
elif display_p_b and not display_s_b:
time_format_b = "%I:%M %p"
world_offset_b = 94
elif not display_p_b and display_s_b:
time_format_b = "%I:%M:%S %p"
world_offset_b = 94
else:
time_format_b = "%I:%M %p"
world_offset_b = 106
else:
if display_p_b and display_s_b:
time_format_b = "%H:%M:%S %p"
world_offset_b = 82
elif display_p_b and not display_s_b:
time_format_b = "%H:%M %p"
world_offset_b = 94
elif not display_p_b and display_s_b:
time_format_b = "%H:%M:%S %p"
world_offset_b = 94
else:
time_format_b = "%H:%M %p"
world_offset_b = 106
img_width2, img_height2 = image2.size
# SCROLL, DISPLAY, PAUSE CLOCK 2
if top[i1 % len(top)] == 'Clock 2':
#Initial image generation so it doesn't appear blank for the first second
if offset_x1 == 128 or offset_y1 == -16:
draw.rectangle([(0,0),(128,16)], (0,0,0))
current_time = datetime.now(pytz.timezone(timezone1)).strftime(time_format + ",%a %d %b %Y").split(',')
time_t = current_time[0]
date_t = current_time[1].upper()
date_width, date_height = draw.textsize(date_t, font2)
text_width, text_height = draw.textsize(time_t, font)
draw.text(((128-text_width)/2, -2), time_t, time_colors1[time_color1], font)
draw.text(((128-date_width)/2, 8), date_t, time_colors1[date_color1], font2)
#If time now is greater than 1 second of the previously updated image time, update image and reset updated image time to another second
if time.time() >= the_time + 1:
the_time = time.time()
draw.rectangle([(0,0),(128,16)], (0,0,0))
current_time = datetime.now(pytz.timezone(timezone1)).strftime(time_format + ",%a %d %b %Y").split(',')
time_t = current_time[0]
date_t = current_time[1].upper()
date_width, date_height = draw.textsize(date_t, font2)
text_width, text_height = draw.textsize(time_t, font)
draw.text(((128-text_width)/2, -2), time_t, time_colors1[time_color1], font)
draw.text(((128-date_width)/2, 8), date_t, time_colors1[date_color1], font2)
if time.time() - update_t1 > delay_t1:
update_t1 = time.time()
#Get the pause time right before image is done transitioning in
if offset_y1 == -1 or offset_x1 == 1:
pause_time = time.time() + pause1
if offset_y1 < 0:
offset_y1+=1
else: #If the scrolling reaches 0 pixel, pause it
if offset_x1 != 0:
offset_x1 -= 1
else:
try: #after the pause time, scroll iamge past 0 pixel to continue scrolling
if time.time() >= pause_time:
offset_x1 -= 1
except:
pass
# SCROLL, DISPLAY, PAUSE CLOCK 1
elif top[i1 % len(top)] == 'Clock 1':
#Initial image generation so it doesn't appear blank for the first second
if offset_x1 == 128 or offset_y1 == -16:
draw.rectangle([(0,0),(128,16)], (0,0,0))
current_time = datetime.now(pytz.timezone(timezone2)).strftime(time_format + ",%A,%d %b").split(',')
time_t = current_time[0]
weekday_t = current_time[1].upper()
date_t = current_time[2].upper()
date_width, date_height = draw.textsize(date_t, font_2)
wday_width, wday_height = draw.textsize(weekday_t, font_2)
text_width, text_height = draw.textsize(time_t, font_1)
total_width = text_width + 6 + max(wday_width, date_width)
starting_coord = (128-total_width)/2
draw.text((starting_coord, 1), time_t, time_colors1[time_color2], font_1)
draw.text((starting_coord + text_width + 6, 1), date_t, time_colors1[date_color2], font_2)
draw.text((starting_coord + text_width + 7, 8), weekday_t, time_colors1[weekday_color2], font_2)
#If time now is greater than 1 second of the previously updated image time, update image and reset updated image time to another second
if time.time() >= the_time + 1:
the_time = time.time()
draw.rectangle([(0,0),(128,16)], (0,0,0))
current_time = datetime.now(pytz.timezone(timezone2)).strftime(time_format + ",%A,%d %b").split(',')
time_t = current_time[0]
weekday_t = current_time[1].upper()
date_t = current_time[2].upper()
date_width, date_height = draw.textsize(date_t, font_2)
wday_width, wday_height = draw.textsize(weekday_t, font_2)
text_width, text_height = draw.textsize(time_t, font_1)
total_width = text_width + 6 + max(wday_width, date_width)
starting_coord = (128-total_width)/2
draw.text((starting_coord, 1), time_t, time_colors1[time_color2], font_1)
draw.text((starting_coord + text_width + 6, 1), date_t, time_colors1[date_color2], font_2)
draw.text((starting_coord + text_width + 7, 8), weekday_t, time_colors1[weekday_color2], font_2)
if time.time() - update_t1 > delay_t1:
update_t1 = time.time()
#Get the pause time right before image is done transitioning in
if offset_y1 == -1 or offset_x1 == 1:
pause_time = time.time() + pause1
if offset_y1 < 0:
offset_y1+=1
else: #If the scrolling reaches 0 pixel, pause it
if offset_x1 != 0:
offset_x1 -= 1
else:
try: #after the pause time, scroll iamge past 0 pixel to continue scrolling
if time.time() >= pause_time:
offset_x1 -= 1
except:
pass
# SCROLL, DISPLAY, PAUSE WORLD CLOCK
elif top[i1 % len(top)] == 'World Clock':
#Initial image generation so it doesn't appear blank for the first second
if offset_x1 == 128 or offset_y1 == -16:
draw.rectangle([(0,0),(128,16)], (0,0,0))
ny_time = datetime.now(pytz.timezone('America/New_York')).strftime(time_format)
london_time = datetime.now(pytz.timezone('Europe/London')).strftime(time_format)
ny_color = day_colors['day'] if isDaytime1(ny_time,twelvehours) else day_colors['night']
london_color = day_colors['day'] if isDaytime1(london_time,twelvehours) else day_colors['night']
if not display_p:
ny_time = ny_time.replace("PM", "").replace("AM", "")
london_time = london_time.replace("PM", "").replace("AM", "")
draw.text((world_offset, 1), ny_time, ny_color, font_1)
draw.text((world_offset, 9), london_time, london_color, font_1)
draw.line([0,7,128,7],(50,50,50), width=1)
draw.text((3, 1), 'NEW YORK', time_colors1[worldcity_color], font_1)
draw.text((3, 9), 'LONDON', time_colors1[worldcity_color], font_1)
#If time now is greater than 1 second of the previously updated image time, update image and reset updated image time to another second
if time.time() >= the_time + 1:
the_time = time.time()
if counter == 0 or counter == 1:
draw.rectangle([(0,0),(128,16)], (0,0,0))
ny_time = datetime.now(pytz.timezone('America/New_York')).strftime(time_format)
london_time = datetime.now(pytz.timezone('Europe/London')).strftime(time_format)
ny_color = day_colors['day'] if isDaytime1(ny_time,twelvehours) else day_colors['night']
london_color = day_colors['day'] if isDaytime1(london_time,twelvehours) else day_colors['night']
if not display_p:
ny_time = ny_time.replace("PM", "").replace("AM", "")
london_time = london_time.replace("PM", "").replace("AM", "")
draw.text((world_offset, 1), ny_time, ny_color, font_1)
draw.text((world_offset, 9), london_time, london_color, font_1)
draw.line([0,7,128,7],(50,50,50), width=1)
draw.text((3, 1), 'NEW YORK', time_colors1[worldcity_color], font_1)
draw.text((3, 9), 'LONDON', time_colors1[worldcity_color], font_1)
elif counter == 2:
draw.rectangle([(0,0),(128,16)], (0,0,0))
tokyo_time = datetime.now(pytz.timezone('Asia/Tokyo')).strftime(time_format)
au_time = datetime.now(pytz.timezone('Australia/Sydney')).strftime(time_format)
tokyo_color = day_colors['day'] if isDaytime1(tokyo_time,twelvehours) else day_colors['night']
au_color = day_colors['day'] if isDaytime1(au_time,twelvehours) else day_colors['night']
if not display_p:
au_time = au_time.replace("PM", "").replace("AM", "")
tokyo_time = tokyo_time.replace("PM", "").replace("AM", "")
draw.text((world_offset, 1), tokyo_time, tokyo_color, font_1)
draw.text((world_offset, 9), au_time, au_color, font_1)
draw.line([0,7,128,7],(50,50,50), width=1)
draw.text((3, 1), 'TOKYO', time_colors1[worldcity_color], font_1)
draw.text((3, 9), 'SYDNEY', time_colors1[worldcity_color], font_1)
elif counter == 3:
draw.rectangle([(0,0),(128,16)], (0,0,0))
dubai_time = datetime.now(pytz.timezone('Asia/Dubai')).strftime(time_format)
la_time = datetime.now(pytz.timezone('America/Los_Angeles')).strftime(time_format)
dubai_color = day_colors['day'] if isDaytime1(dubai_time,twelvehours) else day_colors['night']
la_color = day_colors['day'] if isDaytime1(la_time,twelvehours) else day_colors['night']
if not display_p:
dubai_time = dubai_time.replace("PM", "").replace("AM", "")
la_time = la_time.replace("PM", "").replace("AM", "")
draw.text((world_offset, 1), dubai_time, dubai_color, font_1)
draw.text((world_offset, 9), la_time, la_color, font_1)
draw.line([0,7,128,7],(50,50,50), width=1)
draw.text((3, 1), 'DUBAI', time_colors1[worldcity_color], font_1)
draw.text((3, 9), 'LOS ANGELES', time_colors1[worldcity_color], font_1)
elif counter == 4:
draw.rectangle([(0,0),(128,16)], (0,0,0))
cn_time = datetime.now(pytz.timezone('Asia/Shanghai')).strftime(time_format)
paris_time = datetime.now(pytz.timezone('Europe/Paris')).strftime(time_format)
cn_color = day_colors['day'] if isDaytime1(cn_time,twelvehours) else day_colors['night']
paris_color = day_colors['day'] if isDaytime1(paris_time,twelvehours) else day_colors['night']
if not display_p:
cn_time = cn_time.replace("PM", "").replace("AM", "")
paris_time = paris_time.replace("PM", "").replace("AM", "")
draw.text((world_offset, 1), cn_time, cn_color, font_1)
draw.text((world_offset, 9), paris_time, paris_color, font_1)
draw.line([0,7,128,7],(50,50,50), width=1)
draw.text((3, 1), 'SHANGHAI', time_colors1[worldcity_color], font_1)
draw.text((3, 9), 'PARIS', time_colors1[worldcity_color], font_1)
elif counter == 5:
draw.rectangle([(0,0),(128,16)], (0,0,0))
in_time = datetime.now(pytz.timezone('Asia/Kolkata')).strftime(time_format)
auck_time = datetime.now(pytz.timezone('Pacific/Auckland')).strftime(time_format)
in_color = day_colors['day'] if isDaytime1(in_time,twelvehours) else day_colors['night']
auck_color = day_colors['day'] if isDaytime1(auck_time,twelvehours) else day_colors['night']
if not display_p:
in_time = in_time.replace("PM", "").replace("AM", "")
auck_time = auck_time.replace("PM", "").replace("AM", "")
draw.text((world_offset, 1), in_time, in_color, font_1)
draw.text((world_offset, 9), auck_time, auck_color, font_1)
draw.line([0,7,128,7],(50,50,50), width=1)
draw.text((3, 1), 'MUMBAI', time_colors1[worldcity_color], font_1)
draw.text((3, 9), 'AUCKLAND', time_colors1[worldcity_color], font_1)
elif counter == 6:
draw.rectangle([(0,0),(128,16)], (0,0,0))
bang_time = datetime.now(pytz.timezone('Asia/Bangkok')).strftime(time_format)
istan_time = datetime.now(pytz.timezone('Europe/Istanbul')).strftime(time_format)
bang_color = day_colors['day'] if isDaytime1(bang_time,twelvehours) else day_colors['night']
istan_color = day_colors['day'] if isDaytime1(istan_time,twelvehours) else day_colors['night']
if not display_p:
istan_time = istan_time.replace("PM", "").replace("AM", "")
bang_time = bang_time.replace("PM", "").replace("AM", "")
draw.text((world_offset, 1), bang_time, bang_color, font_1)
draw.text((world_offset, 9), istan_time, istan_color, font_1)
draw.line([0,7,128,7],(50,50,50), width=1)
draw.text((3, 1), 'BANGKOK', time_colors1[worldcity_color], font_1)
draw.text((3, 9), 'ISTANBUL', time_colors1[worldcity_color], font_1)
if the_time >= next_six_seconds:
counter += 1
next_six_seconds = the_time + 6
if counter > 6:
counter = 1
if time.time() - update_t1 > delay_t1:
update_t1 = time.time()
#Get the pause time right before image is done transitioning in
if offset_y1 == -1 or offset_x1 == 1:
pause_time = time.time() + pause1
if offset_y1 < 0:
offset_y1+=1
else: #If the scrolling reaches 0 pixel, pause it
if offset_x1 != 0:
offset_x1 -= 1
else:
try: #after the pause time, scroll iamge past 0 pixel to continue scrolling
if time.time() >= pause_time:
offset_x1 -= 1
except:
pass
#NORMAL SCROLLING
elif 'Clock' not in top[i1 % len(top)]:
if time.time() - update_t1 > delay_t1:
update_t1 = time.time()
if offset_y1 < 0:
offset_y1+=1
else:
offset_x1 -= 1
#BOTTOM ROW
if 'Clock' not in bottom[i2 % len(bottom)]:
if time.time() - update_t2 > delay_t2:
update_t2 = time.time()
if offset_y2 > 16:
offset_y2-=1
else:
offset_x2 -= 1
# SCROLL, DISPLAY, PAUSE CLOCK 2
elif bottom[i2 % len(bottom)] == 'Clock 2':
#Initial image generation so it doesn't appear blank for the first second
if offset_x2 == 128 or offset_y2 == 32:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
current_time_b = datetime.now(pytz.timezone(timezone1_b)).strftime(time_format_b + ",%a %d %b %Y").split(',')
time_t_b = current_time_b[0]
date_t_b = current_time_b[1].upper()
date_width_b, date_height_b = draw2.textsize(date_t_b, font2_b)
text_width_b, text_height_b = draw2.textsize(time_t_b, font_b)
draw2.text(((128-text_width_b)/2, -2), time_t_b, time_colors1[time_color1_b], font_b)
draw2.text(((128-date_width_b)/2, 8), date_t_b, time_colors1[date_color1_b], font2_b)
#If time now is greater than 1 second of the previously updated image time, update image and reset updated image time to another second
if time.time() >= the_time2 + 1:
the_time2 = time.time()
draw2.rectangle([(0,0),(128,16)], (0,0,0))
current_time_b = datetime.now(pytz.timezone(timezone1_b)).strftime(time_format_b + ",%a %d %b %Y").split(',')
time_t_b = current_time_b[0]
date_t_b = current_time_b[1].upper()
date_width_b, date_height_b = draw2.textsize(date_t_b, font2_b)
text_width_b, text_height_b = draw2.textsize(time_t_b, font_b)
draw2.text(((128-text_width_b)/2, -2), time_t_b, time_colors1[time_color1_b], font_b)
draw2.text(((128-date_width_b)/2, 8), date_t_b, time_colors1[date_color1_b], font2_b)
if time.time() - update_t2 > delay_t2:
update_t2 = time.time()
#Get the pause time right before image is done transitioning in
if offset_y2 == 17 or offset_x2 == 1:
pause_time2 = time.time() + pause2
if offset_y2 > 16:
offset_y2-=1
else: #If the scrolling reaches 0 pixel, pause it
if offset_x2 != 0:
offset_x2 -= 1
else:
try: #after the pause time, scroll iamge past 0 pixel to continue scrolling
if time.time() >= pause_time2:
offset_x2 -= 1
except:
pass
# SCROLL, DISPLAY, PAUSE CLOCK 1
elif bottom[i2 % len(bottom)] == 'Clock 1':
#Initial image generation so it doesn't appear blank for the first second
if offset_x2 == 128 or offset_y2 == 32:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
current_time_b = datetime.now(pytz.timezone(timezone2_b)).strftime(time_format_b + ",%A,%d %b").split(',')
time_t_b = current_time_b[0]
weekday_t_b = current_time_b[1].upper()
date_t_b = current_time_b[2].upper()
date_width_b, date_height_b = draw2.textsize(date_t_b, font_2_b)
wday_width_b, wday_height_b = draw2.textsize(weekday_t_b, font_2_b)
text_width_b, text_height_b = draw2.textsize(time_t_b, font_1_b)
total_width_b = text_width_b + 6 + max(wday_width_b, date_width_b)
starting_coord_b = (128-total_width_b)/2
draw2.text((starting_coord_b, 1), time_t_b, time_colors1[time_color2_b], font_1_b)
draw2.text((starting_coord_b + text_width_b + 6, 1), date_t_b, time_colors1[date_color2_b], font_2_b)
draw2.text((starting_coord_b + text_width_b + 7, 8), weekday_t_b, time_colors1[weekday_color2_b], font_2_b)
#If time now is greater than 1 second of the previously updated image time, update image and reset updated image time to another second
if time.time() >= the_time2 + 1:
the_time2 = time.time()
draw2.rectangle([(0,0),(128,16)], (0,0,0))
current_time_b = datetime.now(pytz.timezone(timezone2_b)).strftime(time_format_b + ",%A,%d %b").split(',')
time_t_b = current_time_b[0]
weekday_t_b = current_time_b[1].upper()
date_t_b = current_time_b[2].upper()
date_width_b, date_height_b = draw2.textsize(date_t_b, font_2_b)
wday_width_b, wday_height_b = draw2.textsize(weekday_t_b, font_2_b)
text_width_b, text_height_b = draw2.textsize(time_t_b, font_1_b)
total_width_b = text_width_b + 6 + max(wday_width_b, date_width_b)
starting_coord_b = (128-total_width_b)/2
draw2.text((starting_coord_b, 1), time_t_b, time_colors1[time_color2_b], font_1_b)
draw2.text((starting_coord_b + text_width_b + 6, 1), date_t_b, time_colors1[date_color2_b], font_2_b)
draw2.text((starting_coord_b + text_width_b + 7, 8), weekday_t_b, time_colors1[weekday_color2_b], font_2_b)
if time.time() - update_t2 > delay_t2:
update_t2 = time.time()
#Get the pause time right before image is done transitioning in
if offset_y2 == 17 or offset_x2 == 1:
pause_time2 = time.time() + pause2
if offset_y2 > 16:
offset_y2-=1
else: #If the scrolling reaches 0 pixel, pause it
if offset_x2 != 0:
offset_x2 -= 1
else:
try: #after the pause time, scroll iamge past 0 pixel to continue scrolling
if time.time() >= pause_time2:
offset_x2 -= 1
except:
pass
# SCROLL, DISPLAY, PAUSE WORLD CLOCK
elif bottom[i2 % len(bottom)] == 'World Clock':
#Initial image generation so it doesn't appear blank for the first second
if offset_x2 == 128 or offset_y2 == 32:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
ny_time_b = datetime.now(pytz.timezone('America/New_York')).strftime(time_format_b)
london_time_b = datetime.now(pytz.timezone('Europe/London')).strftime(time_format_b)
ny_color_b = day_colors['day'] if isDaytime1(ny_time_b,twelvehours_b) else day_colors['night']
london_color_b = day_colors['day'] if isDaytime1(london_time_b,twelvehours_b) else day_colors['night']
if not display_p_b:
ny_time_b = ny_time_b.replace("PM", "").replace("AM", "")
london_time_b = london_time_b.replace("PM", "").replace("AM", "")
draw2.text((world_offset_b, 1), ny_time_b, ny_color_b, font_12)
draw2.text((world_offset_b, 9), london_time_b, london_color_b, font_12)
draw2.line([0,7,128,7],(50,50,50), width=1)
draw2.text((3, 1), 'NEW YORK', time_colors1[worldcity_color2], font_12)
draw2.text((3, 9), 'LONDON', time_colors1[worldcity_color2], font_12)
#If time now is greater than 1 second of the previously updated image time, update image and reset updated image time to another second
if time.time() >= the_time2 + 1:
the_time2 = time.time()
if counter2 == 0 or counter2 == 1:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
ny_time_b = datetime.now(pytz.timezone('America/New_York')).strftime(time_format_b)
london_time_b = datetime.now(pytz.timezone('Europe/London')).strftime(time_format_b)
ny_color_b = day_colors['day'] if isDaytime1(ny_time_b,twelvehours_b) else day_colors['night']
london_color_b = day_colors['day'] if isDaytime1(london_time_b,twelvehours_b) else day_colors['night']
if not display_p_b:
ny_time_b = ny_time_b.replace("PM", "").replace("AM", "")
london_time_b = london_time_b.replace("PM", "").replace("AM", "")
draw2.text((world_offset_b, 1), ny_time_b, ny_color_b, font_12)
draw2.text((world_offset_b, 9), london_time_b, london_color_b, font_12)
draw2.line([0,7,128,7],(50,50,50), width=1)
draw2.text((3, 1), 'NEW YORK', time_colors1[worldcity_color2], font_12)
draw2.text((3, 9), 'LONDON', time_colors1[worldcity_color2], font_12)
elif counter2 == 2:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
tokyo_time_b = datetime.now(pytz.timezone('Asia/Tokyo')).strftime(time_format_b)
au_time_b = datetime.now(pytz.timezone('Australia/Sydney')).strftime(time_format_b)
tokyo_color_b = day_colors['day'] if isDaytime1(tokyo_time_b,twelvehours_b) else day_colors['night']
au_color_b = day_colors['day'] if isDaytime1(au_time_b,twelvehours_b) else day_colors['night']
if not display_p_b:
au_time_b = au_time_b.replace("PM", "").replace("AM", "")
tokyo_time_b = tokyo_time_b.replace("PM", "").replace("AM", "")
draw2.text((world_offset_b, 1), tokyo_time_b, tokyo_color_b, font_12)
draw2.text((world_offset_b, 9), au_time_b, au_color_b, font_12)
draw2.line([0,7,128,7],(50,50,50), width=1)
draw2.text((3, 1), 'TOKYO', time_colors1[worldcity_color2], font_12)
draw2.text((3, 9), 'SYDNEY', time_colors1[worldcity_color2], font_12)
elif counter2 == 3:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
dubai_time_b = datetime.now(pytz.timezone('Asia/Dubai')).strftime(time_format_b)
la_time_b = datetime.now(pytz.timezone('America/Los_Angeles')).strftime(time_format_b)
dubai_color_b = day_colors['day'] if isDaytime1(dubai_time_b,twelvehours_b) else day_colors['night']
la_color_b = day_colors['day'] if isDaytime1(la_time_b,twelvehours_b) else day_colors['night']
if not display_p_b:
dubai_time_b = dubai_time_b.replace("PM", "").replace("AM", "")
la_time_b = la_time_b.replace("PM", "").replace("AM", "")
draw2.text((world_offset_b, 1), dubai_time_b, dubai_color_b, font_12)
draw2.text((world_offset_b, 9), la_time_b, la_color_b, font_12)
draw2.line([0,7,128,7],(50,50,50), width=1)
draw2.text((3, 1), 'DUBAI', time_colors1[worldcity_color2], font_12)
draw2.text((3, 9), 'LOS ANGELES', time_colors1[worldcity_color2], font_12)
elif counter2 == 4:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
cn_time_b = datetime.now(pytz.timezone('Asia/Shanghai')).strftime(time_format_b)
paris_time_b = datetime.now(pytz.timezone('Europe/Paris')).strftime(time_format_b)
cn_color_b = day_colors['day'] if isDaytime1(cn_time_b,twelvehours_b) else day_colors['night']
paris_color_b = day_colors['day'] if isDaytime1(paris_time_b,twelvehours_b) else day_colors['night']
if not display_p_b:
cn_time_b = cn_time_b.replace("PM", "").replace("AM", "")
paris_time_b = paris_time_b.replace("PM", "").replace("AM", "")
draw2.text((world_offset_b, 1), cn_time_b, cn_color_b, font_12)
draw2.text((world_offset_b, 9), paris_time_b, paris_color_b, font_12)
draw2.line([0,7,128,7],(50,50,50), width=1)
draw2.text((3, 1), 'SHANGHAI', time_colors1[worldcity_color2], font_12)
draw2.text((3, 9), 'PARIS', time_colors1[worldcity_color2], font_12)
elif counter2 == 5:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
in_time_b = datetime.now(pytz.timezone('Asia/Kolkata')).strftime(time_format_b)
auck_time_b = datetime.now(pytz.timezone('Pacific/Auckland')).strftime(time_format_b)
in_color_b = day_colors['day'] if isDaytime1(in_time_b,twelvehours_b) else day_colors['night']
auck_color_b = day_colors['day'] if isDaytime1(auck_time_b,twelvehours_b) else day_colors['night']
if not display_p_b:
in_time_b = in_time_b.replace("PM", "").replace("AM", "")
auck_time_b = auck_time_b.replace("PM", "").replace("AM", "")
draw2.text((world_offset_b, 1), in_time_b, in_color_b, font_12)
draw2.text((world_offset_b, 9), auck_time_b, auck_color_b, font_12)
draw2.line([0,7,128,7],(50,50,50), width=1)
draw2.text((3, 1), 'MUMBAI', time_colors1[worldcity_color2], font_12)
draw2.text((3, 9), 'AUCKLAND', time_colors1[worldcity_color2], font_12)
elif counter2 == 6:
draw2.rectangle([(0,0),(128,16)], (0,0,0))
bang_time_b = datetime.now(pytz.timezone('Asia/Bangkok')).strftime(time_format_b)
istan_time_b = datetime.now(pytz.timezone('Europe/Istanbul')).strftime(time_format_b)
bang_color_b = day_colors['day'] if isDaytime1(bang_time_b,twelvehours_b) else day_colors['night']
istan_color_b = day_colors['day'] if isDaytime1(istan_time_b,twelvehours_b) else day_colors['night']
if not display_p_b:
istan_time_b = istan_time_b.replace("PM", "").replace("AM", "")
bang_time_b = bang_time_b.replace("PM", "").replace("AM", "")
draw2.text((world_offset_b, 1), bang_time_b, bang_color_b, font_12)
draw2.text((world_offset_b, 9), istan_time_b, istan_color_b, font_12)
draw2.line([0,7,128,7],(50,50,50), width=1)
draw2.text((3, 1), 'BANGKOK', time_colors1[worldcity_color2], font_12)
draw2.text((3, 9), 'ISTANBUL', time_colors1[worldcity_color2], font_12)
if the_time2 >= next_six_seconds2:
counter2 += 1
next_six_seconds2 = the_time2 + 6
if counter2 > 6:
counter2 = 1
if time.time() - update_t2 > delay_t2:
update_t2 = time.time()
#Get the pause time right before image is done transitioning in
if offset_y2 == 17 or offset_x2 == 1:
pause_time2 = time.time() + pause2
if offset_y2 > 16:
offset_y2-=1
else: #If the scrolling reaches 0 pixel, pause it
if offset_x2 != 0:
offset_x2 -= 1
else:
try: #after the pause time, scroll iamge past 0 pixel to continue scrolling
if time.time() >= pause_time2:
offset_x2 -= 1
except:
pass
if kill: break
# SCROLLING OF THE IMAGE
self.double_buffer.SetImage(image1, offset_x1, offset_y1)
self.double_buffer.SetImage(image2, offset_x2, offset_y2)
# remove the ppixels behind the image, to stop trailing
self.double_buffer = self.matrix.SwapOnVSync(self.double_buffer)
for y in range(16):
self.matrix.SetPixel(offset_x1 + img_width1 +1 , y , 0,0,0)
self.matrix.SetPixel(offset_x1 + img_width1 , y , 0,0,0)
for y in range(16,32):
self.matrix.SetPixel(offset_x2 + img_width2 +1 , y , 0,0,0)
self.matrix.SetPixel(offset_x2 + img_width2 , y , 0,0,0)
kill = self.checkKilled()
if kill: break
def scrollMultiple(self, animation = 'down'):
# scrolls trhough all functions with animation. Updates functions and remakes images when each function not being dispplayed
# read lines from csv
images = []
delays = []
kinds = []
f = open('csv/multiple.csv', 'r')
CSV = csv.reader(f)
next(CSV)
font = ImageFont.load("./fonts/texgyre-27.pil")
for row in CSV:
kind, content, delay = row
delays.append(delay)
kinds.append(kind)
if kind == 'text':
images.append(self.textImage(content, font, 255, 255, 0, True, w_buff = 50))
elif kind == 'image':
images.append(self.openImage(content).convert('RGB'))
elif kind == 'gif':
images.append(self.openImage(content))
f.close()
kill = False
i = 0 # keep track of which image we are displaying
self.double_buffer = self.matrix.CreateFrameCanvas()
while True:
image = images[i%len(images)]
delay = delays[i%len(images)]
kind = kinds[i%len(images)]
img_width, img_height = image.size
offset_x = 0
if animation == 'traditional':
offset_x = 128
elif animation == 'continuous':
offset_x = 0
elif animation in ['up', 'down']:
offset_x = max(0, 128-img_width)
offset_y = 0
#first scroll image in from bottom
frame_skip = int((1/15)/self.delay) #controls how fast gifs run
self.frame = 0
pause_frames = int(float(delay)/self.delay)
if animation == 'up':
offset_y = 33
direction = -1
kill = self.scrollImageY(image, direction = direction, offset_x = offset_x, offset_y = offset_y, frame_skip = frame_skip, gif = kind=='gif')
elif animation == 'down':
direction = 1
offset_y = -33
kill = self.scrollImageY(image, direction = direction, offset_x = offset_x, offset_y = offset_y, frame_skip = frame_skip, gif = kind=='gif')
offset_y = 0
if kill: break
kill = self.scrollImage(image, offset_x = offset_x, offset_y = offset_y, frame_skip = frame_skip, gif = kind=='gif', pause_frames = pause_frames)
if kill: break
i+=1
def textImage(self, text, font, r = 255, g = 255, b = 255, matrix_height = False, w_buff = 3, h_buff = 3, background = False, location = False):
#creates and returns a ppm image containing the text in the supplied font and colour
width, height = self.get_text_dimensions(text, font)
if matrix_height:
height = 32
img = Image.new('RGB', (width + w_buff, height + h_buff))
d = ImageDraw.Draw(img)
if background:
br, bg, bb = background
d.rectangle(xy = (0, 0, width + w_buff, height + h_buff),
fill = (br, bg, bb))
#outline = (255, 255, 255),
#width = 0) #use outline and width to add a border
if location:
d.text(location, text, fill=(r, g, b), font=font)
else:
d.text((0, 0), text, fill=(r, g, b), font=font)
return img
def getUserMessages(self):
#displays the text entered in the webpage by the user.
f = open('csv/message_settings.json', 'r')
all_settings = json.load(f)
f.close()
colours = {'Black':(0,0,0),
'White':(255,255,255),
'Red':(255,0,0),
'Green':(0,255,0),
'Dark Green':(0,100,0),
'Blue':(0,0,255),
'Purple':(145,0,255),
'Pink':(255,0,255),
'Yellow':(255,255,0),
'Orange':(255,130,0),
'Gold':(255,190,0),
'Gray':(100,100,100),
'Cyan':(0,255,255)}
imgs = []
for ind, message in enumerate(all_settings['messages']):
font = ImageFont.load("./fonts/10x20.pil")
location = (0, 4)
if message["size"] == 'Large':
font = ImageFont.load("./fonts/texgyre-27.pil")
location = (0, -2)
elif message["size"] == 'Small':
font = ImageFont.load("./fonts/6x13.pil")
location = (0, 7)
r,g,b = colours[message['text_colour']]
background = colours[message['background_colour']]
decoded = message['text'].encode("ascii","ignore")
message['text'] = decoded.decode()
img = self.textImage(message['text'], font, int(r), int(g), int(b), True, w_buff = 5, background = background, location = location)
if all_settings['title'] and ind == 0:
title_img = self.openImage('feature_titles/message.png')
imgs.append(self.stitchImage([title_img, img]))
else:
imgs.append(img)
return imgs
def getUserMessagesProfessional(self):
f = open('csv/message_settings.json', 'r')
all_settings = json.load(f)
f.close()
if all_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/message.png')
image_list = [title_img]
else:
image_list = []
colours = {'Black':(0,0,0),
'White':(255,255,255),
'Red':(255,0,0),
'Green':(0,255,0),
'Dark Green':(0,100,0),
'Blue':(0,0,255),
'Purple':(145,0,255),
'Pink':(255,0,255),
'Yellow':(255,255,0),
'Orange':(255,130,0),
'Gold':(255,190,0),
'Gray':(100,100,100),
'Cyan':(0,255,255)}
blank = Image.new('RGB', (0, 16))
for i, message in enumerate(all_settings['messages']):
if (i == len(all_settings['messages'])-1):
font = ImageFont.load("./fonts/6x13.pil")
location = (5, 2)
r,g,b = colours[message['text_colour']]
background = colours[message['background_colour']]
decoded = message['text'].encode("ascii","ignore")
message['text'] = decoded.decode()
msg_img = self.textImage(message['text'], font, int(r), int(g), int(b), True, w_buff = 11, background = background, location = location)
img = Image.new('RGB', (msg_img.size[0] + 5, 32))
img.paste(msg_img, (0,0))
image_list.append(img)
image_list.append(blank)
else:
font = ImageFont.load("./fonts/6x13.pil")
location = (5, 2)
r,g,b = colours[message['text_colour']]
background = colours[message['background_colour']]
decoded = message['text'].encode("ascii","ignore")
message['text'] = decoded.decode()
msg_img = self.textImage(message['text'], font, int(r), int(g), int(b), True, w_buff = 11, background = background, location = location)
img = Image.new('RGB', (msg_img.size[0] + 130, 32))
img.paste(msg_img, (0,0))
image_list.append(img)
image_list.append(blank)
return self.stitchImage(image_list)
def displayGIF(self, gif, delay = 0.5, repeat = True):
# To iterate through the entire gif
i = 0
while True:
try:
gif.seek(i)
except EOFError:
if not repeat: break
i = 0
gif.seek(i)
# do something to im
self.setImage(gif.convert('RGB'))
time.sleep(delay)
i += 1
try:
msg = getInput()
if msg == 'K':
gif.close()
self.resetMatrix()
break
self.process_msg(msg)
except KeyboardInterrupt:
sys.stdout.flush()
pass
def scrollGIF(self, gif, offset_x = 0, offset_y = 0):
# To iterate through the entire gif
i = 0
img_width, img_height = gif.size
while offset_x > -img_width:
offset_x -= 1
try:
gif.seek(i)
except EOFError:
i = 0
gif.seek(i)
# do something to im
self.setImage(gif.convert('RGB'), offset_x = offset_x)
time.sleep(self.delay)
if offset_x % 20 == 0:
i += 1
for x in range(offset_x + img_width, 128):
for y in range(self.matrix.height):
self.matrix.SetPixel(x , y , 0,0,0)
kill = self.checkKilled()
if kill:
break
return kill
#Using change between min and day price give appropriate arrow
#and set the overall change colour
def getArrow(self, CHANGE, professional = False):
self.greenORred
logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'stocks')
if(CHANGE>0):
Arrow = Image.open(os.path.join(logos_path, 'up-1.png'))
self.greenORred = (0, 255, 0)
else:
Arrow = Image.open(os.path.join(logos_path, 'down-1.png'))
self.greenORred = (255, 0, 0)
CHANGE = (CHANGE * -1)
if professional:
w, h = Arrow.size
Arrow = Arrow.resize((int(w/2), int(h/2)))
return Arrow, CHANGE
def get_text_dimensions(self, text_string, font):
canvas = Image.new('RGB', (10000,100))
draw = ImageDraw.Draw(canvas)
monospace = font
text = text_string
white = (255,255,255)
draw.text((0, 0), text, font=monospace, fill=white)
bbox = canvas.getbbox()
width = bbox[2]-bbox[0]
height = bbox[3]-bbox[1]
return width,height
#Draw Ticker, current and change onto one image
def textToImage(self, TICKER, CURRENT, ARROW, percent_change = False, point_change = False, font = ImageFont.load("./fonts/10x20.pil")):
w1, text_height = self.get_text_dimensions(TICKER, font)
w2, text_height = self.get_text_dimensions(CURRENT, font)
text_width_current = max(w1,w2)
img = Image.new('RGB', (text_width_current +1000 , 32))
d = ImageDraw.Draw(img)
d.text((4, 0), TICKER, fill=(255, 255, 255), font=font)
d.text((4, 16), CURRENT, fill=self.greenORred, font=font)
if percent_change:
d.text(((w1+7), 14 - text_height), percent_change, fill=self.greenORred, font=font)
w, h = self.get_text_dimensions(percent_change, font)
w1 += 7 + w
if point_change:
img.paste(ARROW, ((w2+ 9),18))
d.text(((w2+29), 16), point_change, fill=self.greenORred, font=font)
w,h = self.get_text_dimensions(point_change, font)
w2 += 29 + w
if not point_change and not percent_change:
img.paste(ARROW, ((w2+ 9),18))
w2 += ARROW.size[0] + 9
img = img.crop((0,0,max(w1, w2) + 8,32))
return img
def textToImageProf(self, TICKER, CURRENT, CHANGE, ARROW, font):
if 'E-MINI' in TICKER:
w1, text_height = self.get_text_dimensions(TICKER, font)
w2, text_height = self.get_text_dimensions(CURRENT, font)
text_width_current = max(w1,w2)
img = Image.new('RGB', (text_width_current +100 , 32))
d = ImageDraw.Draw(img)
d.text((4, 0), TICKER, fill=(255, 255, 255), font=font)
d.text((4, 8), CURRENT, fill=self.greenORred, font=font)
img.paste(ARROW, ((w2 + 7),10))
d.text(((w2+18), 8), CHANGE, fill=self.greenORred, font=font)
text_width_change, text_height = self.get_text_dimensions(CHANGE, font)
newWidth = max(w2 + text_width_change, text_width_current) +15
img = img.crop((0,0,newWidth,32))
elif 'display_name' in TICKER:
TICKER = TICKER.replace('display_name','')
w1, text_height = self.get_text_dimensions(TICKER, font)
w2, text_height = self.get_text_dimensions(CURRENT, font)
text_width_current = max(w1,w2)
img = Image.new('RGB', (text_width_current +100 , 32))
d = ImageDraw.Draw(img)
d.text((4, 0), TICKER, fill=(255, 255, 255), font=font)
d.text((4, 8), CURRENT, fill=self.greenORred, font=font)
img.paste(ARROW, ((w2 + 7),10))
d.text(((w2+18), 8), CHANGE, fill=self.greenORred, font=font)
text_width_change, text_height = self.get_text_dimensions(CHANGE, font)
newWidth = max(w2 + 15 + text_width_change, text_width_current) +15
img = img.crop((0,0,newWidth,32))
elif 'Sector' in CHANGE:
w1, text_height = self.get_text_dimensions(TICKER, font)
w2, text_height = self.get_text_dimensions(CURRENT, font)
text_width_current = max(w1,w2)
img = Image.new('RGB', (text_width_current +100 , 32))
d = ImageDraw.Draw(img)
d.text((4, 0), TICKER, fill=(255, 255, 255), font=font)
d.text((4, 8), CURRENT, fill=self.greenORred, font=font)
img.paste(ARROW, ((w2 + 7),10))
newWidth = max(w2 + ARROW.size[0] + 7, text_width_current) +15
img = img.crop((0,0,newWidth,32))
else:
text_width_current, text_height = self.get_text_dimensions(CURRENT, font)
img = Image.new('RGB', (text_width_current +100 , 32))
d = ImageDraw.Draw(img)
d.text((4, 0), TICKER, fill=(255, 255, 255), font=font)
d.text((4, 8), CURRENT, fill=self.greenORred, font=font)
img.paste(ARROW, ((text_width_current + 7),10))
d.text(((text_width_current+18), 8), CHANGE, fill=self.greenORred, font=font)
text_width_change, text_height = self.get_text_dimensions(CHANGE, font)
newWidth = text_width_current + text_width_change +30
img = img.crop((0,0,newWidth,32))
return img
#Stitch the logo & prices picture into one image
def stitchImage(self, image_list):
widths, heights = zip(*(i.size for i in image_list))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in image_list:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
return new_im
def resetMatrix(self):
for x in range(self.matrix.width):
for y in range(self.matrix.height):
self.matrix.SetPixel(x , y , 0,0,0)
def getCryptoImage(self):
f = open('csv/crypto_settings.json', 'r')
all_crypto_settings = json.load(f)
f.close()
if all_crypto_settings['title']:
title_img = self.openImage('feature_titles/crypto.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
if all_crypto_settings['chart']:
try:
f = open('csv/portfolio_crypto_settings.json', 'r')
portfolio_settings = json.load(f)['symbols']
f.close()
except:
pass
try:
if all_crypto_settings['display_name']:
names = True
else:
names = False
except:
names = False
pass
coin_info = all_crypto_settings['symbols']
coin_bases = list(coin_info.keys())
for i, cb in enumerate(coin_bases):
try:
ticker, base = cb.split(',')
current = float(coin_info[cb]["current"])
point_change = float(coin_info[cb]["24hr_change"])
point_change2 = abs(point_change)
point_changefinal = '{0:.10f}'.format(point_change2).rstrip("0")
current_final = '{0:.10f}'.format(current).rstrip("0")
percent_change = float(coin_info[cb]["percent_change"])
arrow, change = self.getArrow(point_change)
percent_change = '%.2f' % abs(percent_change) + '%'
num3 = point_changefinal.split('.')
if len(num3[1]) <= 1:
point_change = '%.2f' % float(point_changefinal)
else:
point_change = str(point_changefinal)
num2 = current_final.split('.')
if len(num2[1]) <= 1:
current = '%.2f' % float(current_final)
else:
current = str(current_final)
if not all_crypto_settings['percent']:
percent_change = False
if not all_crypto_settings['point']:
point_change = False
if names:
try:
ticker = coin_info[cb]['name'].upper()
midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT
except:
ticker, base = cb.split(',')
midFrame = self.textToImage(ticker + '(' + base + ')', current, arrow, percent_change, point_change) #IMAGE THE TEXT
else:
midFrame = self.textToImage(ticker + '(' + base + ')', current, arrow, percent_change, point_change) #IMAGE THE TEXT
if all_crypto_settings['logos']:
try:
ticker, base = cb.split(',')
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 Exception as e:
stitchedStock = midFrame
else:
stitchedStock = midFrame
try:
if all_crypto_settings['lohivol']:
font = ImageFont.load("./fonts/5x8.pil")
try:
day_low1 = '{0:.10f}'.format(float(coin_info[cb]['day_low'])).rstrip("0")
day_high1 = '{0:.10f}'.format(float(coin_info[cb]['day_high'])).rstrip("0")
day_low2 = day_low1.split('.')
day_high2 = day_high1.split('.')
if len(day_low2[1]) <= 1:
day_low = '%.2f' % float(day_low1)
else:
day_low = day_low1
if len(day_high2[1]) <= 1:
day_high = '%.2f' % float(day_high1)
else:
day_high = day_high1
volume = coin_info[cb]['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_img.size[0] + daylow_t_img.size[0], dayhi_img.size[0] + dayhi_t_img.size[0],
vol_img.size[0] + vol_t_img.size[0]) + 5, 32))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 12))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 12))
lohivol_img.paste(vol_t_img, (0, 21))
lohivol_img.paste(vol_img, (vol_t_img.size[0], 21))
except:
pass
except:
pass
try:
if all_crypto_settings['chart'] and (cb in portfolio_settings): #IF USER INPUTTED PORTFOLIO SETTINGS, DISPLAY PORTFOLIO INFO
try:
cost = portfolio_settings[cb]['cost']
day = portfolio_settings[cb]['day']
day_start = datetime.strptime(str(day), "%Y-%m-%d")
day_today = datetime.strptime(datetime.now(pytz.utc).strftime("%Y-%m-%d"), "%Y-%m-%d")
day = str((day_today - day_start).days)
shares = portfolio_settings[cb]['shares']
original_value = float(cost) * float(shares)
new_value = float(coin_info[cb]['current']) * float(shares)
value_day_change_percent = ((float(coin_info[cb]['percent_change'])/100) * new_value)
font = ImageFont.load("./fonts/5x8.pil")
cost_img = self.textImage('Cost', font, r = 255, g = 255 , b = 255)
cost2_img = self.textImage(cost, font, r = 0, g = 255, b = 0)
shares_img = self.textImage('Shares', font, r = 255, g = 255 , b = 255)
shares2_img = self.textImage(shares, font, r = 0, g = 255, b = 0)
pnlchange = new_value - original_value
pnlpercent = ((new_value - original_value) / original_value) * 100
pnlpercent_img = self.textImage('P/L%', font, r = 255, g = 255 , b = 255)
if pnlpercent >= 0:
pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 0, g = 255, b = 0)
else:
pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 255, g = 0, b = 0)
daypercent_img = self.textImage('Day%', font, r = 255, g = 255 , b = 255)
if float(coin_info[cb]['percent_change']) >= 0:
daypercent2_img = self.textImage(str('%.2f' % abs(float(coin_info[cb]['percent_change']))) +'%', font, r = 0, g = 255, b = 0)
else:
daypercent2_img = self.textImage(str('%.2f' % abs(float(coin_info[cb]['percent_change'])))+'%', font, r = 255, g = 0, b = 0)
days_img = self.textImage('Days', font, r = 255, g = 255 , b = 255)
days2_img = self.textImage(day, font, r = 0, g = 255, b = 0)
value_img = self.textImage('Value', font, r = 255, g = 255 , b = 255)
value2_img = self.textImage(str('%.2f' % abs(original_value)), font, r = 0, g = 255, b = 0)
pnlchange_img = self.textImage('P/L$', font, r = 255, g = 255 , b = 255)
if pnlchange >= 0:
pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 0, g = 255, b = 0)
else:
pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 255, g = 0, b = 0)
daychange_img = self.textImage('Day$', font, r = 255, g = 255 , b = 255)
if value_day_change_percent >= 0:
daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 0, g = 255, b = 0)
else:
daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 255, g = 0, b = 0)
x_offset = 0
img = Image.new('RGB', (max(cost_img.size[0], cost2_img.size[0], days_img.size[0], days2_img.size[0]) + 7 +
max(shares_img.size[0], shares2_img.size[0], value2_img.size[0], value_img.size[0]) + 7 +
max(pnlpercent_img.size[0], pnlpercent2_img.size[0], pnlchange_img.size[0], pnlchange2_img.size[0]) + 7 +
max(daypercent_img.size[0], daypercent2_img.size[0], daychange_img.size[0], daychange2_img.size[0]) + 15, 32))
img.paste(cost_img, (x_offset, 0))
img.paste(cost2_img, (x_offset, 8))
img.paste(days_img, (x_offset, 16))
img.paste(days2_img, (x_offset, 24))
x_offset += max(cost_img.size[0], cost2_img.size[0], days_img.size[0], days2_img.size[0]) + 7
img.paste(shares_img, (x_offset, 0))
img.paste(shares2_img, (x_offset, 8))
img.paste(value_img, (x_offset, 16))
img.paste(value2_img, (x_offset, 24))
x_offset += max(shares_img.size[0], shares2_img.size[0], value2_img.size[0], value_img.size[0]) + 7
img.paste(pnlpercent_img, (x_offset, 0))
img.paste(pnlpercent2_img, (x_offset, 8))
img.paste(pnlchange_img, (x_offset, 16))
img.paste(pnlchange2_img, (x_offset, 24))
x_offset += max(pnlpercent_img.size[0], pnlpercent2_img.size[0], pnlchange_img.size[0], pnlchange2_img.size[0]) + 7
img.paste(daypercent_img, (x_offset, 0))
img.paste(daypercent2_img, (x_offset, 8))
img.paste(daychange_img, (x_offset,16))
img.paste(daychange2_img, (x_offset, 24))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if all_crypto_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
try:
if all_crypto_settings['chart'] and (cb in portfolio_settings):
try:
image_list.append(img)
except:
pass
except:
pass
image_list.append(self.blank)
except Exception as e:
pass
finalDisplayImage = self.stitchImage(image_list)
return finalDisplayImage
def getCryptoProfessional(self):
self.blank = Image.new('RGB', (0, 16))
f = open('csv/crypto_settings.json', 'r')
all_crypto_settings = json.load(f)
f.close()
if all_crypto_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/crypto.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
if all_crypto_settings['chart']:
try:
f = open('csv/portfolio_crypto_settings.json', 'r')
portfolio_settings = json.load(f)['symbols']
f.close()
except:
pass
try:
if all_crypto_settings['display_name']:
names = True
else:
names = False
except:
names = False
pass
coin_info = all_crypto_settings['symbols']
coin_bases = list(coin_info.keys())
for i, cb in enumerate(coin_bases):
try:
ticker, base = cb.split(',')
current = float(coin_info[cb]["current"])
current_final = '{0:.10f}'.format(current).rstrip("0")
change = float(coin_info[cb]["24hr_change"])
change2 = abs(change)
changefinal = '{0:.10f}'.format(change2).rstrip("0")
arrow, change = self.getArrow(change, professional=True)
if all_crypto_settings["percent"]:
# convert percent to points
change = '%.2f' % abs(float(coin_info[cb]['percent_change'])) + '%'
else:
num3 = changefinal.split('.')
if len(num3[1]) <= 1:
change = '%.2f' % float(changefinal)
else:
change = str(changefinal)
num2 = current_final.split('.')
if len(num2[1]) <= 1:
current = '%.2f' % float(current_final)
else:
current = str(current_final)
if names:
try:
ticker = coin_info[cb]['name'].upper() + 'display_name'
midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
except:
ticker, base = cb.split(',')
midFrame = self.textToImageProf(ticker + '(' + base + ')', current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
else:
midFrame = self.textToImageProf(ticker + '(' + base + ')', current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
if all_crypto_settings['logos']:
try:
ticker, base = cb.split(',')
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
try:
if all_crypto_settings['lohivol']:
font = ImageFont.load("./fonts/4x6.pil")
try:
day_low1 = '{0:.10f}'.format(float(coin_info[cb]['day_low'])).rstrip("0")
day_high1 = '{0:.10f}'.format(float(coin_info[cb]['day_high'])).rstrip("0")
day_low2 = day_low1.split('.')
day_high2 = day_high1.split('.')
if len(day_low2[1]) <= 1:
day_low = '%.2f' % float(day_low1)
else:
day_low = day_low1
if len(day_high2[1]) <= 1:
day_high = '%.2f' % float(day_high1)
else:
day_high = day_high1
volume = coin_info[cb]['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0] + vol_img.size[0] + 8, 16))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 9))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 9))
lohivol_img.paste(vol_t_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0])+2, 3))
lohivol_img.paste(vol_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0], 3))
except:
pass
except:
pass
try:
if all_crypto_settings['chart'] and (cb in portfolio_settings): #IF USER INPUTTED PORTFOLIO SETTINGS, DISPLAY PORTFOLIO INFO
try:
cost = portfolio_settings[cb]['cost']
day = portfolio_settings[cb]['day']
day_start = datetime.strptime(str(day), "%Y-%m-%d")
day_today = datetime.strptime(datetime.now(pytz.utc).strftime("%Y-%m-%d"), "%Y-%m-%d")
day = str((day_today - day_start).days)
shares = portfolio_settings[cb]['shares']
original_value = float(cost) * float(shares)
new_value = float(coin_info[cb]['current']) * float(shares)
value_day_change_percent = ((float(coin_info[cb]['percent_change'])/100) * new_value)
font = ImageFont.load("./fonts/5x8.pil")
cost_img = self.textImage('Cost', font, r = 255, g = 255 , b = 255)
cost2_img = self.textImage(cost, font, r = 0, g = 255, b = 0)
shares_img = self.textImage('Shares', font, r = 255, g = 255 , b = 255)
shares2_img = self.textImage(shares, font, r = 0, g = 255, b = 0)
pnlchange = new_value - original_value
pnlpercent = ((new_value - original_value) / original_value) * 100
pnlpercent_img = self.textImage('P/L%', font, r = 255, g = 255 , b = 255)
if pnlpercent >= 0:
pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 0, g = 255, b = 0)
else:
pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 255, g = 0, b = 0)
daypercent_img = self.textImage('Day%', font, r = 255, g = 255 , b = 255)
if float(coin_info[cb]['percent_change']) >= 0:
daypercent2_img = self.textImage(str('%.2f' % abs(float(coin_info[cb]['percent_change']))) +'%', font, r = 0, g = 255, b = 0)
else:
daypercent2_img = self.textImage(str('%.2f' % abs(float(coin_info[cb]['percent_change'])))+'%', font, r = 255, g = 0, b = 0)
days_img = self.textImage('Days', font, r = 255, g = 255 , b = 255)
days2_img = self.textImage(day, font, r = 0, g = 255, b = 0)
value_img = self.textImage('Value', font, r = 255, g = 255 , b = 255)
value2_img = self.textImage(str('%.2f' % abs(original_value)), font, r = 0, g = 255, b = 0)
pnlchange_img = self.textImage('P/L$', font, r = 255, g = 255 , b = 255)
if pnlchange >= 0:
pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 0, g = 255, b = 0)
else:
pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 255, g = 0, b = 0)
daychange_img = self.textImage('Day$', font, r = 255, g = 255 , b = 255)
if value_day_change_percent >= 0:
daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 0, g = 255, b = 0)
else:
daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 255, g = 0, b = 0)
x_offset = 0
img = Image.new('RGB', (max(cost_img.size[0], cost2_img.size[0]) + 5 + max(days_img.size[0], days2_img.size[0]) + 5 +
max(shares_img.size[0], shares2_img.size[0]) + 5 + max(value2_img.size[0], value_img.size[0]) + 5 +
max(pnlpercent_img.size[0], pnlpercent2_img.size[0]) + 5 + max(pnlchange_img.size[0], pnlchange2_img.size[0]) + 5 +
max(daypercent_img.size[0], daypercent2_img.size[0]) + 5 + max(daychange_img.size[0], daychange2_img.size[0]) + 10,16))
img.paste(cost_img, (x_offset, 1))
img.paste(cost2_img, (x_offset, 9))
x_offset += max(cost_img.size[0], cost2_img.size[0]) + 4
img.paste(days_img, (x_offset, 1))
img.paste(days2_img, (x_offset, 9))
x_offset += max(days_img.size[0], days2_img.size[0]) + 4
img.paste(shares_img, (x_offset, 1))
img.paste(shares2_img, (x_offset, 9))
x_offset += max(shares_img.size[0], shares2_img.size[0]) + 4
img.paste(value_img, (x_offset, 1))
img.paste(value2_img, (x_offset, 9))
x_offset += max(value2_img.size[0], value_img.size[0]) + 4
img.paste(pnlpercent_img, (x_offset, 1))
img.paste(pnlpercent2_img, (x_offset, 9))
x_offset += max(pnlpercent_img.size[0], pnlpercent2_img.size[0]) + 4
img.paste(pnlchange_img, (x_offset, 1))
img.paste(pnlchange2_img, (x_offset, 9))
x_offset += max(pnlchange_img.size[0], pnlchange2_img.size[0]) + 4
img.paste(daypercent_img, (x_offset, 1))
img.paste(daypercent2_img, (x_offset, 9))
x_offset += max(daypercent_img.size[0], daypercent2_img.size[0]) + 4
img.paste(daychange_img, (x_offset,1))
img.paste(daychange2_img, (x_offset, 9))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if all_crypto_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
try:
if all_crypto_settings['chart'] and (cb in portfolio_settings):
try:
image_list.append(img)
except:
pass
except:
pass
image_list.append(self.blank)
except Exception as e:
pass
finalDisplayImage = self.stitchImage(image_list)
self.blank = Image.new('RGB', (10, 32))
return finalDisplayImage
def getIndicesImage(self):
f = open('csv/indices_settings.json', 'r')
all_indices_settings = json.load(f)
f.close()
if all_indices_settings['title']:
title_img = self.openImage('feature_titles/indices.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
index_info = all_indices_settings['symbols']
symbols = list(index_info.keys())
for i, symbol in enumerate(symbols):
try:
info = index_info[symbol]
change = float(info['point_change']) #TEXT
symb = symbol
ticker = info['name'] #TEXT
arrow, change = self.getArrow(change)
point_change = '%.2f' % abs(change)
percent_change = '%.2f' % abs(float(info['percent_change'])) + '%'
# point_change2 = abs(change)
# point_changefinal = '{0:.10f}'.format(point_change2).rstrip("0")
# point_change = str(point_changefinal)
current = '%.2f' % float(info['current'])
# current_final = '{0:.10f}'.format(current).rstrip("0")
# current = str(current_final)
if not all_indices_settings['percent']:
percent_change = False
if not all_indices_settings['point']:
point_change = False
midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT
if all_indices_settings['logos']:
try:
logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'indices')
logo = self.openImage(os.path.join(logos_path, symb + '.png'))
stitchedIndex = self.stitchImage([logo,midFrame])
except Exception as e:
stitchedIndex = midFrame
else:
stitchedIndex = midFrame
image_list.append(stitchedIndex)
image_list.append(self.blank)
except Exception as e:
pass
finalDisplayImage = self.stitchImage(image_list)
return finalDisplayImage
def getIndicesProfessional(self):
self.blank = Image.new('RGB', (0, 16))
f = open('csv/indices_settings.json', 'r')
all_indices_settings = json.load(f)
f.close()
if all_indices_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/indices.png')
image_list = [title_img, Image.new('RGB', (5, 16))]
image_list.append(self.blank)
else:
image_list = []
index_info = all_indices_settings['symbols']
symbols = list(index_info.keys())
for i, symbol in enumerate(symbols):
try:
info = index_info[symbol]
change = float(info['point_change']) #TEXT
symb = symbol
ticker = info['name'] #TEXT
arrow, change = self.getArrow(change, professional=True)
if all_indices_settings["percent"]:
change = '%.2f' % abs(float(info['percent_change'])) + '%'
else:
change = '%.2f' % abs(change)
current = '%.2f' % float(info['current'])
midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
if all_indices_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_indices')
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'), 'indices')
logo = Image.open(os.path.join(logos_path, symb + '.png'))
# half the size of the logo
width, height = logo.size
logo = logo.resize((int(width/2), int(height/2)))
stitchedIndex = self.stitchImage([logo,midFrame])
except Exception as e:
stitchedIndex = midFrame
else:
stitchedIndex = midFrame
image_list.append(stitchedIndex)
image_list.append(self.blank)
except Exception as e:
pass
finalDisplayImage = self.stitchImage(image_list)
self.blank = Image.new('RGB', (10, 32))
return finalDisplayImage
def getCommoditiesImage(self):
f = open('csv/commodities_settings.json', 'r')
all_commodities_settings = json.load(f)
f.close()
if all_commodities_settings['title']:
title_img = self.openImage('feature_titles/commodities.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
commodity_info = all_commodities_settings['symbols']
symbols = list(commodity_info.keys())
for i, symbol in enumerate(symbols):
try:
info = commodity_info[symbol]
change = float(info['24hr_change']) #TEXT
ticker = symbol #TEXT
unit = info['unit']
ticker = symbol + '(' + unit + ')' #TEXT
arrow, change = self.getArrow(change)
percent_change = '%.2f' % abs(float(info['percent_change'])) + '%'
point_change2 = abs(change)
point_changefinal = '{0:.10f}'.format(point_change2).rstrip("0")
num3 = point_changefinal.split('.')
if len(num3[1]) <= 1:
point_change = '%.2f' % float(point_changefinal)
else:
point_change = str(point_changefinal)
current = float(info["current"])
current_final = '{0:.10f}'.format(current).rstrip("0")
num2 = current_final.split('.')
if len(num2[1]) <= 1:
current = '%.2f' % float(current_final)
else:
current = str(current_final)
if not all_commodities_settings['percent']:
percent_change = False
if not all_commodities_settings['point']:
point_change = False
midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT
if all_commodities_settings['logos']:
try:
logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'commodities')
logo = self.openImage(os.path.join(logos_path, ticker + '.png'))
stitchedCommodity = self.stitchImage([logo,midFrame])
except Exception as e:
stitchedCommodity = midFrame
else:
stitchedCommodity = midFrame
image_list.append(stitchedCommodity)
image_list.append(self.blank)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
finalDisplayImage = self.stitchImage(image_list)
return finalDisplayImage
def getCommoditiesProfessional(self):
self.blank = Image.new('RGB', (0, 16))
f = open('csv/commodities_settings.json', 'r')
all_commodities_settings = json.load(f)
f.close()
if all_commodities_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/commodities.png')
image_list = [title_img, Image.new('RGB', (5, 16))]
image_list.append(self.blank)
else:
image_list = []
commodity_info = all_commodities_settings['symbols']
symbols = list(commodity_info.keys())
for i, symbol in enumerate(symbols):
try:
info = commodity_info[symbol]
change = float(info['24hr_change']) #TEXT
unit = info['unit']
ticker = symbol + '(' + unit + ')' #TEXT
arrow, change = self.getArrow(change, professional=True)
if all_commodities_settings["percent"]:
change = '%.2f' % abs(float(info['percent_change'])) + '%'
else:
point_change2 = abs(change)
point_changefinal = '{0:.10f}'.format(point_change2).rstrip("0")
num3 = point_changefinal.split('.')
if len(num3[1]) <= 1:
change = '%.2f' % float(point_changefinal)
else:
change = str(point_changefinal)
current = float(info["current"])
current_final = '{0:.10f}'.format(current).rstrip("0")
num2 = current_final.split('.')
if len(num2[1]) <= 1:
current = '%.2f' % float(current_final)
else:
current = str(current_final)
midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
if all_commodities_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_commodities')
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'), 'commodities')
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)))
stitchedCommodity = self.stitchImage([logo,midFrame])
except Exception as e:
stitchedCommodity = midFrame
else:
stitchedCommodity = midFrame
image_list.append(stitchedCommodity)
image_list.append(self.blank)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
finalDisplayImage = self.stitchImage(image_list)
self.blank = Image.new('RGB', (10, 32))
return finalDisplayImage
def getForexImage(self):
f = open('csv/forex_settings.json', 'r')
all_forex_settings = json.load(f)
f.close()
if all_forex_settings['title']:
title_img = self.openImage('feature_titles/forex.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
forex_settings = all_forex_settings['symbols']
symbol_bases = list(forex_settings.keys())
for i, sb in enumerate(symbol_bases):
try:
symbol, base = sb.split(',')
current = float(forex_settings[sb]['current'])
current_final = '{0:.10f}'.format(current).rstrip("0")
change = float(forex_settings[sb]['24hr_change'])
change2 = abs(change)
changefinal = '{0:.10f}'.format(change2).rstrip("0")
percent_change = '%.2f' % abs(float(forex_settings[sb]['percent_change'])) +'%'
point_change = str(changefinal)
if not all_forex_settings['percent']:
percent_change = False
if not all_forex_settings['point']:
point_change = False
arrow, change = self.getArrow(change)
current = str(current_final)
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.upper() + '.png'))
bse = Image.open(os.path.join(logos_path, base.upper() + '.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:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
image_list.append(midFrame)
image_list.append(self.blank)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
finalDisplayImage = self.stitchImage(image_list)
return finalDisplayImage
def getForexProfessional(self):
self.blank = Image.new('RGB', (0, 16))
f = open('csv/forex_settings.json', 'r')
all_forex_settings = json.load(f)
f.close()
if all_forex_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/forex.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
forex_settings = all_forex_settings['symbols']
symbol_bases = list(forex_settings.keys())
for i, sb in enumerate(symbol_bases):
try:
symbol, base = sb.split(',')
current = float(forex_settings[sb]['current'])
current_final = '{0:.10f}'.format(current).rstrip("0")
change = float(forex_settings[sb]['24hr_change'])
change2 = abs(change)
changefinal = '{0:.10f}'.format(change2).rstrip("0")
arrow, change = self.getArrow(change, professional = True)
if all_forex_settings["percent"]:
change = abs(float(forex_settings[sb]['percent_change']))
change = '%.2f' % change + '%'
else:
change = str(changefinal)
current = str(current_final)
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.upper() + '.png'))
bse = Image.open(os.path.join(logos_path, base.upper() + '.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'))
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)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
image_list.append(midFrame)
image_list.append(self.blank)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
finalDisplayImage = self.stitchImage(image_list)
self.blank = Image.new('RGB', (10, 32))
return finalDisplayImage
def getStockImage(self):
f = open('csv/stocks_settings.json', 'r')
all_stocks_settings = json.load(f)
f.close()
if all_stocks_settings['title']:
title_img = self.openImage('feature_titles/stocks.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
if all_stocks_settings['chart']:
try:
f = open('csv/portfolio_settings.json', 'r')
portfolio_settings = json.load(f)['symbols']
f.close()
except:
pass
try:
if all_stocks_settings['prepost']:
try:
f = open('csv/prepost_settings.json', 'r')
prepost_settings = json.load(f)
f.close()
except:
pass
except:
pass
try:
if all_stocks_settings['display_name']:
names = True
else:
names = False
except:
names = False
pass
stock_info = all_stocks_settings['symbols']
symbols = list(stock_info.keys())
timenow = datetime.now(ny_zone).replace(tzinfo=None).strftime("%H:%M:%S")
weekday = datetime.now(ny_zone).replace(tzinfo=None).weekday()
for i, symbol in enumerate(symbols):
try:
info = stock_info[symbol]
change = float(info['change']) #TEXT
if names:
try:
ticker = info['name'].upper() #TEXT
except:
ticker = symbol
else:
ticker = symbol
arrow, change = self.getArrow(change)
percent_change = '%.2f' % abs(float(info['percent_change'])) + '%'
point_change = '%.2f' % abs(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:
ticker = symbol
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:
stitchedStock = midFrame
else:
stitchedStock = midFrame
try:
if all_stocks_settings['lohivol']:
font = ImageFont.load("./fonts/5x8.pil")
try:
day_low = '%.2f' % float(info['day_low'])
day_high = '%.2f' % float(info['day_high'])
volume = info['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_img.size[0] + daylow_t_img.size[0], dayhi_img.size[0] + dayhi_t_img.size[0],
vol_img.size[0] + vol_t_img.size[0]) + 5, 32))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 12))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 12))
lohivol_img.paste(vol_t_img, (0, 21))
lohivol_img.paste(vol_img, (vol_t_img.size[0], 21))
except:
pass
except:
pass
try:
if all_stocks_settings['prepost']:
font = ImageFont.load("./fonts/6x13.pil")
time_font = ImageFont.load("./fonts/5x8.pil")
prepost_time = prepost_settings[symbol]['time_now']
if ((timenow < "09:30:00" and timenow > "04:00:00") and (weekday <= 4)): #premarket
try:
preprice = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['preprice']))
prechange = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['prechange']))
prepercent = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['prepercent']))
premkt_img = self.textImage('Pre-Mkt', font, r=255, g=255, b=255)
if '-' in prepost_settings[symbol]['Pre-market']['prechange']:
preprice_img = self.textImage(preprice, font, r = 255, g = 0 , b = 0)
prechange_img = self.textImage(prechange, font, r = 255, g = 0, b = 0)
prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=255, g=0, b=0)
arrow = Image.open('logos/down-tiny.png')
elif prepost_settings[symbol]['Pre-market']['prechange'] == '0.00':
preprice_img = self.textImage(preprice, font, r = 200, g = 200 , b = 200)
prechange_img = self.textImage(prechange, font, r = 200, g = 200, b = 200)
prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=200, g=200, b=200)
arrow = Image.open('logos/up-tiny2.png')
else:
preprice_img = self.textImage(preprice, font, r = 0, g = 255 , b = 0)
prechange_img = self.textImage(prechange, font, r = 0, g = 255, b = 0)
prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=0, g=255, b=0)
arrow = Image.open('logos/up-tiny.png')
time_img = self.textImage(prepost_time, time_font, r=255,g=255,b=255)
prepost_img = Image.new('RGB', (10 + max(premkt_img.size[0] + prepercent_img.size[0], preprice_img.size[0] + 3 + prechange_img.size[0] + arrow.size[0]),32))
prepost_img.paste(premkt_img, (0,0))
prepost_img.paste(prepercent_img, (premkt_img.size[0], 1))
prepost_img.paste(preprice_img,(0,12))
prepost_img.paste(time_img, (0, 24))
prepost_img.paste(arrow, (preprice_img.size[0],18))
prepost_img.paste(prechange_img, (preprice_img.size[0] + arrow.size[0] + 3,12))
except:
pass
elif ((timenow < "04:00:00" or timenow > "16:00:00") and (weekday <= 4)) or (weekday > 4): #postmarket
try:
postprice = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postprice']))
postchange = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postchange']))
postpercent = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postpercent']))
postmkt_img = self.textImage('After-Hrs', font, r=255, g=255, b=255)
if '-' in prepost_settings[symbol]['Post-market']['postchange']:
postprice_img = self.textImage(postprice, font, r = 255, g = 0, b = 0)
postchange_img = self.textImage(postchange, font, r = 255, g = 0, b = 0)
postpercent_img = self.textImage('('+postpercent +'%'+')', font, r=255, g=0, b=0)
arrow = Image.open('logos/down-tiny.png')
elif prepost_settings[symbol]['Post-market']['postchange'] == '0.00':
postprice_img = self.textImage(postprice, font, r = 200, g = 200 , b = 200)
postchange_img = self.textImage(postchange, font, r = 200, g = 200, b = 200)
postpercent_img = self.textImage('('+postpercent + '%' + ')', font, r=200, g=200, b=200)
arrow = Image.open('logos/up-tiny2.png')
else:
postprice_img = self.textImage(postprice, font, r =0, g = 255 , b = 0)
postchange_img = self.textImage(postchange, font, r = 0, g = 255, b = 0)
postpercent_img = self.textImage('(' + postpercent + '%'+')', font, r=0, g=255, b=0)
arrow = Image.open('logos/up-tiny.png')
time_img = self.textImage(prepost_time, time_font, r=255,g=255,b=255)
prepost_img = Image.new('RGB', (10 + max(postmkt_img.size[0] + postpercent_img.size[0], postprice_img.size[0] + 3 + postchange_img.size[0] + arrow.size[0]) , 32))
prepost_img.paste(postmkt_img, (0,0))
prepost_img.paste(postpercent_img, (postmkt_img.size[0], 1))
prepost_img.paste(postprice_img,(0,12))
prepost_img.paste(time_img, (0, 24))
prepost_img.paste(arrow, (postprice_img.size[0],18))
prepost_img.paste(postchange_img, (postprice_img.size[0] + arrow.size[0] + 3,12))
except:
pass
except:
pass
try:
if all_stocks_settings['chart'] and (symbol in portfolio_settings): #IF USER INPUTTED PORTFOLIO SETTINGS, DISPLAY PORTFOLIO INFO
try:
cost = portfolio_settings[symbol]['cost']
day = portfolio_settings[symbol]['day']
day_start = datetime.strptime(str(day), "%Y-%m-%d")
day_today = datetime.strptime(datetime.now(pytz.utc).strftime("%Y-%m-%d"), "%Y-%m-%d")
day = str((day_today - day_start).days)
shares = portfolio_settings[symbol]['shares']
original_value = float(cost) * float(shares)
new_value = float(info['current']) * float(shares)
value_day_change_percent = ((float(info['percent_change'])/100) * new_value)
font = ImageFont.load("./fonts/5x8.pil")
cost_img = self.textImage('Cost', font, r = 255, g = 255 , b = 255)
cost2_img = self.textImage(cost, font, r = 0, g = 255, b = 0)
shares_img = self.textImage('Shares', font, r = 255, g = 255 , b = 255)
shares2_img = self.textImage(shares, font, r = 0, g = 255, b = 0)
pnlchange = new_value - original_value
pnlpercent = ((new_value - original_value) / original_value) * 100
pnlpercent_img = self.textImage('P/L%', font, r = 255, g = 255 , b = 255)
if pnlpercent >= 0:
pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 0, g = 255, b = 0)
else:
pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 255, g = 0, b = 0)
daypercent_img = self.textImage('Day%', font, r = 255, g = 255 , b = 255)
if float(info['percent_change']) >= 0:
daypercent2_img = self.textImage(str('%.2f' % abs(float(info['percent_change']))) +'%', font, r = 0, g = 255, b = 0)
else:
daypercent2_img = self.textImage(str('%.2f' % abs(float(info['percent_change'])))+'%', font, r = 255, g = 0, b = 0)
days_img = self.textImage('Days', font, r = 255, g = 255 , b = 255)
days2_img = self.textImage(day, font, r = 0, g = 255, b = 0)
value_img = self.textImage('Value', font, r = 255, g = 255 , b = 255)
value2_img = self.textImage(str('%.2f' % abs(original_value)), font, r = 0, g = 255, b = 0)
pnlchange_img = self.textImage('P/L$', font, r = 255, g = 255 , b = 255)
if pnlchange >= 0:
pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 0, g = 255, b = 0)
else:
pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 255, g = 0, b = 0)
daychange_img = self.textImage('Day$', font, r = 255, g = 255 , b = 255)
if value_day_change_percent >= 0:
daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 0, g = 255, b = 0)
else:
daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 255, g = 0, b = 0)
x_offset = 0
img = Image.new('RGB', (max(cost_img.size[0], cost2_img.size[0], days_img.size[0], days2_img.size[0]) + 7 +
max(shares_img.size[0], shares2_img.size[0], value2_img.size[0], value_img.size[0]) + 7 +
max(pnlpercent_img.size[0], pnlpercent2_img.size[0], pnlchange_img.size[0], pnlchange2_img.size[0]) + 7 +
max(daypercent_img.size[0], daypercent2_img.size[0], daychange_img.size[0], daychange2_img.size[0]) + 15, 32))
img.paste(cost_img, (x_offset, 0))
img.paste(cost2_img, (x_offset, 8))
img.paste(days_img, (x_offset, 16))
img.paste(days2_img, (x_offset, 24))
x_offset += max(cost_img.size[0], cost2_img.size[0], days_img.size[0], days2_img.size[0]) + 7
img.paste(shares_img, (x_offset, 0))
img.paste(shares2_img, (x_offset, 8))
img.paste(value_img, (x_offset, 16))
img.paste(value2_img, (x_offset, 24))
x_offset += max(shares_img.size[0], shares2_img.size[0], value2_img.size[0], value_img.size[0]) + 7
img.paste(pnlpercent_img, (x_offset, 0))
img.paste(pnlpercent2_img, (x_offset, 8))
img.paste(pnlchange_img, (x_offset, 16))
img.paste(pnlchange2_img, (x_offset, 24))
x_offset += max(pnlpercent_img.size[0], pnlpercent2_img.size[0], pnlchange_img.size[0], pnlchange2_img.size[0]) + 7
img.paste(daypercent_img, (x_offset, 0))
img.paste(daypercent2_img, (x_offset, 8))
img.paste(daychange_img, (x_offset,16))
img.paste(daychange2_img, (x_offset, 24))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if all_stocks_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
try:
if all_stocks_settings['prepost']:
try:
image_list.append(prepost_img)
except:
pass
except:
pass
try:
if all_stocks_settings['chart'] and (symbol in portfolio_settings):
try:
image_list.append(img)
except:
pass
except:
pass
image_list.append(self.blank)
except Exception as e:
pass
finalDisplayImage = self.stitchImage(image_list)
return finalDisplayImage
def getStockProfessional(self):
self.blank = Image.new('RGB', (0, 16))
f = open('csv/stocks_settings.json', 'r')
all_stocks_settings = json.load(f)
f.close()
if all_stocks_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/stocks.png')
image_list = [title_img, Image.new('RGB', (5, 16))]
image_list.append(self.blank)
else:
image_list = []
if all_stocks_settings['chart']:
try:
f = open('csv/portfolio_settings.json', 'r')
portfolio_settings = json.load(f)['symbols']
f.close()
except:
pass
try:
if all_stocks_settings['prepost']:
try:
f = open('csv/prepost_settings.json', 'r')
prepost_settings = json.load(f)
f.close()
except:
pass
except:
pass
try:
if all_stocks_settings['display_name']:
names = True
else:
names = False
except:
names = False
pass
stock_info = all_stocks_settings['symbols']
symbols = list(stock_info.keys())
timenow = datetime.now(ny_zone).replace(tzinfo=None).strftime("%H:%M:%S")
weekday = datetime.now(ny_zone).replace(tzinfo=None).weekday()
for i, symbol in enumerate(symbols):
try:
info = stock_info[symbol]
change = float(info['change'])#TEXT
if names:
try:
ticker = info['name'].upper() + 'display_name' #TEXT
except:
ticker = symbol
else:
ticker = symbol
arrow, change = self.getArrow(change, professional=True)
if all_stocks_settings["percent"]:
change = '%.2f' % abs(float(info['percent_change'])) + '%'
else:
change = '%.2f' % abs(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']:
ticker = symbol
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
try:
if all_stocks_settings['lohivol']:
font = ImageFont.load("./fonts/4x6.pil")
try:
day_low = '%.2f' % float(info['day_low'])
day_high = '%.2f' % float(info['day_high'])
volume = info['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0] + vol_img.size[0] + 8, 16))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 9))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 9))
lohivol_img.paste(vol_t_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0])+2, 3))
lohivol_img.paste(vol_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0], 3))
except:
pass
except:
pass
try:
if all_stocks_settings['prepost']:
font = ImageFont.load("./fonts/5x8.pil")
# prepost_time = prepost_settings[symbol]['time_now']
if ((timenow < "09:30:00" and timenow > "04:00:00") and (weekday <= 4)): #premarket
try:
preprice = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['preprice']))
prechange = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['prechange']))
prepercent = '%.2f' % abs(float(prepost_settings[symbol]['Pre-market']['prepercent']))
premkt_img = self.textImage('Pre-Mkt', font, r=255, g=255, b=255)
if '-' in prepost_settings[symbol]['Pre-market']['prechange']:
preprice_img = self.textImage(preprice, font, r = 255, g = 0 , b = 0)
prechange_img = self.textImage(prechange, font, r = 255, g = 0, b = 0)
prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=255, g=0, b=0)
arrow = Image.open('logos/down-tiny.png')
elif prepost_settings[symbol]['Pre-market']['prechange'] == '0.00':
preprice_img = self.textImage(preprice, font, r = 200, g = 200 , b = 200)
prechange_img = self.textImage(prechange, font, r = 200, g = 200, b = 200)
prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=200, g=200, b=200)
arrow = Image.open('logos/up-tiny2.png')
else:
preprice_img = self.textImage(preprice, font, r = 0, g = 255 , b = 0)
prechange_img = self.textImage(prechange, font, r = 0, g = 255, b = 0)
prepercent_img = self.textImage('('+prepercent + '%' + ')', font, r=0, g=255, b=0)
arrow = Image.open('logos/up-tiny.png')
# time_img = self.textImage(prepost_time, font, r=255,g=255,b=255)
prepost_img = Image.new('RGB', (max(premkt_img.size[0] + prepercent_img.size[0], preprice_img.size[0] + 2 + prechange_img.size[0] + arrow.size[0]) + 10, 16))
prepost_img.paste(premkt_img, (0,0))
prepost_img.paste(prepercent_img, (premkt_img.size[0], 0))
prepost_img.paste(preprice_img,(0,7))
# prepost_img.paste(time_img, (preprice_img.size[0] + prechange_img.size[0] + 2 + arrow.size[0], 8))
prepost_img.paste(arrow, (preprice_img.size[0],10))
prepost_img.paste(prechange_img, (preprice_img.size[0] + arrow.size[0] + 2,7))
except:
pass
elif ((timenow < "04:00:00" or timenow > "16:00:00") and (weekday <= 4)) or (weekday > 4): #postmarket
try:
postprice = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postprice']))
postchange = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postchange']))
postpercent = '%.2f' % abs(float(prepost_settings[symbol]['Post-market']['postpercent']))
postmkt_img = self.textImage('After-Hrs', font, r=255, g=255, b=255)
if '-' in prepost_settings[symbol]['Post-market']['postchange']:
postprice_img = self.textImage(postprice, font, r = 255, g = 0, b = 0)
postchange_img = self.textImage(postchange, font, r = 255, g = 0, b = 0)
postpercent_img = self.textImage('('+postpercent +'%'+')', font, r=255, g=0, b=0)
arrow = Image.open('logos/down-tiny.png')
elif prepost_settings[symbol]['Post-market']['postchange'] == '0.00':
postprice_img = self.textImage(postprice, font, r = 200, g = 200, b = 200)
postchange_img = self.textImage(postchange, font, r = 200, g = 200, b = 200)
postpercent_img = self.textImage('('+postpercent +'%'+')', font, r=200, g=200, b=200)
arrow = Image.open('logos/up-tiny2.png')
else:
postprice_img = self.textImage(postprice, font, r =0, g = 255 , b = 0)
postchange_img = self.textImage(postchange, font, r = 0, g = 255, b = 0)
postpercent_img = self.textImage('(' + postpercent + '%'+')', font, r=0, g=255, b=0)
arrow = Image.open('logos/up-tiny.png')
#time_img = self.textImage(prepost_time, font, r=255,g=255,b=255)
prepost_img = Image.new('RGB', (10 + max(postmkt_img.size[0] + postpercent_img.size[0], postprice_img.size[0] + 2 + postchange_img.size[0] + arrow.size[0]) , 16))
prepost_img.paste(postmkt_img, (0,0))
prepost_img.paste(postpercent_img, (postmkt_img.size[0], 0))
prepost_img.paste(postprice_img,(0,7))
#prepost_img.paste(time_img, (0, 12))
prepost_img.paste(arrow, (postprice_img.size[0],10))
prepost_img.paste(postchange_img, (postprice_img.size[0] + arrow.size[0] + 2,7))
except:
pass
except:
pass
try:
if all_stocks_settings['chart'] and (symbol in portfolio_settings): #IF USER INPUTTED PORTFOLIO SETTINGS, DISPLAY PORTFOLIO INFO
try:
cost = portfolio_settings[symbol]['cost']
day = portfolio_settings[symbol]['day']
day_start = datetime.strptime(str(day), "%Y-%m-%d")
day_today = datetime.strptime(datetime.now(pytz.utc).strftime("%Y-%m-%d"), "%Y-%m-%d")
day = str((day_today - day_start).days)
shares = portfolio_settings[symbol]['shares']
original_value = float(cost) * float(shares)
new_value = float(info['current']) * float(shares)
value_day_change_percent = ((float(info['percent_change'])/100) * new_value)
font = ImageFont.load("./fonts/5x8.pil")
cost_img = self.textImage('Cost', font, r = 255, g = 255 , b = 255)
cost2_img = self.textImage(cost, font, r = 0, g = 255, b = 0)
shares_img = self.textImage('Shares', font, r = 255, g = 255 , b = 255)
shares2_img = self.textImage(shares, font, r = 0, g = 255, b = 0)
pnlchange = new_value - original_value
pnlpercent = ((new_value - original_value) / original_value) * 100
pnlpercent_img = self.textImage('P/L%', font, r = 255, g = 255 , b = 255)
if pnlpercent >= 0:
pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 0, g = 255, b = 0)
else:
pnlpercent2_img = self.textImage(str('%.2f' % abs(pnlpercent)) + '%', font, r = 255, g = 0, b = 0)
daypercent_img = self.textImage('Day%', font, r = 255, g = 255 , b = 255)
if float(info['percent_change']) >= 0:
daypercent2_img = self.textImage(str('%.2f' % abs(float(info['percent_change']))) +'%', font, r = 0, g = 255, b = 0)
else:
daypercent2_img = self.textImage(str('%.2f' % abs(float(info['percent_change'])))+'%', font, r = 255, g = 0, b = 0)
days_img = self.textImage('Days', font, r = 255, g = 255 , b = 255)
days2_img = self.textImage(day, font, r = 0, g = 255, b = 0)
value_img = self.textImage('Value', font, r = 255, g = 255 , b = 255)
value2_img = self.textImage(str('%.2f' % abs(original_value)), font, r = 0, g = 255, b = 0)
pnlchange_img = self.textImage('P/L$', font, r = 255, g = 255 , b = 255)
if pnlchange >= 0:
pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 0, g = 255, b = 0)
else:
pnlchange2_img = self.textImage(str('%.2f' % abs(pnlchange)), font, r = 255, g = 0, b = 0)
daychange_img = self.textImage('Day$', font, r = 255, g = 255 , b = 255)
if value_day_change_percent >= 0:
daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 0, g = 255, b = 0)
else:
daychange2_img = self.textImage(str('%.2f' % abs(value_day_change_percent)), font, r = 255, g = 0, b = 0)
x_offset = 0
img = Image.new('RGB', (max(cost_img.size[0], cost2_img.size[0]) + 5 + max(days_img.size[0], days2_img.size[0]) + 5 +
max(shares_img.size[0], shares2_img.size[0]) + 5 + max(value2_img.size[0], value_img.size[0]) + 5 +
max(pnlpercent_img.size[0], pnlpercent2_img.size[0]) + 5 + max(pnlchange_img.size[0], pnlchange2_img.size[0]) + 5 +
max(daypercent_img.size[0], daypercent2_img.size[0]) + 5 + max(daychange_img.size[0], daychange2_img.size[0]) + 10,16))
img.paste(cost_img, (x_offset, 1))
img.paste(cost2_img, (x_offset, 9))
x_offset += max(cost_img.size[0], cost2_img.size[0]) + 4
img.paste(days_img, (x_offset, 1))
img.paste(days2_img, (x_offset, 9))
x_offset += max(days_img.size[0], days2_img.size[0]) + 4
img.paste(shares_img, (x_offset, 1))
img.paste(shares2_img, (x_offset, 9))
x_offset += max(shares_img.size[0], shares2_img.size[0]) + 4
img.paste(value_img, (x_offset, 1))
img.paste(value2_img, (x_offset, 9))
x_offset += max(value2_img.size[0], value_img.size[0]) + 4
img.paste(pnlpercent_img, (x_offset, 1))
img.paste(pnlpercent2_img, (x_offset, 9))
x_offset += max(pnlpercent_img.size[0], pnlpercent2_img.size[0]) + 4
img.paste(pnlchange_img, (x_offset, 1))
img.paste(pnlchange2_img, (x_offset, 9))
x_offset += max(pnlchange_img.size[0], pnlchange2_img.size[0]) + 4
img.paste(daypercent_img, (x_offset, 1))
img.paste(daypercent2_img, (x_offset, 9))
x_offset += max(daypercent_img.size[0], daypercent2_img.size[0]) + 4
img.paste(daychange_img, (x_offset,1))
img.paste(daychange2_img, (x_offset, 9))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if all_stocks_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
try:
if all_stocks_settings['prepost']:
try:
image_list.append(prepost_img)
except:
pass
except:
pass
try:
if all_stocks_settings['chart'] and (symbol in portfolio_settings):
try:
image_list.append(img)
except:
pass
except:
pass
image_list.append(self.blank)
except Exception as e:
pass
finalDisplayImage = self.stitchImage(image_list)
self.blank = Image.new('RGB', (10, 32))
return finalDisplayImage
def getNewsImage(self):
f = open('csv/news_settings.json', 'r')
all_settings = json.load(f)
f.close()
if all_settings['title']:
title_img = self.openImage('feature_titles/news.png')
image_list = [title_img]
else:
image_list = []
headline_font = ImageFont.load("./fonts/6x13.pil")
source_font = ImageFont.load("./fonts/6x13.pil")
headline_info = all_settings['headlines']
headlines = []
source_date_times = []
source = []
for i, hi in enumerate(headline_info):
try:
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 = source.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'))
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:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
news_image = self.stitchImage(image_list)
return news_image
def getNewsProfessional(self):
f = open('csv/news_settings.json', 'r')
all_settings = json.load(f)
f.close()
if all_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/news.png')
image_list = [title_img]
else:
image_list = []
headline_font = ImageFont.load("./fonts/6x13.pil")
source_font = ImageFont.load("./fonts/6x13.pil")
headline_info = all_settings['headlines']
headlines = []
source_date_times = []
source = []
blank = Image.new('RGB', (0, 16))
for i, hi in enumerate(headline_info):
try:
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 = source.lower().replace(' ', '-')
logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'tiny_news')
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'), 'tiny_news')
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] +22, 32))
img.paste(headline_img, (source_img.size[0]+logo.size[0] + 10, 3))
img.paste(source_img, (logo.size[0]+2,3))
img.paste(logo, (0,0))
image_list.append(img)
image_list.append(blank)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
news_image = self.stitchImage(image_list)
return news_image
def getLeagueImage(self, league=False, time = 'past'):
if time in ['past', 'live']:
filepath = 'csv/{}_games.json'.format(time)
else:
filepath = 'csv/upcoming_games.json'
f = open(filepath, 'r')
all_settings = json.load(f)
f.close()
title_img = self.openImage('feature_titles/sports_'+ time + '.png')
if all_settings['title']:
title_img = self.openImage('feature_titles/sports_{}.png'.format(time))
imgs = [title_img, self.blank]
else:
imgs = []
leagues_info = all_settings['leagues']
leagues = list(leagues_info.keys())
if time == 'live':
for league in leagues:
try:
x_offset = 0
if league == 'NFL':
f = open('csv/live_nfl.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['NFL'][0]
elif league == 'NHL':
f = open('csv/live_nhl.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['NHL'][0]
elif league == 'NBA':
f = open('csv/live_nba.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['NBA'][0]
elif league == 'MLB':
f = open('csv/live_mlb.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['MLB'][0]
elif league == 'MLS':
f = open('csv/live_mls.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['MLS'][0]
elif league == 'PREMIERLEAGUE':
f = open('csv/live_pl.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['PREMIERLEAGUE'][0]
img = Image.new('RGB', (10000, 32))
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
slight_large_font = ImageFont.load("./fonts/9x15.pil")
small_font = ImageFont.load("./fonts/5x7.pil")
med_font = ImageFont.load("./fonts/7x14B.pil")
large_font = ImageFont.load("./fonts/9x18B.pil")
extra_small_font = ImageFont.load("./fonts/4x6.pil")
try:
sports_info = self.readSportsCSV(league)
except:
pass
buff_size = 25
if all_settings['leagues'][league][2] == 'no_live' and all_settings['leagues'][league][3] == 'no_upcoming':
no_match = self.textImage(('No live games').upper(), slight_large_font, r = 255, g = 255 , b = 255)
img.paste(no_match, (x_offset,10))
x_offset += no_match.size[0] + buff_size
elif all_settings['leagues'][league][3] != 'no_upcoming':
next_match = self.textImage('Next game: ' + all_settings['leagues'][league][3], slight_large_font, r=255,g=255,b=255)
img.paste(next_match, (x_offset,10))
x_offset += next_match.size[0] + buff_size
else:
for match in league_info:
if match['isLive'] != 'pre':
dateEvent = match['time']
date_timage = self.textImage(dateEvent, small_font, r=255, g=255, b=255)
strHomeTeam = match['home_team']
strAwayTeam = match['away_team']
intHomeScore = str(match['home_score'])
intAwayScore = str(match['away_score'])
try:
home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strHomeTeam]['logo']))
except Exception as e:
home_logo = self.textImage(strHomeTeam.replace(' ', '\n'), extra_small_font, r = 255, g = 255, b = 255)
try:
away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strAwayTeam]['logo']))
except Exception as e:
away_logo = self.textImage(strAwayTeam.replace(' ', '\n'), extra_small_font, r = 255, g = 255, b = 255)
img.paste(away_logo, (x_offset,0))
x_offset += away_logo.size[0] + 4
score_image = self.textImage(intAwayScore + '-' + intHomeScore, large_font, h_buff = 5, r = 255, g = 255, b = 255)
try:
h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', ''))
except:
pass
try:
a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', ''))
except:
pass
try:
hc_timage = self.textImage(sports_info[strHomeTeam]['code'], small_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255))
except Exception as e:
hc_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255)
try:
ac_timage = self.textImage(sports_info[strAwayTeam]['code'], small_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255))
except Exception as e:
ac_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255)
vs_timage = self.textImage('VS', extra_small_font, r = 255, g = 255, b = 255)
vs_size = hc_timage.size[0] + ac_timage.size[0] + vs_timage.size[0]
main_offset = x_offset + int(max(vs_size, date_timage.size[0], score_image.size[0])/2)
img.paste(date_timage,(main_offset - int(date_timage.size[0]/2),0))
img.paste(vs_timage, (main_offset - int(vs_timage.size[0]/2),10))
img.paste(ac_timage, (main_offset - int(vs_timage.size[0]/2) - ac_timage.size[0], 9))
img.paste(score_image, (main_offset - int(score_image.size[0]/2), 15))
if match['isLive'] == 'post':
if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
ua_image = Image.new("RGB", (hc_timage.size[0] -2, 1))
ua_image1 = ImageDraw.Draw(ua_image)
ua_image1.line((0,0,hc_timage.size[0]-2,0), fill="red", width = 0)
img.paste(ua_image, (main_offset - int(vs_timage.size[0]/2)-ac_timage.size[0], ac_timage.size[1]+7))
img.paste(hc_timage, (main_offset + int(vs_timage.size[0]/2),9))
if match['isLive'] == 'post':
if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
u_image = Image.new("RGB", (ac_timage.size[0] -2, 1))
u_image1 = ImageDraw.Draw(u_image)
u_image1.line((0,0,ac_timage.size[0]-2,0), fill="red", width = 0)
img.paste(u_image, (main_offset + int(vs_timage.size[0]/2), hc_timage.size[1]+7))
x_offset = (main_offset + max(int(date_timage.size[0]/2), int(vs_timage.size[0]/2) + hc_timage.size[0], int(score_image.size[0]/2)) + 4)
img.paste(home_logo, (x_offset,0))
x_offset += home_logo.size[0] + buff_size
img = img.crop((0,0,x_offset,32))
imgs.append(img)
except Exception as e:
pass
else:
for league in leagues:
try:
x_offset = 0
if (league =='PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'):
img = Image.new('RGB', (10000, 32))
else:
img = Image.new('RGB', (10000, 32))
league_info = leagues_info[league]
try:
league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league))
if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'):
x_offset += self.blank.size[0]
else:
img.paste(league_logo, (x_offset,0))
x_offset += league_logo.size[0] +self.blank.size[0]
except:
pass
try:
sports_info = self.readSportsCSV(league)
except:
pass
med_font = ImageFont.load("./fonts/7x14B.pil")
large_font = ImageFont.load("./fonts/9x18B.pil")
extra_small_font = ImageFont.load("./fonts/4x6.pil")
buff_size = 25
if league == 'UFC':
try:
small_font = ImageFont.load("./fonts/6x10.pil")
date_img = self.textImage(league_info[0]['date'], small_font, r=0,g=150,b=255)
eventname_img = self.textImage(league_info[0]['name'].upper(), med_font, r=255, g=0, b=0)
venue_img = self.textImage(league_info[0]['venue'], small_font, r=255, g=255, b=0)
city_img = self.textImage(league_info[0]['city'], small_font, r=255, g=255, b=255)
try:
country_img = self.textImage(league_info[0]['country'], small_font, r=255, g=128, b=0)
except:
pass
broadcast_img = self.textImage(league_info[0]['broadcast'], small_font, r=255, g=0, b=0)
time_img = self.textImage(league_info[0]['time'], small_font, r =0, g=150, b=255)
try:
img.paste(country_img, (x_offset + venue_img.size[0] + 5 + city_img.size[0] +5, 13))
except:
country_img = 0
pass
img.paste(eventname_img, (x_offset, 0))
img.paste(city_img, (x_offset+ venue_img.size[0] + 5, 13))
img.paste(venue_img, (x_offset,13))
img.paste(broadcast_img, (x_offset + date_img.size[0] + 5 + time_img.size[0] + 5, 23))
img.paste(date_img, (x_offset, 23))
img.paste(time_img, (x_offset + date_img.size[0] + 5, 23))
try:
x_offset = 5 + max(x_offset + eventname_img.size[0], x_offset + venue_img.size[0] + 5 + city_img.size[0] + 5 + country_img.size[0], x_offset + date_img.size[0] + 5 + time_img.size[0] + 5 + broadcast_img.size[0])
except:
x_offset = 5 + max(x_offset + eventname_img.size[0], x_offset + venue_img.size[0] + 5 + city_img.size[0] + 5, x_offset + date_img.size[0] + 5 + time_img.size[0] + 5 + broadcast_img.size[0])
for fight in league_info[0]['fights']:
try:
if time != 'past':
fighter1_img = Image.open('logos/ufc/{}.png'.format(fight['fighter1id']))
elif time == 'past':
fighter1_img = Image.open('logos/ufc_past/{}.png'.format(fight['fighter1id']))
#fighter1_img.thumbnail((9000,32))
except:
fighter1_img = Image.open('logos/unknown.png')
pass
try:
if time != 'past':
fighter2_img = Image.open('logos/ufc/{}.png'.format(fight['fighter2id']))
elif time == 'past':
fighter2_img = Image.open('logos/ufc_past/{}.png'.format(fight['fighter2id']))
#fighter2_img.thumbnail((9000,32))
except:
fighter2_img = Image.open('logos/unknown.png')
pass
weight_img = self.textImage(fight['weight_div'].upper(), extra_small_font, r=255,g=255,b=255)
age1_img = self.textImage(fight['fighter1age'], extra_small_font, r=255,g=255,b=255)
age2_img = self.textImage(fight['fighter2age'], extra_small_font, r=255,g=255,b=255)
age_img = self.textImage('AGE', extra_small_font, r=255,g=0,b=0)
height1_img = self.textImage(fight['fighter1height'], extra_small_font, r=255,g=255,b=255)
height2_img = self.textImage(fight['fighter2height'], extra_small_font, r=255,g=255,b=255)
height_img = self.textImage('HEIGHT', extra_small_font, r=255,g=0,b=0)
weight1_img = self.textImage(fight['fighter1weight'], extra_small_font, r=255,g=255,b=255)
weight2_img = self.textImage(fight['fighter2weight'], extra_small_font, r=255,g=255,b=255)
weights_img = self.textImage('WEIGHT', extra_small_font, r=255,g=0,b=0)
reach1_img = self.textImage(fight['fighter1reach'], extra_small_font, r=255,g=255,b=255)
reach2_img = self.textImage(fight['fighter2reach'], extra_small_font, r=255,g=255,b=255)
reach_img = self.textImage('REACH', extra_small_font, r=255,g=0,b=0)
name1_img = self.textImage(fight['fighter1name'], extra_small_font, r=255,g=255,b=255)
record1_img = self.textImage(fight['fighter1record'], extra_small_font, r=255, g=255, b=255)
name2_img = self.textImage(fight['fighter2name'], extra_small_font, r=255,g=255,b=255)
record2_img = self.textImage(fight['fighter2record'], extra_small_font, r=255, g=255, b=255)
if time != 'past':
odds1_img = self.textImage(fight['fighter1odds'], extra_small_font, r=0, g=255, b=0)
#odds2_img = self.textImage(fight['fighter2odds'], extra_small_font, r=0, g=255, b=0)
elif time == 'past':
if fight['fighter1win']:
win1_img = self.textImage('WIN', extra_small_font, r=0, g=255, b=0)
elif not fight['fighter1win'] and not fight['fighter2win']:
win1_img = self.textImage('DRAW', extra_small_font, r=80, g=80, b=80)
else:
win1_img = self.textImage('LOSS', extra_small_font, r=0, g=255, b=0)
max_fighter1_pic = max(fighter1_img.size[0], name1_img.size[0], record1_img.size[0])
draw = ImageDraw.Draw(img, "RGBA")
img.paste(fighter1_img, (x_offset + int(max_fighter1_pic/2) - int(fighter1_img.size[0]/2), 0), mask=fighter1_img)
try:
country1_img = Image.open('logos/ufc_countries/{}'.format(fight['fighter1country'].split('/')[-1].split('&')[0]))
country1_img.thumbnail((9000,12))
img.paste(country1_img,(x_offset, 0))
except:
pass
draw.rectangle([(x_offset,32),(x_offset + max(name1_img.size[0],record1_img.size[0])-4,21)], fill=(5,5,5,200))
draw.text((x_offset + int(max_fighter1_pic/2) - int(name1_img.size[0]/2),21), fight['fighter1name'], fill=(255,255,255),font=extra_small_font)
#img.paste(name1_img, (x_offset + int(max_fighter1_pic/2) - int(name1_img.size[0]/2),21))
draw.text((x_offset + int(max_fighter1_pic/2) - int(record1_img.size[0]/2),27), fight['fighter1record'], fill=(255,255,0),font=extra_small_font)
#img.paste(record1_img, (x_offset + int(max_fighter1_pic/2) - int(record1_img.size[0]/2), 27))
x_offset += max(fighter1_img.size[0], name1_img.size[0], record1_img.size[0])
widest = x_offset + int(max(weight_img.size[0], age1_img.size[0] + 3 + age_img.size[0] + 3 + age2_img.size[0], height1_img.size[0] + 3 + height_img.size[0] + 3 + height2_img.size[0], weight1_img.size[0] + 3 + weights_img.size[0] + 3 + weight2_img.size[0], reach1_img.size[0] + 3 + reach_img.size[0] + 3 + reach2_img.size[0])/2)
largest = max(age_img.size[0],weights_img.size[0],height_img.size[0],reach_img.size[0])
img.paste(weight_img,(widest - int(weight_img.size[0]/2), 0))
if time != 'past':
draw.text((widest - int(weight_img.size[0]/2) - odds1_img.size[0] - 2,0), fight['fighter1odds'], fill=(0,255,0),font=extra_small_font)
# img.paste(odds1_img, (widest - int(weight_img.size[0]/2) - odds1_img.size[0] - 2,0))
elif time == 'past':
if fight['fighter1win']:
draw.text((widest - int(weight_img.size[0]/2) - win1_img.size[0] - 2,0), 'WIN', fill=(0,255,0),font=extra_small_font)
elif not fight['fighter1win'] and not fight['fighter2win']:
draw.text((widest - int(weight_img.size[0]/2) - win1_img.size[0] - 2,0), 'DRAW', fill=(80,80,80),font=extra_small_font)
else:
draw.text((widest - int(weight_img.size[0]/2) - win1_img.size[0] - 2,0), 'LOSS', fill=(255,0,0),font=extra_small_font)
img.paste(age1_img,(widest - int(largest/2) - age1_img.size[0] - 3, 7))
img.paste(age_img,(widest - int(age_img.size[0]/2),7))
img.paste(age2_img, (widest + int(largest/2) + 3, 7))
img.paste(height1_img,(widest - int(largest/2) - height1_img.size[0] - 3, 13))
img.paste(height_img,(widest - int(height_img.size[0]/2),13))
img.paste(height2_img, (widest + int(largest/2) + 3, 13))
img.paste(weight1_img,(widest - int(largest/2) - weight1_img.size[0] - 3, 19))
img.paste(weights_img,(widest - int(weights_img.size[0]/2),19))
img.paste(weight2_img, (widest + int(largest/2) + 3, 19))
img.paste(reach1_img,(widest - int(largest/2) - reach1_img.size[0] - 3, 25))
img.paste(reach_img,(widest - int(reach_img.size[0]/2),25))
img.paste(reach2_img, (widest + int(largest/2) + 3, 25))
x_offset = widest + widest - x_offset + 2
max_fighter2_pic = max(fighter2_img.size[0], name2_img.size[0], record2_img.size[0])
img.paste(fighter2_img, (x_offset + int(max_fighter2_pic/2) - int(fighter2_img.size[0]/2), 0), mask=fighter2_img)
draw.rectangle([(x_offset,32),(x_offset + max(name2_img.size[0],record2_img.size[0])-4,21)], fill=(5,5,5,200))
draw.text((x_offset + int(max_fighter2_pic/2) - int(name2_img.size[0]/2),21), fight['fighter2name'], fill=(255,255,255),font=extra_small_font)
#img.paste(name1_img, (x_offset + int(max_fighter1_pic/2) - int(name1_img.size[0]/2),21))
draw.text((x_offset + int(max_fighter2_pic/2) - int(record2_img.size[0]/2),27), fight['fighter2record'], fill=(255,255,0),font=extra_small_font)
#img.paste(record1_img, (x_offset + int(max_fighter1_pic/2) - int(record1_img.size[0]/2), 27))
x_offset += max(fighter2_img.size[0], name2_img.size[0], record2_img.size[0]) + 25
if time != 'past':
draw.text((widest + int(weight_img.size[0]/2) + 2,0), fight['fighter2odds'], fill=(0,255,0),font=extra_small_font)
#img.paste(odds2_img, (widest + int(weight_img.size[0]/2) + 2,0))
elif time == 'past':
if fight['fighter2win']:
draw.text((widest + int(weight_img.size[0]/2) + 2,0), 'WIN', fill=(0,255,0),font=extra_small_font)
elif not fight['fighter2win'] and not fight['fighter1win']:
draw.text((widest + int(weight_img.size[0]/2) + 2,0), 'DRAW', fill=(80,80,80),font=extra_small_font)
else:
draw.text((widest + int(weight_img.size[0]/2) + 2,0), 'LOSS', fill=(255,0,0),font=extra_small_font)
try:
country2_img = Image.open('logos/ufc_countries/{}'.format(fight['fighter2country'].split('/')[-1].split('&')[0]))
country2_img.thumbnail((9000,12))
img.paste(country2_img,(x_offset-country2_img.size[0]-25, 0))
except:
pass
except:
pass
# DONT FORGET TO CHANGE DIRECTORY FOR PAST UFC GAMES
else:
small_font = ImageFont.load("./fonts/5x7.pil")
for match in league_info:
try:
dateEvent = match['date2']
except:
dateEvent = match['date'].replace('-', '.')
date_timage = self.textImage(dateEvent, small_font, r=255, g=255, b=255)
if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'):
event = match['event']
venue = match['venue']
city = match['city']
country = match['country']
season = match['season']
if (time != 'future') and (league != 'LIV'):
golf_standings1 = match['golf_rankings'][::2]
golf_standings2 = match['golf_rankings'][1::2]
elif (time!= 'future') and (league == 'LIV'):
golf_standings1 = match['golf_rankings'][::2]
golf_standings2 = match['golf_rankings'][1::2]
#golf_standings1_teams = match['golf_standings'][1][::2]
#golf_standings2_teams = match['golf_standings'][1][1::2]
img.paste(league_logo, (x_offset, 0))
x_offset += league_logo.size[0] + 2
try:
if match['purse'] != 'N/A' and match['purse'] != "" and match['purse'] != '0':
purse_timage = self.textImage(match['purse'], small_font, r=0,g=255,b=0)
except:
pass
try:
if match['shots_par'] != 'N/A' and match['shots_par'] != "" and match['shots_par'] != 0:
par_timage = self.textImage('Par' + str(match['shots_par']), small_font, r=255,g=127,b=80)
except:
pass
try:
if match['total_yards'] != 'N/A' and match['total_yards'] != "" and match['total_yards'] != 0:
yards_timage = self.textImage(str(match['total_yards']) + 'yds', small_font, r=255,g=127,b=80)
except:
pass
if time == 'future':
event_timage = self.textImage(event, med_font, r=255, g=255, b=0)
venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0)
city_timage = self.textImage(city, small_font, r=255, g=255, b=255)
country_timage = self.textImage(country, small_font, r=255, g=255, b=255)
date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171)
season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255)
season_timage = self.textImage(season, small_font, r=255, g=255, b=255)
x_offset += 2
x_offset_2nd = x_offset
x_offset_3rd = x_offset
#date
img.paste(date1_timage, (x_offset, 26))
x_offset += date1_timage.size[0]
img.paste(date_timage, (x_offset, 26))
x_offset += date_timage.size[0] + 10
#season
img.paste(season1_timage,(x_offset,26))
x_offset += season1_timage.size[0]
img.paste(season_timage,(x_offset,26))
x_offset += season_timage.size[0] + 3
#event
img.paste(event_timage, (x_offset_2nd, 0))
x_offset_2nd += event_timage.size[0] + 5
#country
img.paste(country_timage,(x_offset_2nd, 5))
x_offset_2nd += country_timage.size[0]
#venue
img.paste(venue_timage,(x_offset_3rd, 16))
x_offset_3rd += venue_timage.size[0] + 10
#city
img.paste(city_timage,(x_offset_3rd, 16))
x_offset_3rd += city_timage.size[0]
try:
if match['total_yards'] != 'N/A' and match['total_yards'] != "" and match['total_yards'] != 0:
img.paste(yards_timage, (x_offset_3rd + 10, 16))
x_offset_3rd += yards_timage.size[0] + 10
except:
pass
try:
if match['shots_par'] != 'N/A' and match['shots_par'] != "" and match['shots_par'] != 0:
img.paste(par_timage, (x_offset_3rd + 5, 16))
x_offset_3rd += par_timage.size[0] + 5
except:
pass
try:
if match['purse'] != 'N/A' and match['purse'] != "" and match['purse'] != '0':
img.paste(purse_timage, (x_offset + 7, 25))
x_offset += purse_timage.size[0] + 3 + 7
except:
pass
x_offset = max(x_offset, x_offset_2nd, x_offset_3rd)
x_offset += buff_size
else:
event_timage = self.textImage(event, med_font, r=255, g=255, b=0)
venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0)
city_timage = self.textImage(city, small_font, r=255, g=255, b=255)
country_timage = self.textImage(country, small_font, r=255, g=255, b=255)
date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171)
season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255)
season_timage = self.textImage(season, small_font, r=255, g=255, b=255)
x_offset += 2
x_offset_2nd = x_offset
x_offset_3rd = x_offset
#date
img.paste(date1_timage, (x_offset, 26))
x_offset += date1_timage.size[0]
img.paste(date_timage, (x_offset, 26))
x_offset += date_timage.size[0] + 10
#season
img.paste(season1_timage,(x_offset,26))
x_offset += season1_timage.size[0]
img.paste(season_timage,(x_offset,26))
x_offset += season_timage.size[0] + 3
#event
img.paste(event_timage, (x_offset_2nd, 0))
x_offset_2nd += event_timage.size[0] + 5
#country
img.paste(country_timage,(x_offset_2nd, 5))
x_offset_2nd += country_timage.size[0]
#venue
img.paste(venue_timage,(x_offset_3rd, 16))
x_offset_3rd += venue_timage.size[0] + 10
#city
img.paste(city_timage,(x_offset_3rd, 16))
x_offset_3rd += city_timage.size[0]
try:
if match['total_yards'] != 'N/A' and match['total_yards'] != "" and match['total_yards'] != 0:
img.paste(yards_timage, (x_offset_3rd + 10, 16))
x_offset_3rd += yards_timage.size[0] + 10
except:
pass
try:
if match['shots_par'] != 'N/A' and match['shots_par'] != "" and match['shots_par'] != 0:
img.paste(par_timage, (x_offset_3rd + 5, 16))
x_offset_3rd += par_timage.size[0] + 5
except:
pass
try:
if match['purse'] != 'N/A' and match['purse'] != "" and match['purse'] != '0':
img.paste(purse_timage, (x_offset + 7, 25))
x_offset += purse_timage.size[0] + 3 + 7
except:
pass
x_offset = max(x_offset, x_offset_2nd, x_offset_3rd) + 5
#x_offset2 = x_offset
symbol1_timage = self.textImage('|', small_font, r=255, g=255, b=0)
for each_player, each_player2 in zip(golf_standings1, golf_standings2):
img.paste(symbol1_timage, (x_offset, 7))
img.paste(symbol1_timage, (x_offset, 20))
x_offset += symbol1_timage.size[0] + 3
golf1_offset = 0
golf2_offset = 0
try:
golf1_rank_timage = self.textImage(each_player['rank'], small_font, r=255, g=255, b=255)
golf1_offset += golf1_rank_timage.size[0] + 3
img.paste(golf1_rank_timage,(x_offset, 7))
try:
golf1_country = Image.open('logos/ufc_countries/{}'.format(each_player['country'].split('/')[-1].split('&')[0]))
golf1_country.thumbnail((9000,12))
img.paste(golf1_country,(x_offset + golf1_rank_timage.size[0] + 3, 4))
golf1_offset += golf1_country.size[0] + 3
except:
pass
golf_standings1_timage = self.textImage(each_player['name'] + ' ' + each_player['score'], small_font, r=255, g=255, b=255)
img.paste(golf_standings1_timage, (x_offset + golf1_offset, 7))
golf1_offset += golf_standings1_timage.size[0]
except:
pass
try:
golf2_rank_timage = self.textImage(each_player2['rank'], small_font, r=255, g=255, b=255)
golf2_offset += golf2_rank_timage.size[0] + 3
img.paste(golf2_rank_timage,(x_offset, 20))
try:
golf2_country = Image.open('logos/ufc_countries/{}'.format(each_player2['country'].split('/')[-1].split('&')[0]))
golf2_country.thumbnail((9000,12))
img.paste(golf2_country,(x_offset + golf2_rank_timage.size[0] + 3, 17))
golf2_offset += golf2_country.size[0] + 3
except:
pass
golf_standings2_timage = self.textImage(each_player2['name'] + ' ' + each_player2['score'], small_font, r=255, g=255, b=255)
img.paste(golf_standings2_timage, (x_offset + golf2_offset, 20))
golf2_offset += golf_standings2_timage.size[0]
except:
pass
x_offset += max(golf2_offset, golf1_offset) + 5
#for each_player in golf_standings1:
# symbol1_timage = self.textImage('|', small_font, r=255, g=255, b=0)
# img.paste(symbol1_timage, (x_offset + 5, 7))
# golf_standings1_timage = self.textImage(each_player, small_font, r=255, g=255, b=255)
# img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 7))
# x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7)
#for each_player2 in golf_standings2:
# symbol2_timage = self.textImage('|', small_font, r=255, g=255, b=0)
# img.paste(symbol2_timage, (x_offset2 + 5, 20))
# golf_standings2_timage = self.textImage(each_player2, small_font, r=255, g=255, b=255)
# img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 20))
# x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7)
# if league == 'LIV':
# if x_offset >= x_offset2:
# x_offset += 10
# x_offset2 = x_offset
# else:
# x_offset2 += 10
# x_offset = x_offset2
#for each_team in golf_standings1_teams:
# symbol1_timage = self.textImage('|', small_font, r=0, g=255, b=0)
# img.paste(symbol1_timage, (x_offset + 5, 7))
# golf_standings1_timage = self.textImage(each_team, small_font, r=255, g=255, b=255)
# img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 7))
# x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7)
#for each_team2 in golf_standings2_teams:
# symbol2_timage = self.textImage('|', small_font, r=0, g=255, b=0)
# img.paste(symbol2_timage, (x_offset2 + 5, 20))
# golf_standings2_timage = self.textImage(each_team2, small_font, r=255, g=255, b=255)
# img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 20))
# x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7)
#if x_offset >= x_offset2:
x_offset += buff_size
#else:
# x_offset = x_offset2
# x_offset += buff_size
else:
strHomeTeam = match['home_team']
strAwayTeam = match['away_team']
if time != 'future':
intHomeScore = str(match['home_score'])
intAwayScore = str(match['away_score'])
try:
home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strHomeTeam]['logo']))
except Exception as e:
home_logo = self.textImage(strHomeTeam.replace(' ', '\n'), extra_small_font, r = 255, g = 255, b = 255)
try:
away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strAwayTeam]['logo']))
except Exception as e:
away_logo = self.textImage(strAwayTeam.replace(' ', '\n'), extra_small_font, r = 255, g = 255, b = 255)
img.paste(away_logo, (x_offset,0))
x_offset += away_logo.size[0] + 4
if time == 'future':
try:
start_time = match['time']
#img.paste(date_timage, (x_offset+5, 0))
time_img = self.textImage(start_time, small_font, r=255,g=255,b=255)
except:
pass
try:
h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', ''))
except:
pass
try:
a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', ''))
except:
pass
vs_timage = self.textImage('vs', med_font, r = 255, g = 255, b = 255, h_buff = 5)
try:
hc_timage = self.textImage(sports_info[strHomeTeam]['code'], med_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255))
except Exception as e:
hc_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255)
try:
ac_timage = self.textImage(sports_info[strAwayTeam]['code'], med_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255))
except Exception as e:
ac_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255)
vs_size = vs_timage.size[0] + ac_timage.size[0] + hc_timage.size[0]
main_offset = 5 + x_offset + int(max(vs_size, date_timage.size[0])/2)
try:
img.paste(time_img, (main_offset - int(time_img.size[0]/2), 26))
except:
pass
img.paste(date_timage, (main_offset - int(date_timage.size[0]/2), 0))
img.paste(vs_timage, (main_offset - int(vs_timage.size[0]/2),9))
img.paste(ac_timage, (main_offset - int(vs_timage.size[0]/2) - ac_timage.size[0], 9))
img.paste(hc_timage, (main_offset + int(vs_timage.size[0]/2),9))
x_offset = (main_offset + max(int(date_timage.size[0]/2), int(vs_timage.size[0]/2) + hc_timage.size[0]) + 6)
else:
score_image = self.textImage(intAwayScore + '-' + intHomeScore, large_font, h_buff = 5, r = 255, g = 255, b = 255)
try:
h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', ''))
except:
pass
try:
a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', ''))
except:
pass
try:
hc_timage = self.textImage(sports_info[strHomeTeam]['code'], small_font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255))
except Exception as e:
hc_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255)
try:
ac_timage = self.textImage(sports_info[strAwayTeam]['code'], small_font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255))
except Exception as e:
ac_timage = self.textImage('.', extra_small_font, r = 255, g = 255, b = 255)
vs_timage = self.textImage('VS', extra_small_font, r = 255, g = 255, b = 255)
vs_size = hc_timage.size[0] + ac_timage.size[0] + vs_timage.size[0]
main_offset = x_offset + int(max(vs_size, date_timage.size[0], score_image.size[0])/2)
img.paste(date_timage,(main_offset - int(date_timage.size[0]/2),0))
img.paste(vs_timage,(main_offset - int(vs_timage.size[0]/2),10))
img.paste(ac_timage, (main_offset - int(vs_timage.size[0]/2) - ac_timage.size[0], 9))
img.paste(score_image, (main_offset - int(score_image.size[0]/2), 15))
if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
ua_image = Image.new("RGB", (ac_timage.size[0] -2, 1))
ua_image1 = ImageDraw.Draw(ua_image)
ua_image1.line((0,0,ac_timage.size[0]-2,0), fill="red", width = 0)
img.paste(ua_image, (main_offset - int(vs_timage.size[0]/2)-ac_timage.size[0], ac_timage.size[1]+7))
img.paste(hc_timage, (main_offset + int(vs_timage.size[0]/2),9))
if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
u_image = Image.new("RGB", (hc_timage.size[0] -2, 1))
u_image1 = ImageDraw.Draw(u_image)
u_image1.line((0,0,hc_timage.size[0]-2,0), fill="red", width = 0)
img.paste(u_image, (main_offset + int(vs_timage.size[0]/2), hc_timage.size[1]+7))
x_offset = (main_offset + max(int(date_timage.size[0]/2), int(vs_timage.size[0]/2) + hc_timage.size[0], int(score_image.size[0]/2)) + 4)
img.paste(home_logo, (x_offset,0))
x_offset += home_logo.size[0]
x_offset += buff_size
img = img.crop((0,0,x_offset ,32))
imgs.append(img)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
return self.stitchImage(imgs)
def getLeagueTableImage(self, league = False):
f = open('csv/league_tables.json', 'r')
all_settings = json.load(f)
f.close()
leagues_info = all_settings['leagues']
leagues = list(leagues_info.keys())
if all_settings['title']:
title_img = self.openImage('feature_titles/sports_team_stats.png')
imgs = [title_img, self.blank]
else:
imgs = []
ten_or_twenty = slice(None)
for league in leagues:
try:
x_offset = 0
img = Image.new('RGB', (10000, 32))
if league == 'PGA':
league_logo = Image.open('logos/sports/league_logos/pga_1.png').convert('RGB')
try:
if all_settings['top20'] == 10:
ten_or_twenty = slice(10)
else:
ten_or_twenty = slice(None)
except:
ten_or_twenty = slice(None)
elif league == 'LPGA':
league_logo = Image.open('logos/sports/league_logos/lpga_1.png').convert('RGB')
try:
if all_settings['top20'] == 10:
ten_or_twenty = slice(10)
else:
ten_or_twenty = slice(None)
except:
ten_or_twenty = slice(None)
else:
league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB')
ten_or_twenty = slice(None)
img.paste(league_logo, (x_offset,0))
x_offset += league_logo.size[0] +self.blank.size[0]
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
try:
sports_info = self.readSportsCSV(league) # gets colour and symbol info etc from csv
except:
pass
buff_size = 20
for team in team_info[ten_or_twenty]:
if league == 'PGA' or league =='LPGA':
pga_font = ImageFont.load("./fonts/7x14.pil")
pga_small = ImageFont.load("./fonts/5x8.pil")
try:
if league == 'PGA':
player_img = Image.open('logos/pga_rank/' + team['photo'].split('/')[-1].split('&')[0])
elif league == 'LPGA':
player_img = Image.open('logos/lpga_rank/' + team['photo'].split('/')[-1])
player_img.thumbnail((9000,32))
try:
img.paste(player_img, (x_offset, 0), mask=player_img)
except:
img.paste(player_img, (x_offset, 0))
x_offset += player_img.size[0] + 2
except:
pass
x_offset2 = x_offset
if league == 'LPGA':
if str(abs(team['rank_change'])) != '-' and str(abs(team['rank_change'])) != '0':
if int(team['rank_change']) > 0:
rank_change_img = self.textImage(str(abs(team['rank_change'])), pga_font, r = 0, g = 255, b = 0)
elif int(team['rank_change']) < 0:
rank_change_img = self.textImage(str(abs(team['rank_change'])), pga_font, r = 255, g = 0, b = 0)
elif league == 'PGA':
if str(team['rank_change']) != '-':
if int(team['rank_change']) > 0:
rank_change_img = self.textImage(str(abs(int(team['rank_change']))), pga_font, r = 0, g = 255, b = 0)
elif int(team['rank_change']) < 0:
rank_change_img = self.textImage(str(abs(int(team['rank_change']))), pga_font, r = 255, g = 0, b = 0)
country_img = Image.open('logos/ufc_countries/' + team['country'].split('/')[-1].split('&')[0])
country_img.thumbnail((9000,13))
img.paste(country_img, (x_offset, 0))
x_offset += country_img.size[0] + 2
rank_img = self.textImage('#' + str(team['rank']), pga_font, r = 255, g=255, b=0)
img.paste(rank_img, (x_offset, 0))
x_offset += rank_img.size[0] + 2
name_img = self.textImage(team['first_name'].upper()[0] + '. ' + team['last_name'].upper(), pga_font, r= 255, g = 255, b = 255)
img.paste(name_img, (x_offset, 0))
x_offset += name_img.size[0] + 5
if league == 'LPGA':
if str(abs(int(team['rank_change']))) != '-' and str(abs(int(team['rank_change']))) != '0':
try:
x_offset = x_offset - 3
up_img = Image.open('logos/up-tiny.png')
down_img = Image.open('logos/down-tiny.png')
if int(team['rank_change']) > 0:
img.paste(up_img, (x_offset, 6))
x_offset += up_img.size[0] + 2
elif int(team['rank_change']) < 0:
img.paste(down_img, (x_offset, 6))
x_offset += down_img.size[0] + 2
img.paste(rank_change_img, (x_offset, 0))
x_offset += rank_change_img.size[0] + 5
except:
pass
elif league == 'PGA':
if str(team['rank_change']) != '-':
try:
x_offset = x_offset - 3
up_img = Image.open('logos/up-tiny.png')
down_img = Image.open('logos/down-tiny.png')
if int(team['rank_change']) > 0:
img.paste(up_img, (x_offset, 6))
x_offset += up_img.size[0] + 2
elif int(team['rank_change']) < 0:
img.paste(down_img, (x_offset, 6))
x_offset += down_img.size[0] + 2
img.paste(rank_change_img, (x_offset, 0))
x_offset += rank_change_img.size[0] + 5
except:
pass
totalpts_img = self.textImage('Total:', pga_small, r = 255, g = 255, b = 255)
totalpts2_img = self.textImage(str(team['total_pts']), pga_small, r = 0, g = 255, b = 0)
img.paste(totalpts_img, (x_offset2, 14))
img.paste(totalpts2_img, (x_offset2 + totalpts_img.size[0] + 2, 14))
avgpts_img = self.textImage('Avg:', pga_small, r = 255, g = 255, b = 255)
avgpts2_img = self.textImage(str(team['avg_pts']), pga_small, r = 0, g = 0, b = 255)
img.paste(avgpts_img, (x_offset2, 23))
img.paste(avgpts2_img, (x_offset2 + 2 + avgpts_img.size[0], 23))
events_img = self.textImage('Events:', pga_small, r= 255, g = 255, b = 255)
events2_img = self.textImage(str(team['events_played']), pga_small, r= 255, g = 128, b = 0)
img.paste(events_img, (x_offset2 + 10 + avgpts_img.size[0] + 2 + avgpts2_img.size[0], 23))
img.paste(events2_img, (x_offset2 + 10 + avgpts_img.size[0] + 2 + avgpts2_img.size[0] + 2 + events_img.size[0], 23))
try:
ptsgained_img = self.textImage('+'+str(team['gained_pts']), pga_small, r=0, g= 255, b=0)
ptslost_img = self.textImage(str(team['lost_pts']), pga_small, r=255, g= 0, b=0)
img.paste(ptsgained_img, (x_offset2 + totalpts_img.size[0] + 2 + totalpts2_img.size[0] + 5, 14))
img.paste(ptslost_img, (x_offset2 + totalpts_img.size[0] + 2 + totalpts2_img.size[0] + 5 + ptsgained_img.size[0] + 3, 14))
x_offset2 += max(avgpts_img.size[0] + 2 + avgpts2_img.size[0] + 10 + events_img.size[0] + 2 + events2_img.size[0], totalpts_img.size[0] + 2 + totalpts2_img.size[0] + 5 + ptsgained_img.size[0] + 3 + ptslost_img.size[0])
except:
x_offset2 += max(avgpts_img.size[0] + 2 + avgpts2_img.size[0] + 10 + events_img.size[0] + 2 + events2_img.size[0], 2 + totalpts_img.size[0] + totalpts2_img.size[0])
pass
x_offset = max(x_offset, x_offset2) + 20
else:
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:
pass
name_timage = self.textImage(team['name'], med_font, r = 255, g = 255, b = 0)
wins_timage = self.textImage('Wins:' + str(team['wins']), small_font, r = 0, g = 255, b = 0)
loss_timage = self.textImage('Losses:' + str(team['loss']), small_font, r = 255, g = 0, b = 0)
draw_timage = self.textImage('Draws:' + str(team['draw']), small_font, r = 0, g = 0, b = 255)
standing_timage = self.textImage('Standing:' + str(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(standing_timage, (x_offset, 22))
x_offset += standing_timage.size[0]
if name_timage.size[0] > max( wins_timage.size[0], loss_timage.size[0], draw_timage.size[0]) + standing_timage.size[0]:
x_offset += name_timage.size[0] - (max( wins_timage.size[0], loss_timage.size[0], draw_timage.size[0]) + standing_timage.size[0])
x_offset += buff_size
img = img.crop((0,0,x_offset ,32))
imgs.append(img)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
return self.stitchImage(imgs)
def getLeagueTableProfessional(self, league = False):
f = open('csv/league_tables.json', 'r')
all_settings = json.load(f)
f.close()
leagues_info = all_settings['leagues']
leagues = list(leagues_info.keys())
if all_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/sports_team_stats.png')
imgs = [title_img, self.blank]
else:
imgs = []
ten_or_twenty = slice(None)
for league in leagues:
try:
x_offset = 0
img = Image.new('RGB', (10000, 32))
if league == 'PGA':
league_logo = Image.open('logos/sports/league_logos/pga_1.png').convert('RGB')
try:
if all_settings['top20'] == 10:
ten_or_twenty = slice(10)
else:
ten_or_twenty = slice(None)
except:
ten_or_twenty = slice(None)
elif league == 'LPGA':
league_logo = Image.open('logos/sports/league_logos/lpga_1.png').convert('RGB')
try:
if all_settings['top20'] == 10:
ten_or_twenty = slice(10)
else:
ten_or_twenty = slice(None)
except:
ten_or_twenty = slice(None)
else:
league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB')
ten_or_twenty = slice(None)
width, height = league_logo.size
league_logo2 = league_logo.resize((int(width/2), int(height/2)))
img.paste(league_logo2, (x_offset,0))
x_offset += (league_logo2.size[0]+5)
team_info = leagues_info[league]
font = ImageFont.load("./fonts/6x10.pil")
try:
sports_info = self.readSportsCSV(league)
except:
pass
buff_size = 20
for team in team_info[ten_or_twenty]:
if league == 'PGA' or league =='LPGA':
pga_small = ImageFont.load("./fonts/4x6.pil")
try:
if league == 'PGA':
player_img = Image.open('logos/pga_rank/' + team['photo'].split('/')[-1].split('&')[0])
elif league == 'LPGA':
player_img = Image.open('logos/lpga_rank/' + team['photo'].split('/')[-1])
player_img.thumbnail((9000,16))
try:
img.paste(player_img, (x_offset, 0), mask=player_img)
except:
img.paste(player_img, (x_offset, 0))
x_offset += player_img.size[0] + 2
except:
pass
if league == 'LPGA':
if str(abs(team['rank_change'])) != '-' and str(abs(team['rank_change'])) != '0':
if int(team['rank_change']) > 0:
rank_change_img = self.textImage(str(abs(team['rank_change'])), font, r = 0, g = 255, b = 0)
elif int(team['rank_change']) < 0:
rank_change_img = self.textImage(str(abs(team['rank_change'])), font, r = 255, g = 0, b = 0)
elif league == 'PGA':
if str(team['rank_change']) != '-':
if int(team['rank_change']) > 0:
rank_change_img = self.textImage(str(abs(int(team['rank_change']))), font, r = 0, g = 255, b = 0)
elif int(team['rank_change']) < 0:
rank_change_img = self.textImage(str(abs(int(team['rank_change']))), font, r = 255, g = 0, b = 0)
x_offset2 = x_offset
country_img = Image.open('logos/ufc_countries/' + team['country'].split('/')[-1].split('&')[0])
country_img.thumbnail((9000,11))
img.paste(country_img, (x_offset, -1))
x_offset += country_img.size[0] + 2
rank_img = self.textImage('#' + str(team['rank']), font, r = 255, g=255, b=0)
img.paste(rank_img, (x_offset, 0))
x_offset += rank_img.size[0] + 2
name_img = self.textImage(team['first_name'].upper()[0] + '. ' + team['last_name'].upper(), font, r= 255, g = 255, b = 255)
img.paste(name_img, (x_offset, 0))
x_offset += name_img.size[0] + 2
if league == 'LPGA':
if str(abs(int(team['rank_change']))) != '-' and str(abs(int(team['rank_change']))) != '0':
try:
up_img = Image.open('logos/up-tiny.png')
down_img = Image.open('logos/down-tiny.png')
if int(team['rank_change']) > 0:
img.paste(up_img, (x_offset, 3))
x_offset += up_img.size[0] + 2
elif int(team['rank_change']) < 0:
img.paste(down_img, (x_offset, 3))
x_offset += down_img.size[0] + 2
img.paste(rank_change_img, (x_offset, 0))
x_offset += rank_change_img.size[0] + 2
except:
pass
elif league == 'PGA':
if str(team['rank_change']) != '-':
try:
up_img = Image.open('logos/up-tiny.png')
down_img = Image.open('logos/down-tiny.png')
if int(team['rank_change']) > 0:
img.paste(up_img, (x_offset, 3))
x_offset += up_img.size[0] + 2
elif int(team['rank_change']) < 0:
img.paste(down_img, (x_offset, 3))
x_offset += down_img.size[0] + 2
img.paste(rank_change_img, (x_offset, 0))
x_offset += rank_change_img.size[0] + 2
except:
pass
try:
ptsgained_img = self.textImage('+'+str(team['gained_pts']), pga_small, r=0, g= 255, b=0)
ptslost_img = self.textImage(str(team['lost_pts']), pga_small, r=255, g= 0, b=0)
img.paste(ptsgained_img, (x_offset, 3))
x_offset += ptsgained_img.size[0] + 2
img.paste(ptslost_img, (x_offset, 3))
x_offset += ptslost_img.size[0] + 2
except:
pass
totalpts_img = self.textImage('Total:', pga_small, r = 255, g = 255, b = 255)
totalpts2_img = self.textImage(str(team['total_pts']), pga_small, r = 0, g = 255, b = 0)
img.paste(totalpts_img, (x_offset2, 10))
x_offset2 += totalpts_img.size[0]
img.paste(totalpts2_img, (x_offset2, 10))
x_offset2 += totalpts2_img.size[0] + 3
avgpts_img = self.textImage('Avg:', pga_small, r = 255, g = 255, b = 255)
avgpts2_img = self.textImage(str(team['avg_pts']), pga_small, r = 0, g = 0, b = 255)
img.paste(avgpts_img, (x_offset2, 10))
x_offset2 += avgpts_img.size[0]
img.paste(avgpts2_img, (x_offset2, 10))
x_offset2 += avgpts2_img.size[0] + 3
events_img = self.textImage('Events:', pga_small, r= 255, g = 255, b = 255)
events2_img = self.textImage(str(team['events_played']), pga_small, r= 255, g = 128, b = 0)
img.paste(events_img, (x_offset2, 10))
x_offset2 += events_img.size[0]
img.paste(events2_img, (x_offset2, 10))
x_offset2 += events2_img.size[0] + 3
x_offsetfinal = max(x_offset2, x_offset)
x_offset = x_offsetfinal + 15
else:
name_timage = self.textImage(team['name'].upper(), font, r = 255, g = 255, b = 0)
wins_timage = self.textImage('W:' + str(team['wins']), font, r = 0, g = 255, b = 0)
loss_timage = self.textImage('L:' + str(team['loss']), font, r = 255, g = 0, b = 0)
draw_timage = self.textImage('D:' + str(team['draw']), font, r = 0, g = 0, b = 255)
standing_timage = self.textImage('#' + str(team['standing']), font, r = 255, g = 255, b = 255)
img.paste(standing_timage, (x_offset, 3))
x_offset += (standing_timage.size[0])
try:
logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[team['name']]['logo']))
width, height = logo.size
logo2 = logo.resize((int(width/2), int(height/2)))
img.paste(logo2, (x_offset, 0))
x_offset += (logo2.size[0] + 3)
except Exception as e:
pass
img.paste(name_timage, (x_offset, 3))
x_offset += (name_timage.size[0] +2)
img.paste(wins_timage, (x_offset, 3))
x_offset += (wins_timage.size[0] +2)
img.paste(loss_timage, (x_offset, 3))
x_offset += (loss_timage.size[0] +2)
img.paste(draw_timage, (x_offset, 3))
x_offset += (draw_timage.size[0]+10)
x_offset += 25
img1 = img.crop((0,0,x_offset ,16))
imgs.append(img1)
except Exception as e:
pass
return self.stitchImage(imgs)
def getLeagueProfessional(self, league=False, time = 'future'):
if time in ['past', 'live']:
filepath = 'csv/{}_games.json'.format(time)
else:
filepath = 'csv/upcoming_games.json'
f = open(filepath, 'r')
all_settings = json.load(f)
f.close()
title_img = self.openImage('feature_titles/sports_'+ time + '.png')
imgs = []
if all_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/sports_{}.png'.format(time))
imgs = [title_img, self.blank]
else:
imgs = []
leagues_info = all_settings['leagues']
leagues = list(leagues_info.keys())
if time == 'live':
for league in leagues:
try:
x_offset = 0
if league == 'NFL':
f = open('csv/live_nfl.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['NFL'][0]
elif league == 'NHL':
f = open('csv/live_nhl.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['NHL'][0]
elif league == 'NBA':
f = open('csv/live_nba.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['NBA'][0]
elif league == 'MLB':
f = open('csv/live_mlb.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['MLB'][0]
elif league == 'MLS':
f = open('csv/live_mls.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['MLS'][0]
elif league == 'PREMIERLEAGUE':
f = open('csv/live_pl.json', 'r')
all_settings = json.load(f)
f.close()
league_info = all_settings['leagues']['PREMIERLEAGUE'][0]
img = Image.new('RGB', (10000, 32))
try:
league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB')
width, height = league_logo.size
league_logo2 = league_logo.resize((int(width/2), int(height/2)))
img.paste(league_logo2, (x_offset,0))
x_offset += (league_logo2.size[0]+10)
except:
pass
font = ImageFont.load("./fonts/6x10.pil")
small_font = ImageFont.load("./fonts/4x6.pil")
try:
sports_info = self.readSportsCSV(league)
except:
pass
buff_size = 20
if all_settings['leagues'][league][2] == 'no_live' and all_settings['leagues'][league][3] == 'no_upcoming':
no_match = self.textImage(('No live games').upper(), font, r = 255, g = 255 , b = 255)
img.paste(no_match, (x_offset,4))
x_offset += no_match.size[0]
elif all_settings['leagues'][league][3] != 'no_upcoming':
next_match = self.textImage('Next game: ' + all_settings['leagues'][league][3], font, r=255,g=255,b=255)
img.paste(next_match, (x_offset,4))
x_offset += next_match.size[0]
else:
for match in league_info:
if match['isLive'] != 'pre':
dateEvent = match['time']
date_timage = self.textImage(dateEvent, small_font, r = 255, g = 255, b = 255)
strHomeTeam = match['home_team']
strAwayTeam = match['away_team']
intHomeScore = str(match['home_score'])
intAwayScore = str(match['away_score'])
try:
home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strHomeTeam]['logo']))
width1, height1 = home_logo.size
home_logo1 = home_logo.resize((int(width1/2), int(height1/2)))
except Exception as e:
home_logo1 = self.textImage(strHomeTeam, small_font, r = 255, g = 255, b = 255)
try:
away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strAwayTeam]['logo']))
width2, height2 = away_logo.size
away_logo1 = away_logo.resize((int(width2/2), int(height2/2)))
except Exception as e:
away_logo1 = self.textImage(strAwayTeam, small_font, r = 255, g = 255, b = 255)
error = False
img.paste(away_logo1, (x_offset,0))
x_offset += (away_logo1.size[0] + 2)
score_image = self.textImage(intAwayScore + '-' + intHomeScore, font, h_buff = 5, r = 255, g = 255, b = 255)
try:
h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', ''))
except:
pass
try:
a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', ''))
except:
pass
try:
hc_timage = self.textImage(sports_info[strHomeTeam]['code'], font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255))
except:
hc_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255)
error = True
try:
ac_timage = self.textImage(sports_info[strAwayTeam]['code'], font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255))
except:
ac_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255)
error = True
if date_timage.size[0] > (hc_timage.size[0] + 2 + score_image.size[0] + ac_timage.size[0]):
x_offset10 = x_offset + int((date_timage.size[0]/2)-(score_image.size[0]/2)-ac_timage.size[0])
img.paste(date_timage,(x_offset, 0))
img.paste(score_image, (x_offset + int((date_timage.size[0]/2)-(score_image.size[0]/2)), 5))
x_offset += date_timage.size[0]
img.paste(ac_timage,(x_offset10, 5))
if match['isLive'] == 'post':
if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
ua_image = Image.new("RGB", (ac_timage.size[0] -3, 1))
ua_image1 = ImageDraw.Draw(ua_image)
ua_image1.line((0,0,ac_timage.size[0]-3,0), fill="red", width = 0)
img.paste(ua_image, (x_offset10, ac_timage.size[1]+4))
x_offset10 += ac_timage.size[0] + score_image.size[0]
img.paste(hc_timage,(x_offset10, 5))
if match['isLive'] == 'post':
if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
u_image = Image.new("RGB", (hc_timage.size[0] -3, 1))
u_image1 = ImageDraw.Draw(u_image)
u_image1.line((0,0,hc_timage.size[0]-3,0), fill="red", width = 0)
img.paste(u_image, (x_offset10, hc_timage.size[1]+4))
x_offset10 += hc_timage.size[0]
if error:
img.paste(home_logo1, (max(x_offset + date_timage.size[0], x_offset10),0))
x_offset += (home_logo1.size[0] + date_timage.size[0])
else:
img.paste(home_logo1, (max(x_offset,x_offset10),0))
x_offset += home_logo1.size[0]
else:
x_offset_date = (x_offset + ac_timage.size[0] + int(score_image.size[0]/2) - int(date_timage.size[0]/2))
img.paste(date_timage, (x_offset_date,0))
#img.paste(date_timage, (x_offset+20+int((score_image.size[0] - date_timage.size[0])/2),0))
img.paste(ac_timage, (x_offset, 5))
if match['isLive'] == 'post':
if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
ua_image = Image.new("RGB", (ac_timage.size[0] -3, 1))
ua_image1 = ImageDraw.Draw(ua_image)
ua_image1.line((0,0,ac_timage.size[0]-3,0), fill="red", width = 0)
img.paste(ua_image, (x_offset, ac_timage.size[1]+4))
x_offset += ac_timage.size[0]
img.paste(score_image, (x_offset, 5))
x_offset += score_image.size[0]
img.paste(hc_timage, (x_offset, 5))
if match['isLive'] == 'post':
if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
u_image = Image.new("RGB", (hc_timage.size[0] -3, 1))
u_image1 = ImageDraw.Draw(u_image)
u_image1.line((0,0,hc_timage.size[0]-3,0), fill="red", width = 0)
img.paste(u_image, (x_offset, hc_timage.size[1]+4))
x_offset += hc_timage.size[0]
x_offset_date += date_timage.size[0]
if error:
img.paste(home_logo1, (max(x_offset + date_timage.size[0], x_offset_date),0))
x_offset += (home_logo1.size[0] + date_timage.size[0])
else:
img.paste(home_logo1, (max(x_offset,x_offset_date),0))
x_offset += home_logo1.size[0]
x_offset += buff_size
x_offset += 20
img = img.crop((0,0,x_offset ,16))
imgs.append(img)
except:
pass
else:
for league in leagues:
try:
x_offset = 0
img = Image.new('RGB', (10000, 32))
league_info = leagues_info[league]
#league logo
try:
league_logo = Image.open('logos/sports/league_logos/{}.png'.format(league)).convert('RGB')
width, height = league_logo.size
league_logo2 = league_logo.resize((int(width/2), int(height/2)))
if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'):
x_offset += 10
else:
img.paste(league_logo2, (x_offset,0))
x_offset += (league_logo2.size[0]+10)
except:
pass
font = ImageFont.load("./fonts/6x10.pil")
small_font = ImageFont.load("./fonts/4x6.pil")
try:
sports_info = self.readSportsCSV(league)
except:
pass
buff_size = 20
if league == 'UFC':
try:
date_img = self.textImage(league_info[0]['date'], small_font, r=0,g=150,b=255)
eventname_img = self.textImage(league_info[0]['name'].upper(), font, r=255, g=0, b=0)
venue_img = self.textImage(league_info[0]['venue'], small_font, r=255, g=255, b=0)
city_img = self.textImage(league_info[0]['city'], small_font, r=255, g=255, b=255)
try:
country_img = self.textImage(league_info[0]['country'], small_font, r=255, g=128, b=0)
except:
pass
broadcast_img = self.textImage(league_info[0]['broadcast'], small_font, r=255, g=0, b=0)
time_img = self.textImage(league_info[0]['time'], small_font, r =0, g=150, b=255)
try:
img.paste(country_img, (x_offset + eventname_img.size[0] + 2, 2))
except:
country_img = 0
pass
img.paste(eventname_img, (x_offset, 0))
img.paste(city_img, (x_offset + date_img.size[0] + 3 + time_img.size[0] + 3 + broadcast_img.size[0] + 7 + venue_img.size[0] + 3, 10))
img.paste(venue_img, (x_offset + date_img.size[0] + 3 + time_img.size[0] + 3 + broadcast_img.size[0] + 7,10))
img.paste(broadcast_img, (x_offset + date_img.size[0] + 3 + time_img.size[0] + 3, 10))
img.paste(date_img, (x_offset, 10))
img.paste(time_img, (x_offset + date_img.size[0] + 3, 10))
try:
x_offset = 10 + max(x_offset + eventname_img.size[0] + 2 + country_img.size[0], x_offset + date_img.size[0] + 3 + time_img.size[0] + 3 + broadcast_img.size[0] + 7 + venue_img.size[0] + 3 + city_img.size[0])
except:
x_offset = 10 + max(x_offset + eventname_img.size[0], x_offset + date_img.size[0] + 3 + time_img.size[0] + 3 + broadcast_img.size[0] + 7 + venue_img.size[0] + 3 + city_img.size[0])
for fight in league_info[0]['fights']:
try:
if time != 'past':
fighter1_img = Image.open('logos/ufc/{}.png'.format(fight['fighter1id']))
elif time == 'past':
fighter1_img = Image.open('logos/ufc_past/{}.png'.format(fight['fighter1id']))
fighter1_img.thumbnail((9000,16))
except:
fighter1_img = Image.open('logos/unknown.png')
fighter1_img.thumbnail((9000,16))
pass
draw = ImageDraw.Draw(img, "RGBA")
name1_img = self.textImage(fight['fighter1name'].split(' ',1)[0][0] + '.' + fight['fighter1name'].split(' ',1)[1], small_font, r=255,g=255,b=255)
max_fighter1pic = max(name1_img.size[0],fighter1_img.size[0])
img.paste(fighter1_img, (x_offset + int(max_fighter1pic/2) - int(fighter1_img.size[0]/2), 0), mask=fighter1_img)
draw.rectangle([(x_offset,16),(x_offset + name1_img.size[0]-4,10)], fill=(5,5,5,200))
draw.text((x_offset + int(max_fighter1pic/2) - int(name1_img.size[0]/2),10), fight['fighter1name'].split(' ',1)[0][0] + '.' + fight['fighter1name'].split(' ',1)[1], fill=(255,255,255),font=small_font)
try:
country1_img = Image.open('logos/ufc_countries/{}'.format(fight['fighter1country'].split('/')[-1].split('&')[0]))
country1_img.thumbnail((9000,8))
img.paste(country1_img,(x_offset, 0))
except:
pass
x_offset += max_fighter1pic
try:
if time != 'past':
fighter2_img = Image.open('logos/ufc/{}.png'.format(fight['fighter2id']))
elif time == 'past':
fighter2_img = Image.open('logos/ufc_past/{}.png'.format(fight['fighter2id']))
fighter2_img.thumbnail((9000,16))
except:
fighter2_img = Image.open('logos/unknown.png')
fighter2_img.thumbnail((9000,16))
pass
weight_img = self.textImage(fight['weight_div'].upper(), small_font, r=255,g=0,b=0)
vs_img = self.textImage('VS', small_font, r=255,g=255,b=255)
if time != 'past':
odds1_img = self.textImage(fight['fighter1odds'], small_font, r=0, g=255, b=0)
odds2_img = self.textImage(fight['fighter2odds'], small_font, r=0, g=255, b=0)
max_middle = max(vs_img.size[0] + odds1_img.size[0] + odds2_img.size[0], weight_img.size[0])
img.paste(weight_img, (x_offset + int(max_middle/2) - int(weight_img.size[0]/2), 1))
img.paste(odds1_img, (x_offset + int(max_middle/2) - int(vs_img.size[0]/2) - odds1_img.size[0],8))
img.paste(vs_img, (x_offset + int(max_middle/2) - int(vs_img.size[0]/2),8))
img.paste(odds2_img, (x_offset + int(max_middle/2) + int(vs_img.size[0]/2),8))
elif time == 'past':
if fight['fighter1win']:
win1_img = self.textImage('WIN', small_font, r=0, g=255, b=0)
win2_img = self.textImage('LOSS', small_font, r=255, g=0, b=0)
elif not fight['fighter1win'] and not fight['fighter2win']:
win1_img = self.textImage('DRAW', small_font, r=80, g=80, b=80)
win2_img = self.textImage('DRAW', small_font, r=80, g=80, b=80)
else:
win1_img = self.textImage('LOSS', small_font, r=255, g=0, b=0)
win2_img = self.textImage('WIN', small_font, r=0, g=255, b=0)
max_middle = max(vs_img.size[0] + win1_img.size[0] + win2_img.size[0], weight_img.size[0])
img.paste(weight_img, (x_offset + int(max_middle/2) - int(weight_img.size[0]/2), 1))
img.paste(win1_img, (x_offset + int(max_middle/2) - int(vs_img.size[0]/2) - int(win1_img.size[0]),8))
img.paste(vs_img, (x_offset + int(max_middle/2) - int(vs_img.size[0]/2),8))
img.paste(win2_img, (x_offset + int(max_middle/2) + int(vs_img.size[0]/2),8))
x_offset += max_middle
name2_img = self.textImage(fight['fighter2name'].split(' ',1)[0][0] + '.' + fight['fighter2name'].split(' ',1)[1], small_font, r=255,g=255,b=255)
max_fighter2pic = max(name2_img.size[0],fighter2_img.size[0])
img.paste(fighter2_img, (x_offset + int(max_fighter2pic/2) - int(fighter2_img.size[0]/2), 0), mask=fighter2_img)
draw.rectangle([(x_offset,16),(x_offset + name2_img.size[0]-4,10)], fill=(5,5,5,200))
draw.text((x_offset + int(max_fighter2pic/2) - int(name2_img.size[0]/2),10), fight['fighter2name'].split(' ',1)[0][0] + '.' + fight['fighter2name'].split(' ',1)[1], fill=(255,255,255),font=small_font)
try:
country2_img = Image.open('logos/ufc_countries/{}'.format(fight['fighter2country'].split('/')[-1].split('&')[0]))
country2_img.thumbnail((9000,8))
img.paste(country2_img,(x_offset + max_fighter2pic - country2_img.size[0] - 2, 0))
except:
pass
x_offset += max_fighter2pic + 15
except:
pass
# DONT FORGET TO CHANGE DIRECTORY FOR PAST UFC GAMES
else:
for match in league_info:
try:
dateEvent = match['date2']
except:
dateEvent = match['date'].replace('-', '.')
if time == 'future':
try:
date_timage = self.textImage(dateEvent + ' ' + match['time'].replace("EST","").replace('PM','P').replace('AM','A').replace('CET',''), small_font, r = 255, g = 255, b = 255)
except:
date_timage = self.textImage(dateEvent, small_font, r = 255, g = 255, b = 255)
else:
date_timage = self.textImage(dateEvent, small_font, r = 255, g = 255, b = 255)
if (league == 'PGA') or (league == 'LPGA') or (league == 'PGA_EU') or (league == 'LIV') or (league == 'NASCAR') or (league == 'F1'):
event = match['event']
venue = match['venue']
city = match['city']
country = match['country']
season = match['season']
if (time != 'future') and (league != 'LIV'):
golf_standings1 = match['golf_rankings'][::2]
golf_standings2 = match['golf_rankings'][1::2]
elif (time!= 'future') and (league == 'LIV'):
golf_standings1 = match['golf_rankings'][::2]
golf_standings2 = match['golf_rankings'][1::2]
img.paste(league_logo2, (x_offset, 0))
x_offset += league_logo2.size[0] + 5
try:
if match['purse'] != 'N/A' and match['purse'] != "" and match['purse'] != '0':
purse_timage = self.textImage(match['purse'], small_font, r=0,g=255,b=0)
except:
pass
try:
if match['shots_par'] != 'N/A' and match['shots_par'] != "" and match['shots_par'] != 0:
par_timage = self.textImage('Par' + str(match['shots_par']), small_font, r=255,g=127,b=80)
except:
pass
try:
if match['total_yards'] != 'N/A' and match['total_yards'] != "" and match['total_yards'] != 0:
yards_timage = self.textImage(str(match['total_yards']) + 'yds', small_font, r=255,g=127,b=80)
except:
pass
if time == 'future':
event_timage = self.textImage(event, small_font, r=255, g=255, b=0)
venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0)
city_timage = self.textImage(city, small_font, r=255, g=255, b=255)
country_timage = self.textImage(country, small_font, r=255, g=255, b=255)
season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255)
season_timage = self.textImage(season, small_font, r=255, g=255, b=255)
date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171)
#event
img.paste(event_timage, (x_offset, 1))
#venue
img.paste(venue_timage,(x_offset, 9))
x_offset += (max(event_timage.size[0], venue_timage.size[0]) + 5)
x_offset_2nd = x_offset
#date
img.paste(date1_timage, (x_offset, 1))
x_offset += date1_timage.size[0]
img.paste(date_timage, (x_offset, 1))
x_offset += date_timage.size[0] + 5
#city
img.paste(city_timage,(x_offset_2nd, 9))
x_offset_2nd += city_timage.size[0] + 7
#country
img.paste(country_timage,(x_offset_2nd,9))
x_offset_2nd += country_timage.size[0] + 5
#season
img.paste(season1_timage,(x_offset,1))
x_offset += season1_timage.size[0]
img.paste(season_timage,(x_offset,1))
x_offset += season_timage.size[0] + 5
try:
if match['purse'] != 'N/A' and match['purse'] != "" and match['purse'] != '0':
img.paste(purse_timage, (x_offset, 1))
x_offset += purse_timage.size[0] + 5
except:
pass
try:
if match['total_yards'] != 'N/A' and match['total_yards'] != "" and match['total_yards'] != 0:
img.paste(yards_timage, (x_offset_2nd, 9))
x_offset_2nd += yards_timage.size[0] + 5
except:
pass
try:
if match['shots_par'] != 'N/A' and match['shots_par'] != "" and match['shots_par'] != 0:
img.paste(par_timage, (x_offset_2nd, 9))
x_offset_2nd += par_timage.size[0] + 5
except:
pass
x_offset = max(x_offset, x_offset_2nd)
#x_offset += max(date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5 + season_timage.size[0], city_timage.size[0] + 7 + country_timage.size[0])
x_offset += (buff_size - 10)
else:
event_timage = self.textImage(event, small_font, r=255, g=255, b=0)
venue_timage = self.textImage(venue, small_font, r=0, g=255, b=0)
city_timage = self.textImage(city, small_font, r=255, g=255, b=255)
country_timage = self.textImage(country, small_font, r=255, g=255, b=255)
season1_timage = self.textImage('Season:', small_font, r=0, g=170, b=255)
season_timage = self.textImage(season, small_font, r=255, g=255, b=255)
date1_timage = self.textImage('Date:', small_font, r=255, g=0, b=171)
#event
img.paste(event_timage, (x_offset, 1))
#venue
img.paste(venue_timage,(x_offset, 9))
x_offset += (max(event_timage.size[0], venue_timage.size[0]) + 5)
x_offset_2nd = x_offset
#date
img.paste(date1_timage, (x_offset, 1))
x_offset += date1_timage.size[0]
img.paste(date_timage, (x_offset, 1))
x_offset += date_timage.size[0] + 5
#city
img.paste(city_timage,(x_offset_2nd, 9))
x_offset_2nd += city_timage.size[0] + 7
#country
img.paste(country_timage,(x_offset_2nd,9))
x_offset_2nd += country_timage.size[0] + 5
#season
img.paste(season1_timage,(x_offset,1))
x_offset += season1_timage.size[0]
img.paste(season_timage,(x_offset,1))
x_offset += season_timage.size[0] + 5
try:
if match['purse'] != 'N/A' and match['purse'] != "" and match['purse'] != '0':
img.paste(purse_timage, (x_offset, 1))
x_offset += purse_timage.size[0] + 5
except:
pass
try:
if match['total_yards'] != 'N/A' and match['total_yards'] != "" and match['total_yards'] != 0:
img.paste(yards_timage, (x_offset_2nd, 9))
x_offset_2nd += yards_timage.size[0] + 5
except:
pass
try:
if match['shots_par'] != 'N/A' and match['shots_par'] != "" and match['shots_par'] != 0:
img.paste(par_timage, (x_offset_2nd, 9))
x_offset_2nd += par_timage.size[0] + 5
except:
pass
x_offset = max(x_offset, x_offset_2nd)
#x_offset += max(date1_timage.size[0] + 2 + date_timage.size[0] + season1_timage.size[0] + 5 + season_timage.size[0], city_timage.size[0] + 7 + country_timage.size[0])
symbol1_timage = self.textImage('|', small_font, r=255, g=255, b=0)
for each_player, each_player2 in zip(golf_standings1, golf_standings2):
img.paste(symbol1_timage, (x_offset, 1))
img.paste(symbol1_timage, (x_offset, 9))
x_offset += symbol1_timage.size[0] + 2
golf1_offset = 0
golf2_offset = 0
try:
golf1_rank_timage = self.textImage(each_player['rank'], small_font, r=255, g=255, b=255)
img.paste(golf1_rank_timage,(x_offset, 1))
golf1_offset += golf1_rank_timage.size[0] + 2
try:
golf1_country = Image.open('logos/ufc_countries/{}'.format(each_player['country'].split('/')[-1].split('&')[0]))
golf1_country.thumbnail((9000,9))
img.paste(golf1_country,(golf1_offset + x_offset, -1))
golf1_offset += golf1_country.size[0] + 2
except:
pass
golf_standings1_timage = self.textImage(each_player['name'] + ' ' + each_player['score'], small_font, r=255, g=255, b=255)
img.paste(golf_standings1_timage, (x_offset + golf1_offset, 1))
golf1_offset += golf_standings1_timage.size[0]
except:
pass
try:
golf2_rank_timage = self.textImage(each_player2['rank'], small_font, r=255, g=255, b=255)
golf2_offset += golf2_rank_timage.size[0] + 2
img.paste(golf2_rank_timage,(x_offset, 9))
try:
golf2_country = Image.open('logos/ufc_countries/{}'.format(each_player2['country'].split('/')[-1].split('&')[0]))
golf2_country.thumbnail((9000,9))
img.paste(golf2_country,(x_offset + golf2_offset, 7))
golf2_offset += golf2_country.size[0] + 2
except:
pass
golf_standings2_timage = self.textImage(each_player2['name'] + ' ' + each_player2['score'], small_font, r=255, g=255, b=255)
img.paste(golf_standings2_timage, (x_offset + golf2_offset, 9))
golf2_offset += golf_standings2_timage.size[0]
except:
pass
x_offset += max(golf2_offset, golf1_offset) + 5
# for each_player in golf_standings1:
# symbol1_timage = self.textImage('|', small_font, r=255, g=255, b=0)
# img.paste(symbol1_timage, (x_offset + 5, 1))
# golf_standings1_timage = self.textImage(each_player, small_font, r=255, g=255, b=255)
# img.paste(golf_standings1_timage, (x_offset + symbol1_timage.size[0] + 7, 1))
# x_offset += (golf_standings1_timage.size[0] + symbol1_timage.size[0] + 7)
#
# for each_player2 in golf_standings2:
# symbol2_timage = self.textImage('|', small_font, r=255, g=255, b=0)
# img.paste(symbol2_timage, (x_offset2 + 5, 9))
# golf_standings2_timage = self.textImage(each_player2, small_font, r=255, g=255, b=255)
# img.paste(golf_standings2_timage, (x_offset2 + symbol2_timage.size[0] + 7, 9))
# x_offset2 += (golf_standings2_timage.size[0] + symbol2_timage.size[0] + 7)
x_offset += (buff_size - 10)
else:
strHomeTeam = match['home_team']
strAwayTeam = match['away_team']
if time != 'future':
intHomeScore = str(match['home_score'])
intAwayScore = str(match['away_score'])
try:
home_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strHomeTeam]['logo']))
width1, height1 = home_logo.size
home_logo1 = home_logo.resize((int(width1/2), int(height1/2)))
except Exception as e:
home_logo1 = self.textImage(strHomeTeam, small_font, r = 255, g = 255, b = 255)
try:
away_logo = Image.open('logos/sports/{}/{}'.format(league, sports_info[strAwayTeam]['logo']))
width2, height2 = away_logo.size
away_logo1 = away_logo.resize((int(width2/2), int(height2/2)))
except Exception as e:
away_logo1 = self.textImage(strAwayTeam, small_font, r = 255, g = 255, b = 255)
error = False
img.paste(away_logo1, (x_offset,0))
x_offset += (away_logo1.size[0] + 2)
if time == 'future':
try:
h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', ''))
except:
pass
try:
a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', ''))
except:
pass
try:
hc_timage = self.textImage(sports_info[strHomeTeam]['code'], font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255))
except:
hc_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255)
error = True
try:
ac_timage = self.textImage(sports_info[strAwayTeam]['code'], font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255))
except:
ac_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255)
error = True
vs_timage = self.textImage('vs', font, r = 255, g = 255, b = 255, h_buff = 5)
x_offsetdate2 = x_offset + int((hc_timage.size[0] + vs_timage.size[0] + ac_timage.size[0])/2)- int(date_timage.size[0]/2)
if date_timage.size[0] > (ac_timage.size[0] + vs_timage.size[0] + hc_timage.size[0]):
x_offset3 = x_offset + int(date_timage.size[0]/2)
img.paste(date_timage, (x_offset,0))
x_offset += date_timage.size[0]
img.paste(ac_timage, (x_offset3 - int(ac_timage.size[0]) - int(vs_timage.size[0]/2), 5))
img.paste(vs_timage, (x_offset3 - int(vs_timage.size[0]/2), 5))
img.paste(hc_timage, (x_offset3 + int(vs_timage.size[0]/2), 5))
else:
img.paste(date_timage, (x_offsetdate2,0))
x_offsetdate2 += date_timage.size[0]
img.paste(ac_timage, (x_offset, 5))
x_offset += ac_timage.size[0]
img.paste(vs_timage, (x_offset, 5))
x_offset += vs_timage.size[0]
img.paste(hc_timage, (x_offset, 5))
x_offset += hc_timage.size[0]
else:
score_image = self.textImage(intAwayScore + '-' + intHomeScore, font, h_buff = 5, r = 255, g = 255, b = 255)
try:
h_colour = mcolors.to_rgb(sports_info[strHomeTeam]['colour'].replace(' ', ''))
except:
pass
try:
a_colour = mcolors.to_rgb(sports_info[strAwayTeam]['colour'].replace(' ', ''))
except:
pass
try:
hc_timage = self.textImage(sports_info[strHomeTeam]['code'], font, r = int(h_colour[0]*255), g = int(h_colour[1]*255), b = int(h_colour[2]*255))
except:
hc_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255)
error = True
try:
ac_timage = self.textImage(sports_info[strAwayTeam]['code'], font, r = int(a_colour[0]*255), g = int(a_colour[1]*255), b = int(a_colour[2]*255))
except:
ac_timage = self.textImage('.', small_font, r = 255, g = 255, b = 255)
error = True
x_offsetdate2 = x_offset + ac_timage.size[0] + int(score_image.size[0]/2)- int(date_timage.size[0]/2)
img.paste(date_timage, (x_offsetdate2,0))
x_offsetdate2 += date_timage.size[0]
#img.paste(date_timage, (x_offset+20+int((score_image.size[0] - date_timage.size[0])/2),0))
img.paste(ac_timage, (x_offset, 5))
if int(intHomeScore) < int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
ua_image = Image.new("RGB", (ac_timage.size[0] -3, 1))
ua_image1 = ImageDraw.Draw(ua_image)
ua_image1.line((0,0,ac_timage.size[0]-3,0), fill="red", width = 0)
img.paste(ua_image, (x_offset, ac_timage.size[1]+4))
x_offset += ac_timage.size[0]
img.paste(score_image, (x_offset, 5))
x_offset += score_image.size[0]
img.paste(hc_timage, (x_offset, 5))
if int(intHomeScore) > int(intAwayScore) or int(intHomeScore) == int(intAwayScore):
u_image = Image.new("RGB", (hc_timage.size[0] -3, 1))
u_image1 = ImageDraw.Draw(u_image)
u_image1.line((0,0,hc_timage.size[0]-3,0), fill="red", width = 0)
img.paste(u_image, (x_offset, hc_timage.size[1]+4))
x_offset += hc_timage.size[0]
if error:
img.paste(home_logo1, (max(x_offset + date_timage.size[0], x_offsetdate2),0))
x_offset += (home_logo1.size[0] + date_timage.size[0])
else:
img.paste(home_logo1, (max(x_offset, x_offsetdate2),0))
x_offset += home_logo1.size[0]
x_offset += buff_size
x_offset += 20 #INDENT THIS OR NO?
img = img.crop((0,0,x_offset ,16))
imgs.append(img)
except:
pass
return self.stitchImage(imgs)
def convertTemp(self,temp, setting):
if setting == 'kelvin':
temp = temp+ 273.15
elif setting == 'fahrenheit':
temp = temp*9/5 + 32
return temp
def getTodayWeatherImage(self):
f = open('csv/current_weather.json', 'r')
all_settings = json.load(f)
f.close()
if all_settings['title']:
title_img = self.openImage('feature_titles/weather.png')
imgs = [title_img, self.blank]
else:
imgs = []
current_weathers = all_settings['locations']
locations = list(current_weathers.keys())
for i, location in enumerate(locations):
try:
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)
main = current_weather['main_weather']
if main == 'Clouds':
main = current_weather['description']
if main == 'Rain':
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', 'light rain': '10', 'moderate rain': '10', 'heavy intensity rain': '10',
'very heavy rain': '10', 'extreme rain': '10', 'freezing rain': '13', 'light intensity shower rain': '09', 'shower rain': '09',
'heavy intensity shower rain': '09', 'ragged shower rain': '09'}
weather_dir = './logos/weather_icons'
weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png')
temp = self.convertTemp(current_weather['temp'], all_settings['temp'])
feels_temp = self.convertTemp(current_weather['feels_like'], all_settings['temp'])
temp_img = self.textImage(str("{0:.0f}".format(temp)), large_font)
deg_img = self.textImage('o', small_font)
main = current_weather['main_weather']
main_img = self.textImage(main.upper(), small_font)
feels_img = self.textImage('Feels like:'.upper() + str("{0:.0f}".format(feels_temp)), small_font)
min_img = self.textImage( "{0:.0f}".format(self.convertTemp(current_weather['min_temp'], all_settings['temp'])), small_font, r=0, g=0, b=255)
max_img = self.textImage( "{0:.0f}".format(self.convertTemp(current_weather['max_temp'], all_settings['temp'])), small_font, r=255, g=0, b=0)
hum_img = Image.open(weather_dir + '/humidity.png')
htext_img = self.textImage(str(current_weather['humidity']) + '%', small_font)
uv_img = Image.open(weather_dir + '/uv.png')
utext_img = self.textImage(str(round(current_weather['uv'], 1)) , 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(), small_font)
rain_img = Image.open(weather_dir + '/rain-chance.png')
rtext_img = self.textImage(str(current_weather['rain_chance']) + '%', 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')
w_speed = current_weather['wind_speed']
w_unit = 'K/H'
if all_settings["wind_speed"] == "miles/hour":
w_speed = current_weather['wind_speed']/1.609
w_unit = 'M/H'
wtext_img = self.textImage("{0:.0f}".format(w_speed) + w_unit, small_font)
wdir_img = self.textImage(self.degreesToCompass(current_weather['wind_direction']).upper(), small_font)
vis_img = Image.open(weather_dir + '/visibility.png')
vtext_img = self.textImage(str(round(current_weather['visibility']/1000, 1)) + 'km'.upper(), small_font)
'------------------------------------------'
img = Image.new('RGB', (1000, 32))
img.paste(weather_img, (5,9))
x_offset = 5 + weather_img.size[0] + 1
img.paste(main_img, (x_offset, 26))
img.paste(temp_img, (x_offset + main_img.size[0]//2 - temp_img.size[0]//2,9))
img.paste(deg_img, (x_offset + main_img.size[0]//2 - temp_img.size[0]//2 + temp_img.size[0], 8))
x_offset += max( main_img.size[0], temp_img.size[0] + deg_img.size[0])
img.paste(min_img, (x_offset - 0, 12))
img.paste(max_img, (x_offset - 0, 21))
x_offset += max(min_img.size[0], max_img.size[0]) + 2
img.paste(hum_img, ( x_offset - 1, 8))
img.paste(uv_img, ( x_offset - 1, 22))
img.paste(htext_img, (x_offset + hum_img.size[0], 10))
img.paste(utext_img, (x_offset + uv_img.size[0], 23))
x_offset += max(hum_img.size[0], uv_img.size[0]+2)
x_offset += max(htext_img.size[0], utext_img.size[0]) + 6
img.paste(rain_img, (x_offset,8))
img.paste(cloud_img, (x_offset,20))
img.paste(ctext_img, (x_offset + cloud_img.size[0] + 2, 22))
img.paste(rtext_img, (x_offset + rain_img.size[0]+ 2, 10))
x_offset += max(cloud_img.size[0], rain_img.size[0])+6
x_offset += max(ctext_img.size[0], rtext_img.size[0])+6
img.paste(wind_img, (x_offset,8))
img.paste(vis_img, (x_offset,20))
img.paste(wtext_img, (x_offset + wind_img.size[0] + 2, 10))
img.paste(vtext_img, (x_offset + vis_img.size[0] + 2, 22))
x_offset += wind_img.size[0] + wtext_img.size[0] + 4
img.paste(wdir_img, (x_offset, 10))
img.paste(location_img, (5,0))
img.paste(feels_img, (location_img.size[0] + 10, 0))
img.paste(date_img, (location_img.size[0] + feels_img.size[0] + 15, 0))
img = img.crop((0,0,max(x_offset +wdir_img.size[0] + 4, location_img.size[0] + feels_img.size[0] + 15 + date_img.size[0]) ,32))
imgs.append(img)
imgs.append(self.blank)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
return self.stitchImage(imgs)
def getTodayWeatherProfessional(self):
f = open('csv/current_weather.json', 'r')
all_settings = json.load(f)
f.close()
if all_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/weather.png')
image_list = [title_img, Image.new('RGB', (3, 16))]
else:
image_list = []
current_weathers = all_settings['locations']
locations = list(current_weathers.keys())
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()]
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")
main = current_weather['main_weather']
if main == 'Clouds':
main = current_weather['description']
if main == 'Rain':
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', 'light rain': '10', 'moderate rain': '10', 'heavy intensity rain': '10',
'very heavy rain': '10', 'extreme rain': '10', 'freezing rain': '13', 'light intensity shower rain': '09', 'shower rain': '09',
'heavy intensity shower rain': '09', 'ragged shower rain': '09'}
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
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 + '/small_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 = self.convertTemp(current_weather['temp'], all_settings['temp'])
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)
img.paste(deg_img, (x_offset+1, 1))
x_offset += deg_img.size[0] -2
min_img = self.textImage( "{0:.0f}".format(self.convertTemp(current_weather['min_temp'], all_settings['temp'])), small_font, r=0, g=0, b=255)
img.paste(min_img, (x_offset+2, 2))
max_img = self.textImage( "{0:.0f}".format(self.convertTemp(current_weather['max_temp'], all_settings['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(current_weather['rain_chance']) + '%', 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']
w_unit = 'K/H'
if all_settings["wind_speed"] == "miles/hour":
w_speed = current_weather['wind_speed']/1.609
w_unit = 'M/H'
wtext_img = self.textImage("{0:.0f}".format(w_speed) + w_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))
image_list.append(img)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
return self.stitchImage(image_list)
def getDailyWeatherImageAlt(self):
f = open( "csv/weather_location.txt", 'r' )
location = f.read()
f.close()
img = Image.new('RGB', (128, 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)
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)
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, (75,0))
img.paste(rtext_img, (88, 1))
img.paste(hum_img, (102, 0))
img.paste(htext_img, (113, 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))
img0 = img
img = Image.new('RGB', (1000, 32))
daily_weather = json.load(open('csv/daily_weather.json', 'r'))
#img.paste(date_img, (70, 0))
x_offset = 64
for i in range(0,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 += 35
img1 = img.crop((64,0,x_offset ,32))
img1.save('display_images/weather.ppm')
return img0, img1
def getDailyWeatherImage(self):
f = open('csv/daily_weather.json', 'r')
all_settings = json.load(f)
f.close()
if all_settings['title']:
title_img = self.openImage('feature_titles/forecast.png')
imgs = [title_img, self.blank]
else:
imgs = []
f = open('csv/daily_weather.json', 'r')
daily_weathers = json.load(f)
f.close()
locations = list(daily_weathers['locations'].keys())
for i, location in enumerate(locations):
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(), small_font, r = 255, g = 255, b = 0)
main = daily_weather[0]['main_weather']
if main == 'Clouds':
main = daily_weather[0]['description']
if main == 'Rain':
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', 'light rain': '10', 'moderate rain': '10', 'heavy intensity rain': '10',
'very heavy rain': '10', 'extreme rain': '10', 'freezing rain': '13', 'light intensity shower rain': '09', 'shower rain': '09',
'heavy intensity shower rain': '09', 'ragged shower rain': '09'}
weather_dir = './logos/weather_icons'
weather_img = Image.open(weather_dir + '/weather_type_icons/' + weather_ids[main] + '.png')
temp = self.convertTemp(daily_weather[0]['temp'], daily_weathers['temp'])
min_temp = self.convertTemp(daily_weather[0]['min_temp'], daily_weathers['temp'])
max_temp = self.convertTemp(daily_weather[0]['max_temp'], daily_weathers['temp'])
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, daily_weathers['temp']), small_font, r=0, g=0, b=255)
max_img = self.textImage( "{0:.0f}".format(max_temp, daily_weathers['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(), small_font)
if daily_weathers['current_weather']:
rain_img = Image.open(weather_dir + '/rain-chance.png')
rtext_img = self.textImage(str(daily_weather[0]['rain_chance']) + '%', small_font)
hum_img = Image.open(weather_dir + '/humidity.png')
htext_img = self.textImage(str(daily_weather[0]['humidity']) + '%', small_font)
wind_img = Image.open(weather_dir + '/wind.png')
wtext_img = self.textImage(str(daily_weather[0]['wind_speed']) + 'm/s'.upper(), 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']
w_unit = 'K/H'
if daily_weathers['wind_speed'] == "miles/hour":
w_speed = daily_weather[0]['wind_speed']/1.609
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_offset2 = location_img.size[0]+5
img.paste(weather_img, (5,9))
x_offset = 5 + weather_img.size[0] + 1
img.paste(main_img, (x_offset, 26))
img.paste(temp_img, (x_offset + main_img.size[0]//2 - temp_img.size[0]//2,9))
img.paste(deg_img, (x_offset + main_img.size[0]//2 - temp_img.size[0]//2 + temp_img.size[0], 8))
x_offset += max( main_img.size[0], temp_img.size[0] + deg_img.size[0])
img.paste(min_img, (x_offset - 0, 12))
img.paste(max_img, (x_offset - 0, 21))
x_offset += max(min_img.size[0], max_img.size[0]) + 2
img.paste(date_img, (x_offset2, 0))
x_offset2 += date_img.size[0]+5
if daily_weathers['current_weather']:
img.paste(rain_img, (x_offset2,0))
x_offset2 += rain_img.size[0]+2
img.paste(rtext_img, (x_offset2,1))
x_offset2 += rtext_img.size[0]+2
img.paste(hum_img, (x_offset2, 0))
x_offset2 += hum_img.size[0]+2
img.paste(htext_img, (x_offset2, 1))
x_offset2+= htext_img.size[0]+2
img.paste(uv_img, ( x_offset2, 0))
x_offset2 += uv_img.size[0]+2
img.paste(utext_img, (x_offset2, 1))
x_offset2 += utext_img.size[0]+2
img.paste(cloud_img, (x_offset2,0))
x_offset2 += cloud_img.size[0]+2
img.paste(ctext_img, (x_offset2, 1))
x_offset2 += ctext_img.size[0]+2
img.paste(wind_img, (x_offset2,0))
x_offset2 += wind_img.size[0]+2
img.paste(wtext_img, (x_offset2, 1))
x_offset2 += wtext_img.size[0]+2
img.paste(wdir_img, (x_offset2, 1))
x_offset2+= wdir_img.size[0]+2
img.paste(vis_img, (x_offset2,-1))
x_offset2+= vis_img.size[0]+2
img.paste(vtext_img, (x_offset2, 1))
x_offset2 += vtext_img.size[0] +2
for i in range(1,len(daily_weather)):
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']
if main == 'Rain':
main = weather['description']
min_temp = self.convertTemp(weather['min_temp'], daily_weathers['temp'])
max_temp = self.convertTemp(weather['max_temp'], daily_weathers['temp'])
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 += 43
img1 = img.crop((0,0,max(x_offset, x_offset2 + 10) ,32))
imgs.append(img1)
imgs.append(self.blank)
# add the image text
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
return self.stitchImage(imgs)
def getDailyWeatherProfessional(self):
f = open('csv/daily_weather.json', 'r')
all_settings = json.load(f)
f.close()
if all_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/forecast.png')
image_list = [title_img, Image.new('RGB', (3, 16))]
else:
image_list = []
f = open('csv/daily_weather.json', 'r')
daily_weathers = json.load(f)
f.close()
locations = list(daily_weathers['locations'].keys())
for i, location in enumerate(locations):
try:
img = Image.new('RGB', (1000, 32))
daily_weather = daily_weathers['locations'][location]
small_font = ImageFont.load("./fonts/4x6.pil")
font = ImageFont.load("./fonts/6x10.pil")
large_font = ImageFont.load("./fonts/10x20.pil")
main = daily_weather[0]['main_weather']
if main == 'Clouds':
main = daily_weather[0]['description']
if main == 'Rain':
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', 'light rain': '10', 'moderate rain': '10', 'heavy intensity rain': '10',
'very heavy rain': '10', 'extreme rain': '10', 'freezing rain': '13', 'light intensity shower rain': '09', 'shower rain': '09',
'heavy intensity shower rain': '09', 'ragged shower rain': '09'}
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
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(), font)
img.paste(date_img, (x_offset, 3))
x_offset += date_img.size[0] + 2
weather_img = Image.open(weather_dir + '/small_icons/' + weather_ids[main] + '.png')
w, h = weather_img.size
#weather_img = weather_img.resize((int(w/2), int(h/2)))
main = daily_weather[0]['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 = self.convertTemp(daily_weather[0]['temp'], daily_weathers['temp'])
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)
img.paste(deg_img, (x_offset+1, 1))
x_offset += deg_img.size[0] -2
min_img = self.textImage( "{0:.0f}".format(self.convertTemp(daily_weather[0]['min_temp'], daily_weathers['temp'])), small_font, r=0, g=0, b=255)
img.paste(min_img, (x_offset+2, 2))
max_img = self.textImage( "{0:.0f}".format(self.convertTemp(daily_weather[0]['max_temp'], daily_weathers['temp'])), small_font, r=255, g=0, b=0)
img.paste(max_img, (x_offset+2, 8))
x_offset += max_img.size[0] + 15
crop_x = x_offset
for i in range(1,len(daily_weather)):
weekday = weekdays[(datetime.today().weekday() + i)%7]
day_img = self.textImage( weekday.upper(), font)
weather = daily_weather[i]
main = weather['main_weather']
if main == 'Clouds':
main = weather['description']
if main == 'Rain':
main = weather['description']
min_img = self.textImage( "{0:.0f}".format(self.convertTemp(weather['min_temp'], daily_weathers['temp'])), small_font, r=0, g=0, b=255)
max_img = self.textImage( "{0:.0f}".format(self.convertTemp(weather['max_temp'], daily_weathers['temp'])), small_font, r=255, g=0, b=0)
weather_img = Image.open(weather_dir + '/small_icons/' + weather_ids[main] + '.png')
img.paste(day_img, (x_offset, 3))
x_offset += (day_img.size[0])
img.paste(weather_img, (x_offset, 3))
x_offset += (weather_img.size[0]+2)
img.paste(min_img, (x_offset, 2))
img.paste(max_img, (x_offset, 8))
x_offset += (max(min_img.size[0], max_img.size[0])+5)
x_offset += 35
img1 = img.crop((0,0,x_offset,16))
# img1 = img.crop((0,0,max(x_offset, crop_x) ,16))
image_list.append(img1)
except Exception as e:
pass
return self.stitchImage(image_list)
def readSportsCSV(self, league):
team_info = {}
f = open('csv/sports/{}/team_info.csv'.format(league), 'r')
CSV = csv.reader(f)
next(CSV)
for row in CSV:
team_info[row[0]] = {}
team_info[row[0]]['id'] = row[1]
team_info[row[0]]['code'] = row[2]
team_info[row[0]]['logo'] = row[4]
team_info[row[0]]['colour'] = row[3]
f.close()
return team_info
def displayDailyWeatherAlt(self):
img0, img1 = self.getDailyWeatherImageAlt()
while True:
self.setImage(img0, offset_x = 0, offset_y = 0)
image = img1
img_width, img_height = image.size
offset_x = 64
offset_y = 0
while offset_x > 64-img_width:
offset_x -= 1
self.setImage(image, offset_x = offset_x, offset_y = offset_y, min_x = 64, min_y = 9)
if offset_x + img_width < self.matrix.width: # if the image is ending
self.setImage(image, offset_x = offset_x + img_width, offset_y = offset_y, min_x = 64, min_y = 9)
try:
msg = getInput()
if msg == 'K':
self.resetMatrix()
return True
self.process_msg(msg)
except KeyboardInterrupt:
sys.stdout.flush()
pass
time.sleep(self.delay*1.1)
def getUserImages(self):
f = open('csv/image_settings.json', 'r')
all_settings = json.load(f)
f.close()
imgs = []
for ind,image in enumerate(all_settings['images']):
try:
img = self.openImage(os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'user_uploads'), image))
img.thumbnail((99999, 32))
if img.size[0] < 128:
diff = 128 - img.size[0]
new_image = Image.new('RGB',(128,32))
new_image.paste(img,(64-int(img.size[0]/2),0))
img = new_image
if all_settings['title'] and ind == 0:
title_img = self.openImage('feature_titles/images.png')
imgs.append(self.stitchImage([title_img, img]))
else:
imgs.append(img)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
return imgs
def getUserImagesProfessional(self):
f = open('csv/image_settings.json', 'r')
all_settings = json.load(f)
f.close()
if all_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/images.png')
image_list = [title_img]
else:
image_list = []
blank = Image.new('RGB', (0, 16))
for i,image in enumerate(all_settings['images']):
if (i == len(all_settings['images'])-1):
try:
user_image = self.openImage(os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'user_uploads'), image))
user_image.thumbnail((99999, 16))
#user_image.convert('RGB')
img = Image.new('RGB', (user_image.size[0] + 5, 32))
img.paste(user_image, (0,0))
image_list.append(img)
image_list.append(blank)
except Exception as e:
pass
else:
try:
user_image = self.openImage(os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'user_uploads'), image))
user_image.thumbnail((99999, 16))
#user_image.convert('RGB')
img = Image.new('RGB', (user_image.size[0] + 130, 32))
img.paste(user_image, (0,0))
image_list.append(img)
image_list.append(blank)
except Exception as e:
pass
return self.stitchImage(image_list)
def getUserGIFs(self):
f = open('csv/GIF_settings.json', 'r')
all_settings = json.load(f)
f.close()
GIFs = []
for ind,fle in enumerate(all_settings['images']):
try:
GIF = Image.open(os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'user_uploads'), fle))
frames = []
if ind == 0 and all_settings['title']:
#title_img = self.openImage('feature_titles/gifs.png')
for i, frame in enumerate(ImageSequence.Iterator(GIF)):
frame = frame.convert('P')
frame.thumbnail((128, 32),Image.NEAREST)
if frame.size[0] < 128:
diff = 128 - frame.size[0]
new_image = Image.new('RGB',(128,32))
new_image.paste(frame,(64-int(frame.size[0]/2),0))
frame = new_image
#f = self.stitchImage([title_img, frame])
frames.append(frame)
else:
for i, frame in enumerate(ImageSequence.Iterator(GIF)):
frame = frame.convert('P')
frame.thumbnail((128, 32),Image.NEAREST)
if frame.size[0] < 128:
diff = 128 - frame.size[0]
new_image = Image.new('RGB',(128,32))
new_image.paste(frame,(64-int(frame.size[0]/2),0))
frame = new_image
#frame = frame.resize((99999, 32))
#f = self.stitchImage([frame])
frames.append(frame)
frames[0].save('./display_images/working_gif{}.gif'.format(str(ind)), save_all=True, append_images=frames[1:], loop=0, optimize = False)
GIF = Image.open('./display_images/working_gif{}.gif'.format(str(ind)))
GIFs.append(GIF)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()
#below code stitches title and GIF together
# frames = []
# for i, frame in enumerate(ImageSequence.Iterator(gif)):
# if all_settings['title']:
# f = self.stitchImage([title_img, frame])
# else:
# f = self.stitchImage([frame])
# frames.append(f)
# frames[0].save('./display_images/Custom GIFs.gif', save_all=True, append_images=frames[1:], loop=0, optimize = False)
return GIFs
def getPlaceImage(self):
f = open('csv/place_settings.json', 'r')
all_settings = json.load(f)
f.close()
imgs = []
feature_title = False
global place_featuretitle
place_featuretitle = False
for place in all_settings['places']:
if "2017" in place:
try:
img = self.openImage('logos/r_place/r_place 2017.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/place2017.png')
place_featuretitle = True
except:
pass
elif "2022" in place:
try:
img = self.openImage('logos/r_place/r_place 2022.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/place2022.png')
place_featuretitle = True
except:
pass
elif "2023" in place:
try:
img = self.openImage('logos/r_place/r_place 2023.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/place2023.png')
place_featuretitle = True
except:
pass
try:
max_x = img.width - int(all_settings['width'])
max_y = img.height - 32
x = random.randint(0, max_x)
y = random.randint(0, max_y)
snapshot = img.crop((x, y, x + int(all_settings['width']), y + 32))
try:
imgs.append(self.stitchImage([feature_title,snapshot]))
except:
imgs.append(snapshot)
img.close()
try:
feature_title.close()
except:
pass
except:
pass
return imgs
def getPlaceImageProfessional(self):
f = open('csv/place_settings.json', 'r')
all_settings = json.load(f)
f.close()
imgs = []
feature_title = False
for i,place in enumerate(all_settings['places']):
if (i == len(all_settings['places'])-1):
if "2017" in place:
try:
img = self.openImage('logos/r_place/r_place 2017.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/small_feature_titles/place2017.png')
except:
pass
elif "2022" in place:
try:
img = self.openImage('logos/r_place/r_place 2022.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/small_feature_titles/place2022.png')
except:
pass
elif "2023" in place:
try:
img = self.openImage('logos/r_place/r_place 2023.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/small_feature_titles/place2023.png')
except:
pass
try:
max_x = img.width - int(all_settings['width'])
max_y = img.height - 16
x = random.randint(0, max_x)
y = random.randint(0, max_y)
snapshot = Image.new('RGB', (int(all_settings['width']) + 5, 32))
snapshot2 = img.crop((x, y, x + int(all_settings['width']), y + 16))
snapshot.paste(snapshot2, (0,0))
try:
imgs.append(self.stitchImage([feature_title,snapshot]))
except:
imgs.append(snapshot)
img.close()
try:
feature_title.close()
except:
pass
except:
pass
else:
if "2017" in place:
try:
img = self.openImage('logos/r_place/r_place 2017.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/small_feature_titles/place2017.png')
except:
pass
elif "2022" in place:
try:
img = self.openImage('logos/r_place/r_place 2022.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/small_feature_titles/place2022.png')
except:
pass
elif "2023" in place:
try:
img = self.openImage('logos/r_place/r_place 2023.png')
if all_settings['title']:
feature_title = self.openImage('feature_titles/small_feature_titles/place2023.png')
except:
pass
try:
max_x = img.width - int(all_settings['width'])
max_y = img.height - 16
x = random.randint(0, max_x)
y = random.randint(0, max_y)
snapshot = Image.new('RGB', (int(all_settings['width']) + 130, 32))
snapshot2 = img.crop((x, y, x + int(all_settings['width']), y + 16))
snapshot.paste(snapshot2, (0,0))
try:
imgs.append(self.stitchImage([feature_title,snapshot]))
except:
imgs.append(snapshot)
img.close()
try:
feature_title.close()
except:
pass
except:
pass
return self.stitchImage(imgs)
def getMoviesImage(self):
f = open('csv/movie_settings.json', 'r')
all_movie_settings = json.load(f)
f.close()
if all_movie_settings['title']:
title_img = self.openImage('feature_titles/movies.png')
image_list = [title_img]
else:
image_list = []
font = ImageFont.load("./fonts/6x13.pil")
small_font = ImageFont.load("./fonts/5x8.pil")
for movie in all_movie_settings['movies']:
x_offset = 0
movie_title_img = self.textImage(movie['title'] + ' (' + movie['media_type'] + ')', font, r = 255, g = 180, b = 0)
lang_img = self.textImage('Lan:' + movie['language'], small_font, r = 255, g = 0, b = 100)
vote_img = self.textImage(movie['votes'], small_font, r = 255, g = 255, b = 255)
star_img = Image.open('logos/star.png').convert('RGB')
date_img = self.textImage(movie['date'], small_font, r = 0, g = 162, b = 255)
try:
if movie['media_type'] == 'Movie':
if movie['budget'] == '0':
budget_img = self.textImage('$N/A', small_font, r = 255, g = 0, b = 0)
else:
budget_img = self.textImage('$' + movie['budget'], small_font, r = 255, g = 0, b = 0)
except:
pass
try:
if movie['media_type'] == 'Movie':
if movie['revenue'] == '0':
rev_img = self.textImage('$N/A', small_font, r = 0, g = 255, b = 0)
else:
rev_img = self.textImage('$' + movie['revenue'], small_font, r = 0, g = 255, b = 0)
except:
pass
try:
logo = Image.open('logos/movies/' + movie['backdrop'])
logo.thumbnail((9000,32))
logo.convert('P')
except:
logo = self.textImage('No Logo', small_font, r=255, g=255, b=255)
x_offset += logo.size[0] + 3
genre_offset = 0
for genre in movie['genre']:
genre_img = self.textImage(genre + ',', small_font, r = 255, g = 255, b = 255)
genre_offset += genre_img.size[0]
try:
if movie['media_type'] == 'Movie':
img = Image.new('RGB', (max(x_offset + movie_title_img.size[0], x_offset + date_img.size[0] + 3 + star_img.size[0] + vote_img.size[0] + 3 + 5 + budget_img.size[0] + 5 + rev_img.size[0], x_offset + date_img.size[0] + 3 + genre_offset) + 15, 32))
else:
img = Image.new('RGB', (max(x_offset + movie_title_img.size[0], x_offset + date_img.size[0] + 3 + star_img.size[0] + vote_img.size[0] + 3, x_offset + date_img.size[0] + 3 + genre_offset) + 15, 32))
except:
img = Image.new('RGB', (max(x_offset + movie_title_img.size[0], x_offset + date_img.size[0] + 3 + star_img.size[0] + vote_img.size[0] + 3, x_offset + date_img.size[0] + 3 + genre_offset) + 15, 32))
img.paste(logo, (0, 0))
img.paste(movie_title_img, (x_offset,0))
img.paste(date_img, (x_offset, 14))
img.paste(lang_img, (x_offset, 23))
x_offset += max(date_img.size[0], lang_img.size[0]) + 3
x_offset2 = x_offset
img.paste(star_img, (x_offset2 , 14))
img.paste(vote_img, (x_offset2 + star_img.size[0] + 3, 14))
try:
if movie['media_type'] == 'Movie':
img.paste(budget_img, (x_offset2 + star_img.size[0] + 3 + vote_img.size[0] + 5, 14))
except:
pass
try:
if movie['media_type'] == 'Movie':
img.paste(rev_img,(x_offset2 + star_img.size[0] + 3 + vote_img.size[0] + 5 + budget_img.size[0] + 5, 14))
except:
pass
for genre in movie['genre'][:-1]:
genre_img = self.textImage(genre + ',', small_font, r = 255, g = 255, b = 255)
img.paste(genre_img, (x_offset2, 23))
x_offset2 += genre_img.size[0]
else:
genre_img2 = self.textImage(movie['genre'][-1], small_font, r = 255, g = 255, b = 255)
img.paste(genre_img2, (x_offset2, 23))
x_offset2 += genre_img2.size[0]
image_list.append(img)
return self.stitchImage(image_list)
def getMoviesProfessional(self):
f = open('csv/movie_settings.json', 'r')
all_movie_settings = json.load(f)
f.close()
if all_movie_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/movies.png')
image_list = [title_img]
else:
image_list = []
font = ImageFont.load("./fonts/6x10.pil")
small_font = ImageFont.load("./fonts/4x6.pil")
for movie in all_movie_settings['movies']:
x_offset = 0
movie_title_img = self.textImage(movie['title'] + ' (' + movie['media_type'] + ')', font, r = 255, g = 180, b = 0)
lang_img = self.textImage('Lan:' + movie['language'], small_font, r = 255, g = 0, b = 100)
vote_img = self.textImage(movie['votes'], small_font, r = 255, g = 255, b = 255)
star_img = Image.open('logos/star.png').convert('RGB')
date_img = self.textImage(movie['date'], small_font, r = 0, g = 162, b = 255)
try:
if movie['media_type'] == 'Movie':
if movie['budget'] == '0':
budget_img = self.textImage('$N/A', small_font, r = 255, g = 0, b = 0)
else:
budget_img = self.textImage('$' + movie['budget'], small_font, r = 255, g = 0, b = 0)
except:
pass
try:
if movie['media_type'] == 'Movie':
if movie['revenue'] == '0':
rev_img = self.textImage('$N/A', small_font, r = 0, g = 255, b = 0)
else:
rev_img = self.textImage('$' + movie['revenue'], small_font, r = 0, g = 255, b = 0)
except:
pass
try:
logo = Image.open('logos/movies/' + movie['backdrop'])
logo.thumbnail((1000,16))
logo.convert('P')
except:
logo = self.textImage('No Logo', small_font, r=255, g=255, b=255)
x_offset += logo.size[0] + 3
genre_offset = 0
# img = Image.new('RGB', (200,16))
for genre in movie['genre']:
genre_img = self.textImage(genre + ',', small_font, r = 255, g = 255, b = 255)
genre_offset += genre_img.size[0]
try:
if movie['media_type'] == 'Movie':
img = Image.new('RGB', (max(x_offset + movie_title_img.size[0] + 3 + star_img.size[0] + 2 + vote_img.size[0] + 10 + 3 + budget_img.size[0] + 3 + rev_img.size[0], x_offset + date_img.size[0] + 7 + lang_img.size[0] + 7 + genre_offset + 10), 16))
else:
img = Image.new('RGB', (max(x_offset + movie_title_img.size[0] + 3 + star_img.size[0] + 2 + vote_img.size[0] + 10, x_offset + date_img.size[0] + 7 + lang_img.size[0] + 7 + genre_offset + 10), 16))
except:
img = Image.new('RGB', (max(x_offset + movie_title_img.size[0] + 3 + star_img.size[0] + 2 + vote_img.size[0] + 10, x_offset + date_img.size[0] + 7 + lang_img.size[0] + 7 + genre_offset + 10), 16))
img.paste(logo, (0, 0))
img.paste(movie_title_img, (x_offset,0))
x_offset2 = x_offset + movie_title_img.size[0] + 3
img.paste(star_img, (x_offset2, 1))
x_offset2 += star_img.size[0] + 2
img.paste(vote_img, (x_offset2, 2))
x_offset2 += vote_img.size[0]
try:
if movie['media_type'] == 'Movie':
img.paste(budget_img, (x_offset2 + 3, 2))
except:
pass
try:
if movie['media_type'] == 'Movie':
img.paste(rev_img,(x_offset2 + 3 + budget_img.size[0] + 3, 2))
except:
pass
img.paste(date_img, (x_offset, 10))
x_offset += date_img.size[0] + 7
img.paste(lang_img, (x_offset, 10))
x_offset += lang_img.size[0] + 7
for genre in movie['genre'][:-1]:
genre_img = self.textImage(genre + ',', small_font, r = 255, g = 255, b = 255)
img.paste(genre_img, (x_offset, 10))
x_offset += genre_img.size[0]
else:
genre_img2 = self.textImage(movie['genre'][-1], small_font, r = 255, g = 255, b = 255)
img.paste(genre_img2, (x_offset, 10))
x_offset += genre_img2.size[0]
image_list.append(img)
return self.stitchImage(image_list)
def getIpoImage(self):
f = open('csv/ipo_settings.json', 'r')
ipo_settings = json.load(f)
f.close()
if ipo_settings['title']:
title_img = self.openImage('feature_titles/ipo.png')
image_list = [title_img]
else:
image_list = []
font = ImageFont.load("./fonts/7x14B.pil")
font2 = ImageFont.load("./fonts/6x13.pil")
small_font = ImageFont.load("./fonts/6x10.pil")
if ipo_settings['symbols'][0] != 'No Data':
try:
for ipo in ipo_settings['symbols']:
x_offset = 10
x_offset2 = 10
name_img = self.textImage(ipo['name'].upper(), font, r = 255, g = 255, b = 255)
try:
if ipo['symbol'] == "":
symbol_img = self.textImage('($N/A)', font2, r = 255, g = 255, b = 255)
else:
symbol_img = self.textImage('($'+ ipo['symbol'] + ')', font2, r = 255, g = 255, b = 255)
except:
symbol_img = self.textImage('($N/A)', font2, r = 255, g = 255, b = 255)
date_img = self.textImage(ipo['date'], font2, r = 255, g = 255, b = 0)
status_1 = self.textImage('Status:', small_font, r=255, g=255, b=255)
if ipo['status'] == 'expected':
status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 255, g = 255, b = 0) # diff color
elif ipo['status'] == 'priced':
status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 0, g = 255, b = 0) # diff color
elif ipo['status'] == 'withdrawn':
status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 255, g = 0, b = 0) # diff color
elif ipo['status'] == 'filed':
status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 54, g = 69, b = 79) # diff color
shares_1 = self.textImage('Shares:', small_font, r = 255, g = 255, b = 255)
try:
shares_img = self.textImage(ipo['shares'], small_font, r = 38, g = 59, b = 232)
except:
shares_img = self.textImage('N/A', small_font, r = 38, g = 59, b = 232)
price_1 = self.textImage('Price:', small_font, r = 255, g = 255, b = 255)
try:
price_img = self.textImage(ipo['price'], small_font, r = 0, g = 255, b = 0)
except:
price_img = self.textImage('N/A', small_font, r = 0, g = 255, b = 0)
sharesvalue_1 = self.textImage('Value:', small_font, r=255, g=255, b=255)
try:
sharesvalue_img = self.textImage(ipo['sharesvalue'], small_font, r = 213, g = 117, b = 0)
except:
sharesvalue_img = self.textImage('N/A', small_font, r = 213, g = 117, b = 0)
img = Image.new('RGB', (max(x_offset + name_img.size[0] + 2 + symbol_img.size[0] + 8 + date_img.size[0], x_offset2 + status_1.size[0] +
status_img.size[0] + 8 + price_1.size[0] + price_img.size[0] + 8 + shares_1.size[0] + shares_img.size[0] +8
+ sharesvalue_1.size[0] + sharesvalue_img.size[0])+30,32))
img.paste(status_1,(x_offset2, 19))
x_offset2 += status_1.size[0]
img.paste(status_img, (x_offset2, 19))
x_offset2 += status_img.size[0] + 8
img.paste(price_1, (x_offset2, 19))
x_offset2 += price_1.size[0]
img.paste(price_img, (x_offset2, 19))
x_offset2 += price_img.size[0] + 8
img.paste(shares_1, (x_offset2, 19))
x_offset2 += shares_1.size[0]
img.paste(shares_img, (x_offset2, 19))
x_offset2 += shares_img.size[0] + 8
img.paste(sharesvalue_1, (x_offset2, 19))
x_offset2 += sharesvalue_1.size[0]
img.paste(sharesvalue_img, (x_offset2, 19))
img.paste(name_img, (x_offset,0))
x_offset += name_img.size[0] + 2
img.paste(symbol_img, (x_offset, 0))
x_offset += symbol_img.size[0] + 8
img.paste(date_img, (x_offset, 0))
line_image = Image.new("RGB", (name_img.size[0] + 2 + symbol_img.size[0] + 8 + date_img.size[0], 1))
line_image1 = ImageDraw.Draw(line_image)
line_image1.line((0,0,name_img.size[0] + 2 + symbol_img.size[0] + 8 + date_img.size[0],0), fill="blue", width = 0)
img.paste(line_image, (10, max(name_img.size[1],symbol_img.size[1])-1))
image_list.append(img)
except:
time.sleep(0.1)
no_ipo = self.textImage('No Upcoming IPOs for the next 3 weeks.', font, r = 255, g = 255, b = 255)
img = Image.new('RGB', (no_ipo.size[0] + 15, 32))
img.paste(no_ipo, (10, 10))
image_list.append(img)
elif ipo_settings['symbols'][0] == 'No Data':
time.sleep(0.1)
no_ipo = self.textImage('No Upcoming IPOs for the next 3 weeks.', font, r = 255, g = 255, b = 255)
img = Image.new('RGB', (no_ipo.size[0] + 15, 32))
img.paste(no_ipo, (10, 10))
image_list.append(img)
return self.stitchImage(image_list)
def getIpoProfessional(self):
f = open('csv/ipo_settings.json', 'r')
ipo_settings = json.load(f)
f.close()
if ipo_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/ipo.png')
image_list = [title_img]
else:
image_list = []
font = ImageFont.load("./fonts/5x8.pil")
small_font = ImageFont.load("./fonts/4x6.pil")
if ipo_settings['symbols'][0] != 'No Data':
try:
for ipo in ipo_settings['symbols']:
x_offset = 10
x_offset2 = 10
name_img = self.textImage(ipo['name'].upper(), font, r = 255, g = 255, b = 255)
try:
if ipo['symbol'] == "":
symbol_img = self.textImage('($N/A)', font, r = 255, g = 255, b = 255)
else:
symbol_img = self.textImage('($'+ ipo['symbol'] + ')', font, r = 255, g = 255, b = 255)
except:
symbol_img = self.textImage('($N/A)', font, r = 255, g = 255, b = 255)
date_img = self.textImage(ipo['date'], font, r = 255, g = 255, b = 0)
status_1 = self.textImage('Status:', small_font, r=255, g=255, b=255)
if ipo['status'] == 'expected':
status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 255, g = 255, b = 0) # diff color
elif ipo['status'] == 'priced':
status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 0, g = 255, b = 0) # diff color
elif ipo['status'] == 'withdrawn':
status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 255, g = 0, b = 0) # diff color
elif ipo['status'] == 'filed':
status_img = self.textImage(ipo['status'].capitalize(), small_font, r = 54, g = 69, b = 79) # diff color
shares_1 = self.textImage('Shares:', small_font, r = 255, g = 255, b = 255)
try:
shares_img = self.textImage(ipo['shares'], small_font, r = 38, g = 59, b = 232)
except:
shares_img = self.textImage('N/A', small_font, r = 38, g = 59, b = 232)
price_1 = self.textImage('Price:', small_font, r = 255, g = 255, b = 255)
try:
price_img = self.textImage(ipo['price'], small_font, r = 0, g = 255, b = 0)
except:
price_img = self.textImage('N/A', small_font, r = 0, g = 255, b = 0)
sharesvalue_1 = self.textImage('Value:', small_font, r=255, g=255, b=255)
try:
sharesvalue_img = self.textImage(ipo['sharesvalue'], small_font, r = 213, g = 117, b = 0)
except:
sharesvalue_img = self.textImage('N/A', small_font, r = 213, g = 117, b = 0)
img = Image.new('RGB', (max(x_offset + name_img.size[0] + 2 + symbol_img.size[0] + 5 + date_img.size[0], x_offset2 + status_1.size[0] +
status_img.size[0] + 8 + price_1.size[0] + price_img.size[0] + 8 + shares_1.size[0] + shares_img.size[0] +8
+ sharesvalue_1.size[0] + sharesvalue_img.size[0])+30,16))
img.paste(status_1,(x_offset2, 10))
x_offset2 += status_1.size[0]
img.paste(status_img, (x_offset2, 10))
x_offset2 += status_img.size[0] + 8
img.paste(price_1, (x_offset2, 10))
x_offset2 += price_1.size[0]
img.paste(price_img, (x_offset2, 10))
x_offset2 += price_img.size[0] + 8
img.paste(shares_1, (x_offset2, 10))
x_offset2 += shares_1.size[0]
img.paste(shares_img, (x_offset2, 10))
x_offset2 += shares_img.size[0] + 8
img.paste(sharesvalue_1, (x_offset2, 10))
x_offset2 += sharesvalue_1.size[0]
img.paste(sharesvalue_img, (x_offset2, 10))
img.paste(name_img, (x_offset,0))
x_offset += name_img.size[0] + 2
img.paste(symbol_img, (x_offset, 0))
x_offset += symbol_img.size[0] + 5
img.paste(date_img, (x_offset, 0))
line_image = Image.new("RGB", (name_img.size[0] + 2 + symbol_img.size[0] + 5 + date_img.size[0], 1))
line_image1 = ImageDraw.Draw(line_image)
line_image1.line((0,0,name_img.size[0] + 2 + symbol_img.size[0] + 5 + date_img.size[0],0), fill="blue", width = 0)
img.paste(line_image, (10, max(name_img.size[1],symbol_img.size[1])-2))
image_list.append(img)
except:
time.sleep(0.1)
font = ImageFont.load("./fonts/6x13.pil")
no_ipo = self.textImage('No Upcoming IPOs for the next 3 weeks.', font, r = 255, g = 255, b = 255)
img = Image.new('RGB', (no_ipo.size[0] + 15, 16))
img.paste(no_ipo, (10, 1))
image_list.append(img)
elif ipo_settings['symbols'][0] == 'No Data':
time.sleep(0.1)
font = ImageFont.load("./fonts/6x13.pil")
no_ipo = self.textImage('No Upcoming IPOs for the next 3 weeks.', font, r = 255, g = 255, b = 255)
img = Image.new('RGB', (no_ipo.size[0] + 15, 16))
img.paste(no_ipo, (10, 1))
image_list.append(img)
return self.stitchImage(image_list)
def getEconomicImage(self):
f = open('csv/economic_settings.json', 'r')
econ_settings = json.load(f)
f.close()
if econ_settings['title']:
title_img = self.openImage('feature_titles/economy.png')
image_list = [title_img]
else:
image_list = []
font = ImageFont.load("./fonts/7x14B.pil")
font2 = ImageFont.load("./fonts/6x12.pil")
small_font = ImageFont.load("./fonts/6x10.pil")
if len(econ_settings['events']) != 0:
try:
for event in econ_settings['events']:
if event['importance'] == -1:
imp_img = Image.open('logos/low_imp.png')
elif event['importance'] == 0:
imp_img = Image.open('logos/med_imp.png')
elif event['importance'] == 1:
imp_img = Image.open('logos/high_imp.png')
x_offset = 15
if event['period'] != "":
clock_img = Image.open('logos/period.png')
period_img = self.textImage(event['period'].upper(), small_font, r=255, g= 255, b =255)
else:
clock_img = None
period_img = None
flag_img = Image.open('logos/economic_logos/' + event['country'] + '.png')
circle_img = Image.open('logos/indicator.png')
title_img = self.textImage((event['title'].upper()).replace("(", '').replace(")", '').replace("/", " "), font, r = 255, g = 255, b = 255)
country_img = self.textImage(event['country'].upper(), font2, r= 255, g = 255, b = 0)
date_img = self.textImage(event['time'], small_font, r=0, g=150, b=255)
indicator_img = self.textImage(event['indicator'], font2, r=255, g=255, b=255)
after_offset = 0
if event['forecast'] != None or event['previous'] != None or event['actual'] != None:
tiny_font = ImageFont.load("./fonts/5x7.pil")
try:
if event['forecast'] != None:
fore_img = self.textImage('Forecast', tiny_font, r=255,g=255,b=255)
fore2_img = self.textImage(str(event['forecast']), tiny_font, r=0, g=255, b=0)
after_offset += max(fore_img.size[0], fore2_img.size[0]) + 3
if event['previous'] != None:
prev_img = self.textImage('Prior', tiny_font, r=255,g=255,b=255)
prev2_img = self.textImage(str(event['previous']), tiny_font, r=0, g=255, b=0)
after_offset += max(prev_img.size[0], prev2_img.size[0]) + 3
actual_img = self.textImage('Actual', tiny_font, r=255,g=255,b=255)
if event['actual'] == None:
actual2_img = self.textImage('Soon', tiny_font, r=255, g=40, b=40)
else:
actual2_img = self.textImage(str(event['actual']), tiny_font, r=0, g=255, b=0)
after_offset += max(actual_img.size[0], actual2_img.size[0]) + 3
except:
pass
try:
img = Image.new('RGB', (
max(flag_img.size[0] + x_offset + 5 + 3 + title_img.size[0] + country_img.size[0],
max(flag_img.size[0] + x_offset + 5 + 1 + circle_img.size[0] + 2 + indicator_img.size[0] + 2 + imp_img.size[0],
flag_img.size[0] + x_offset + 5 + 1 + date_img.size[0] + 3 + 2 + clock_img.size[0] + period_img.size[0]) + 10 + after_offset
)
,32))
except:
img = Image.new('RGB', (
max(flag_img.size[0] + x_offset + 5 + 3 + title_img.size[0] + country_img.size[0],
max(flag_img.size[0] + x_offset + 5 + 1 + circle_img.size[0] + 2 + indicator_img.size[0] + 2 + imp_img.size[0],
flag_img.size[0] + x_offset + 5 + 1 + date_img.size[0]) + 10 + after_offset
)
,32))
img.paste(flag_img,(x_offset, 0))
x_offset += flag_img.size[0] + 5
x_offset2 = x_offset + 1
img.paste(circle_img, (x_offset2, 15))
img.paste(indicator_img, (x_offset2 + circle_img.size[0] + 2, 11))
img.paste(imp_img, (x_offset2 + circle_img.size[0] + 2 + indicator_img.size[0] + 2, 15))
img.paste(title_img, (x_offset , 0))
x_offset += title_img.size[0] + 3
img.paste(country_img, (x_offset, 2))
x_offset += country_img.size[0]
img.paste(date_img, (x_offset2, 23))
try:
img.paste(clock_img, (x_offset2 + 3 + date_img.size[0], 24))
img.paste(period_img, (x_offset2 + 3 + date_img.size[0] + 2 + clock_img.size[0], 23))
x_offset2 += max(circle_img.size[0] + 2 + indicator_img.size[0] + 2 + imp_img.size[0],
date_img.size[0] + clock_img.size[0] + 3 + 2 + period_img.size[0]) + 10
except:
x_offset2 += max(circle_img.size[0] + 2 + indicator_img.size[0] + 2 + imp_img.size[0], date_img.size[0]) + 10
try:
if event['forecast'] != None:
img.paste(fore_img, (x_offset2, 14))
img.paste(fore2_img, (x_offset2, 22))
x_offset2 += max(fore_img.size[0], fore2_img.size[0]) + 3
except:
pass
try:
if event['previous'] != None:
img.paste(prev_img, (x_offset2, 14))
img.paste(prev2_img, (x_offset2, 22))
x_offset2 += max(prev_img.size[0], prev2_img.size[0]) + 3
img.paste(actual_img, (x_offset2, 14))
img.paste(actual2_img, (x_offset2, 22))
x_offset2 += max(actual_img.size[0], actual2_img.size[0]) + 3
except:
pass
image_list.append(img)
except:
pass
elif len(econ_settings['events']) == 0:
time.sleep(0.1)
no_econ = self.textImage('No upcoming economic events today.', font, r = 255, g = 255, b = 255)
img = Image.new('RGB', (no_econ.size[0] + 15, 32))
img.paste(no_econ, (10, 10))
image_list.append(img)
return self.stitchImage(image_list)
def getEconomicProfessional(self):
f = open('csv/economic_settings.json', 'r')
econ_settings = json.load(f)
f.close()
if econ_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/economy.png')
image_list = [title_img]
else:
image_list = []
font = ImageFont.load("./fonts/5x8.pil")
small_font = ImageFont.load("./fonts/4x6.pil")
if len(econ_settings['events']) != 0:
try:
for event in econ_settings['events']:
x_offset = 5
if event['importance'] == -1:
imp_img = Image.open('logos/low_imp.png')
elif event['importance'] == 0:
imp_img = Image.open('logos/med_imp.png')
elif event['importance'] == 1:
imp_img = Image.open('logos/high_imp.png')
if event['period'] != "":
clock_img = Image.open('logos/period.png')
period_img = self.textImage(event['period'].upper(), small_font, r=255, g= 85, b =0)
else:
clock_img = None
period_img = None
flag_img = Image.open('logos/economic_logos/' + event['country'] + '.png')
width, height = flag_img.size
flag_img = flag_img.resize((int(width/2), int(height/2)))
circle_img = Image.open('logos/indicator.png')
title_img = self.textImage((event['title'].upper()).replace("(", '').replace(")", '').replace("/", " "), font, r = 255, g = 255, b = 255)
country_img = self.textImage(event['country'].upper(), small_font, r= 255, g = 255, b = 0)
date_img = self.textImage(event['time'].split(' ')[2], small_font, r=0, g=150, b=255)
indicator_img = self.textImage(event['indicator'], small_font, r=255, g=255, b=255)
if event['forecast'] != None or event['previous'] != None or event['actual'] != None:
try:
if event['forecast'] != None:
fore_img = self.textImage('Forecast', small_font, r=255,g=255,b=255)
fore2_img = self.textImage(str(event['forecast']), small_font, r=0, g=255, b=0)
if event['previous'] != None:
prev_img = self.textImage('Prior', small_font, r=255,g=255,b=255)
prev2_img = self.textImage(str(event['previous']), small_font, r=0, g=255, b=0)
actual_img = self.textImage('Actual', small_font, r=255,g=255,b=255)
if event['actual'] == None:
actual2_img = self.textImage('Soon', small_font, r=255, g=40, b=40)
else:
actual2_img = self.textImage(str(event['actual']), small_font, r=0, g=255, b=0)
except:
pass
x_off1 = x_offset + flag_img.size[0] + 2 + title_img.size[0] + 2 + country_img.size[0] + imp_img.size[0] + 2
x_off2 = x_offset + flag_img.size[0] + 2 + circle_img.size[0] + 2 + indicator_img.size[0] + 2 + date_img.size[0] + 2
try:
x_off2 += clock_img.size[0] + 2 + period_img.size[0] + 2
except:
pass
x_off3 = max(x_off1, x_off2)
try:
if event['forecast'] != None:
x_off3 += max(fore_img.size[0], fore2_img.size[0]) + 2
except:
pass
try:
if event['previous'] != None:
x_off3 += max(prev_img.size[0], prev2_img.size[0]) + 2
x_off3 += max(actual_img.size[0], actual2_img.size[0]) + 2
except:
pass
img = Image.new('RGB', (x_off3 + 5,16))
img.paste(flag_img, (x_offset, 0))
x_offset += flag_img.size[0] + 2
x_offset2 = x_offset
img.paste(title_img, (x_offset, 0))
x_offset += title_img.size[0] +2
img.paste(country_img, (x_offset, 2))
x_offset += country_img.size[0]
img.paste(imp_img, (x_offset, 1))
x_offset += imp_img.size[0] + 2
img.paste(circle_img, (x_offset2, 9))
x_offset2 += circle_img.size[0] + 2
img.paste(indicator_img, (x_offset2, 9))
x_offset2 += indicator_img.size[0] + 2
img.paste(date_img, (x_offset2, 9))
x_offset2 += date_img.size[0] + 2
try:
img.paste(clock_img, (x_offset2, 8))
x_offset2 += clock_img.size[0] + 2
img.paste(period_img, (x_offset2, 9))
x_offset2 += period_img.size[0] + 2
except:
pass
x_offset3 = max(x_offset, x_offset2)
try:
if event['forecast'] != None:
img.paste(fore_img, (x_offset3, 3))
img.paste(fore2_img, (x_offset3, 9))
x_offset3 += max(fore_img.size[0], fore2_img.size[0]) + 2
except:
pass
try:
if event['previous'] != None:
img.paste(prev_img, (x_offset3, 3))
img.paste(prev2_img, (x_offset3, 9))
x_offset3 += max(prev_img.size[0], prev2_img.size[0]) + 2
img.paste(actual_img, (x_offset3, 3))
img.paste(actual2_img, (x_offset3, 9))
x_offset3 += max(actual_img.size[0], actual2_img.size[0]) + 2
except:
pass
image_list.append(img)
except:
time.sleep(0.1)
no_econ = self.textImage('No upcoming economic events today.', font, r = 255, g = 255, b = 255)
img = Image.new('RGB', (no_econ.size[0] + 15, 16))
img.paste(no_econ, (10, 1))
image_list.append(img)
elif len(econ_settings['events']) == 0:
time.sleep(0.1)
no_econ = self.textImage('No upcoming economic events today.', font, r = 255, g = 255, b = 255)
img = Image.new('RGB', (no_econ.size[0] + 15, 16))
img.paste(no_econ, (10, 1))
image_list.append(img)
return self.stitchImage(image_list)
def getJokesImage(self):
f = open('csv/jokes_settings.json', 'r')
jokes_settings = json.load(f)
f.close()
if jokes_settings['title']:
title_img = self.openImage('feature_titles/jokes.png')
image_list = [title_img]
else:
image_list = []
font = ImageFont.load("./fonts/BonusCoffee-16.pil")
small_font = ImageFont.load("./fonts/5x8.pil")
colours = { 'White':(255,255,255),
'Red':(255,0,0),
'Green':(0,255,0),
'Dark Green':(0,100,0),
'Blue':(0,0,255),
'Purple':(145,0,255),
'Pink':(255,0,255),
'Yellow':(255,255,0),
'Orange':(255,130,0),
'Gold':(255,190,0),
'Cyan':(0,255,255)}
if len(jokes_settings['jokes']) > 0:
try:
for joke in jokes_settings['jokes']:
random_color = random.choice(list(colours.keys()))
r,g,b = colours[random_color]
random_number = str(random.randint(1, 8)) + '.png'
emoji = self.openImage('logos/emojis/emoji' + random_number)
category_icon = self.openImage('logos/emojis/category.png')
category = self.textImage(joke['category'], small_font, r=255, g=255,b=255)
if joke['safe']:
safe = self.textImage('Safe', small_font, r=255, g=255, b=0)
else:
safe = self.textImage('Unsafe', small_font, r=255, g=0, b=0)
if joke['type'] == 'twopart':
decoded = joke['setup'].encode("ascii","ignore")
joke['setup'] = decoded.decode()
joke1 = self.textImage(joke['setup'].replace('\n', ' '), font, int(r),int(g),int(b))
random_color = random.choice(list(colours.keys()))
r,g,b = colours[random_color]
decoded = joke['delivery'].encode("ascii","ignore")
joke['delivery'] = decoded.decode()
joke2 = self.textImage(joke['delivery'].replace('\n', ' '), font, int(r), int(g), int(b))
else:
decoded = joke['joke'].encode("ascii","ignore")
joke['joke'] = decoded.decode()
joke1 = self.textImage(joke['joke'].replace('\n', ' '), font, int(r), int(g), int(b))
joke2 = None
try:
true_flags = [key for key, value in joke['flags'].items() if value]
flags = ", ".join(true_flags)
flags_final = self.textImage(flags, small_font, r=255, g=145, b=0)
except:
flags_final = None
pass
if flags_final != None:
flags_icon = self.openImage('logos/emojis/flags.png')
else:
flags_icon = None
x_offset = 10
if joke2 != None:
try:
img = Image.new('RGB', (20 + emoji.size[0] + 5 + max(joke1.size[0], category_icon.size[0] + 2 + category.size[0] + 5 + safe.size[0] + 5 + flags_icon.size[0] + 2 + flags_final.size[0] + 5) + joke2.size[0], 32))
except:
img = Image.new('RGB', (20 + emoji.size[0] + 5 + max(joke1.size[0], category_icon.size[0] + 2 + category.size[0] + 5 + safe.size[0] + 5) + joke2.size[0], 32))
else:
try:
img = Image.new('RGB', (20 + emoji.size[0] + 5 + max(joke1.size[0], category_icon.size[0] + 2 + category.size[0] + 5 + safe.size[0] + 5 + flags_icon.size[0] + 2 + flags_final.size[0] + 5), 32))
except:
img = Image.new('RGB', (20 + emoji.size[0] + 5 + max(joke1.size[0], category_icon.size[0] + 2 + category.size[0] + 5 + safe.size[0] + 5), 32))
img.paste(emoji, (x_offset, 3))
x_offset += emoji.size[0] + 5
x_offset2 = x_offset
img.paste(joke1, (x_offset, 1))
x_offset += joke1.size[0]
img.paste(category_icon, (x_offset2, 20))
x_offset2 += category_icon.size[0] + 2
img.paste(category, (x_offset2, 20))
x_offset2 += category.size[0] + 5
img.paste(safe, (x_offset2, 20))
x_offset2 += safe.size[0] + 5
try:
img.paste(flags_icon, (x_offset2, 20))
x_offset2 += flags_icon.size[0] + 2
img.paste(flags_final, (x_offset2, 20))
x_offset2 += flags_final.size[0] + 5
except:
pass
try:
img.paste(joke2, (max(x_offset, x_offset2), 16))
except:
pass
image_list.append(img)
except:
pass
return self.stitchImage(image_list)
def getJokesProfessional(self):
f = open('csv/jokes_settings.json', 'r')
jokes_settings = json.load(f)
f.close()
if jokes_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/jokes.png')
image_list = [title_img]
else:
image_list = []
font = ImageFont.load("./fonts/6x10.pil")
small_font = ImageFont.load("./fonts/4x6.pil")
colours = { 'White':(255,255,255),
'Red':(255,0,0),
'Green':(0,255,0),
'Dark Green':(0,100,0),
'Blue':(0,0,255),
'Purple':(145,0,255),
'Pink':(255,0,255),
'Yellow':(255,255,0),
'Orange':(255,130,0),
'Gold':(255,190,0),
'Cyan':(0,255,255)}
if len(jokes_settings['jokes']) > 0:
try:
for joke in jokes_settings['jokes']:
random_color = random.choice(list(colours.keys()))
r,g,b = colours[random_color]
random_number = str(random.randint(1, 8)) + '.png'
emoji = self.openImage('logos/emojis/small_emojis/emoji' + random_number)
category_icon = self.openImage('logos/emojis/small_emojis/category.png')
category = self.textImage(joke['category'], small_font, r=255, g=255,b=255)
if joke['safe']:
safe = self.textImage('Safe', small_font, r=255, g=255, b=0)
else:
safe = self.textImage('Unsafe', small_font, r=255, g=0, b=0)
if joke['type'] == 'twopart':
joke1 = self.textImage(joke['setup'].replace('\n', ' '), font, int(r),int(g),int(b))
random_color = random.choice(list(colours.keys()))
r,g,b = colours[random_color]
joke2 = self.textImage(joke['delivery'].replace('\n', ' '), font, int(r), int(g), int(b))
else:
joke1 = self.textImage(joke['joke'].replace('\n', ' '), font, int(r), int(g), int(b))
joke2 = None
try:
true_flags = [key for key, value in joke['flags'].items() if value]
flags = ", ".join(true_flags)
flags_final = self.textImage(flags, small_font, r=255, g=145, b=0)
except:
flags_final = None
pass
if flags_final != None:
flags_icon = self.openImage('logos/emojis/small_emojis/flags.png')
else:
flags_icon = None
x_offset = 10
if joke2 != None:
try:
img = Image.new('RGB', (20 + emoji.size[0] + 5 + max(joke1.size[0], category_icon.size[0] + 2 + category.size[0] + 5 + safe.size[0] + 5 + flags_icon.size[0] + 2 + flags_final.size[0] + 5) + joke2.size[0], 16))
except:
img = Image.new('RGB', (20 + emoji.size[0] + 5 + max(joke1.size[0], category_icon.size[0] + 2 + category.size[0] + 5 + safe.size[0] + 5) + joke2.size[0], 16))
else:
try:
img = Image.new('RGB', (20 + emoji.size[0] + 5 + max(joke1.size[0], category_icon.size[0] + 2 + category.size[0] + 5 + safe.size[0] + 5 + flags_icon.size[0] + 2 + flags_final.size[0] + 5), 16))
except:
img = Image.new('RGB', (20 + emoji.size[0] + 5 + max(joke1.size[0], category_icon.size[0] + 2 + category.size[0] + 5 + safe.size[0] + 5), 16))
img.paste(emoji, (x_offset, 0))
x_offset += emoji.size[0] + 5
x_offset2 = x_offset
img.paste(joke1, (x_offset, 0))
x_offset += joke1.size[0]
img.paste(category_icon, (x_offset2, 10))
x_offset2 += category_icon.size[0] + 2
img.paste(category, (x_offset2, 10))
x_offset2 += category.size[0] + 5
img.paste(safe, (x_offset2, 10))
x_offset2 += safe.size[0] + 5
try:
img.paste(flags_icon, (x_offset2, 10))
x_offset2 += flags_icon.size[0] + 2
img.paste(flags_final, (x_offset2, 10))
x_offset2 += flags_final.size[0] + 5
except:
pass
try:
img.paste(joke2, (max(x_offset, x_offset2), 6))
except:
pass
image_list.append(img)
except:
pass
return self.stitchImage(image_list)
def getMarketImage(self):
f = open('csv/market_settings.json', 'r')
market_settings = json.load(f)
f.close()
if market_settings['title']:
title_img = self.openImage('feature_titles/market.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
try:
if market_settings['display_name']:
names = True
else:
names = False
except:
names = False
pass
active_info = market_settings['mostactive']
active_symbols = list(active_info.keys())
gainers_info = market_settings['gainers']
gainers_symbols = list(gainers_info.keys())
losers_info = market_settings['losers']
losers_symbols = list(losers_info.keys())
for category in market_settings['categories']:
if category == 'Most Active':
most_active = self.openImage('logos/active.png')
image_list.append(most_active)
for i, symbol in enumerate(active_symbols):
try:
info = active_info[symbol]
change = float(info['change']) #TEXT
if names:
try:
ticker = info['name'].upper() #TEXT
except:
ticker = symbol
else:
ticker = symbol
arrow, change = self.getArrow(change)
percent_change = '%.2f' % abs(float(info['percent_change'])) + '%'
point_change = '%.2f' % abs(change)
current = '%.2f' % float(info['current']) #TEXT
if not market_settings['percent']:
percent_change = False
if not market_settings['point']:
point_change = False
midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT
if market_settings['logos']:
try:
ticker = symbol
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:
stitchedStock = midFrame
else:
stitchedStock = midFrame
try:
if market_settings['lohivol']:
font = ImageFont.load("./fonts/5x8.pil")
try:
day_low = '%.2f' % float(info['day_low'])
day_high = '%.2f' % float(info['day_high'])
volume = info['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_img.size[0] + daylow_t_img.size[0], dayhi_img.size[0] + dayhi_t_img.size[0],
vol_img.size[0] + vol_t_img.size[0]) + 5, 32))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 12))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 12))
lohivol_img.paste(vol_t_img, (0, 21))
lohivol_img.paste(vol_img, (vol_t_img.size[0], 21))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if market_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
image_list.append(self.blank)
except:
pass
elif category == 'Top Gainers':
top_gainers = self.openImage('logos/gainers.png')
image_list.append(top_gainers)
for i, symbol in enumerate(gainers_symbols):
try:
info = gainers_info[symbol]
change = float(info['change']) #TEXT
if names:
try:
ticker = info['name'].upper() #TEXT
except:
ticker = symbol
else:
ticker = symbol
arrow, change = self.getArrow(change)
percent_change = '%.2f' % abs(float(info['percent_change'])) + '%'
point_change = '%.2f' % abs(change)
current = '%.2f' % float(info['current']) #TEXT
if not market_settings['percent']:
percent_change = False
if not market_settings['point']:
point_change = False
midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT
if market_settings['logos']:
try:
ticker = symbol
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:
stitchedStock = midFrame
else:
stitchedStock = midFrame
try:
if market_settings['lohivol']:
font = ImageFont.load("./fonts/5x8.pil")
try:
day_low = '%.2f' % float(info['day_low'])
day_high = '%.2f' % float(info['day_high'])
volume = info['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_img.size[0] + daylow_t_img.size[0], dayhi_img.size[0] + dayhi_t_img.size[0],
vol_img.size[0] + vol_t_img.size[0]) + 5, 32))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 12))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 12))
lohivol_img.paste(vol_t_img, (0, 21))
lohivol_img.paste(vol_img, (vol_t_img.size[0], 21))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if market_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
image_list.append(self.blank)
except:
pass
elif category == 'Top Losers':
top_losers = self.openImage('logos/losers.png')
image_list.append(top_losers)
for i, symbol in enumerate(losers_symbols):
try:
info = losers_info[symbol]
change = float(info['change']) #TEXT
if names:
try:
ticker = info['name'].upper()
except:
ticker = symbol
else:
ticker = symbol #TEXT
arrow, change = self.getArrow(change)
percent_change = '%.2f' % abs(float(info['percent_change'])) + '%'
point_change = '%.2f' % abs(change)
current = '%.2f' % float(info['current']) #TEXT
if not market_settings['percent']:
percent_change = False
if not market_settings['point']:
point_change = False
midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT
if market_settings['logos']:
try:
ticker = symbol
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:
stitchedStock = midFrame
else:
stitchedStock = midFrame
try:
if market_settings['lohivol']:
font = ImageFont.load("./fonts/5x8.pil")
try:
day_low = '%.2f' % float(info['day_low'])
day_high = '%.2f' % float(info['day_high'])
volume = info['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_img.size[0] + daylow_t_img.size[0], dayhi_img.size[0] + dayhi_t_img.size[0],
vol_img.size[0] + vol_t_img.size[0]) + 5, 32))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 12))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 12))
lohivol_img.paste(vol_t_img, (0, 21))
lohivol_img.paste(vol_img, (vol_t_img.size[0], 21))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if market_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
image_list.append(self.blank)
except:
pass
finalDisplayImage = self.stitchImage(image_list)
return finalDisplayImage
def getMarketProfessional(self):
self.blank = Image.new('RGB', (0, 16))
f = open('csv/market_settings.json', 'r')
market_settings = json.load(f)
f.close()
if market_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/market.png')
image_list = [title_img, Image.new('RGB', (5, 16))]
image_list.append(self.blank)
else:
image_list = []
try:
if market_settings['display_name']:
names = True
else:
names = False
except:
names = False
pass
active_info = market_settings['mostactive']
active_symbols = list(active_info.keys())
gainers_info = market_settings['gainers']
gainers_symbols = list(gainers_info.keys())
losers_info = market_settings['losers']
losers_symbols = list(losers_info.keys())
for category in market_settings['categories']:
if category == 'Most Active':
most_active = self.openImage('logos/active_prof.png')
image_list.append(most_active)
for i, symbol in enumerate(active_symbols):
try:
info = active_info[symbol]
change = float(info['change'])#TEXT
if names:
try:
ticker = info['name'].upper() + 'display_name' #TEXT
except:
ticker = symbol
else:
ticker = symbol
arrow, change = self.getArrow(change, professional=True)
if market_settings["percent"]:
change = '%.2f' % abs(float(info['percent_change'])) + '%'
else:
change = '%.2f' % abs(change)
current = '%.2f' % float(info['current']) #TEXT
midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
if market_settings['logos']:
ticker = symbol
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
try:
if market_settings['lohivol']:
font = ImageFont.load("./fonts/4x6.pil")
try:
day_low = '%.2f' % float(info['day_low'])
day_high = '%.2f' % float(info['day_high'])
volume = info['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0] + vol_img.size[0] + 8, 16))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 9))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 9))
lohivol_img.paste(vol_t_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0])+2, 3))
lohivol_img.paste(vol_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0], 3))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if market_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
image_list.append(self.blank)
except Exception as e:
pass
elif category == 'Top Losers':
top_losers = self.openImage('logos/losers_prof.png')
image_list.append(top_losers)
for i, symbol in enumerate(losers_symbols):
try:
info = losers_info[symbol]
change = float(info['change'])#TEXT
if names:
try:
ticker = info['name'].upper() + 'display_name' #TEXT
except:
ticker = symbol
else:
ticker = symbol
arrow, change = self.getArrow(change, professional=True)
if market_settings["percent"]:
change = '%.2f' % abs(float(info['percent_change'])) + '%'
else:
change = '%.2f' % abs(change)
current = '%.2f' % float(info['current']) #TEXT
midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
if market_settings['logos']:
ticker = symbol
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
try:
if market_settings['lohivol']:
font = ImageFont.load("./fonts/4x6.pil")
try:
day_low = '%.2f' % float(info['day_low'])
day_high = '%.2f' % float(info['day_high'])
volume = info['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0] + vol_img.size[0] + 8, 16))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 9))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 9))
lohivol_img.paste(vol_t_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0])+2, 3))
lohivol_img.paste(vol_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0], 3))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if market_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
image_list.append(self.blank)
except Exception as e:
pass
elif category == 'Top Gainers':
top_gainers = self.openImage('logos/gainers_prof.png')
image_list.append(top_gainers)
for i, symbol in enumerate(gainers_symbols):
try:
info = gainers_info[symbol]
change = float(info['change'])#TEXT
if names:
try:
ticker = info['name'].upper() + 'display_name' #TEXT
except:
ticker = symbol
else:
ticker = symbol
arrow, change = self.getArrow(change, professional=True)
if market_settings["percent"]:
change = '%.2f' % abs(float(info['percent_change'])) + '%'
else:
change = '%.2f' % abs(change)
current = '%.2f' % float(info['current']) #TEXT
midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
if market_settings['logos']:
ticker = symbol
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
try:
if market_settings['lohivol']:
font = ImageFont.load("./fonts/4x6.pil")
try:
day_low = '%.2f' % float(info['day_low'])
day_high = '%.2f' % float(info['day_high'])
volume = info['volume']
daylow_img = self.textImage(day_low, font, r=0, g=255, b=0)
daylow_t_img = self.textImage('Lo', font, r=255, g=255, b=255)
dayhi_img = self.textImage(day_high, font, r=0,g=255,b=0)
dayhi_t_img = self.textImage('Hi', font, r=255,g=255,b=255)
vol_img = self.textImage(volume, font, r=0,g=255,b=0)
vol_t_img = self.textImage('Vol', font, r=255,g=255,b=255)
lohivol_img = Image.new('RGB', (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0] + vol_img.size[0] + 8, 16))
lohivol_img.paste(daylow_t_img, (0, 3))
lohivol_img.paste(daylow_img, (daylow_t_img.size[0],3))
lohivol_img.paste(dayhi_t_img, (0, 9))
lohivol_img.paste(dayhi_img, (dayhi_t_img.size[0], 9))
lohivol_img.paste(vol_t_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0])+2, 3))
lohivol_img.paste(vol_img, (max(daylow_t_img.size[0] + daylow_img.size[0], dayhi_t_img.size[0] + dayhi_img.size[0]) + 2+vol_t_img.size[0], 3))
except:
pass
except:
pass
image_list.append(stitchedStock)
try:
if market_settings['lohivol']:
try:
image_list.append(lohivol_img)
except:
pass
except:
pass
image_list.append(self.blank)
except Exception as e:
pass
finalDisplayImage = self.stitchImage(image_list)
self.blank = Image.new('RGB', (10, 32))
return finalDisplayImage
def getSectorImage(self):
f = open('csv/sector_settings.json', 'r')
sector_settings = json.load(f)
f.close()
if sector_settings['title']:
title_img = self.openImage('feature_titles/sector.png')
image_list = [title_img]
image_list.append(self.blank)
else:
image_list = []
data_info = sector_settings['data']
data_symbols = list(data_info.keys())
for category in sector_settings['sectors']:
try:
info = data_info[category]
change = float(info['current']) #TEXT
ticker = category.upper() #TEXT
arrow, change = self.getArrow(change)
current = '%.2f' % abs(float(info['current'])) + '%' #TEXT
percent_change = False
point_change = False
midFrame = self.textToImage(ticker, current, arrow, percent_change, point_change) #IMAGE THE TEXT
if sector_settings['logos']:
try:
logos_path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos'), 'sector')
logo = self.openImage(os.path.join(logos_path, category + '.png'))
stitchedStock = self.stitchImage([logo,midFrame])
except Exception as e:
stitchedStock = midFrame
else:
stitchedStock = midFrame
image_list.append(stitchedStock)
image_list.append(self.blank)
except:
pass
finalDisplayImage = self.stitchImage(image_list)
return finalDisplayImage
def getSectorProfessional(self):
self.blank = Image.new('RGB', (0, 16))
f = open('csv/sector_settings.json', 'r')
sector_settings = json.load(f)
f.close()
if sector_settings['title']:
title_img = self.openImage('feature_titles/small_feature_titles/sector.png')
image_list = [title_img, Image.new('RGB', (5, 16))]
image_list.append(self.blank)
else:
image_list = []
data_info = sector_settings['data']
data_symbols = list(data_info.keys())
for category in sector_settings['sectors']:
try:
info = data_info[category]
change = float(info['current'])#TEXT
ticker = category.upper() #TEXT
arrow, change = self.getArrow(change, professional=True)
change = 'Sector'
current = '%.2f' % abs(float(info['current'])) + '%' #TEXT
midFrame = self.textToImageProf(ticker, current, change, arrow, font=ImageFont.load("./fonts/6x10.pil")) #IMAGE THE TEXT
if sector_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_sectors')
logo = Image.open(os.path.join(logos_path, category + '.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'), 'sector')
logo = Image.open(os.path.join(logos_path, category + '.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
image_list.append(stitchedStock)
image_list.append(self.blank)
except Exception as e:
pass
finalDisplayImage = self.stitchImage(image_list)
self.blank = Image.new('RGB', (10, 32))
return finalDisplayImage
def showClock1(self):
kill=False
canvas = self.double_buffer
try:
with open('csv/clock1_settings.json', 'r') as f:
clock1_set = json.load(f)
except:
clock1_set1 = {"speed": "fast", "transition": "up", "pause": "20", "speed2": "fast"}
with open('csv/clock1_settings.json', 'w') as f:
json.dump(clock1_set1, f)
clock1_set = clock1_set1
try:
with open('clock_screensaver.json', 'r') as f:
settings = json.load(f)['clock1']
except:
settings1 = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(settings1, f)
settings = settings1['clock1']
gmt1 = settings['timezone']
if '+' in gmt1:
gmt = gmt1.replace('+', '-')
elif '-' in gmt1:
gmt = gmt1.replace('-', '+')
else:
gmt = gmt1
#TIMEZONE NOT WORKING?!?!?!!?!?!?!?!?!??
timezone = pytz.timezone(gmt)
font = graphics.Font()
font.LoadFont("fonts/6x12.bdf") # Change this to the path of your desired font file
font2 = graphics.Font()
font2.LoadFont("fonts/8x13B.bdf")
color = graphics.Color(255, 255, 255) # White color
time_colors = {
"White": graphics.Color(255,255,255),
"Red": graphics.Color(255, 0,0),
"Green": graphics.Color(0,255,0),
"Dark Green": graphics.Color(0, 100,0),
"Blue": graphics.Color(0,0,255),
"Purple": graphics.Color(145,0,255),
"Pink": graphics.Color(255,0,255),
"Yellow": graphics.Color(255,255,0),
"Orange": graphics.Color(255,130,0),
"Gold": graphics.Color(255,190,0),
"Gray": graphics.Color(100,100,100),
"Cyan": graphics.Color(0,255,255)
}
colon_visible = False
colon_counter = 0
counter = 0
counter2 = 0
pause = int(clock1_set['pause'])
transition = clock1_set['transition'].lower()
if clock1_set['speed'].lower() == 'slow':
speed = 0.05
elif clock1_set['speed'].lower() == 'medium':
speed = 0.02
else:
speed = 0.01
#DOWN
y_coord_down = -32
y_time_down = 44
y_date_down = 63
y_weekday_down = 54
#UP
y_coord_up = 32
y_time_up = -20
y_date_up = -1
y_weekday_up = -10
#CONT
x_coordinate_weekday = 0
x_coordinate_date = 0
x_coordinate_time = 0
x_coordinate_weekday2 = 128
x_coordinate_time2 = 128
x_coordinate_date2 = 128
x_coord_cont = 0
#SCROLL OUT
x_coord = 0
x_date = 0
x_time = 0
x_weekday = 0
if settings['12hour']:
if settings['display_pm'] and settings['display_seconds']:
the_time = "%I:%M:%S %p"
elif settings['display_pm'] and not settings['display_seconds']:
the_time = "%I:%M %p"
elif not settings['display_pm'] and settings['display_seconds']:
the_time = "%I:%M:%S"
else:
the_time = "%I:%M"
else:
if settings['display_pm'] and settings['display_seconds']:
the_time = "%H:%M:%S %p"
elif settings['display_pm'] and not settings['display_seconds']:
the_time = "%H:%M %p"
elif not settings['display_pm'] and settings['display_seconds']:
the_time = "%H:%M:%S"
else:
the_time = "%H:%M"
while counter2 <= 130:
while counter <= (pause*2):
canvas.Clear()
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_weekday = datetime.now(timezone).strftime("%A")
current_date = datetime.now(timezone).strftime("%d %b %Y")
weekday_width = graphics.DrawText(canvas, font, 0, 0, color, current_weekday.upper())
time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
canvas.Clear()
x_coordinate_weekday = int((128 - weekday_width) / 2)
x_coordinate_time = int((128 - time_width) / 2)
x_coordinate_date = int((128 - date_width) /2)
x_coordinate_weekday2 += x_coordinate_weekday
x_coordinate_time2 += x_coordinate_time
x_coordinate_date2 += x_coordinate_date
if transition == 'up':
while y_coord_down < 0:
y_coord_down += 1
y_time_down -= 1
y_date_down -= 1
y_weekday_down -= 1
if colon_counter % (0.5/speed) == 0:
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_weekday = datetime.now(timezone).strftime("%A")
current_date = datetime.now(timezone).strftime("%d %b %Y")
weekday_width = graphics.DrawText(canvas, font, 0, 0, color, current_weekday.upper())
time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
canvas.Clear()
x_coordinate_weekday = int((128 - weekday_width) / 2)
x_coordinate_time = int((128 - time_width) / 2)
x_coordinate_date = int((128 - date_width) /2)
graphics.DrawText(canvas, font2, x_coordinate_time, y_time_down, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_weekday, y_weekday_down, time_colors[settings['weekday_color']], current_weekday.upper())
graphics.DrawText(canvas, font, x_coordinate_date, y_date_down, time_colors[settings['date_color']], current_date.upper())
canvas = self.matrix.SwapOnVSync(canvas)
canvas.Clear()
colon_counter += 1
time.sleep(speed)
if y_coord_down == 0:
break
if transition == 'down':
while y_coord_up > 0:
y_coord_up -= 1
y_time_up += 1
y_date_up += 1
y_weekday_up += 1
if colon_counter % (0.5/speed) == 0:
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_weekday = datetime.now(timezone).strftime("%A")
current_date = datetime.now(timezone).strftime("%d %b %Y")
weekday_width = graphics.DrawText(canvas, font, 0, 0, color, current_weekday.upper())
time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
canvas.Clear()
x_coordinate_weekday = int((128 - weekday_width) / 2)
x_coordinate_time = int((128 - time_width) / 2)
x_coordinate_date = int((128 - date_width) /2)
graphics.DrawText(canvas, font2, x_coordinate_time, y_time_up, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_weekday, y_weekday_up, time_colors[settings['weekday_color']], current_weekday.upper())
graphics.DrawText(canvas, font, x_coordinate_date, y_date_up, time_colors[settings['date_color']], current_date.upper())
canvas = self.matrix.SwapOnVSync(canvas)
canvas.Clear()
colon_counter += 1
time.sleep(speed)
if y_coord_up == 0:
break
if transition == 'continuous':
while x_coord_cont < 128:
x_coord_cont += 1
x_coordinate_date2 -= 1
x_coordinate_time2 -= 1
x_coordinate_weekday2 -= 1
if colon_counter % (0.5/speed) == 0:
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_weekday = datetime.now(timezone).strftime("%A")
current_date = datetime.now(timezone).strftime("%d %b %Y")
graphics.DrawText(canvas, font2, x_coordinate_time2, 12, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_weekday2, 22, time_colors[settings['weekday_color']], current_weekday.upper())
graphics.DrawText(canvas, font, x_coordinate_date2, 31, time_colors[settings['date_color']], current_date.upper())
canvas = self.matrix.SwapOnVSync(canvas)
canvas.Clear()
colon_counter += 1
time.sleep(speed)
if x_coord_cont == 0:
break
# Draw the time, weekday, and date on the canvas
graphics.DrawText(canvas, font2, x_coordinate_time, 12, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_weekday, 22, time_colors[settings['weekday_color']], current_weekday.upper())
graphics.DrawText(canvas, font, x_coordinate_date, 31, time_colors[settings['date_color']], current_date.upper())
# Swap the canvas onto the matrix
canvas = self.matrix.SwapOnVSync(canvas)
counter += 1
# Wait for 1 second before updating the clock
time.sleep(0.5)
# if counter == (pause*2):
# break
kill=self.checkKilled()
if kill:break
canvas.Clear()
if colon_counter % (0.5/speed) == 0:
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_weekday = datetime.now(timezone).strftime("%A")
current_date = datetime.now(timezone).strftime("%d %b %Y")
weekday_width = graphics.DrawText(canvas, font, 0, 0, color, current_weekday.upper())
time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
canvas.Clear()
x_coordinate_weekday = int((128 - weekday_width) / 2)
x_coordinate_time = int((128 - time_width) / 2)
x_coordinate_date = int((128 - date_width) /2)
graphics.DrawText(canvas, font2, x_coordinate_time+x_time, 12, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_weekday+x_weekday, 22, time_colors[settings['weekday_color']], current_weekday.upper())
graphics.DrawText(canvas, font, x_coordinate_date+x_date, 31, time_colors[settings['date_color']], current_date.upper())
x_date -= 1
x_time -= 1
x_weekday -= 1
counter2 += 1
colon_counter += 1
canvas = self.matrix.SwapOnVSync(canvas)
time.sleep(speed)
#if counter2 == 130:
# break
kill=self.checkKilled()
if kill:break
return kill
def showClock2(self):
kill = False
try:
with open('csv/clock2_settings.json', 'r') as f:
clock2_set = json.load(f)
except:
clock2_set = {"speed": "fast", "transition": "up", "pause": "20", "speed2": "fast"}
with open('csv/clock2_settings.json', 'w') as f:
json.dump(clock2_set, f)
try:
with open('clock_screensaver.json', 'r') as f:
settings = json.load(f)['clock2']
except:
settings1 = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(settings1, f)
settings = settings1['clock2']
# Create a canvas to draw on
canvas = self.double_buffer
gmt1 = settings['timezone']
if '+' in gmt1:
gmt = gmt1.replace('+', '-')
elif '-' in gmt1:
gmt = gmt1.replace('-', '+')
else:
gmt = gmt1
#TIMEZONE NOT WORKING?!?!?!!?!?!?!?!?!??
timezone = pytz.timezone(gmt)
# Set the font and text color
font = graphics.Font()
font.LoadFont("fonts/clR6x12.bdf")
#font.LoadFont("fonts/6x12.bdf") # Change this to the path of your desired font file
font2 = graphics.Font()
font2.LoadFont("fonts/texgyre-27.bdf")
time_colors = {
"White": graphics.Color(255,255,255),
"Red": graphics.Color(255, 0,0),
"Green": graphics.Color(0,255,0),
"Dark Green": graphics.Color(0, 100,0),
"Blue": graphics.Color(0,0,255),
"Purple": graphics.Color(145,0,255),
"Pink": graphics.Color(255,0,255),
"Yellow": graphics.Color(255,255,0),
"Orange": graphics.Color(255,130,0),
"Gold": graphics.Color(255,190,0),
"Gray": graphics.Color(100,100,100),
"Cyan": graphics.Color(0,255,255)
}
colon_visible = False
colon_counter = 0
counter = 0
counter2 = 0
pause = int(clock2_set['pause'])
transition = clock2_set['transition'].lower()
if clock2_set['speed'].lower() == 'slow':
speed = 0.05
elif clock2_set['speed'].lower() == 'medium':
speed = 0.02
else:
speed = 0.01
#DOWN
y_coord_down = -32
y_time_down = 53
y_date_down = 63
#UP
y_coord_up = 32
y_time_up = -11
y_date_up = -1
#CONT
x_coordinate_time = 0
x_coordinate_date = 0
x_coordinate_time2 = 128
x_coordinate_date2 = 128
x_coord_cont = 0
#SCROLL OUT
x_coord = 0
x_date = 0
x_time = 0
if settings['12hour']:
if settings['display_pm']:
the_time = "%I:%M %p"
else:
the_time = "%I:%M"
else:
if settings['display_pm']:
the_time = "%H:%M %p"
else:
the_time = "%H:%M"
while counter2 <= 130:
while counter <= (pause*2):
canvas.Clear()
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_date = datetime.now(timezone).strftime("%a %d %b %Y")
date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
canvas.Clear()
x_coordinate_time = int((128 - time_width) / 2)
x_coordinate_date = int((128 - date_width) /2)
x_coordinate_date2 += x_coordinate_date
x_coordinate_time2 += x_coordinate_time
if transition == 'up':
while y_coord_down < 0:
y_coord_down += 1
y_time_down -= 1
y_date_down -= 1
#current_time = datetime.now(timezone).strftime(the_time)
if colon_counter % (0.5/speed) == 0:
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_date = datetime.now(timezone).strftime("%a %d %b %Y")
date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
canvas.Clear()
x_coordinate_time = int((128 - time_width) / 2)
x_coordinate_date = int((128 - date_width) /2)
graphics.DrawText(canvas, font2, x_coordinate_time, y_time_down, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_date, y_date_down, time_colors[settings['date_color']], current_date.upper())
canvas = self.matrix.SwapOnVSync(canvas)
canvas.Clear()
colon_counter += 1
time.sleep(speed)
if y_coord_down == 0:
break
if transition == 'down':
while y_coord_up > 0:
y_coord_up -= 1
y_time_up += 1
y_date_up += 1
# current_time = datetime.now(timezone).strftime(the_time)
if colon_counter % (0.5/speed) == 0:
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_date = datetime.now(timezone).strftime("%a %d %b %Y")
date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
canvas.Clear()
x_coordinate_time = int((128- time_width) / 2)
x_coordinate_date = int((128 - date_width) /2)
graphics.DrawText(canvas, font2, x_coordinate_time, y_time_up, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_date, y_date_up, time_colors[settings['date_color']], current_date.upper())
canvas = self.matrix.SwapOnVSync(canvas)
canvas.Clear()
colon_counter += 1
time.sleep(speed)
if y_coord_up == 0:
break
if transition == 'continuous':
while x_coord_cont < 128:
x_coord_cont+= 1
x_coordinate_date2 -= 1
x_coordinate_time2 -= 1
# current_time = datetime.now(timezone).strftime(the_time)
if colon_counter % (0.5/speed) == 0:
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_date = datetime.now(timezone).strftime("%a %d %b %Y")
# date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
# time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
# canvas.Clear()
# x_coordinate_time = int((options.cols - time_width) / 2)
# x_coordinate_date = int((options.cols - date_width) /2)
graphics.DrawText(canvas, font2, x_coordinate_time2, 21, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_date2, 31, time_colors[settings['date_color']], current_date.upper())
canvas = self.matrix.SwapOnVSync(canvas)
canvas.Clear()
colon_counter += 1
time.sleep(speed)
if x_coord_cont == 0:
break
graphics.DrawText(canvas, font2, x_coordinate_time, 21, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_date, 31, time_colors[settings['date_color']], current_date.upper())
canvas = self.matrix.SwapOnVSync(canvas)
counter += 1
time.sleep(0.5)
kill = self.checkKilled()
if kill:
break
# if counter == (pause*2):
# break
canvas.Clear()
if colon_counter % (0.5/speed) == 0:
current_time = datetime.now(timezone).strftime(the_time)
if colon_visible:
current_time = current_time.replace(":", " ")
colon_visible = False
else:
colon_visible = True
current_date = datetime.now(timezone).strftime("%a %d %b %Y")
date_width = graphics.DrawText(canvas, font, 0, 0, time_colors[settings['date_color']], current_date.upper())
time_width = graphics.DrawText(canvas, font2, 0, 0, time_colors[settings['time_color']], current_time)
canvas.Clear()
x_coordinate_time = int((128 - time_width) / 2)
x_coordinate_date = int((128 - date_width) /2)
graphics.DrawText(canvas, font2, x_coordinate_time+x_time, 21, time_colors[settings['time_color']], current_time)
graphics.DrawText(canvas, font, x_coordinate_date+x_date, 31, time_colors[settings['date_color']], current_date.upper())
x_date -= 1
x_time -= 1
counter2 += 1
colon_counter += 1
canvas = self.matrix.SwapOnVSync(canvas)
time.sleep(speed)
kill = self.checkKilled()
if kill:
break
#if counter2 == 130:
# break
return kill
def showWorldclock(self):
kill=False
canvas = self.double_buffer
try:
with open('csv/worldclock_settings.json', 'r') as f:
worldclock_set = json.load(f)
except:
worldclock_set1 = {"speed": "fast", "transition": "up", "pause": "20", "speed2": "fast"}
with open('csv/worldclock_settings.json', 'w') as f:
json.dump(worldclock_set1, f)
worldclock_set = worldclock_set1
try:
with open('clock_screensaver.json', 'r') as f:
settings = json.load(f)['world_clock']
except:
settings1 = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
with open('clock_screensaver.json', 'w') as f:
json.dump(settings1, f)
settings = settings1['world_clock']
font = graphics.Font()
city_colors = {
"White": graphics.Color(255,255,255),
"Red": graphics.Color(255, 0,0),
"Green": graphics.Color(0,255,0),
"Dark Green": graphics.Color(0, 100,0),
"Blue": graphics.Color(0,0,255),
"Purple": graphics.Color(145,0,255),
"Pink": graphics.Color(255,0,255),
"Yellow": graphics.Color(255,255,0),
"Orange": graphics.Color(255,130,0),
"Gold": graphics.Color(255,190,0),
"Gray": graphics.Color(100,100,100),
"Cyan": graphics.Color(0,255,255)
}
color = city_colors[settings['city_color']]
line_c = graphics.Color(50,50,50)
font.LoadFont("fonts/5x7.bdf")
time_colors = {
"day": graphics.Color(255, 191, 0), # Orange color
"night": graphics.Color(0, 71,171), # Dark blue / purple color
}
def getTimes(timezone):
if settings['12hour']:
if settings['display_pm'] and settings['display_seconds']:
time = datetime.now(timezone).strftime("%I:%M:%S %p")
elif settings['display_pm'] and not settings['display_seconds']:
time = datetime.now(timezone).strftime("%I:%M %p")
elif not settings['display_pm'] and settings['display_seconds']:
time = datetime.now(timezone).strftime("%I:%M:%S %p")
else:
time = datetime.now(timezone).strftime("%I:%M %p")
else:
if settings['display_pm'] and settings['display_seconds']:
time = datetime.now(timezone).strftime("%H:%M:%S %p")
elif settings['display_pm'] and not settings['display_seconds']:
time = datetime.now(timezone).strftime("%H:%M %p")
elif not settings['display_pm'] and settings['display_seconds']:
time = datetime.now(timezone).strftime("%H:%M:%S %p")
else:
time = datetime.now(timezone).strftime("%H:%M %p")
return time
def isDaytime(time):
if settings['12hour']:
hour = int(time.split(':')[0])
daytime_start_hour = 6
daytime_end_hour = 6
am_pm = time[-2:]
if (6 <= hour <= 11 and am_pm == 'AM') or (1 <= hour <= 6 and am_pm == 'PM') or (hour == 12 and am_pm == 'PM'):
return True
else:
return False
else:
hour = time.split(':')[0]
daytime_start_hour = 6
daytime_end_hour = 18
if daytime_start_hour <= int(hour) <= daytime_end_hour:
return True
else:
return False
ny_timezone = pytz.timezone('America/New_York')
london_timezone = pytz.timezone('Europe/London')
tokyo_timezone = pytz.timezone('Asia/Tokyo')
au_timezone = pytz.timezone('Australia/Sydney')
dubai_timezone = pytz.timezone('Asia/Dubai')
la_timezone = pytz.timezone('America/Los_Angeles')
cn_timezone = pytz.timezone('Asia/Shanghai')
paris_timezone = pytz.timezone('Europe/Paris')
in_timezone = pytz.timezone('Asia/Kolkata')
auck_timezone = pytz.timezone('Pacific/Auckland')
bang_timezone = pytz.timezone('Asia/Bangkok')
istan_timezone = pytz.timezone('Europe/Istanbul')
pause = int(worldclock_set['pause'])
if pause % 2 != 0:
pause += 1
transition = worldclock_set['transition'].lower()
if worldclock_set['speed'].lower() == 'slow':
speed = 0.05
elif worldclock_set['speed'].lower() == 'medium':
speed = 0.02
else:
speed = 0.01
counter = 0
counter2 = 0
time_offset = 0
#DOWN
y_coord_down = -32
y_time1_down = 40
y_time2_down = 51
y_time3_down = 62
y_line1_down = 42
y_line2_down = 53
#UP
y_coord_up = 32
y_time1_up = -24
y_time2_up = -13
y_time3_up = -2
y_line1_up = -22
y_line2_up = -11
#CONT
if settings['display_pm'] and settings['display_seconds']:
x_offset = 72
elif settings['display_pm'] and not settings['display_seconds']:
x_offset = 87
elif not settings['display_pm'] and settings['display_seconds']:
x_offset = 87
else:
x_offset = 102
x_coord_cont = 0
x_time = x_offset + 128
x_line = 128
x_city = 130
#SCROLL OUT
finalcount = 0
counter3 = 0
x_time_out = 0
x_line_out = 0
x_city_out = 0
time_offset2 = 0
while counter3 <= 130:
while counter2 <= (pause):
if transition == 'up':
while y_coord_down < 0:
y_coord_down += 1
y_time1_down -= 1
y_time2_down -= 1
y_time3_down -= 1
y_line1_down -= 1
y_line2_down -= 1
if 0 <= counter <= 5:
canvas.Clear()
if time_offset % (1/speed) == 0:
ny_time = getTimes(ny_timezone)
london_time = getTimes(london_timezone)
tokyo_time = getTimes(tokyo_timezone)
counter += 1
ny_color = time_colors['day'] if isDaytime(ny_time) else time_colors['night']
london_color = time_colors['day'] if isDaytime(london_time) else time_colors['night']
tokyo_color = time_colors['day'] if isDaytime(tokyo_time) else time_colors['night']
if not settings['display_pm']:
ny_time = ny_time.replace("PM", "").replace("AM", "")
london_time = london_time.replace("PM", "").replace("AM", "")
tokyo_time = tokyo_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, 2, y_time1_down, color, 'NEW YORK')
graphics.DrawText(canvas, font, x_offset, y_time1_down, ny_color, ny_time)
graphics.DrawLine(canvas, 0, y_line1_down, 128, y_line1_down, line_c)
graphics.DrawText(canvas, font, 2, y_time2_down, color, 'LONDON')
graphics.DrawText(canvas, font, x_offset, y_time2_down, london_color, london_time)
graphics.DrawLine(canvas, 0, y_line2_down, 128, y_line2_down, line_c)
graphics.DrawText(canvas, font, 2, y_time3_down, color, 'TOKYO')
graphics.DrawText(canvas, font, x_offset, y_time3_down, tokyo_color, tokyo_time)
canvas = self.matrix.SwapOnVSync(canvas)
elif 6 <= counter <= 11:
canvas.Clear()
if counter == 6:
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if time_offset % (1/speed) == 0:
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
counter += 1
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if not settings['display_pm']:
au_time = au_time.replace("PM", "").replace("AM", "")
dubai_time = dubai_time.replace("PM", "").replace("AM", "")
la_time = la_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, y_time1_down, au_color, au_time)
graphics.DrawText(canvas, font, 2, y_time1_down, color, 'SYDNEY')
graphics.DrawLine(canvas, 0, y_line1_down, 128, y_line1_down, line_c)
graphics.DrawText(canvas, font, x_offset, y_time2_down, dubai_color, dubai_time)
graphics.DrawText(canvas, font, 2, y_time2_down, color, 'DUBAI')
graphics.DrawLine(canvas, 0, y_line2_down, 128, y_line2_down, line_c)
graphics.DrawText(canvas, font, x_offset, y_time3_down, la_color, la_time)
graphics.DrawText(canvas, font, 2, y_time3_down, color, 'LOS ANGELES')
canvas = self.matrix.SwapOnVSync(canvas)
elif 12 <= counter <= 17:
canvas.Clear()
if counter == 12:
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if time_offset % (1/speed) == 0:
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
counter += 1
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if not settings['display_pm']:
cn_time = cn_time.replace("PM", "").replace("AM", "")
paris_time = paris_time.replace("PM", "").replace("AM", "")
in_time = in_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, y_time1_down, cn_color, cn_time)
graphics.DrawText(canvas, font, 2, y_time1_down, color, 'SHANGHAI')
graphics.DrawText(canvas, font, x_offset, y_time2_down, paris_color, paris_time)
graphics.DrawLine(canvas, 0, y_line1_down, 128, y_line1_down, line_c)
graphics.DrawText(canvas, font, 2, y_time2_down, color, 'PARIS')
graphics.DrawText(canvas, font, x_offset, y_time3_down, in_color, in_time)
graphics.DrawLine(canvas, 0, y_line2_down, 128, y_line2_down, line_c)
graphics.DrawText(canvas, font, 2, y_time3_down, color, 'MUMBAI')
canvas = self.matrix.SwapOnVSync(canvas)
elif 18 <= counter <= 23:
canvas.Clear()
if counter == 18:
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if time_offset % (1/speed) == 0:
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
counter += 1
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if not settings['display_pm']:
auck_time = auck_time.replace("PM", "").replace("AM", "")
bang_time = bang_time.replace("PM", "").replace("AM", "")
istan_time = istan_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, y_time1_down, auck_color, auck_time)
graphics.DrawText(canvas, font, 2, y_time1_down, color, 'AUCKLAND')
graphics.DrawText(canvas, font, x_offset, y_time2_down, bang_color, bang_time)
graphics.DrawLine(canvas, 0, y_line1_down, 128, y_line1_down, line_c)
graphics.DrawText(canvas, font, 2, y_time2_down, color, 'BANGKOK')
graphics.DrawText(canvas, font, x_offset, y_time3_down, istan_color, istan_time)
graphics.DrawLine(canvas, 0, y_line2_down, 128, y_line2_down, line_c)
graphics.DrawText(canvas, font, 2, y_time3_down, color, 'ISTANBUL')
canvas = self.matrix.SwapOnVSync(canvas)
if counter == 24:
counter = 0
time_offset += 1
time.sleep(speed)
if y_coord_down == 0:
break
if transition == 'down':
while y_coord_up > 0:
y_coord_up -= 1
y_time1_up += 1
y_time2_up += 1
y_time3_up += 1
y_line1_up += 1
y_line2_up += 1
if 0 <= counter <= 5:
canvas.Clear()
if time_offset % (1/speed) == 0:
ny_time = getTimes(ny_timezone)
london_time = getTimes(london_timezone)
tokyo_time = getTimes(tokyo_timezone)
counter += 1
ny_color = time_colors['day'] if isDaytime(ny_time) else time_colors['night']
london_color = time_colors['day'] if isDaytime(london_time) else time_colors['night']
tokyo_color = time_colors['day'] if isDaytime(tokyo_time) else time_colors['night']
if not settings['display_pm']:
ny_time = ny_time.replace("PM", "").replace("AM", "")
london_time = london_time.replace("PM", "").replace("AM", "")
tokyo_time = tokyo_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, 2, y_time1_up, color, 'NEW YORK')
graphics.DrawText(canvas, font, x_offset, y_time1_up, ny_color, ny_time)
graphics.DrawLine(canvas, 0, y_line1_up, 128, y_line1_up, line_c)
graphics.DrawText(canvas, font, 2, y_time2_up, color, 'LONDON')
graphics.DrawText(canvas, font, x_offset, y_time2_up, london_color, london_time)
graphics.DrawLine(canvas, 0, y_line2_up, 128, y_line2_up, line_c)
graphics.DrawText(canvas, font, 2, y_time3_up, color, 'TOKYO')
graphics.DrawText(canvas, font, x_offset, y_time3_up, tokyo_color, tokyo_time)
canvas = self.matrix.SwapOnVSync(canvas)
elif 6 <= counter <= 11:
canvas.Clear()
if counter == 6:
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if time_offset % (1/speed) == 0:
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
counter += 1
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if not settings['display_pm']:
au_time = au_time.replace("PM", "").replace("AM", "")
dubai_time = dubai_time.replace("PM", "").replace("AM", "")
la_time = la_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, y_time1_up, au_color, au_time)
graphics.DrawText(canvas, font, 2, y_time1_up, color, 'SYDNEY')
graphics.DrawLine(canvas, 0, y_line1_up, 128, y_line1_up, line_c)
graphics.DrawText(canvas, font, x_offset, y_time2_up, dubai_color, dubai_time)
graphics.DrawText(canvas, font, 2, y_time2_up, color, 'DUBAI')
graphics.DrawLine(canvas, 0, y_line2_up, 128, y_line2_up, line_c)
graphics.DrawText(canvas, font, x_offset, y_time3_up, la_color, la_time)
graphics.DrawText(canvas, font, 2, y_time3_up, color, 'LOS ANGELES')
canvas = self.matrix.SwapOnVSync(canvas)
elif 12 <= counter <= 17:
canvas.Clear()
if counter == 12:
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if time_offset % (1/speed) == 0:
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
counter += 1
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if not settings['display_pm']:
cn_time = cn_time.replace("PM", "").replace("AM", "")
paris_time = paris_time.replace("PM", "").replace("AM", "")
in_time = in_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, y_time1_up, cn_color, cn_time)
graphics.DrawText(canvas, font, 2, y_time1_up, color, 'SHANGHAI')
graphics.DrawText(canvas, font, x_offset, y_time2_up, paris_color, paris_time)
graphics.DrawLine(canvas, 0, y_line1_up, 128, y_line1_up, line_c)
graphics.DrawText(canvas, font, 2, y_time2_up, color, 'PARIS')
graphics.DrawText(canvas, font, x_offset, y_time3_up, in_color, in_time)
graphics.DrawLine(canvas, 0, y_line2_up, 128, y_line2_up, line_c)
graphics.DrawText(canvas, font, 2, y_time3_up, color, 'MUMBAI')
canvas = self.matrix.SwapOnVSync(canvas)
elif 18 <= counter <= 23:
canvas.Clear()
if counter == 18:
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if time_offset % (1/speed) == 0:
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
counter += 1
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if not settings['display_pm']:
auck_time = auck_time.replace("PM", "").replace("AM", "")
bang_time = bang_time.replace("PM", "").replace("AM", "")
istan_time = istan_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, y_time1_up, auck_color, auck_time)
graphics.DrawText(canvas, font, 2, y_time1_up, color, 'AUCKLAND')
graphics.DrawText(canvas, font, x_offset, y_time2_up, bang_color, bang_time)
graphics.DrawLine(canvas, 0, y_line1_up, 128, y_line1_up, line_c)
graphics.DrawText(canvas, font, 2, y_time2_up, color, 'BANGKOK')
graphics.DrawText(canvas, font, x_offset, y_time3_up, istan_color, istan_time)
graphics.DrawLine(canvas, 0, y_line2_up, 128, y_line2_up, line_c)
graphics.DrawText(canvas, font, 2, y_time3_up, color, 'ISTANBUL')
canvas = self.matrix.SwapOnVSync(canvas)
if counter == 24:
counter = 0
time_offset += 1
time.sleep(speed)
if y_coord_up == 0:
break
if transition == 'continuous':
while x_coord_cont < 128:
x_coord_cont += 1
x_time -= 1
x_line -= 1
x_city -= 1
if 0 <= counter <= 5:
canvas.Clear()
if time_offset % (1/speed) == 0:
ny_time = getTimes(ny_timezone)
london_time = getTimes(london_timezone)
tokyo_time = getTimes(tokyo_timezone)
counter += 1
ny_color = time_colors['day'] if isDaytime(ny_time) else time_colors['night']
london_color = time_colors['day'] if isDaytime(london_time) else time_colors['night']
tokyo_color = time_colors['day'] if isDaytime(tokyo_time) else time_colors['night']
if not settings['display_pm']:
ny_time = ny_time.replace("PM", "").replace("AM", "")
london_time = london_time.replace("PM", "").replace("AM", "")
tokyo_time = tokyo_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_city, 8, color, 'NEW YORK')
graphics.DrawText(canvas, font, x_time, 8, ny_color, ny_time)
graphics.DrawLine(canvas, x_line, 10, 128, 10, line_c)
graphics.DrawText(canvas, font, x_city, 19, color, 'LONDON')
graphics.DrawText(canvas, font, x_time, 19, london_color, london_time)
graphics.DrawLine(canvas, x_line, 21, 128, 21, line_c)
graphics.DrawText(canvas, font, x_city, 30, color, 'TOKYO')
graphics.DrawText(canvas, font, x_time, 30, tokyo_color, tokyo_time)
canvas = self.matrix.SwapOnVSync(canvas)
elif 6 <= counter <= 11:
canvas.Clear()
if counter == 6:
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if time_offset % (1/speed) == 0:
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
counter += 1
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if not settings['display_pm']:
au_time = au_time.replace("PM", "").replace("AM", "")
dubai_time = dubai_time.replace("PM", "").replace("AM", "")
la_time = la_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_time, 8, au_color, au_time)
graphics.DrawText(canvas, font, x_city, 8, color, 'SYDNEY')
graphics.DrawLine(canvas, x_line, 10, 128, 10, line_c)
graphics.DrawText(canvas, font, x_time, 19, dubai_color, dubai_time)
graphics.DrawText(canvas, font, x_city, 19, color, 'DUBAI')
graphics.DrawLine(canvas, x_line, 21, 128, 21, line_c)
graphics.DrawText(canvas, font, x_time, 30, la_color, la_time)
graphics.DrawText(canvas, font, x_city, 30, color, 'LOS ANGELES')
canvas = self.matrix.SwapOnVSync(canvas)
elif 12 <= counter <= 17:
canvas.Clear()
if counter == 12:
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if time_offset % (1/speed) == 0:
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
counter += 1
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if not settings['display_pm']:
cn_time = cn_time.replace("PM", "").replace("AM", "")
paris_time = paris_time.replace("PM", "").replace("AM", "")
in_time = in_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_time, 8, cn_color, cn_time)
graphics.DrawText(canvas, font, x_city, 8, color, 'SHANGHAI')
graphics.DrawText(canvas, font, x_time, 19, paris_color, paris_time)
graphics.DrawLine(canvas, x_line, 10, 128, 10, line_c)
graphics.DrawText(canvas, font, x_city, 19, color, 'PARIS')
graphics.DrawText(canvas, font, x_time, 30, in_color, in_time)
graphics.DrawLine(canvas, x_line, 21, 128, 21, line_c)
graphics.DrawText(canvas, font, x_city, 30, color, 'MUMBAI')
canvas = self.matrix.SwapOnVSync(canvas)
elif 18 <= counter <= 23:
canvas.Clear()
if counter == 18:
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if time_offset % (1/speed) == 0:
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
counter += 1
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if not settings['display_pm']:
auck_time = auck_time.replace("PM", "").replace("AM", "")
bang_time = bang_time.replace("PM", "").replace("AM", "")
istan_time = istan_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_time, 8, auck_color, auck_time)
graphics.DrawText(canvas, font, x_city, 8, color, 'AUCKLAND')
graphics.DrawText(canvas, font, x_time, 19, bang_color, bang_time)
graphics.DrawLine(canvas, x_line, 10, 128, 10, line_c)
graphics.DrawText(canvas, font, x_city, 19, color, 'BANGKOK')
graphics.DrawText(canvas, font, x_time, 30, istan_color, istan_time)
graphics.DrawLine(canvas, x_line, 21, 128, 21, line_c)
graphics.DrawText(canvas, font, x_city, 30, color, 'ISTANBUL')
canvas = self.matrix.SwapOnVSync(canvas)
if counter == 24:
counter = 0
time_offset += 1
time.sleep(speed)
if x_coord_cont == 0:
break
#WHEN TRANSITION ENDS, PAUSE ON SCREEN
if 0 <= counter <= 5:
canvas.Clear()
ny_time = getTimes(ny_timezone)
london_time = getTimes(london_timezone)
tokyo_time = getTimes(tokyo_timezone)
ny_color = time_colors['day'] if isDaytime(ny_time) else time_colors['night']
london_color = time_colors['day'] if isDaytime(london_time) else time_colors['night']
tokyo_color = time_colors['day'] if isDaytime(tokyo_time) else time_colors['night']
if not settings['display_pm']:
ny_time = ny_time.replace("PM", "").replace("AM", "")
london_time = london_time.replace("PM", "").replace("AM", "")
tokyo_time = tokyo_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, 2, 8, color, 'NEW YORK')
graphics.DrawText(canvas, font, x_offset, 8, ny_color, ny_time)
graphics.DrawLine(canvas, 0, 10, 128, 10, line_c)
graphics.DrawText(canvas, font, 2, 19, color, 'LONDON')
graphics.DrawText(canvas, font, x_offset, 19, london_color, london_time)
graphics.DrawLine(canvas, 0, 21, 128, 21, line_c)
graphics.DrawText(canvas, font, 2, 30, color, 'TOKYO')
graphics.DrawText(canvas, font, x_offset, 30, tokyo_color, tokyo_time)
canvas = self.matrix.SwapOnVSync(canvas)
counter += 1
elif 6 <= counter <= 11:
canvas.Clear()
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if not settings['display_pm']:
au_time = au_time.replace("PM", "").replace("AM", "")
dubai_time = dubai_time.replace("PM", "").replace("AM", "")
la_time = la_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, 8, au_color, au_time)
graphics.DrawText(canvas, font, 2, 8, color, 'SYDNEY')
graphics.DrawLine(canvas, 0, 10, 128, 10, line_c)
graphics.DrawText(canvas, font, x_offset, 19, dubai_color, dubai_time)
graphics.DrawText(canvas, font, 2, 19, color, 'DUBAI')
graphics.DrawLine(canvas, 0, 21, 128, 21, line_c)
graphics.DrawText(canvas, font, x_offset, 30, la_color, la_time)
graphics.DrawText(canvas, font, 2, 30, color, 'LOS ANGELES')
canvas = self.matrix.SwapOnVSync(canvas)
counter += 1
elif 12 <= counter <= 17:
canvas.Clear()
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if not settings['display_pm']:
cn_time = cn_time.replace("PM", "").replace("AM", "")
paris_time = paris_time.replace("PM", "").replace("AM", "")
in_time = in_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, 8, cn_color, cn_time)
graphics.DrawText(canvas, font, 2, 8, color, 'SHANGHAI')
graphics.DrawText(canvas, font, x_offset, 19, paris_color, paris_time)
graphics.DrawLine(canvas, 0, 10, 128, 10, line_c)
graphics.DrawText(canvas, font, 2, 19, color, 'PARIS')
graphics.DrawText(canvas, font, x_offset, 30, in_color, in_time)
graphics.DrawLine(canvas, 0, 21, 128, 21, line_c)
graphics.DrawText(canvas, font, 2, 30, color, 'MUMBAI')
canvas = self.matrix.SwapOnVSync(canvas)
counter += 1
elif 18 <= counter <= 23:
canvas.Clear()
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if not settings['display_pm']:
auck_time = auck_time.replace("PM", "").replace("AM", "")
bang_time = bang_time.replace("PM", "").replace("AM", "")
istan_time = istan_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset, 8, auck_color, auck_time)
graphics.DrawText(canvas, font, 2, 8, color, 'AUCKLAND')
graphics.DrawText(canvas, font, x_offset, 19, bang_color, bang_time)
graphics.DrawLine(canvas, 0, 10, 128, 10, line_c)
graphics.DrawText(canvas, font, 2, 19, color, 'BANGKOK')
graphics.DrawText(canvas, font, x_offset, 30, istan_color, istan_time)
graphics.DrawLine(canvas, 0, 21, 128, 21, line_c)
graphics.DrawText(canvas, font, 2, 30, color, 'ISTANBUL')
canvas = self.matrix.SwapOnVSync(canvas)
counter += 1
if counter == 24:
counter = 0
counter2 += 1
time.sleep(1)
kill=self.checkKilled()
if kill:break
#SCROLL OUT BEGINS
if finalcount == 0:
ny_time = getTimes(ny_timezone)
london_time = getTimes(london_timezone)
tokyo_time = getTimes(tokyo_timezone)
ny_color = time_colors['day'] if isDaytime(ny_time) else time_colors['night']
london_color = time_colors['day'] if isDaytime(london_time) else time_colors['night']
tokyo_color = time_colors['day'] if isDaytime(tokyo_time) else time_colors['night']
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
finalcount += 1
if 0 <= counter <= 5:
canvas.Clear()
if time_offset2 % (1/speed) == 0:
counter += 1
ny_time = getTimes(ny_timezone)
london_time = getTimes(london_timezone)
tokyo_time = getTimes(tokyo_timezone)
ny_color = time_colors['day'] if isDaytime(ny_time) else time_colors['night']
london_color = time_colors['day'] if isDaytime(london_time) else time_colors['night']
tokyo_color = time_colors['day'] if isDaytime(tokyo_time) else time_colors['night']
if not settings['display_pm']:
ny_time = ny_time.replace("PM", "").replace("AM", "")
london_time = london_time.replace("PM", "").replace("AM", "")
tokyo_time = tokyo_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, 2 + x_city_out, 8, color, 'NEW YORK')
graphics.DrawText(canvas, font, x_offset + x_time_out, 8, ny_color, ny_time)
graphics.DrawLine(canvas, 0, 10, 128 + x_line_out, 10, line_c)
graphics.DrawText(canvas, font, 2 + x_city_out, 19, color, 'LONDON')
graphics.DrawText(canvas, font, x_offset + x_time_out, 19, london_color, london_time)
graphics.DrawLine(canvas, 0, 21, 128 + x_line_out, 21, line_c)
graphics.DrawText(canvas, font, 2 + x_city_out, 30, color, 'TOKYO')
graphics.DrawText(canvas, font, x_offset + x_time_out, 30, tokyo_color, tokyo_time)
canvas = self.matrix.SwapOnVSync(canvas)
elif 6 <= counter <= 11:
canvas.Clear()
if counter == 6:
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if time_offset2 % (1/speed) == 0:
counter += 1
au_time = getTimes(au_timezone)
dubai_time = getTimes(dubai_timezone)
la_time = getTimes(la_timezone)
au_color = time_colors['day'] if isDaytime(au_time) else time_colors['night']
dubai_color = time_colors['day'] if isDaytime(dubai_time) else time_colors['night']
la_color = time_colors['day'] if isDaytime(la_time) else time_colors['night']
if not settings['display_pm']:
au_time = au_time.replace("PM", "").replace("AM", "")
dubai_time = dubai_time.replace("PM", "").replace("AM", "")
la_time = la_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset + x_time_out, 8, au_color, au_time)
graphics.DrawText(canvas, font, 2 + x_city_out, 8, color, 'SYDNEY')
graphics.DrawLine(canvas, 0, 10, 128 + x_line_out, 10, line_c)
graphics.DrawText(canvas, font, x_offset + x_time_out, 19, dubai_color, dubai_time)
graphics.DrawText(canvas, font, 2 + x_city_out, 19, color, 'DUBAI')
graphics.DrawLine(canvas, 0, 21, 128 + x_line_out, 21, line_c)
graphics.DrawText(canvas, font, x_offset + x_time_out, 30, la_color, la_time)
graphics.DrawText(canvas, font, 2 + x_city_out, 30, color, 'LOS ANGELES')
canvas = self.matrix.SwapOnVSync(canvas)
elif 12 <= counter <= 17:
canvas.Clear()
if counter == 12:
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if time_offset2 % (1/speed) == 0:
counter += 1
cn_time = getTimes(cn_timezone)
paris_time = getTimes(paris_timezone)
in_time = getTimes(in_timezone)
cn_color = time_colors['day'] if isDaytime(cn_time) else time_colors['night']
paris_color = time_colors['day'] if isDaytime(paris_time) else time_colors['night']
in_color = time_colors['day'] if isDaytime(in_time) else time_colors['night']
if not settings['display_pm']:
cn_time = cn_time.replace("PM", "").replace("AM", "")
paris_time = paris_time.replace("PM", "").replace("AM", "")
in_time = in_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset + x_time_out, 8, cn_color, cn_time)
graphics.DrawText(canvas, font, 2 + x_city_out, 8, color, 'SHANGHAI')
graphics.DrawText(canvas, font, x_offset + x_time_out, 19, paris_color, paris_time)
graphics.DrawLine(canvas, 0, 10, 128 + x_line_out, 10, line_c)
graphics.DrawText(canvas, font, 2 + x_city_out, 19, color, 'PARIS')
graphics.DrawText(canvas, font, x_offset + x_time_out, 30, in_color, in_time)
graphics.DrawLine(canvas, 0, 21, 128 + x_line_out, 21, line_c)
graphics.DrawText(canvas, font, 2 + x_city_out, 30, color, 'MUMBAI')
canvas = self.matrix.SwapOnVSync(canvas)
elif 18 <= counter <= 23:
canvas.Clear()
if counter == 18:
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if time_offset2 % (1/speed) == 0:
counter += 1
auck_time = getTimes(auck_timezone)
bang_time = getTimes(bang_timezone)
istan_time = getTimes(istan_timezone)
auck_color = time_colors['day'] if isDaytime(auck_time) else time_colors['night']
bang_color = time_colors['day'] if isDaytime(bang_time) else time_colors['night']
istan_color = time_colors['day'] if isDaytime(istan_time) else time_colors['night']
if not settings['display_pm']:
auck_time = auck_time.replace("PM", "").replace("AM", "")
bang_time = bang_time.replace("PM", "").replace("AM", "")
istan_time = istan_time.replace("PM", "").replace("AM", "")
graphics.DrawText(canvas, font, x_offset + x_time_out, 8, auck_color, auck_time)
graphics.DrawText(canvas, font, 2 + x_city_out, 8, color, 'AUCKLAND')
graphics.DrawText(canvas, font, x_offset + x_time_out, 19, bang_color, bang_time)
graphics.DrawLine(canvas, 0, 10, 128 + x_line_out, 10, line_c)
graphics.DrawText(canvas, font, 2 + x_city_out, 19, color, 'BANGKOK')
graphics.DrawText(canvas, font, x_offset + x_time_out, 30, istan_color, istan_time)
graphics.DrawLine(canvas, 0, 21, 128 + x_line_out, 21, line_c)
graphics.DrawText(canvas, font, 2 + x_city_out, 30, color, 'ISTANBUL')
canvas = self.matrix.SwapOnVSync(canvas)
if counter == 24:
counter = 0
time_offset2 += 1
x_city_out -= 1
x_time_out -= 1
x_line_out -= 1
counter3 += 1
time.sleep(speed)
kill=self.checkKilled()
if kill:break
return kill
def ip_viewer(self):
font = ImageFont.load("./fonts/6x10.pil")
image = Image.new('RGB', (128, 32))
hostname = str(os.popen('hostname').read()).strip() + ".local:1024"
mac_add = str(os.popen('cat /sys/class/net/wlan0/address').read()).replace(" ", "").strip()
ip_add = str(os.popen('hostname -I').read()).replace(" ", "").strip() + ":1024"
hostname_img = self.textImage(hostname, font, r = 255, g = 255 , b = 255)
ip_img = self.textImage(ip_add, font, r = 255, g = 255 , b = 255)
mac_img = self.textImage(mac_add, font, r = 255, g = 255 , b = 255)
image.paste(hostname_img, (0,0))
image.paste(ip_img, (0,12))
image.paste(mac_img, (0,23))
stock_ticker.setImage(image)
time.sleep(10)
def displayStocks(self):
self.scrollImageTransition(['final.ppm', 'final.ppm'], offset_x = 0, offset_y = 0)
def displayProfessional(self):
forex = self.getForexProfessional()
crypto = self.getCryptoProfessional()
news = self.getNewsProfessional()
stock = self.getStockProfessional()
weather = self.getTodayWeatherProfessional()
commodities = self.getCommoditiesProfessional()
indices = self.getIndicesProfessional()
daily_forecast = self.getDailyWeatherProfessional()
sports_stats = self.getLeagueTableProfessional()
sports_upcoming = self.getLeagueProfessional()
sports_past = self.getLeagueProfessional()
sports_live = self.getLeagueProfessional()
movies = self.getMoviesProfessional()
messages = self.getUserMessagesProfessional()
images = self.getUserImagesProfessional()
ipo = self.getIpoProfessional()
economic = self.getEconomicProfessional()
jokes = self.getJokesProfessional()
market = self.getMarketProfessional()
sector = self.getSectorProfessional()
place = self.getPlaceImageProfessional()
x_offset = 0
news.paste(weather, (x_offset, 16))
x_offset += weather.size[0]
news.paste(crypto, (x_offset, 16))
x_offset += crypto.size[0]
news.paste(stock, (x_offset, 16))
x_offset += stock.size[0]
news.paste(forex, (x_offset, 16))
x_offset += forex.size[0]
news.paste(commodities, (x_offset, 16))
x_offset += commodities.size[0]
news.paste(indices, (x_offset, 16))
x_offset += indices.size[0]
news.paste(daily_forecast, (x_offset, 16))
x_offset += daily_forecast.size[0]
news.paste(sports_stats, (x_offset, 16))
x_offset += sports_stats.size[0]
news.paste(sports_upcoming, (x_offset, 16))
x_offset += sports_upcoming.size[0]
news.paste(sports_past, (x_offset, 16))
x_offset += sports_past.size[0]
news.paste(sports_live, (x_offset, 16))
x_offset += sports_live.size[0]
news.paste(movies, (x_offset, 16))
x_offset += movies.size[0]
news.paste(messages, (x_offset, 16))
x_offset += messages.size[0]
news.paste(images, (x_offset, 16))
x_offset += images.size[0]
news.paste(ipo, (x_offset, 16))
x_offset += ipo.size[0]
news.paste(economic, (x_offset, 16))
x_offset += economic.size[0]
news.paste(jokes, (x_offset, 16))
x_offset += jokes.size[0]
news.paste(market, (x_offset, 16))
x_offset += market.size[0]
news.paste(sector, (x_offset, 16))
x_offset += sector.size[0]
news.paste(place, (x_offset, 16))
x_offset += place.size[0]
self.double_buffer = self.matrix.CreateFrameCanvas()
while True:
kill = stock_ticker.scrollImage(news, offset_x = 128)
if kill:
break
def process_msg(self, msg):
if msg == 'S': # stocks
self.scrollFunctionsAnimated(['stocks', 'stocks'], animation = 'traditional')
elif msg == 'C': # crypto
self.scrollFunctionsAnimated(['crypto', 'crypto'], animation = 'traditional')
elif msg == 'F': # forex
self.scrollFunctionsAnimated(['forex', 'forex'], animation = 'traditional')
elif msg == 'N': #news
self.scrollFunctionsAnimated(['news', 'news'], animation = 'traditional')
# speed settings
elif msg == 's':
self.delay = 0.03
elif msg == 'm':
self.delay = 0.02
elif msg == 'f':
self.delay = 0.01
elif msg in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: # birghtness ettings
self.brightness = (float(msg)+1)*10
self.matrix.brightness = self.brightness
elif msg == 'T':# text
self.scrollFunctionsAnimated(['text', 'text'], animation = 'traditional')
elif msg == 'I': # image
self.scrollFunctionsAnimated(['display_image', 'display_image'], animation = 'traditional')
elif msg == 'RP': # image
self.scrollFunctionsAnimated(['place', 'place'], animation = 'traditional')
elif msg == 'G': # gif
self.scrollFunctionsAnimated(['display_gif', 'display_gif'], animation = 'traditional')
elif msg == 'W': # weather
self.scrollFunctionsAnimated(['today_weather', 'today_weather'], animation = 'traditional')
elif msg == 'D': # daily weather
self.scrollFunctionsAnimated(['daily_weather', 'daily_weather'],animation = 'traditional')
elif msg == 'P': # past league
self.scrollFunctionsAnimated(['past_games', 'past_games'],animation = 'traditional')
elif msg == 'l': # future league
self.scrollFunctionsAnimated(['future_games', 'future_games'],animation = 'traditional')
elif msg == 'L': # live game
self.scrollFunctionsAnimated(['live_games', 'live_games'],animation = 'traditional')
elif msg == 't': #legue tble
self.scrollFunctionsAnimated(['league_table', 'league_table'],animation = 'traditional')
elif msg == 'CO': #commodities
self.scrollFunctionsAnimated(['commodities', 'commodities'],animation = 'traditional')
elif msg == 'WI': #indices
self.scrollFunctionsAnimated(['indices', 'indices'],animation = 'traditional')
elif msg == 'MO': #movies
self.scrollFunctionsAnimated(['movies', 'movies'],animation = 'traditional')
elif msg == 'IPO': #ipo
self.scrollFunctionsAnimated(['ipo', 'ipo'],animation = 'traditional')
elif msg == 'EC': #economic calendar
self.scrollFunctionsAnimated(['economic', 'economic'],animation = 'traditional')
elif msg == 'JO': # jokes
self.scrollFunctionsAnimated(['jokes', 'jokes'],animation = 'traditional')
elif msg == 'MA': # market
self.scrollFunctionsAnimated(['market', 'market'],animation = 'traditional')
elif msg == 'SE':
self.scrollFunctionsAnimated(['sector', 'sector'],animation = 'traditional')
elif msg == 'CL':
self.scrollFunctionsAnimated(['clock1', 'clock1'],animation = 'traditional')
elif msg == 'CL2':
self.scrollFunctionsAnimated(['clock2', 'clock2'],animation = 'traditional')
elif msg == 'WCL':
self.scrollFunctionsAnimated(['worldclock', 'worldclock'],animation = 'traditional')
elif msg == 'A': #everything
#userSettings = ['display_gif', 'text', 'display_image', 'stocks', 'crypto', 'forex', 'today_weather', 'daily_weather', 'league_table', 'league_games', 'news'] # these wil be read from csv, just for demo
#userSettings = [ 'daily_weather']
#userSettings = ['crypto', 'stocks'] # these wil be read from csv, just for demo
#userSettings = [ 'display_image', 'news'] # these wil be read from csv, just for demo
f = open('csv/display_settings.json', 'r')
user_settings = json.load(f)
f.close()
if 'Professional'==user_settings[0] and len(user_settings[1][0])>0 and len(user_settings[1][1])>0: #if professional display
self.scrollProfessionalAnimated(user_settings[1])
elif len(user_settings[1][0])>0 and 'Standard'==user_settings[0]:
self.scrollFunctionsAnimated(user_settings[1][0], animation = 'down')
elif msg == 'b':
userSettings = json.load(open('csv/display_settings.json'))
self.scrollProfessionalAnimated(userSettings)
#self.displayProfessional()
elif msg == '+':
stock_ticker.scrollMultiple()
elif msg == 'K': # kill
self.resetMatrix()
elif msg =='-':
self.run_intro_screen()
elif msg == '*':
#
#
start_GIF = Image.open('./logos/startup_logo1.gif')
self.displayGIF(start_GIF, delay = 0.02, repeat = False)
#stock_ticker.setImage(start_image)
time.sleep(10)
self.resetMatrix()
time.sleep(2)
self.ip_viewer()
time.sleep(2)
self.resetMatrix()
def run_intro_screen(self):
dct = {"feature": "Custom Messages", "speed": "Medium", "animation": "Down", "title": False, "messages": [{"name": "welcome", "text": "Welcome to Fintic!", "text_colour": "White", "size": "Large", "background_colour": "Black"}, {"name": "get_started", "text": "To get started, connect your device to the \"Fintic Hotspot\" and access \"fintic.local:1024\" on your web browser. You can connect your ticker to Wi-Fi there.", "text_colour": "White", "size": "Small", "background_colour": "Black"}]}
json.dump(dct, open('csv/message_settings.json', 'w'))
self.scrollFunctionsAnimated(['Custom Messages'], repeat = True)
if __name__ == '__main__':
try:
stock_ticker = StockTicker()
while True:
msg = getInput()
stock_ticker.process_msg(msg)
except Exception as e:
pass
# logf = open('log.txt', "a")
# 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])))
# logf.close()