Skip to content
This repository was archived by the owner on Mar 31, 2020. It is now read-only.

Commit 71d07b0

Browse files
committed
Offloaded caching to separate module
1 parent 1f23905 commit 71d07b0

File tree

2 files changed

+117
-121
lines changed

2 files changed

+117
-121
lines changed

src/cache.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import aiohttp
2+
from random import randint, choice, sample
3+
from PIL import Image, ImageTk
4+
import os
5+
import io
6+
7+
8+
class Cache:
9+
'''Class used for caching images and data about the cats.'''
10+
11+
def __init__(self):
12+
# setting class variables for use later
13+
self.cats = list()
14+
self.session = None
15+
16+
# getting the directory folder for use later when opening files
17+
self.dir = os.path.dirname(os.path.realpath(__file__))
18+
19+
async def refill(self):
20+
'''Gets a cache of cat data and adds it to the self.cats list'''
21+
22+
# if we haven't created a session yet, do so
23+
if not self.session:
24+
self.session = aiohttp.ClientSession()
25+
26+
# Run 10 times to get 10 cats
27+
for i in range(10):
28+
# initialize a dict of cat data
29+
cat_data = dict()
30+
31+
# randomly make jumpscares happen, but not on the first image
32+
if randint(1, 10) == 5 and i:
33+
# get a random number for an image
34+
image_number = randint(1, 10)
35+
# open and resize the image using Pillow
36+
im = Image.open(os.path.join(self.dir, os.path.join("res",
37+
os.path.join("images", f"{image_number}.jpg"))))
38+
im = im.resize((self.screen_x, self.screen_y - 150), Image.NEAREST)
39+
# make the image a tkinter image
40+
image = ImageTk.PhotoImage(im)
41+
# update the cat data dict
42+
cat_data.update({"image": image})
43+
cat_data.update({"jumpscare": True})
44+
else:
45+
# set jumpscare to False because it isnt a jumpscare image
46+
cat_data.update({"jumpscare": False})
47+
48+
# get a url from The Cat API
49+
async with self.session.get('https://api.thecatapi.com/v1/images/search') as res:
50+
data = await res.json()
51+
url = data[0]['url']
52+
# get image data from that url
53+
async with self.session.get(url) as res:
54+
image_bytes = await res.read()
55+
# open and the image in pillow
56+
im = Image.open(io.BytesIO(image_bytes))
57+
im = im.resize((400, 440), Image.NEAREST)
58+
# make the image a tkinter image
59+
image = ImageTk.PhotoImage(im)
60+
# update the cat data dict
61+
cat_data.update({"image": image})
62+
63+
# get a random name
64+
async with self.session.get(
65+
"https://www.pawclub.com.au/assets/js/namesTemp.json") as res:
66+
data = await res.json()
67+
# get a random letter for the name
68+
# Note: website doesn't have any b names which is why it is left out here
69+
letter = choice(list('acdefghijklmnopqrstuvwxyz'))
70+
# randomly choose a name from the json with that letter
71+
cat = choice(data[letter])
72+
# update the cat data dict
73+
cat_data.update({"name": cat["name"]})
74+
cat_data.update({"gender": cat["gender"]})
75+
76+
# get 5 random hobbies
77+
async with self.session.get(
78+
"https://gist.githubusercontent.com/mbejda/" +
79+
"453fdb77ef8d4d3b3a67/raw/e8334f09109dc212892406e25fdee03efdc23f56/" +
80+
"hobbies.txt"
81+
) as res:
82+
text = await res.text()
83+
# split the raw text of hobbies into a list
84+
all_hobbies = text.split("\n")
85+
# get 5 of those hobbies
86+
hobby_list = sample(all_hobbies, 5)
87+
# join those 5 hobbies into a bulleted list (string)
88+
list_of_hobbies = "\n •".join(hobby_list)
89+
hobbies = f"Hobbies:\n{list_of_hobbies}"
90+
# update the cat_data dict
91+
cat_data.update({"hobbies": hobbies})
92+
93+
# get a random age between 1 and 15 (avg lifespan of a cat)
94+
age = str(randint(1, 15))
95+
# update the cat data dict
96+
cat_data.update({"age": age})
97+
98+
# get a random number of miles away between 1 and 5
99+
miles = randint(1, 5)
100+
location = f"{miles} miles away"
101+
# update the cat data dict
102+
cat_data.update({"location": location})
103+
self.cats.append(cat_data)

