-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot_cache.py
173 lines (128 loc) · 7.23 KB
/
bot_cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import requests
import urllib.parse
import json
import time
from PIL import Image
import io
import jumpstartdata as jsd
class BotCache:
uniqueListCache = {}
uniqueListCacheStats = {'cacheHit': 0, 'cacheMiss': 0}
uniqueListFetchStats = {'fetchCount': 0, 'fetchFailures': 0, 'timeFetching': 0}
scryFallJSONCardCache = {}
scryFallJSONCardCacheStats = {'cacheHit': 0, 'cacheMiss': 0}
scryFallJSONCardFetchStats = {'fetchCount': 0, 'fetchFailures': 0, 'timeFetching': 0}
imageCache = {}
imageCacheStats = {'cacheHit': 0, 'cacheMiss': 0}
imageFetchStats = {'fetchCount': 0, 'fetchFailures': 0, 'timeFetching': 0}
def __init__(self):
theVariable = 0
#Get the list from GitHub
def fetchGitHubList(self, jset, uniqueList):
theListText = ""
startTime = time.time()
self.uniqueListFetchStats['fetchCount'] = self.uniqueListFetchStats['fetchCount'] + 1
url = f'https://raw.githubusercontent.com/tyraziel/MTG-JumpStart/main/etc/{urllib.parse.quote(jset)}/{urllib.parse.quote(uniqueList)}.txt'
req = requests.get(url)
if(req.status_code == requests.codes.ok):
theListText = f'{req.text}'
else:
self.uniqueListFetchStats['fetchFailures'] = self.uniqueListFetchStats['fetchFailures'] + 1
endTime = time.time()
self.uniqueListFetchStats['timeFetching'] = self.uniqueListFetchStats['timeFetching'] + (endTime - startTime)
return theListText
#Get the list from GitHub or the cache
def fetchWithCacheGitHubList(self, jset, uniqueList):
theListText = ""
cacheKey = f"{jset}{uniqueList}"
if(cacheKey not in self.uniqueListCache):
self.uniqueListCacheStats['cacheMiss'] = self.uniqueListCacheStats['cacheMiss'] + 1
theListText = self.fetchGitHubList(jset, uniqueList)
self.uniqueListCache[cacheKey] = theListText
else:
self.uniqueListCacheStats['cacheHit'] = self.uniqueListCacheStats['cacheHit'] + 1
theListText = self.uniqueListCache[cacheKey]
return theListText
#Get the JSON from ScryFall (be nice with hitting this)
def fetchScryFallCardJSON(self, jset, exactCardName):
scryFallJSON = json.loads("{}")
startTime = time.time()
self.scryFallJSONCardFetchStats['fetchCount'] = self.scryFallJSONCardFetchStats['fetchCount'] + 1
#Fixing scryfall strangness
if(jset == "BRO" and exactCardName == "UNEARTH"):
exactCardName = "UNEARTH-(THEME)"
elif(jset == "J22" and exactCardName == "BLINK"):
exactCardName = "BLINK-(FRONT-CARD)"
elif(jset == "J25" and exactCardName == "N'ER-DO-WELLS"):
exactCardName = "NEER-DO-WELLS"
# elif(jset == "J25" and exactCardName == "N'ER-DO-WELLS"):
# exactCardName = "NEER-DO-WELLS"
#too many -> TOO-MANY
#ne'er-do-wells -> neer-do-wells
#fun guys -> FUN-GUYS
url = f"https://api.scryfall.com/cards/named?exact={urllib.parse.quote(exactCardName)}&pretty=true&set={urllib.parse.quote(jsd.sets[jset]['ScryfallFrontSetCode'])}"
req = requests.get(url)
if(req.status_code == requests.codes.ok):
scryFallJSON = json.loads(req.text)
else:
self.scryFallJSONCardFetchStats['fetchFailures'] = self.scryFallJSONCardFetchStats['fetchFailures'] + 1
scryFallJSON = json.loads("{}")
print(f"FAILURE - '{jset}' '{exactCardName}'\n")
endTime = time.time()
self.scryFallJSONCardFetchStats['timeFetching'] = self.scryFallJSONCardFetchStats['timeFetching'] + (endTime - startTime)
return scryFallJSON
#Get the card image url from scryFall or the cache
def fetchThemeImageURLWithCacheScryfallCardJSONURL(self, jset, theme):
theListThemeCardImageUrl = ""
cacheKey = f"{jset}{theme}"
if(cacheKey not in self.scryFallJSONCardCache):
self.scryFallJSONCardCacheStats['cacheMiss'] = self.scryFallJSONCardCacheStats['cacheMiss'] + 1
scryFallJSON = self.fetchScryFallCardJSON(jset, theme)
self.scryFallJSONCardCache[cacheKey] = scryFallJSON
theListThemeCardImageUrl = self.scryFallJSONCardCache[cacheKey]["image_uris"]["small"]
else:
self.scryFallJSONCardCacheStats['cacheHit'] = self.scryFallJSONCardCacheStats['cacheHit'] + 1
theListThemeCardImageUrl = self.scryFallJSONCardCache[cacheKey]["image_uris"]["small"]
return theListThemeCardImageUrl
def fetchScryFallCardImage(self, jset, exactCardName):
cardImage = Image.new('RGBA', (1, 1))
theListThemeCardImageUrl = self.fetchThemeImageURLWithCacheScryfallCardJSONURL(jset, exactCardName)
startTime = time.time()
self.imageFetchStats['fetchCount'] = self.imageFetchStats['fetchCount'] + 1
imageDataResults = requests.get(theListThemeCardImageUrl, stream=True)
if(imageDataResults.status_code == requests.codes.ok):
cardImage = Image.open(imageDataResults.raw)
else:
self.imageFetchStats['fetchFailures'] = self.imageFetchStats['fetchFailures'] + 1
cardImage = Image.new('RGBA', (1, 1))
endTime = time.time()
self.imageFetchStats['timeFetching'] = self.imageFetchStats['timeFetching'] + (endTime - startTime)
return cardImage
#Get the card image url from scryFall or the cache
def fetchThemeImageWithCacheScryfallCardImage(self, jset, theme):
cardImage = Image.new('RGBA', (1, 1))
cacheKey = f"{jset}{theme}"
if(cacheKey not in self.imageCache):
self.imageCacheStats['cacheMiss'] = self.imageCacheStats['cacheMiss'] + 1
cardImage = self.fetchScryFallCardImage(jset, theme)
self.imageCache[cacheKey] = cardImage
else:
self.imageCacheStats['cacheHit'] = self.imageCacheStats['cacheHit'] + 1
cardImage = self.imageCache[cacheKey]
return cardImage
def purgeImageCache(self):
self.imageCache = {}
def purgeScryfallJSONCardCache(self):
self.scryFallJSONCardCache = {}
def purgeListCache(self):
self.uniqueListCache = {}
def __str__(self):
return f"""Bot Cache Statistics: (hits / misses / items)
uniqueListCache {self.uniqueListCacheStats['cacheHit']} / {self.uniqueListCacheStats['cacheMiss']} / {len(self.uniqueListCache)}
scryFallJSONCardCache {self.scryFallJSONCardCacheStats['cacheHit']} / {self.scryFallJSONCardCacheStats['cacheMiss']} / {len(self.scryFallJSONCardCache)}
imageCache {self.imageCacheStats['cacheHit']} / {self.imageCacheStats['cacheMiss']} / {len(self.imageCache)}
Bot Fetch Statistics: (fetches (failures)/ total time)
uniqueListFetch {self.uniqueListFetchStats['fetchCount']} ({self.uniqueListFetchStats['fetchFailures']}) / {self.uniqueListFetchStats['timeFetching']}
scryFallJSONCardFetch {self.scryFallJSONCardFetchStats['fetchCount']} ({self.scryFallJSONCardFetchStats['fetchFailures']}) / {self.scryFallJSONCardFetchStats['timeFetching']}
imageFetch {self.imageFetchStats['fetchCount']} ({self.imageFetchStats['fetchFailures']}) / {self.imageFetchStats['timeFetching']}
"""