-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathabcdbook.py
More file actions
3290 lines (2727 loc) · 139 KB
/
abcdbook.py
File metadata and controls
3290 lines (2727 loc) · 139 KB
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys, io, requests, threading, webbrowser, urllib, os, platform, openpyxl, string, textwrap, re, time, textstat
import traceback
import tkinter as tk
from tkinter import ttk, messagebox
from pptx import Presentation
import pptx.util
from pptx.util import Inches, Pt
from pptx.enum.text import PP_ALIGN
from pptx.dml.color import RGBColor
from PIL import Image
import pandas as pd
from pandas import Series, DataFrame
from concurrent.futures import ThreadPoolExecutor, as_completed
from textblob import TextBlob
from bs4 import BeautifulSoup
import wikipediaapi
import openai
import random
from xml.dom.expatbuilder import FragmentBuilderNS
from localspelling import convert_spelling
from localspelling.spelling_converter import get_dictionary
import requests
import pyttsx3
import webbrowser
import tempfile
import datetime
from gtts import gTTS
from tkinter import filedialog
from pptx.util import Inches, Pt
from pptx.enum.text import PP_ALIGN
from pptx.dml.color import RGBColor
from pptx import Presentation
from pptx.enum.shapes import MSO_CONNECTOR
from pptx.shapes.connector import Connector
from pptx.enum.shapes import MSO_SHAPE
# pip install googletrans
# pip install googletrans==4.0.0-rc1
import googletrans
openai.api_key = 'private'
ROOT_WIDTH = 1000 # app window width
ROOT_HEIGHT = 600 # app window height
root = tk.Tk()
root.title("Project ABCD Admin Panel")
sw_placement = int(root.winfo_screenwidth()/2 - ROOT_WIDTH/2) # to place at half width of screen
sh_placement = int(root.winfo_screenheight()/2 - ROOT_HEIGHT/2) # to place at half height of screen
root.geometry(f"{ROOT_WIDTH}x{ROOT_HEIGHT}+{sw_placement}+{sh_placement}")
root.minsize(ROOT_WIDTH, ROOT_HEIGHT)
# Set sys.stdout to use utf-8 encoding
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
MAIN_FONT = ("helvetica", 12)
LABEL_FONT = ("helvetica bold", 14)
LANGUAGES = [
"Telugu",
"Hindi",
"Spanish"
]
# creates preferences dictionary from preferences.txt
# creates default preferences.txt file if one does not exist
try:
with open("preferences.txt", "r", encoding="utf8") as file:
lines = file.readlines()
preferences = {}
for line in lines:
key, value = line.split('=')
preferences[key.strip()] = value.strip().replace('“', '').replace('”', '').replace('"', '').replace("'", '')
except FileNotFoundError:
preferences = {
"TEXT_SIZE" : "14",
"TEXT_FONT" : "Times New Roman",
"TITLE_SIZE" : "32",
"TITLE_FONT" : "Arial",
"SUBTITLE_SIZE" : "24",
"SUBTITLE_FONT" : "Arial",
"PIC_WIDTH" : "720",
"PIC_HEIGHT" : "1040"
}
tk.messagebox.showwarning(title='Warning', message='No preferences.txt file exists in directory. Default preferences.txt will be created and used.')
print('No preferences.txt file exists in directory. Default preferences.txt will be created and used.')
with open('preferences.txt', 'w') as f:
f.write('TEXT_SIZE = 14\nTEXT_FONT = Times New Roman\nTITLE_SIZE = 32\nTITLE_FONT = Arial\nSUBTITLE_SIZE = 24\nSUBTITLE_FONT = Arial\nPIC_WIDTH = 720\nPIC_HEIGHT = 1040')
'''
Gathers data from API
'''
def downloadAPIData(url, id_number):
try:
response = requests.get(url, headers={"User-Agent": "XY"})
# append dress info to dress data if response status_code == 200
if response.ok:
return response.json()['data']
else:
print(f'Request for dress ID: {id_number} failed.')
except requests.exceptions.RequestException as e:
print(f'-- DEBUG -- in downloadAPIData: {e}')
except Exception as e:
# tk.messagebox.showerror(title="Error", message=f'Could not make connection!\n\nError: {e}')
print(f'Error: {e}')
'''
Sets up and starts threads for gathering API data
'''
def apiRunner():
# dress ids in entry field
dress_ids = getSlideNumbers()
# create list of all urls to send requests to
url_list = []
for id_number in dress_ids:
url_list.append(f'https://abcd2.projectabcd.com/api/getinfo.php?id={id_number}')
dress_data = [] # dress data from API
threads= [] # working threads
# create progress bar
progress_window, pb, percent_label = progress_bar('Retrieving API Data')
# spins up 10 threads at a time and stores retrieved data into dress_data upon completion
with ThreadPoolExecutor(max_workers=10) as exec:
for index, url in enumerate(url_list):
threads.append(exec.submit(downloadAPIData, url, dress_ids[index]))
complete = 0 # number of threads that have finished
for task in as_completed(threads):
complete += 1
pb['value'] = (complete/len(dress_ids))*100 # calculate percentage of data retrieved
percent_label.config(text=f'Retrieving API Data...{int(pb["value"])}%') # update completion percent label
if task.result() is not None:
dress_data.append(task.result()) # append retrieved data to dress_data
progress_window.destroy()
return dress_data
'''
Gets dress IDs from entry field
'''
def getSlideNumbers():
# get update for dress number input
update_dress_list = []
# get dress numbers from text field
get_text_field = text_field.get("1.0", "end-1c").split(',')
# add to list
for number in get_text_field:
if (number.strip().isnumeric()):
update_dress_list.append(int(number.strip()))
# remove duplicates
dress_ids = []
[dress_ids.append(x) for x in update_dress_list if x not in dress_ids]
return dress_ids
'''
Downloads dress images
'''
def downloadImages(folder_name, url, img_name):
try:
# downloads dress image
img_url = url
img_path = f'./{folder_name}/{img_name}'
opener = urllib.request.build_opener()
opener.addheaders=[('User-Agent', 'XY')]
urllib.request.install_opener(opener)
urllib.request.urlretrieve(img_url, img_path)
except Exception as e:
print(f'Error downloading images: {e}')
'''
Sets up and starts threads for downloading dress images
'''
def imageRunner(dress_data):
# list of all urls to send requests to
url_list = []
# list of all image names
img_name_list = []
for data in dress_data:
url_list.append(f'http://projectabcd.com/images/dress_images/{data["image_url"]}')
img_name_list.append(f'{data["image_url"]}')
# create progress bar
progress_window, pb, percent_label = progress_bar('Downloading Images')
threads= [] # working threads
# spins up 10 threads at a time and calls downloadImages with url and image name
with ThreadPoolExecutor(max_workers=10) as exec:
for index, url in enumerate(url_list):
threads.append(exec.submit(downloadImages, "images", url, img_name_list[index]))
complete = 0 # number of threads that have finished
for task in as_completed(threads):
complete += 1
pb['value'] = (complete/len(url_list))*100 # calculate percentage of images downloaded
percent_label.config(text=f'Downloading Images...{int(pb["value"])}%') # update completion percent label
progress_window.destroy() # close progress bar window
'''
Generates progress bar
'''
def progress_bar(title):
# progress bar window for API data retrieval
progress_window = tk.Toplevel(root)
progress_window.title(title)
sw = int(progress_window.winfo_screenwidth()/2 - 450/2)
sh = int(progress_window.winfo_screenheight()/2 - 70/2)
progress_window.geometry(f'450x70+{sw}+{sh}')
progress_window.resizable(False, False)
progress_window.attributes('-disable', True)
progress_window.focus()
# progress bar custom style
pb_style = ttk.Style()
pb_style.theme_use('clam')
pb_style.configure('green.Horizontal.TProgressbar', foreground='#1ec000', background='#1ec000')
# frame to hold progress bar
pb_frame = tk.Frame(progress_window)
pb_frame.pack()
# progress bar
pb = ttk.Progressbar(pb_frame, length=400, style='green.Horizontal.TProgressbar', mode='determinate', maximum=100, value=0)
pb.pack(pady=10)
# label for percent complete
percent_label = tk.Label(pb_frame, text=f'{title}...0%')
percent_label.pack()
return progress_window, pb, percent_label
'''
Translate text to selected language
'''
def translateText(text):
# Build the translator
if translate.get() == 1:
if language.get() == "Telugu":
dest_language = 'te'
elif language.get() == "Hindi":
dest_language = 'hi'
elif language.get() == "Spanish":
dest_language = 'es'
else:
return text # return text if english
try:
# Create the translator
translator = googletrans.Translator()
translated_text = translator.translate(text, dest = dest_language)
return translated_text.text
except Exception as e:
print("Error:", e)
return ""
'''
Sorts dress data based on user selection
'''
def sortDresses(dress_data):
if sort_order.get() == 1:
return sorted(dress_data, key=lambda x : str(x['name']).lower())
elif sort_order.get() == 2:
return sorted(dress_data, key=lambda x : x['id'])
elif sort_order.get() == 3:
return dress_data
'''
Opens file depending on OS
'''
def openFile(file_name):
current_os = platform.system()
try:
if current_os == "Windows":
print(f"-- DEBUG -- Windows {file_name}")
os.system(f"start {file_name}")
elif current_os == "Darwin":
print(f"-- DEBUG -- Darwin {file_name}")
os.system(f"open {file_name}")
elif current_os == "Linux":
print(f"-- DEBUG -- Linux {file_name}")
os.system(f"xdg-open {file_name}")
else:
print("Error: Cannot open file " + current_os + " not supported.")
except Exception as e:
print("Error:", e)
'''
Create the Dress Name Title textbox
'''
def add_title_box(slide, dress_name, left, top, width, height):
title = slide.shapes.title
title.left = Inches(left)
title.top = Inches(top)
title.width = Inches(width)
title.height = Inches(height)
title.text = f'{dress_name.upper()}'
title.text_frame.paragraphs[0].font.color.rgb = RGBColor(0x09, 0x09, 0x82)
title.text_frame.paragraphs[0].text = title.text_frame.paragraphs[0].text.upper()
title.text_frame.paragraphs[0].font.name = title_font_var.get()
title.text_frame.paragraphs[0].font.size = Pt(int(title_size_var.get()))
title.text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
'''
Create the subtitle highlight
'''
def add_subtitle_highlight(slide, left, top, width, height):
# create the shape
rectangle1 = slide.shapes.add_shape(1, Inches(left), Inches(top), Inches(width), Inches(height))
rectangle1.rotation = 357
# color fill
fill1 = rectangle1.fill
fill1.solid()
fill1.fore_color.rgb = RGBColor(202, 246, 189)
# no outline
line1 = rectangle1.line
line1.color.rgb = RGBColor(255, 255, 255)
# no shaddow
shadow1 = rectangle1.shadow
shadow1.inherit = False
'''
Create the Description subtitle
'''
def add_description_subtitle(slide, left, top, width, height):
description_subtitle_box = slide.shapes.add_textbox(Inches(left), Inches(top), Inches(width), Inches(height))
description_subtitle_frame = description_subtitle_box.text_frame
description_subtitle = description_subtitle_frame.add_paragraph()
description_subtitle.font.color.rgb = RGBColor(0x6E, 0xD8, 0xFF)
description_subtitle.font.bold = True
description_subtitle.font.name = subtitle_font_var.get()
description_subtitle.text = translateText("DESCRIPTION:")
# make text smaller for layout 4
if layout.get() == 4:
description_subtitle.font.size = Pt(16)
else:
description_subtitle.font.size = Pt(int(subtitle_size_var.get()))
'''
Add the Description text
'''
def add_description_text(slide, dress_description, left, top, width, height):
# description - text (left, top, width, height)
description_text_box = slide.shapes.add_textbox(Inches(left), Inches(top), Inches(width), Inches(height))
description_text_frame = description_text_box.text_frame
description_text_frame.word_wrap = True
description_text = description_text_frame.add_paragraph()
description_text.font.name = text_font_var.get()
description_text.text = f'{translateText(dress_description)}'
# make text smaller for layout 4
if layout.get() == 4:
description_text.font.size = Pt(11)
else:
description_text.font.size = Pt(int(text_size_var.get()))
'''
Create Did You Know subtitle
'''
def add_did_you_know_subtitle(slide, left, top, width, height):
did_you_know_subtitle_box = slide.shapes.add_textbox(Inches(left), Inches(top), Inches(width), Inches(height))
did_you_know_subtitle_frame = did_you_know_subtitle_box.text_frame
did_you_know_subtitle = did_you_know_subtitle_frame.add_paragraph()
did_you_know_subtitle.font.color.rgb = RGBColor(0x6E, 0xD8, 0xFF)
did_you_know_subtitle.font.bold = True
did_you_know_subtitle.font.name = subtitle_font_var.get()
did_you_know_subtitle.text = translateText("DID YOU KNOW?")
# make text smaller for layout 4
if layout.get() == 4:
did_you_know_subtitle.font.size = Pt(16)
else:
did_you_know_subtitle.font.size = Pt(int(subtitle_size_var.get()))
'''
Create Did You Know text
'''
def add_did_you_know_text(slide, dress_did_you_know, left, top, width, height):
did_you_know_text_box = slide.shapes.add_textbox(Inches(left), Inches(top), Inches(width), Inches(height))
did_you_know_text_frame = did_you_know_text_box.text_frame
did_you_know_text_frame.word_wrap = True
did_you_know_text = did_you_know_text_frame.add_paragraph()
did_you_know_text.font.name = text_font_var.get()
did_you_know_text.text = f'{translateText(dress_did_you_know)}'
# make text smaller for layout 4
if layout.get() == 4:
did_you_know_text.font.size = Pt(11)
else:
did_you_know_text.font.size = Pt(int(text_size_var.get()))
'''
Add the dress image
'''
def add_image(slide, dress_info, left, top):
print(dress_info, flush=True)
image_width_px = int(pic_width_var.get())
image_height_px = int(pic_height_var.get())
image_width_inch = image_width_px / 96
image_height_inch = image_height_px / 96
# change image size for layout 4
if layout.get() == 4:
image_width_inch = 3.71
image_height_inch = 4.94
try:
picture = slide.shapes.add_picture(f'./images/Slide{dress_info["id"]}.png', 0, Inches(0.83), Inches(image_width_inch), Inches(image_height_inch))
except FileNotFoundError:
# tk.messagebox.showerror(title="Error", message="When the Download Images check box is not checked make sure you have an images \
# directory in the root of this project that includes the correct images. (example: 1 == Slide1.PNG)")
print(f'Image Slide{dress_info["id"]}.png Not Found!')
'''
Create the Dress Id & Page Number text
'''
def add_numbering(slide, dress_info, index, left, top, width, height, left2, top2, width2, height2):
# show both page num & dress id
if numbering.get() == 1:
# dress id (left, top, width, height)
dress_id_box = slide.shapes.add_textbox(Inches(left), Inches(top), Inches(width), Inches(height))
dress_id_box_frame = dress_id_box.text_frame
dress_id = dress_id_box_frame.add_paragraph()
dress_id.font.name = text_font_var.get()
dress_id.text = translateText(f'Dress ID: {dress_info["id"]}')
# aligns text left & make text smaller
if layout.get() == 4:
dress_id.alignment = PP_ALIGN.LEFT
dress_id.font.size = Pt(11)
else:
dress_id.alignment = PP_ALIGN.RIGHT
dress_id.font.size = Pt(int(text_size_var.get()))
# page number (left, top, width, height)
page_number_box = slide.shapes.add_textbox(Inches(left2), Inches(top2), Inches(width2), Inches(height2))
page_number_box_frame = page_number_box.text_frame
page_number = page_number_box_frame.add_paragraph()
page_number.font.name = text_font_var.get()
page_number.text = translateText(f'Page No. {index+1}')
# aligns text left & make text smaller
if layout.get() == 4:
page_number.alignment = PP_ALIGN.LEFT
page_number.font.size = Pt(11)
else:
page_number.alignment = PP_ALIGN.RIGHT
page_number.font.size = Pt(int(text_size_var.get()))
# show page num or dress id
elif numbering.get() == 2 or numbering.get() == 3:
number_box = slide.shapes.add_textbox(Inches(left2), Inches(top2), Inches(width2), Inches(height2))
number_box_frame = number_box.text_frame
number_box = number_box_frame.add_paragraph()
number_box.font.name = text_font_var.get()
# aligns text left & make text smaller
if layout.get() == 4:
number_box.alignment = PP_ALIGN.LEFT
number_box.font.size = Pt(11)
else:
number_box.alignment = PP_ALIGN.RIGHT
number_box.font.size = Pt(int(text_size_var.get()))
# show page num
if numbering.get() == 2:
number_box.text = translateText(f'Page No. {index+1}')
# show dress id
elif numbering.get() == 3:
number_box.text = translateText(f'Dress ID: {dress_info["id"]}')
'''
Closes the pop alert message
'''
def close_popup(popup):
popup.destroy()
'''
Updates the timer for the alert popup
'''
def update_timer(popup, timer_label, seconds_left):
timer_label.config(text=f"Auto closes in {seconds_left} sec.")
if seconds_left > 0:
# Update the timer every second
root.after(1000, update_timer, popup, timer_label, seconds_left - 1)
else:
close_popup(popup)
'''
Displays the alert message
'''
def show_error_popup(text_message, duration_num):
popup = tk.Toplevel(root)
popup.title("Alert Message")
label = tk.Label(popup, text=text_message)
label.pack(padx=10, pady=10)
timer_label = tk.Label(popup, text="")
timer_label.pack(pady=5)
duration = duration_num
update_timer(popup, timer_label, duration)
'''
Performs update once generate button clicked
'''
def generateBook():
# check if Generate from Local is active
if gen_local.get() == 1:
# get update for dress number input
update_dress_list = []
# get dress numbers from text field
get_text_field = text_field.get("1.0", "end-1c").split(',')
# add to list
for number in get_text_field:
if (number.strip().isnumeric()):
update_dress_list.append(int(number.strip()))
# remove duplicates
dress_ids = []
[dress_ids.append(x) for x in update_dress_list if x not in dress_ids]
# path to local Excel data
file_path = "APIData.xlsx"
# gets and cleans dress data from Excel file
sheet_dress_data = pd.read_excel(file_path)
sheet_dress_data.dropna(subset=['id'], inplace=True) # drops any rows with na ID
sheet_dress_data['description'].fillna('', inplace=True) # removes na/nan from description column
sheet_dress_data['did_you_know'].fillna('', inplace=True) # removes na/nan from did_you_know column
sheet_dress_data['description'] = sheet_dress_data['description'].astype(str).apply(openpyxl.utils.escape.unescape) # convert escaped strings to ASCII
sheet_dress_data['did_you_know'] = sheet_dress_data['did_you_know'].astype(str).apply(openpyxl.utils.escape.unescape) # Convert escaped strings to ASCII
# holds dress data from local Excel sheet
dress_data = []
# cycle through dress_ids and append data from excel sheet to dress_data
for id in dress_ids:
row = sheet_dress_data.loc[id-1]
dress_data.append({'id':row.loc['id'], 'name':row.loc['name'], 'description':row.loc['description'], 'did_you_know':row.loc['did_you_know']})
else:
dress_data = apiRunner() # gather all dress data from api
# sort dress data
sorted_dress_data = sortDresses(dress_data)
# if there is no image in the local folder then download from web
if download_imgs.get() == 0:
if not os.path.exists('./images'):
os.makedirs('./images')
if not os.listdir('./images'):
text_message = "Local folder is empty. Attempting to grab image(s) from web."
duration_num = 4
show_error_popup(text_message, duration_num)
time.sleep(duration_num+1)
imageRunner(sorted_dress_data)
# download images from web if download images check box is selected
if download_imgs.get() == 1:
# creates directory to save images if one does not exist
if not os.path.exists('./images'):
os.makedirs('./images')
imageRunner(sorted_dress_data) # download images for each dress in list
# create powerpoint
prs = Presentation() # create the pptx presentation
ppt_file_name = "abcdbook.pptx"
file_name = "abcdbook.pptx"
count = 0
while os.path.exists(file_name): # check if file name exist,
count += 1
file_name = f"{os.path.splitext(ppt_file_name)[0]}({count}).pptx" # if file name exisit create new filename
# progress bar window for API data retrieval
progress_window = tk.Toplevel(root)
progress_window.title('Creating Book')
sw = int(progress_window.winfo_screenwidth()/2 - 450/2)
sh = int(progress_window.winfo_screenheight()/2 - 70/2)
progress_window.geometry(f'450x70+{sw}+{sh}')
progress_window.resizable(False, False)
progress_window.attributes('-disable', True)
progress_window.focus()
# progress bar custom style
pb_style = ttk.Style()
pb_style.theme_use('clam')
pb_style.configure('green.Horizontal.TProgressbar', foreground='#1ec000', background='#1ec000')
# frame to hold progress bar
pb_frame = tk.Frame(progress_window)
pb_frame.pack()
# progress bar
pb = ttk.Progressbar(pb_frame, length=400, style='green.Horizontal.TProgressbar', mode='determinate', maximum=100, value=0)
pb.pack(pady=10)
# label for percent complete
percent_label = tk.Label(pb_frame, text='Creating Book...0%')
percent_label.pack()
complete = 0
# get dress info for items in list & translate
for index, dress_info in enumerate(sorted_dress_data):
left = None
image_left = None
dress_name = dress_info['name']
dress_description = dress_info['description']
dress_did_you_know = dress_info['did_you_know']
dress_description_len = len(dress_description)
#--------------------------------Portrait--------------------------------
# PORTRAIT MODE
if layout.get() == 1 or layout.get() == 4:
prs.slide_width = pptx.util.Inches(7.5) # define slide width
prs.slide_height = pptx.util.Inches(10.83) # define slide height
slide_layout = prs.slide_layouts[5] # use slide with only title
slide_layout2 = prs.slide_layouts[6] # use empty slide
# LAYOUT 1 == picture on left page - text on right page - two page
if layout.get() == 1:
slide_empty = prs.slides.add_slide(slide_layout2)
slide_title = prs.slides.add_slide(slide_layout)
add_image(slide_empty, dress_info, 0, 0)
add_title_box(slide_title, dress_name, 0, 0.15, 7.5, 0.91)
add_subtitle_highlight(slide_title, 0.37, 1.58, 2.44, 0.3) # description - highlight box
add_description_subtitle(slide_title, 0.28, 1.07, 6.94, 0.51)
add_description_text(slide_title, dress_description, 0.28, 1.65, 6.94, 5.99)
add_subtitle_highlight(slide_title, 0.37, 8.36, 2.78, 0.3) # did you know - highlight box
add_did_you_know_subtitle(slide_title, 0.28, 7.87, 6.94, 0.51)
add_did_you_know_text(slide_title, dress_did_you_know, 0.28, 8.46, 6.94, 1.04)
add_numbering(slide_title, dress_info, index, 4.47, 10.06, 1.28, 0.34, 5.94, 10.06, 1.28, 0.34)
# LAYOUT 4 == picture on left - text on right - single page
elif layout.get() == 4:
slide_title = prs.slides.add_slide(slide_layout)
add_image(slide_title, dress_info, 0, 1.39)
add_title_box(slide_title, dress_name, 0, 0.09, 7.5, 0.91)
add_subtitle_highlight(slide_title, 3.71, 1.21, 1.83, 0.23) # description - highlight box
add_description_subtitle(slide_title, 3.63, 0.88, 3.71, 0.37)
add_description_text(slide_title, dress_description, 3.63, 1.35, 3.71, 7.57)
# adjust the text height based on text length
if dress_description_len < 600:
add_subtitle_highlight(slide_title, 3.72, 5.83, 1.83, 0.23) # did you know - highlight box
add_did_you_know_subtitle(slide_title, 3.63, 5.42, 3.71, 0.37)
add_did_you_know_text(slide_title, dress_did_you_know, 3.63, 5.94, 3.71, 0.91)
elif dress_description_len > 600 and dress_description_len < 1300:
add_subtitle_highlight(slide_title, 3.72, 7.99, 1.83, 0.23) # did you know - highlight box
add_did_you_know_subtitle(slide_title, 3.63, 7.58, 3.71, 0.37)
add_did_you_know_text(slide_title, dress_did_you_know, 3.63, 8.1, 3.71, 0.91)
else:
add_subtitle_highlight(slide_title, 3.72, 9.32, 1.83, 0.23) # did you know - highlight box
add_did_you_know_subtitle(slide_title, 3.63, 8.91, 3.71, 0.37)
add_did_you_know_text(slide_title, dress_did_you_know, 3.63, 9.43, 3.71, 0.91)
add_numbering(slide_title, dress_info, index, 0.49, 6.46, 1.33, 0.27, 1.95, 6.46, 1.33, 0.27)
#--------------------------------Landscape--------------------------------
# LANDSCAPE MODE
elif layout.get() == 2 or layout.get() == 3:
left = None
image_left = None
rectangle_left = None
# slide size (left, top, width, height)
prs.slide_width = pptx.util.Inches(16.18) # define slide width
prs.slide_height = pptx.util.Inches(12.53) # define slide height
slide_layout = prs.slide_layouts[5] # use empty slide
slide = prs.slides.add_slide(slide_layout) # add empty slide to pptx
# LAYOUT 2 == picture on right - text on left
if layout.get() == 2:
rectangle_left = 0.4
left = 0.34
image_left = 8.45
image_top = 1.17
numbering1_left = 1.05
numbering2_left = 2.53
# LAYOUT 3 == picture on left - text on right
elif layout.get() == 3:
image_left = 0.25
image_top = 1.17
rectangle_left = 8.15
left = 8.09
numbering1_left = 12.78
numbering2_left = 14.26
add_title_box(slide, dress_name, 0, 0.15, 16.18, 0.91)
add_subtitle_highlight(slide, rectangle_left, 1.75, 2.44, 0.3) # decription - highlight box
add_description_subtitle(slide, left, 1.26, 7.81, 0.51)
add_description_text(slide, dress_description, left, 1.88, 7.81, 5.35)
add_subtitle_highlight(slide, rectangle_left, 8.04, 2.76, 0.28) # did you know - highlight box
add_did_you_know_subtitle(slide, left, 7.56, 7.81, 0.51)
add_did_you_know_text(slide, dress_did_you_know, left, 8.19, 7.81, 1.11)
add_numbering(slide, dress_info, index, numbering1_left, 11.08, 1.28, 0.34, numbering2_left, 11.08, 1.28, 0.34)
add_image(slide, dress_info, image_left, image_top)
complete += 1
pb['value'] = (complete/len(sorted_dress_data))*100 # calculate percentage of images downloaded
percent_label.config(text=f'Creating Book...{int(pb["value"])}%') # update completion percent label
try:
prs.save(file_name)
except Exception as e:
print(f"-- DEBUG -- saving presentation: {e}")
finally:
book_gen_generate_button.config(state="normal")
progress_window.destroy() # close progress bar window
openFile(file_name)
print(sorted_dress_data)
'''
Helper function to wrap text
'''
def wrap(string, length=150):
return '\n'.join(textwrap.wrap(string, length))
'''
Generates treeview table of data
'''
def generate_table(table_data, report_name, column_headers, row_h, col_w, anchor_point, num_buttons=2):
# create window to display table
table_window = tk.Toplevel(root)
table_window.title(report_name)
table_window.geometry(f"1000x600")
table_window.minsize(1000,600)
# create frame to hold table
table_frame = tk.Frame(table_window)
table_frame.pack_propagate(False)
table_frame.place(x=0, y=0, relwidth=1, relheight=.89, anchor="nw")
# using style to set row height and heading colors
style = ttk.Style()
style.theme_use('clam')
style.configure('Treeview', rowheight=row_h)
style.configure('Treeview.Heading', background='#848484', foreground='white')
# vertical scrollbar
table_scrolly = tk.Scrollbar(table_frame)
table_scrolly.pack(side="right", fill='y')
# horizontal scrollbar
table_scrollx = tk.Scrollbar(table_frame, orient='horizontal')
table_scrollx.pack(side="bottom", fill='x')
# use ttk Treeview to create table
table = ttk.Treeview(table_frame, yscrollcommand=table_scrolly.set, xscrollcommand=table_scrollx.set, columns=column_headers, show='headings')
# configure the scroll bars with the table
table_scrolly.config(command=table.yview)
table_scrollx.config(command=table.xview)
# create the headers and set column variables
for index, column_header in enumerate(column_headers):
table.heading(column_header, text=column_header)
if index == 0:
table.column(column_header, width=75, stretch=False)
elif index == 1:
table.column(column_header, width=145, stretch=False)
else:
table.column(column_header, width=col_w, stretch=False, anchor=anchor_point)
# pack table into table_frame
table.pack(fill='both', expand=True)
# fill table with difference report data
for index, data in enumerate(table_data):
# word wrap text
for i, cell in enumerate(data):
if len(str(data[i])) > 2000:
data[i] = wrap(str(cell), 400)
else:
data[i] = wrap(str(cell), 250)
# if new row, set tag to new
# if changed row, set tag to changed
if data[-1] == 'new':
table.insert(parent='', index=tk.END, values=data, tags=('new',))
elif data[-1] == 'changed':
table.insert(parent='', index=tk.END, values=data, tags=('changed',))
else:
# if even row, set tag to evenrow
# if odd row, set tag to oddrow
if index % 2 == 0:
table.insert(parent='', index=tk.END, values=data, tags=('evenrow',))
else:
table.insert(parent='', index=tk.END, values=data, tags=('oddrow',))
# color rows
table.tag_configure('new', background='#BAFFA4')
table.tag_configure('changed', background='#FFA5A4')
table.tag_configure('evenrow', background='#e8f3ff')
table.tag_configure('oddrow', background='#f7f7f7')
# create button frame and place one table_window
btn_frame = tk.Frame(table_window)
btn_frame.pack(side='bottom', pady=15)
if num_buttons == 2:
# create buttons and pack on button_frame
btn = tk.Button(btn_frame, text='Export SQL File', font=LABEL_FONT, width=25, height=1, bg="#007FFF", fg="#ffffff", command=lambda: exportSQL(table_data, column_headers, report_name))
btn.pack(side='left', padx=25)
btn2 = tk.Button(btn_frame, text='Export to HTML', font=LABEL_FONT, width=25, height=1, bg="#007FFF", fg="#ffffff", command=lambda: exportHTML(table_data, column_headers, report_name))
btn2.pack(side='left', padx=25)
elif num_buttons == 1:
btn = tk.Button(btn_frame, text='Export to HTML', font=LABEL_FONT, width=25, height=1, bg="#007FFF", fg="#ffffff", command=lambda: exportHTML(table_data, column_headers, report_name))
btn.pack(side='left', padx=25)
'''
Exports table data to Excel file
'''
def exportExcel(data, excel_columns, sheet_name):
df = pd.DataFrame(data, columns=excel_columns)
df.to_excel(f'{sheet_name}.xlsx', index=False)
'''
Exports difference report data to SQL update script
'''
def exportSQL(dress_data, column_headers, report_name):
if report_name == 'difference_report':
sql_queries = [] # stores sql query
# cycle through the diff_dress_data and create queries for each
for index, data in enumerate(dress_data):
data[1] = str(data[1]).replace('"', '\\"') # replace " with \" so quotations don't mess up query
data[2] = str(data[2]).replace('"', '\\"') # replace " with \" so quotations don't mess up query
data[3] = str(data[3]).replace('"', '\\"') # replace " with \" so quotations don't mess up query
if data[-1] == 'changed':
sql_queries.append(f'UPDATE dresses\nSET name="{data[1]}", description="{data[2]}", did_you_know="{data[3]}"\nWHERE id={data[0]};\n')
elif data[-1] == 'new':
sql_queries.append(f'INSERT INTO dresses (id, name, description, did_you_know)\nVALUES ({data[0]}, "{data[1]}", "{data[2]}", "{data[3]}");\n')
# create path for sql script
update_script_path = 'abcdbook_SQL_update.sql'
update_script_name = 'abcdbook_SQL_update'
count = 1
while os.path.exists(update_script_path):
update_script_path = f'{update_script_name}({count}).sql'
count += 1
# write sql queries into .sql script
with open(update_script_path, 'w') as f:
for query in sql_queries:
f.write(f'{query}\n')
elif report_name == 'wiki_link_report':
with open(f'{report_name}_update.sql', 'w') as sql_file:
# Create SQL CREATE TABLE statement
create_table_query = f'CREATE TABLE IF NOT EXISTS resources (\n'
create_table_query += ', '.join(f'{column} TEXT' for column in column_headers)
create_table_query += '\n);\n\n'
sql_file.write(create_table_query)
# Create SQL INSERT INTO statement
sql_file.write(f'INSERT INTO resources ({", ".join(column_headers)}) VALUES\n')
# Iterate through data and write values
for row in dress_data:
values = ', '.join(f"'{str(value)}'" for value in row)
sql_file.write(f'({values}),\n')
# Remove the trailing comma from the last line
sql_file.seek(sql_file.tell() - 2)
sql_file.truncate()
# Add a semicolon to the end of the SQL script
sql_file.write(';')
'''
Exports data to JQuery data table HTML page
'''
def exportHTML(data, column_headers, file_name):
#read in data and create column headers
table_data = pd.DataFrame(data)
table_data.columns = column_headers
#convert table_data to html
html_table_data = table_data.to_html(table_id='html_table_data', border=0, classes='display')
#html template to generate JQuery DataTable of data
html_temp = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=width-device, initial-scale=1.0">
<title>{file_name}</title>
<!--jQuery cdn-->
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<!--Datatable style-->
<link rel="stylesheet" href="https:////cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" />
<!--Datatable cdn-->
<script src="https:////cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<!--Datatable button libraries-->
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<!--Initialize datatables-->
<script>
$(document).ready(function() {{
$('#html_table_data').DataTable({{
pageLength: 25,
dom: 'Bfrtip',
buttons: [
'csv', 'excel', 'pdf'
]
}},
style_table = {{
'width': '100%'
}});
}});
</script>
</head>
<body>
{html_table_data}
</body>
</html>
"""
#write html template into datatable.html file
with open(f'{file_name}.html', 'w', encoding='utf-8') as f:
f.write(html_temp)
#open datatable.html
webbrowser.open(f'{file_name}.html')
'''
Performs difference report on Excel sheet compared to API data
'''
def diffReport():
file_path = 'APIData.xlsx' # Change to path where file is located
dress_ids = sorted(getSlideNumbers()) # gets dress IDs in entry field
diff_dress_data = [] # data in spreadsheet that is different from API
api_dress_data = sorted(apiRunner(), key=lambda x : x['id']) # gets dress data from API and sorts by ID
try:
# gets and cleans dress data from Excel file
sheet_dress_data = pd.read_excel(file_path)
sheet_dress_data.dropna(subset=['id'], inplace=True) # drops any rows with na ID
sheet_dress_data['description'].fillna('', inplace=True) # removes na/nan from description column
sheet_dress_data['did_you_know'].fillna('', inplace=True) # removes na/nan from did_you_know column
sheet_dress_data['description'] = sheet_dress_data['description'].astype(str).apply(openpyxl.utils.escape.unescape) # convert escaped strings to ASCII
sheet_dress_data['did_you_know'] = sheet_dress_data['did_you_know'].astype(str).apply(openpyxl.utils.escape.unescape) # Convert escaped strings to ASCII
# cycle through api_dress_data
for api_data in api_dress_data:
# row of data with an ID that matches api_data ID
row = sheet_dress_data.loc[api_data['id']-1] # row of data in spreadsheet
# check if name, description, or did_you_know is different from the API data
if row.loc['name'] != api_data['name']:
new_row = [item for item in row]
new_row.append('changed')
diff_dress_data.append(new_row)
continue
if row.loc['description'] != api_data['description']:
new_row = [item for item in row]
new_row.append('changed')
diff_dress_data.append(new_row)
continue
if row.loc['did_you_know'] != api_data['did_you_know']:
new_row = [item for item in row]
new_row.append('changed')
diff_dress_data.append(new_row)
continue
# check for new entries in Excel sheet that do not exist in retrieved api data
for id in dress_ids: