goodread-phat/good_sprite.py
2018-08-28 23:12:00 -04:00

114 lines
3.0 KiB
Python

import datetime
import os
from collections import defaultdict
from PIL import ImageFont, Image
import inkyphat
FAKE = True
text = Image.open("numbers.png")
text_mask = inkyphat.create_mask(text, [inkyphat.WHITE])
def print_digit(position, digit):
"""Print a single digit using the sprite sheet.
Each number is grabbed from the masked sprite sheet,
and then used as a mask to paste the desired color
onto Inky pHATs image buffer.
"""
o_x, o_y = position
num_margin = 2
num_width = 6
num_height = 7
s_x = num_margin + (digit * (num_width + num_margin))
sprite = text_mask.crop((s_x, 0, s_x + num_width, num_height))
inkyphat.paste(inkyphat.BLACK, (o_x, o_y), sprite)
def print_number(position, number):
"""Prints a number using the sprite sheet."""
for digit in str(number):
print_digit(position, int(digit))
position = (position[0] + 8, position[1])
def main():
pages = {'2014': 7375, '2015': 23508, '2016': 17696, '2017': 19706, '2018': 9388}
books = {"2018":33,"2017":64,"2016":47,"2015":75,"2014":19}
if not FAKE:
pages, books = get_goodreads_stats()
stats = get_stats(pages, books)
draw(stats)
def get_goodreads_stats():
from selenium import webdriver
payload = {
'email': os.environ.get('EMAIL'),
'password': os.environ.get('PASSW'),
}
LOGIN_URL= 'https://www.goodreads.com/user/sign_in'
driver = webdriver.PhantomJS()
driver.get(LOGIN_URL)
username = driver.find_element_by_id('user_email')
password = driver.find_element_by_id('user_password')
username.send_keys(payload['email'])
password.send_keys(payload['password'])
form = driver.find_element_by_name('sign_in')
form.submit()
driver.get('https://www.goodreads.com/review/stats/24381583#pages')
pages = driver.execute_script('return page_stats')
books = driver.execute_script('return year_stats')
return pages, books
def get_stats(pages, books):
size = 5
coords = defaultdict(list)
columns = ["year", "books", "pages"]
start_x, start_y = 12, 25
column_offset = [0,78,140]
year_offset = 15
_stats = []
for idy, year in enumerate(sorted(pages.keys(), key=lambda yr: -int(yr))):
row = {}
col_data = {'year':year, 'pages': pages[year], 'books': books[year]}
y = start_y + (year_offset * idy)
for idx, column in enumerate(columns):
x = start_x + column_offset[idx]
row[column] = (col_data[column], (x,y))
_stats.append(row)
return _stats
def draw(stats):
inkyphat.set_colour('red')
inkyphat.set_border(inkyphat.WHITE)
inkyphat.set_image("./background.png")
draw_row('year', stats)
draw_row('books', stats)
draw_row('pages', stats)
inkyphat.show()
def draw_row(row, stats):
for year in stats:
count = year[row][0]
x,y = year[row][1]
print_number((x,y), count)
if __name__ == "__main__":
main()