src/mainwindow.py

Lines changed: 14 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
1-
import configparser
21
import tkinter as tk
3-
from PIL import Image, ImageTk
4-
import io
5-
from random import randint, choice, sample
62
import asyncio
7-
import aiohttp
8-
import os
93
from pygame import mixer
4+
from cache import Cache
105

116

127
class Tinder:
@@ -16,133 +11,33 @@ def __init__(self):
1611
# setup for pygame mixer
1712
mixer.init()
1813

19-
# getting the directory folder for use later when opening files
20-
self.dir = os.path.dirname(os.path.realpath(__file__))
21-
22-
# get settings
23-
cp = configparser.ConfigParser()
24-
cp.read('settings.ini')
25-
26-
# for now, let's just look up the DEV settings
27-
# can change this later
28-
# configparser will use values from DEFAULT section if none provided elsewhere
29-
if 'DEV' in cp.sections():
30-
self.config = cp['DEV']
31-
else:
32-
self.config = cp['DEFAULT']
33-
3414
# setting up the tkinter root
3515
self.root = tk.Tk()
36-
self.root.title(self.config['main.title'])
37-
self.root.geometry(self.config['main.geometry'])
16+
self.root.title("Cat Tinder")
17+
self.root.geometry("400x500")
3818
self.root.minsize(400, 500)
3919
self.root.maxsize(400, 500)
40-
self.root.configure(background=self.config['main.background'])
20+
self.root.configure(background='black')
4121
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
4222

4323
# getting screen width and height for use with teleporting window/jumpscare
4424
self.screen_x = self.root.winfo_screenwidth()
4525
self.screen_y = self.root.winfo_screenheight()
4626

4727
# setting class variables to be used later
28+
self.cache = Cache()
4829
self.jumpscare = False
4930
self.loop = asyncio.get_event_loop()
50-
self.session = None
51-
self.cats = list()
52-
53-
self.frame = tk.Frame()
5431

5532
def start(self):
5633
'''Starts the Tinder application'''
5734

5835
# getting a cache of cat info
59-
self.loop.run_until_complete(self.get_cache())
36+
self.loop.run_until_complete(self.cache.refill())
6037

6138
# starting the program loop
6239
self.new_image()
6340

