-
Notifications
You must be signed in to change notification settings - Fork 1
/
deckFactory.py
437 lines (389 loc) · 17.4 KB
/
deckFactory.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 08:04:38 2019
deckFactory.py - Main Driver of the deck factory including the GUI and calling into the other systems
@author: Benjamin
"""
import sheetMaker as sm
import tkinter as tk
from tkinter import filedialog
import tkinter.scrolledtext as tkst
import numpy as np
import DeckEditor as dedit
import glob
import os
import sys
import json
import shutil
import logging
from imgurpython import ImgurClient
config = {
"saved":False,
"workingDir":"",
"deckListPath":"",
"cardDumpPath":"",
"printSheetsPath":"",
"referenceImagesPath":"",
"TTSSavedObjectsPath":"",
"systemSlash":'/',
"logLevel":"ERROR",
"imgurAccessToken":"",
"imgurRefreshToken":""
}
client_id = '46a5b17af3f323c'
client_secret = '293b64d937f56991f261334f4c7e928fb258c304'
def loadConfig():
'''
checks for configuration file adjacent to the executable and runs from there
'''
global config
currentPath = os.path.abspath(os.curdir)
config["workingDir"] = currentPath
if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == 'darwin':
currentStuffs = glob.glob(currentPath+"/*")
currentPath += '/'
config["systemSlash"] = '/'
elif sys.platform == 'win32':
currentStuffs = glob.glob(currentPath+"\*")
currentPath += '\\'
config["systemSlash"] = '\\'
if currentPath+"config.json" in currentStuffs:
config = json.load(open(currentPath+"config.json","r"))
else:
if currentPath+"DeckLists" in currentStuffs and config["deckListPath"] == '':
config["deckListPath"] = currentPath+"DeckLists"
elif config["deckListPath"] == '':
#make a decklists folder there
os.mkdir("DeckLists")
config["deckListPath"] = currentPath+"DeckLists"
if currentPath+"PrintSheets" in currentStuffs and config["printSheetsPath"] == '':
config["printSheetsPath"] = currentPath+"PrintSheets"
elif config["printSheetsPath"] == '':
#make a PrintSheets folder there
os.mkdir("PrintSheets")
config["printSheetsPath"] = currentPath+"PrintSheets"
if currentPath+"CardDump" in currentStuffs and config["cardDumpPath"] == '':
config["cardDumpPath"] = currentPath+"CardDump"
elif config["cardDumpPath"] == '':
#make a CardDump folder there
os.mkdir("CardDump")
config["cardDumpPath"] = currentPath+"CardDump"
if currentPath+"referenceImages" in currentStuffs and config["referenceImagesPath"] == '':
config["referenceImagesPath"] = currentPath+"referenceImages"
elif config["referenceImagesPath"] == '':
#make a referenceImages folder there
os.mkdir("referenceImages")
config["referenceImagesPath"] = currentPath+"referenceImages"
#also need to populate the reference images folder with appropriate things
if currentPath+"deck_template.png" in currentStuffs:
shutil.copy2(currentPath+"deck_template.png",
config["referenceImagesPath"]+config["systemSlash"]+"deck_template.png")
config['TTSSavedObjectsPath'] = config["deckListPath"]
# default to ERROR if its not set yet
config["logLevel"] = config.get("logLevel", "ERROR")
if(config["imgurAccessToken"] == ""):
imgurAuthProcess()
return config
def imgurAuthProcess():
'''
in the case of an expired/or unretreived set of tokens, prompt the user to set this part up.
'''
global config
client = ImgurClient(client_id,client_secret)
authorization_url = client.get_auth_url('pin')
authWindow = tk.Tk();
authWindow.title("Imgur Tokens setup")
authWindow.minsize(width=700,height=150)
authWindow.geometry("400x300")
authWindow.lift()
textbits = tk.Label(master=authWindow,text="You appear to have not registered your imgur account with the Deckfactory.\nPlease go to the below url\nand type the pin given in the box below, then hit OK.")
textbits.place(x=20,y=80)
pinEnter = tk.ttk.Entry(master = authWindow,width=50)
pinEnter.place(x=20,y=220)
urlOut = tk.Text(master=authWindow, height = 1, width= 85,borderwidth=0)
urlOut.insert(1.0,authorization_url)
urlOut.place(x=20,y=200)
urlOut.configure(state="disabled")
def confirmPinEntry(event):
confirmPin()
def confirmPin():
nonlocal pinEnter
global config
pin = pinEnter.get()
credentials = client.authorize(pin,'pin')
config["imgurAccessToken"] = credentials["access_token"]
config["imgurRefreshToken"] = credentials["refresh_token"]
killAuthWindow()
def killAuthWindow():
authWindow.destroy()
authWindow.quit()
pinEnter.bind('<Return>',confirmPinEntry)
cancelButton = tk.Button(authWindow,text='Cancel', command = killAuthWindow,
width=13,height=2)
cancelButton.place(x=250,y=250)
confirmButton = tk.Button(authWindow,text='Confirm', command = confirmPin,
bg='green',fg='white',
width=13,height=2)
confirmButton.place(x=20,y=250)
authWindow.mainloop()
def saveConfig():
'''
should save the current config as a json
'''
global config
config["saved"] = True
if(config["workingDir"]+config["systemSlash"]+"config.json" in glob.glob(config["workingDir"]+config["systemSlash"]+"*")):
os.remove(config["workingDir"]+config["systemSlash"]+"config.json")
with open('config.json','w') as file:
json.dump(config,file)
def editConfigWindow():
'''
this is the edit config window
'''
global config
configEditor = tk.Tk()
configEditor.title("Edit Configuration")
configEditor.minsize(375,375)
def changeDeckListFolder():
'''
reassigns the decklist folder
'''
global config
deckListPathSelection = filedialog.askdirectory(initialdir = config["workingDir"],
title = "Select DeckLists Folder")
config["deckListPath"] = deckListPathSelection
saveConfig()
def changePrintSheetFolder():
'''
reassigns the printSheets folder
'''
global config
pathSelection = filedialog.askdirectory(initialdir = config["workingDir"],
title = "Select PrintSheets Folder")
config["printSheetsPath"] = pathSelection
saveConfig()
def changeReferenceImagesFolder():
'''
reassigns the referenceImages folder
'''
global config
pathSelection = filedialog.askdirectory(initialdir = config["workingDir"],
title = "Select referenceImages Folder")
config["referenceImagesPath"] = pathSelection
saveConfig()
def changeCardDumpFolder():
'''
reassigns the printSheets folder
'''
global config
pathSelection = filedialog.askdirectory(initialdir = config["workingDir"],
title = "Select CardDump Folder")
config["cardDumpPath"] = pathSelection
saveConfig()
def changeTTSSaveObjectFolder():
'''
reassigns the TTSSavedObjects folder
'''
global config
iDir = "C:\\"
if sys.platform == "linux" or sys.platform == "linux2":
iDir = "/home/"
pathSelection = filedialog.askdirectory(initialdir = iDir,
title = "Select TableTop Simulator Saved Objects Folder")
config["TTSSavedObjectsPath"] = pathSelection.replace('/',config["systemSlash"])
saveConfig()
def close():
nonlocal configEditor
configEditor.destroy()
configEditor.quit()
dListButton = tk.Button(configEditor,text="Select Decklists Folder",
command = changeDeckListFolder,
bg='blue',fg='white',
width=20,height=4)
dListButton.place(x=20,y=20)
printSheetsButton = tk.Button(configEditor,text="Select PrintSheets Folder",
command = changePrintSheetFolder,
bg='blue',fg='white',
width=20,height=4)
printSheetsButton.place(x=200,y=20)
referenceImagesButton = tk.Button(configEditor,text="Select ReferenceImage\nFolder",
command = changeReferenceImagesFolder,
bg='blue',fg='white',
width=20,height=4)
referenceImagesButton.place(x=20,y=100)
cardDumpButton = tk.Button(configEditor,text="Select CardDump Folder",
command = changeCardDumpFolder,
bg='blue',fg='white',
width=20,height=4)
cardDumpButton.place(x=200,y=100)
TTSSavedObjectsButton = tk.Button(configEditor,text="Select TTSSavedObjects\nFolder",
command = changeTTSSaveObjectFolder,
bg='blue',fg='white',
width=20,height=4)
TTSSavedObjectsButton.place(x=20,y=180)
closeButton = tk.Button(configEditor,text="Close", command = close,
bg='red',fg='white',
width=20,height=4)
closeButton.place(x=110,y=270)
configEditor.lift()
configEditor.mainloop()
def main():
'''
this is the main driver of the script set
'''
global config
loadConfig()
saveConfig()
master = tk.Tk()
master.minsize(800,700)
master.title("Deck Factory 2.8")
master.geometry("800x700")
master.lift()
deckListPaths = []
def initLogging(logLevelParm):
loglevel = logging.ERROR
if (logLevelParm == "DEBUG") :
loglevel = logging.DEBUG
elif (logLevelParm == "INFO") :
loglevel = logging.INFO
elif (logLevelParm == "WARNING") :
loglevel = logging.WARNING
elif (logLevelParm == "CRITICAL") :
loglevel = logging.CRITICAL
logging.basicConfig(level=loglevel,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='debug.log',
filemode='w')
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create logger called deckfactory
logger = logging.getLogger('deckFactory')
logger.error("Log level set to :" + logLevelParm)
logger.addHandler(ch)
def killWindow():
master.destroy()
def getDeckLists():
nonlocal deckListPaths
global config
clearDList()
deckListPaths = filedialog.askopenfilenames(initialdir = config["deckListPath"]+config["systemSlash"],
title = "Select Decks for Formatting",
filetypes = (("All Files","*.*"),
("Manual Decklists","*.txt"),
("Xmage Decks","*.dck")))
for i in deckListPaths:
temp = sm.stripName(i)
logger.debug("adding: " + temp + " to decklist")
dList.insert(tk.END,temp+'\n')
def clearSelection():
logger.debug("clear decklist paths")
nonlocal deckListPaths
deckListPaths = []
clearDList()
def buildSheets():
logger.debug("entering buildSheets")
nonlocal deckListPaths
global config
count = 0
for i in deckListPaths:
logger.debug("calling buildSheet: " + i)
failedCards,ambiguities,dictVersionOfDeck,TTSversionofDeck = sm.buildSheet(i,buildLogPrint)
logger.debug("returned from buildSheet")
strippedName = str(sm.stripName(i))
justName = str(sm.justName(i))
if(np.size(failedCards) >0 or np.size(ambiguities) > 0):
#cards failed in this run some how
buildLogPrint("The file "+strippedName+" ran into the following issues:")
for j in failedCards:
if j.setCode == '' :
buildLogPrint(j.cardName+" was not found.")
else:
if j.cn == '' :
buildLogPrint(j.cardName+" from set "+j.setCode+" was not found.")
else:
buildLogPrint("Card #"+j.cn+" from set "+j.setCode+" was not found.")
for j in ambiguities:
if j.setCode == '':
buildLogPrint(j.cardName+" was an ambiguous search.")
else:
if j.cn=='':
buildLogPrint(j.cardName+" from set "+j.setCode+" was an ambiguous search.")
else:
buildLogPrint("Card #"+j.cn+" from set "+j.setCode+" was an ambiguous search.")
if np.size(ambiguities) > 0:
buildLogPrint("")
buildLogPrint("Ambiguities can be helped by specifying a set code or using the collector's number and set code rather than the name.")
buildLogPrint("No print sheets were generated for "+strippedName)
else:
count += 1
buildLogPrint("Print sheet(s) successfully generated for "+strippedName)
#here is an example of dropping the deck manifest component into place
if(config["deckListPath"]+config["systemSlash"]+justName+".json" in glob.glob(config["deckListPath"]+config["systemSlash"]+"*")):
os.remove(config["deckListPath"]+config["systemSlash"]+justName+".json")
with open(config["deckListPath"]+config["systemSlash"]+justName+".json","w") as file:
dictVersionOfDeck["deck_name"] = justName
json.dump(dictVersionOfDeck,file)
buildLogPrint("JSONIFIED version of "+justName+" saved")
with open(config["TTSSavedObjectsPath"]+config["systemSlash"]+justName+".json","w") as file:
json.dump(TTSversionofDeck,file)
buildLogPrint("TTS version of deck saved")
buildLogPrint(config["TTSSavedObjectsPath"]+config["systemSlash"]+justName+".json")
buildLogPrint("")
if(count > 0):
buildLogPrint("Print Sheets have been generated!\nThey can be found in " + config["printSheetsPath"]+"\n")
def clearDList():
dList.delete('1.0',tk.END)
dList.insert(tk.END,"Files set to build:\n")
def clearBuildLog():
buildLog.delete('1.0',tk.END)
def buildLogPrint(string):
buildLog.insert(tk.END,str(string)+"\n")
master.update_idletasks()
def editDeckWindow():
dedit.editDeck()
def editConfig():
'''
this is a button event that will spawn a seperate window for setting config paths
'''
editConfigWindow()
#default the logLevel to ERROR if it doesn't exist in the config.json file yet.
initLogging(config.get("logLevel", "ERROR"))
logger = logging.getLogger("deckFactory")
dList = tk.Text(master,height = 12, width = 40)
dList.place(x=325,y=20)
clearDList()
buildLog = tkst.ScrolledText(master,height=25,width =95)
buildLog.place(x=20,y=220)
clearBuildLog()
#button structure
selectButton = tk.Button(master,text="Select Decklists", command = getDeckLists,
bg='blue',fg='white',
width=17,height=4)
selectButton.place(x = 20, y = 20)
buildButton = tk.Button(master, text = "Build Print Sheets", command = buildSheets,
bg='green',fg='white',
width=17,height=4)
buildButton.place(x = 20, y = 100)
editButton = tk.Button(master, text = "Edit/Create Deck", command = editDeckWindow,
bg='blue',fg='white',
width=17,height=4)
editButton.place(x = 170, y = 20)
changeConfigButton = tk.Button(master, text = "Change Folder Defaults", command = editConfig,
bg='blue',fg='white',
width=17,height=4)
changeConfigButton.place(x = 170, y = 100)
exitButton = tk.Button(master,text='Exit', command = killWindow,
bg='red',fg='white',
width=4,height=2)
exitButton.place(x=740,y=645)
clearSelectionButton = tk.Button(master,text="Clear Selection", command=clearSelection,
bg='blue',fg='white')
clearSelectionButton.place(x = 660, y = 100)
clearBuildLogButton = tk.Button(master,text = "Clear Log", command = clearBuildLog,
bg='blue',fg='white')
clearBuildLogButton.place(x=20,y=645)
#button.pack()
master.mainloop()
if __name__ == '__main__':
main()