64-
async def get_cache(self):
65-
'''Gets a cache of cat data and adds it to the self.cats list'''
66-
67-
# if we haven't created a session yet, do so
68-
if not self.session:
69-
self.session = aiohttp.ClientSession()
70-
71-
cachesize = int(self.config['cachesize'])
72-
# Run 10 times to get 10 cats
73-
for i in range(cachesize):
74-
# initialize a dict of cat data
75-
cat_data = dict()
76-
77-
# randomly make jumpscares happen, but not on the first image
78-
if randint(1, 10) == 5 and i:
79-
# get a random number for an image
80-
image_number = randint(1, 10)
81-
# open and resize the image using Pillow
82-
im = Image.open(os.path.join(self.dir, os.path.join("res",
83-
os.path.join("images", f"{image_number}.jpg"))))
84-
im = im.resize((self.screen_x, self.screen_y - 150), Image.NEAREST)
85-
# make the image a tkinter image
86-
image = ImageTk.PhotoImage(im)
87-
# update the cat data dict
88-
cat_data.update({"image": image})
89-
cat_data.update({"jumpscare": True})
90-
else:
91-
# set jumpscare to False because it isnt a jumpscare image
92-
cat_data.update({"jumpscare": False})
93-
94-
# get a url from The Cat API
95-
async with self.session.get(self.config['catapi']) as res:
96-
data = await res.json()
97-
url = data[0]['url']
98-
# get image data from that url
99-
async with self.session.get(url) as res:
100-
image_bytes = await res.read()
101-
# open and the image in pillow
102-
im = Image.open(io.BytesIO(image_bytes))
103-
im = im.resize((400, 440), Image.NEAREST)
104-
# make the image a tkinter image
105-
image = ImageTk.PhotoImage(im)
106-
# update the cat data dict
107-
cat_data.update({"image": image})
108-
109-
# get a random name
110-
async with self.session.get(self.config['namefile']) as res:
111-
data = await res.json()
112-
# get a random letter for the name
113-
# Note: website doesn't have any b names which is why it is left out here
114-
letter = choice(list('acdefghijklmnopqrstuvwxyz'))
115-
# randomly choose a name from the json with that letter
116-
cat = choice(data[letter])
117-
# update the cat data dict
118-
cat_data.update({"name": cat["name"]})
119-
cat_data.update({"gender": cat["gender"]})
120-
121-
# get 5 random hobbies
122-
async with self.session.get(self.config['hobbiesfile']) as res:
123-
text = await res.text()
124-
# split the raw text of hobbies into a list
125-
all_hobbies = text.split("\n")
126-
# get 5 of those hobbies
127-
hobby_list = sample(all_hobbies, 5)
128-
# join those 5 hobbies into a bulleted list (string)
129-
list_of_hobbies = "\n •".join(hobby_list)
130-
hobbies = f"Hobbies:\n{list_of_hobbies}"
131-
# update the cat_data dict
132-
cat_data.update({"hobbies": hobbies})
133-
134-
# get a random age between 1 and 15 (avg lifespan of a cat)
135-
age = str(randint(1, 15))
136-
# update the cat data dict
137-
cat_data.update({"age": age})
138-
139-
# get a random number of miles away between 1 and 5
140-
miles = randint(1, 5)
141-
location = f"{miles} miles away"
142-
# update the cat data dict
143-
cat_data.update({"location": location})
144-
self.cats.append(cat_data)
145-
14641
def all_children(self):
14742
'''Used to get all children of the root window
14843
@@ -168,6 +63,7 @@ def new_image(self, cat=None):
16863

16964
# if the previous image was a jumpscare, resize the window and reset the variable
17065
if self.jumpscare:
66+
self.root.geometry()
17167
self.root.maxsize(400, 500)
17268
self.jumpscare = False
17369

@@ -183,11 +79,11 @@ def new_image(self, cat=None):
18379
# if a dict wasn't passed to the function, get a dict from self.cats
18480
if not cat:
18581
try:
186-
cat = self.cats.pop(0)
82+
cat = self.cache.cats.pop(0)
18783
except IndexError:
18884
# the cache is empty so refill it
189-
self.loop.run_until_complete(self.get_cache())
190-
cat = self.cats.pop(0)
85+
self.loop.run_until_complete(self.cache.refill())
86+
cat = self.cache.cats.pop(0)
19187

19288
# getting base cat variables from the dict
19389
image = cat["image"]
@@ -287,24 +183,21 @@ def get_bio():
287183

288184
# setting up like/dislike/Back to Photo buttons on the bio screen
289185
tk.Button(
290-
self.frame, text=self.config['like.text'],
291-
background=self.config['like.background'],
186+
self.frame, text="Like", background="green",
292187
command=self.new_image).pack(side=tk.RIGHT)
293188
tk.Button(
294-
self.frame, text=self.config['dislike.text'],
295-
background=self.config['dislike.background'],
189+
self.frame, text="Dislike", background="red",
296190
command=self.new_image).pack(side=tk.LEFT)
297191
tk.Button(
298-
self.root, text=self.config['back.text'],
299-
background=self.config['back.background'],
192+
self.root, text="Back To Photo", background="blue",
300193
command=back_to_photo).pack(side=tk.BOTTOM)
301194

302195
# packing the frame
303196
self.frame.pack()
304197

305198
# making and packing the Bio button for users to look at the cat's bio
306199
tk.Button(
307-
self.frame, text=self.config['bio.text'], background=self.config['bio.background'],
200+
self.frame, text="Bio", background="blue",
308201
command=get_bio).pack(side=tk.BOTTOM)
309202

310203
# packing the frame

0 commit comments

Comments
 (0)