forked from flips22/mylar-league
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CBLgenerator.py
1961 lines (1564 loc) · 84.7 KB
/
CBLgenerator.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
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 requests
import json
import os
import time
from enum import IntEnum
import xml.etree.ElementTree as ET
from glob import glob
from sys import argv
import numpy as np
import re
from simyan.comicvine import Comicvine
from simyan.sqlite_cache import SQLiteCache
import configparser
#import xlsxwriter
from PIL import Image
import pandas as pd
import io
import shutil
import sys
import glob
import random
import base64
import pandas as pd
from PIL import Image
from io import BytesIO
from IPython.display import HTML
import unicodedata # Needed to strip character accents
from datetime import datetime
#from datetime import date
#import datetime
import sqlite3
config = configparser.ConfigParser(allow_no_value=True)
if os.path.exists('configPRIVATE.ini'): # an attempt to prevent me from sharing my api keys (again) :)
config.read('configPRIVATE.ini')
else:
config.read('config.ini')
### DEV OPTIONS
#Enable verbose output
VERBOSE = True
#Prevent overwriting of main CSV data file
TEST_MODE = False
searchTruthDB = False
#Change forceCreateCBL to True to create CBL even if there are missing issues.
forceCreateCBL = False
#File prefs
SCRIPT_DIR = os.getcwd()
READINGLIST_DIR = os.path.join(SCRIPT_DIR, "ReadingLists")
DATA_FILE = os.path.join(SCRIPT_DIR, "Wishlist-Output.csv")
IMAGE_DIR = os.path.join(SCRIPT_DIR, "CVCoverImages")
#CV prefs
#CV_SEARCH_LIMIT = 10000 #Maximum allowed number of CV API calls
CACHE_RETENTION_TIME = 180 #days
CV_API_KEY = config['comicVine']['cv_api_key']
CV_API_RATE = 1 #Seconds between CV API calls
FORCE_RECHECK_CV = False
PUBLISHER_BLACKLIST = ["Panini Comics","Editorial Televisa","Planeta DeAgostini","Unknown","Urban Comics","Dino Comics","Ediciones Zinco","Abril","Panini Verlag","Panini España","Panini France","Panini Brasil","Egmont Polska","ECC Ediciones","RW Edizioni","Titan Comics","Dargaud","Federal", "Marvel UK/Panini UK","Grupo Editorial Vid","JuniorPress BV","Pocket Books", "Caliber Comics", "Panini Comics","Planeta DeAgostini","Newton Comics","Atlas Publishing"]
PUBLISHER_PREFERRED = ["Marvel","DC Comics","Vertigo"] #If multiple matches found, prefer this result
SERIESID_BLACKLIST = [137835,147775,89852,96070,78862,58231,50923]
SERIESID_GOODLIST = [42722,3824,4975,69322,3816,38005,1628] #index matches above list
#CV = None
dynamicNameTemplate = '[^a-zA-Z0-9]'
stop_words = ['the', 'a', 'and']
yearStringCleanTemplate = '[^0-9]'
#cleanStringTemplate = '[^a-zA-Z0-9\:\-\(\) ]'
#cleanStringTemplate = '[^a-zA-Z0-9:\-\(\) ]'
dfOrderList = ['SeriesName', 'SeriesStartYear', 'IssueNum', 'IssueType', 'CoverDate', 'Name', 'SeriesID', 'IssueID', 'CV Series Name', 'CV Series Year', 'CV Issue Number', 'CV Series Publisher', 'CV Cover Image', 'CV Issue URL', 'Days Between Issues']
'''
class col(IntEnum):
# listOrder = 0
# SeriesName = 1
# SeriesStartYear = 2
# IssueNum = 3
# IssueType = 4
# CoverDate = 5
# SeriesID = 6
# IssueID = 7
# cvSeriesName = 8
# csSeriesYear = 9
# cvCoverImage = 10
# cvIssueURL = 11
LISTORDER = 0
SERIESNAME = 1
SERIESYEAR = 2
ISSUENUM = 3
ISSUETYPE = 4
COVERDATE = 5
SERIESID = 6
ISSUEID = 7
CVSERIESNAME = 8
CVSERIESYEAR = 9
CVCOVERIMAGE = 10
CVISSUEURL = 11
xlsheader = [
#header / data field
"List Order",
"SeriesName",
"SeriesStartYear",
"IssueNum",
"IssueType",
"CoverDate",
"SeriesID",
"IssueID",
"CV Series Name",
"CV Series Year",
"CV Cover Image",
"CV Issue URL"
]
timeString = time.strftime("%y%m%d%H%M%S")
#File prefs
SCRIPT_DIR = os.getcwd()
RESULTS_DIR = os.path.join(SCRIPT_DIR, "Results")
DATA_DIR = os.path.join(SCRIPT_DIR, "Data")
READINGLIST_DIR = os.path.join(SCRIPT_DIR, "ReadingLists")
DATA_FILE = os.path.join(DATA_DIR, "data.csv")
RESULTS_FILE = os.path.join(RESULTS_DIR, "results-%s.txt" % (timeString))
#Create folders if needed
if not os.path.isdir(DATA_DIR): os.mkdirs(DATA_DIR)
if not os.path.isdir(RESULTS_DIR): os.mkdirs(RESULTS_DIR)
if not os.path.isdir(READINGLIST_DIR): os.mkdirs(READINGLIST_DIR)
OUTPUT_FILE = os.path.join(DATA_DIR, "data-%s.csv" % (timeString))
'''
timeString = datetime.today().strftime("%y%m%d%H%M%S")
rootDirectory = os.getcwd()
#rootDirectory = os.path.dirname(rootDirectory)
dataDirectory = os.path.join(rootDirectory, "ReadingList-DB")
readingListDirectory = os.path.join(rootDirectory, "ReadingList-ImportExport")
resultsDirectory = os.path.join(rootDirectory, "ReadingList-Results")
outputDirectory = os.path.join(rootDirectory, "ReadingList-Output")
#jsonOutputDirectory = os.path.join(outputDirectory, "JSON")
#cblOutputDirectory = os.path.join(outputDirectory, "CBL")
#truthTableDirectory = os.path.join(rootDirectory, "ReadingList-truthDB")
#dataFile = os.path.join(dataDirectory, "data.db")
#cvCacheFile = os.path.join(dataDirectory, "cv.db")
#overridesFile = os.path.join(dataDirectory,'SeriesOverrides.json')
#configFile = os.path.join(rootDirectory, 'config.ini')
resultsFile = os.path.join(resultsDirectory, "results-%s.txt" % (timeString))
problemsFile = os.path.join(resultsDirectory, "problems-%s.txt" % (timeString))
uniqueSeriesFile = os.path.join(resultsDirectory, "uniqueSeriesWarnings-%s.txt" % (timeString))
duplicateIssueFile = os.path.join(resultsDirectory, "duplicateIssuesRemoved-%s.txt" % (timeString))
#truthDB = os.path.join(dataDirectory, "truthDB.db")
#truthDB = os.path.join(dataDirectory, "CBRO.db")
#truthDB = os.path.join(dataDirectory, "x-men.db")
truthDB = os.path.join(dataDirectory, "CMRO.db")
#cvCacheFile = os.path.join(dataDirectory, "CV.db")
cvCacheFile = os.path.join(dataDirectory, "CV-NEW.db")
#vCacheFile = os.path.join(dataDirectory, "CV-TEMP.db")
# inputfile = " ".join(sys.argv[1:])
# #inputfile = '[Marvel] All-New, All Different Marvel- All-New, All-Different Marvel Part #2 (WEB-RIPCBRO).json'
# #inputfile = '[Marvel] Marvel Master Reading Order Part #5 (WEB-RIPCBRO).json'
# #inputfile = '102 One More Day (2007).cbl'
# #inputfile = '[Marvel] Marvel Master Reading Order Part #2 (WEB-RIPCBRO).json'
# #inputfile = '[Marvel] Infinity Gauntlet (WEB-CMROLIST).json'
# outputfile = inputfile.strip('.json') + '-USER.xlsx'
# outputcsvfile = inputfile.strip('.json') + '-USER.csv'
# outputhtmlfile = inputfile.strip('.json') + '-USER.html'
# print(inputfile)
# print(outputfile)
# if os.path.exists(outputfile):
# firstRun = False
# print('Not First Run')
# else:
# firstRun = True
# print('First Run')
def main():
checkDirectories()
summaryResults = []
problemResults = []
uniqueSeriesWarnings = []
uniqueSeriesWarnings.append('Found series with the same title and different Series IDs:\n')
global duplicateIssues
duplicateIssues = []
try:
sqliteConnection = sqlite3.connect(truthDB,detect_types=sqlite3.PARSE_DECLTYPES)
cursor = sqliteConnection.cursor()
#print("Database created and Successfully Connected to SQLite")
# sqlite_select_Query = "select sqlite_version();"
# cursor.execute(sqlite_select_Query)
# record = cursor.fetchall()
# print("SQLite Database Version is: ", record)
# df = pd.read_sql_query("SELECT * from comics", sqliteConnection)
# df=df.fillna({'year':0, 'issue':0}).astype({'year':int})
# rows = cursor.execute(
# "SELECT * FROM comics WHERE SeriesName = ? AND IssueNum = ?",
# ('Action Comics','1'),
# ).fetchall()
# #print(rows)
# print(rows[0][0])
# cursor.close()
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
#readingLists = []
fileCount = 0
for root, dirs, files in os.walk(readingListDirectory):
for file in files:
if file.endswith(".cbl") or file.endswith(".ccc") or file.endswith(".xlsx"):#file.endswith(".json") or
inputfile = file
print('Processing %s'%(inputfile))
#if file.endswith(".json"):
#outputfile = os.path.join(readingListDirectory, inputfile.replace('.json','') + '.xlsx')
#outputcsvfile = os.path.join(readingListDirectory, inputfile.replace('.json','') + '.csv')
#outputhtmlfile = os.path.join(readingListDirectory, inputfile.replace('.json','') + '.html')
#outputcblfile = os.path.join(outputDirectory, inputfile.replace('.json','') + '.cbl')
if file.endswith(".cbl"):
outputfile = os.path.join(readingListDirectory, inputfile.replace('.cbl','') + '.xlsx')
outputcsvfile = os.path.join(readingListDirectory, inputfile.replace('.cbl','') + '.csv')
outputhtmlfile = os.path.join(readingListDirectory, inputfile.replace('.cbl','') + '.html')
outputcblfile = os.path.join(outputDirectory, inputfile.replace('.cbl','') + '.cbl')
if file.endswith(".ccc"):
outputfile = os.path.join(readingListDirectory, inputfile.replace('.ccc','') + '.xlsx')
outputcsvfile = os.path.join(readingListDirectory, inputfile.replace('.ccc','') + '.csv')
outputhtmlfile = os.path.join(readingListDirectory, inputfile.replace('.ccc','') + '.html')
outputcblfile = os.path.join(outputDirectory, inputfile.replace('.ccc','') + '.cbl')
if file.endswith(".xlsx"):
outputfile = os.path.join(readingListDirectory, inputfile)
outputcsvfile = os.path.join(readingListDirectory, inputfile.replace('.xlsx','') + '.csv')
outputhtmlfile = os.path.join(readingListDirectory, inputfile.replace('.xlsx','') + '.html')
outputcblfile = os.path.join(outputDirectory, inputfile.replace('.xlsx','') + '.cbl')
inputfile = os.path.join(readingListDirectory, inputfile)
#Get year range from file name
# Example string
# Extract years from the string
global seriesNotFoundList
seriesNotFoundList = []
global year1
global year2
year1, year2 = extract_years_from_filename(inputfile)
#print (year1)
#print (year2)
if int(year1) > 0 and int(year2) > 0:
year1 = int(year1) -1
year2 = int(year2) +1
print(f" If no date is in defined, the year range for searching will be: {year1} to {year2}")
else:
print(f" Year range was not found in file name. Continuing...")
if os.path.exists(outputfile):
firstRun = False
#will also not be first run if xlsx is input file.
#print('Previous run detected')
else:
firstRun = True
#print('First run for this file')
fileCount += 1
if firstRun and inputfile.endswith(".json"):
df = importJSON(inputfile)
elif firstRun and inputfile.endswith(".cbl"):
df = importCBL(inputfile)
elif firstRun and inputfile.endswith(".ccc"):
df = importCCC(inputfile)
else:
df = importXLSX(outputfile)
df.index = np.arange(1, len(df) + 1)
#df = df.reset_index()
for index, row in df.iterrows():
#print(index)
seriesName = row['SeriesName']
seriesStartYear = row['SeriesStartYear']
dbissueNum = row['IssueNum']
issueNum = row['CV Issue Number']
if isinstance(issueNum, float):
issueNum = f'{issueNum:g}'
#issueNum = f'{float(issueNum):g}'
#issueNum = int(issueNum)
issueType = row['IssueType']
coverDate = row['CoverDate']
seriesID = row['SeriesID']
issueID = row['IssueID']
cvSeriesName = row['CV Series Name']
cvSeriesYear = row['CV Series Year']
cvIssueNum = row['CV Issue Number']
if isinstance(cvIssueNum, float):
cvIssueNum = f'{cvIssueNum:g}'
try:
cvSeriesPublisher = row['CV Series Publisher']
except:
cvSeriesPublisher = ''
#continue
cvIssueURL = row['CV Issue URL']
coverImage = row['CV Cover Image']
#print(seriesID)
if (df['SeriesID'] == 0).all():
firstRun = True
#if sqliteConnection:
if sqliteConnection and searchTruthDB and issueID == 0:# and firstRun:
try:
#truthMatch = cursor.execute(
#"SELECT * FROM comics WHERE SeriesName = ? AND SeriesStartYear = ? AND IssueNum = ? AND ReadingList = ?",
#(seriesName,seriesStartYear,dbissueNum,file),
#).fetchall()
truthMatch = cursor.execute(
"SELECT * FROM comics WHERE SeriesName = ? AND SeriesStartYear = ? AND IssueNum = ?",
(seriesName,seriesStartYear,dbissueNum),
).fetchall()
#'Action Comics', 1938, '1', 'Issue', '1938-06-30 00:00:00', 'Comicvine', 18005, 105403, 'Action Comics', 1938, ' ', 'https://comicvine.gamespot.com/issue/4000-105403/', 153, '1')
#coverDate = truthMatch[0][4]
print('Match found in truth table')
#print(truthMatch)
seriesID = truthMatch[0][6]
issueID = truthMatch[0][7]
cvSeriesName = truthMatch[0][8]
cvSeriesYear = truthMatch[0][9]
issueNum = truthMatch[0][10]
cvIssueURL = truthMatch[0][13]
cvSeriesPublisher = truthMatch[0][11]
# try:
# cvSeriesPublisher = truthMatch[0][11]
# except:
# cvSeriesPublisher = ''
except:
print('No match found in truth table, trying only series and year')
try:
truthMatch = cursor.execute(
"SELECT * FROM comics WHERE SeriesName = ? AND SeriesStartYear = ?",
(seriesName,seriesStartYear),
).fetchall()
#'Action Comics', 1938, '1', 'Issue', '1938-06-30 00:00:00', 'Comicvine', 18005, 105403, 'Action Comics', 1938, ' ', 'https://comicvine.gamespot.com/issue/4000-105403/', 153, '1')
#coverDate = truthMatch[0][4]
#print(truthMatch)
seriesID = truthMatch[0][6]
except:
print('No match found in truth table')
if issueNum == '' or issueNum == 'nan':
issueNum = dbissueNum
if seriesStartYear == 0:
#print(f"Checking {seriesName} #{issueNum}...")
pass
else:
#print(f"Checking {seriesName} ({seriesStartYear}) #{issueNum}...")
pass
#if isinstance(coverDate, str):
#print('coveDate is a string')
if isinstance(seriesID,int) and not seriesID == 0:
seriesIDPres = True
else:
seriesIDPres = False
if isinstance(issueID,int) and not issueID == 0:
issueIDPres = True
else:
issueIDPres = False
if cvIssueURL == '' or coverImage == '' or coverDate == '' or isinstance(coverDate, str) or isinstance(coverDate, int) or cvIssueNum =='nan' or cvIssueNum == '':
missingIssueDetails = True
else:
missingIssueDetails = False
if cvSeriesName == '' or cvSeriesYear =='' or cvSeriesPublisher == '':
missingSeriesDetails = True
else:
missingSeriesDetails = False
if issueIDPres and not seriesIDPres:
print(' Searching for series id from issueid')
seriesID = getSeriesIDfromIssue(issueID)
if not seriesID == 0:
seriesIDPres = True
#seriesID = seriesIDList[0]
validYear = is_valid_year(seriesStartYear)
if not seriesIDPres and not issueIDPres:
if validYear:
volumeresults = findVolume(seriesName,seriesStartYear)
print(f"Seaching for match using series and year...")
print(seriesID)
if not volumeresults[1] == 0:
seriesID = volumeresults[1]
seriesIDPres = True
if not validYear and not year1 == 0:
#try:
#seriesSearch = df.loc[df['SeriesName'] == seriesName, 'SeriesID'].values[0]# or .item()
#seriesSearch = df.query("SeriesName==seriesName")["SeriesID"]
#print(f" Checking if series name was searched for previously")
if seriesName in seriesNotFoundList:
print(f" Searched for series previously and wasn't found, skipping...")
else:
seriesSearch = df.loc[(df['SeriesName'] == seriesName,'SeriesID')].values[0]
#print('seriesSearch: ' + str(seriesSearch))
if not seriesSearch == 0:
#
seriesID = seriesSearch
seriesIDPres = True
print(f" Found series ID ({seriesSearch}) in previous search...")
else:
print(f" Searching for match using series and year range...")
volumeresults = findVolumeNoYear(seriesName, issueNum)
#print(seriesID)
if not volumeresults[1] == 0:
seriesIDPres = True
seriesID = volumeresults[1]
print(f" Found matching series id: {seriesID}")
if not volumeresults[2] == 0:
issueIDPres = True
issueID = volumeresults[2]
print(f" Found matching issue ID: {issueID}")
# if seriesIDPres:
# imageFileName = str(issueID) + '.jpg'
# imageFilePath = os.path.join(IMAGE_DIR, imageFileName)
# if not os.path.exists(imageFilePath):
# cvIssueDetails = getIssueDetails(issueID)
# cvImageURL = cvIssueDetails[0]
# cvIssueURL = cvIssueDetails[1]
# coverDate = cvIssueDetails[2]
# if not cvImageURL == '':
# try:
# imageFilePath = getcvimage(issueID,cvImageURL)
# coverImage = get_thumbnail(imageFilePath)
# coverImage = image_formatter(imageFilePath)
# #print(imageFilePath)
# except:
# print('Not able to load issueID image from %s'%(imageFilePath))
# if seriesIDPres: #acting strange
# if seriesID in SERIESID_BLACKLIST:
# print('SeriesID in Blacklist replacing....')
# index = SERIESID_BLACKLIST.index(seriesID)
# print(seriesID)
# print('to:')
# seriesID = SERIESID_GOODLIST[index]
# print(seriesID)
# volumedetails = getVolumeDetails(seriesID)
# cvSeriesName = volumedetails[0]
# cvSeriesYear = volumedetails[1]
# df.loc[df['SeriesID'] == seriesID, 'CV Series Name'] = cvSeriesName #testing
# df.loc[df['SeriesID'] == seriesID, 'CV Series Year'] = cvSeriesYear
if seriesIDPres and missingSeriesDetails:
volumedetails = getVolumeDetails(seriesID)
#print (volumedetails)
cvSeriesName = volumedetails[0]
cvSeriesYear = volumedetails[1]
cvSeriesPublisher = volumedetails[2]
df.loc[df['SeriesID'] == seriesID, 'CV Series Name'] = cvSeriesName #testing
df.loc[df['SeriesID'] == seriesID, 'CV Series Year'] = cvSeriesYear
df.loc[df['SeriesID'] == seriesID, 'CV Series Publisher'] = cvSeriesPublisher
if seriesIDPres and not issueIDPres:
cvIssueFind = findIssueID(seriesID,issueNum)
issueID = cvIssueFind
if issueID == 0:
print(' Could not find issue: %s from %s' % (issueNum,seriesID))
if not issueID == 0:
cvIssueDetails = getIssueDetails(issueID)
cvImageURL = cvIssueDetails[0]
cvIssueURL = cvIssueDetails[1]
coverDate = cvIssueDetails[2]
cvIssueNum = cvIssueDetails[3]
if not cvImageURL == '':
try:
imageFilePath = getcvimage(issueID,cvImageURL)
coverImage = get_thumbnail(imageFilePath)
coverImage = image_formatter(imageFilePath)
#print(imageFilePath)
except:
print('Not able to load issueID image from %s'%(imageFilePath))
if issueIDPres:# and 'google' in cvIssueURL:
cvIssueURL = 'https://comicvine.gamespot.com/issue/4000-' + str(issueID) + '/'
if issueIDPres and missingIssueDetails:
cvIssueDetails = getIssueDetails(issueID)
cvImageURL = cvIssueDetails[0]
cvIssueURL = cvIssueDetails[1]
coverDate = cvIssueDetails[2]
cvIssueNum = cvIssueDetails[3]
if not cvImageURL == '':
try:
imageFilePath = getcvimage(issueID,cvImageURL)
coverImage = get_thumbnail(imageFilePath)
coverImage = image_formatter(imageFilePath)
except:
print('Not able to load issueID image from %s'%(imageFilePath))
if issueIDPres and coverImage == ' ':
imageFileName = str(issueID) + '.jpg'
imageFilePath = os.path.join(IMAGE_DIR, imageFileName)
#print(imageFilePath)
if os.path.exists(imageFilePath):
try:
coverImage = get_thumbnail(imageFilePath)
coverImage = image_formatter(imageFilePath)
#print('image exists')
except:
print('Not able to load issueID image from %s'%(imageFilePath))
else:
try:
cvIssueDetails = getIssueDetails(issueID)
cvImageURL = cvIssueDetails[0]
cvIssueURL = cvIssueDetails[1]
coverDate = cvIssueDetails[2]
cvIssueNum = cvIssueDetails[3]
imageFilePath = getcvimage(issueID,cvImageURL)
print('image doesnt exist')
coverImage = get_thumbnail(imageFilePath)
coverImage = image_formatter(imageFilePath)
except:
print('Not able to load issueID image from %s'%(imageFilePath))
if not issueIDPres:
#print(str(seriesStartYear))
#cvIssueURL = searchCV(seriesName,seriesStartYear)
#cvIssueURL = ('https://www.google.com/search?q=' + str(seriesName) + '+' + str(seriesStartYear) + '+comicvine').replace(" ", "%20")
cvIssueURL = ('https://comicvine.gamespot.com/search/?i=volume&q=' + str(seriesName) + '+' + str(seriesStartYear)).replace(' &', '+%26').replace(" ", "+")
dateDelta = pd.to_timedelta(0, unit='D')#pd.Timedelta(0)#
if index == 0:
dateDelta = pd.to_timedelta(0, unit='D')#pd.Timedelta(0)#
indexbefore = index + 1
try:
coverDateAbove = (df.iloc[index]['CoverDate'])
except:
print('Possible date issue, moving along...')
#continue
if not coverDate == pd.NaT and not coverDateAbove == pd.NaT:
#dateDelta = daysBetween(coverDate,coverDateAbove)
try:
#dateDelta = abs(coverDate - coverDateAbove)
dateDelta = coverDateAbove - coverDate
if dateDelta == 0:
dateDelta = pd.NaT
#print(coverDateAbove)
#print(coverDate)
# #print(dateDelta)
except:
print('Possible date issue, moving along...')
#continue
#print(' Found issueid: %s'%(str(issueID)))
df.loc[index,'CoverDate'] = coverDate
df.loc[index,'IssueID'] = issueID
df.loc[index,'CV Series Name'] = cvSeriesName
df.loc[index,'CV Series Year'] = cvSeriesYear
df.loc[index,'CV Issue Number'] = cvIssueNum
df.loc[index,'CV Series Publisher'] = cvSeriesPublisher
df.loc[index,'CV Issue URL'] = cvIssueURL
df.loc[index,'CV Cover Image'] = coverImage
df.loc[index,'IssueType'] = 'Issue' # everything's an issue?
df.loc[index,'Name'] = 'Comicvine'
df.loc[index,'SeriesID'] = seriesID
df = df.astype({'Days Between Issues':'timedelta64[ns]'})
df.loc[index,'Days Between Issues'] = dateDelta
# clear variables
coverDate = ''
issueID = 0
cvSeriesName = ''
cvSeriesYear = ''
cvIssueURL = ''
coverImage = ''
cvSeriesPublisher = ''
#issueType = ''
seriesID = 0
dateDelta = pd.to_timedelta(0, unit='D')#pd.Timedelta(0)#
#df=df.drop('Name',axis='columns')
#df=df.drop('IssueType',axis='columns')
#df.to_excel(outputfile)
#df = df.style.format({'CV Issue URL': make_clickable})
#df = df.style.highlight_null(null_color="red")
#df.style.applymap(color_cells, subset=['total_amt_usd_diff','total_amt_usd_pct_diff'])
#df['CoverDate'] = pd.to_datetime(df['CoverDate'], errors='coerce').dt.date()
numIssueFound = len(df[df['IssueID']>0])
numIssueTotal = len(df['IssueID'])
numIssueMissing = numIssueTotal - numIssueFound
try:
maxDays = df['Days Between Issues'].max()
minDays = df['Days Between Issues'].min()
maxAbsDays = max(abs(maxDays),abs(minDays))
except:
maxAbsDays = 'Unknown'
summaryString = 'Reading list has ' + str(numIssueMissing) + ' unidentified issues out of ' + str(numIssueTotal) + ' total issues. Maximum days between consecutive issues: ' + str(maxAbsDays)
# if numIssueMissing == 0:
# cblData = getCBLData(df,inputfile,numIssueFound)
# with open(outputcblfile, 'w') as f:
# f.writelines(cblData)
uniqueSeriesList = df.SeriesName.unique()
for uniqueseries in uniqueSeriesList:
seriestemp = df.loc[(df['SeriesName'] == uniqueseries)]
if not len(seriestemp) == 0:
if len(seriestemp.SeriesID.unique()) > 1:
print('Found possible TPB, logging....')
print(len(seriestemp.SeriesID.unique()))
#print(uniqueseries)
uniqueSeriesWarnings.append('\n' + outputfile + '\n ' + uniqueseries + '\n ' + str(seriestemp.SeriesID.unique()) + '\n['+str(seriestemp.IssueNum)+']\n')
#.set_caption(summaryString)
df = df[dfOrderList]
dfe = df
df = df.style.set_table_styles(
[{"selector": "", "props": [("border", "1px solid grey")]},
{"selector": "tbody td", "props": [("border", "1px solid grey")]},
{"selector": "th", "props": [("border", "1px solid grey")]}
]).set_caption(summaryString).map(color_cels).format({'CV Issue URL': make_clickable})#.to_html(outputhtmlfile)#,formatters={'CV Cover Image': image_formatter}, escape=False)
df.to_html(outputhtmlfile)
#FIX dfe['CoverDate'] = pd.to_datetime(dfe['CoverDate']).dt.date
dfe['CV Cover Image'] = ' '
dfe.to_csv(outputcsvfile)
dfe = dfe.style.set_table_styles(
[{"selector": "", "props": [("border", "1px solid grey")]},
{"selector": "tbody td", "props": [("border", "1px solid grey")]},
{"selector": "th", "props": [("border", "1px solid grey")]}
]).map(color_cels).format({'CV Issue URL': make_clickable})#.to_html(outputhtmlfile)#,formatters={'CV Cover Image': image_formatter}, escape=False)
dfe.to_excel(outputfile)
print(outputfile)
print(summaryString)
summaryResults.append(inputfile + '\n' + outputfile + '\n' + summaryString + '\n')
if not numIssueMissing == 0:
problemResults.append(inputfile + '\n' + outputfile + '\n' + summaryString + '\n')
if numIssueMissing == 0 or forceCreateCBL:
try:
print(inputfile)
cblName = str(file).replace(readingListDirectory,'').replace('.json','').replace('.cbl','').replace('.ccc','').replace('.xlsx','').strip('\\')
print(cblName)
cblData = getCBLData(df.data,cblName,numIssueFound)
with open(outputcblfile, 'w', encoding='utf-8') as f:
f.writelines(cblData)
except:
problemResults.append('\n -- CBL Export Failed -- ' + inputfile + '\n' + outputfile + '\n' + '\n')
# cblData = getCBLData(df.data,inputfile,numIssueFound)
# with open(outputcblfile, 'w') as f:
# f.writelines(cblData)
if sqliteConnection:
cursor.close()
sqliteConnection.close()
print("The truthDB connection is closed")
with open(resultsFile, 'w', encoding='utf-8') as f:
f.writelines(summaryResults)
with open(problemsFile, 'w', encoding='utf-8') as f:
f.writelines(problemResults)
with open(uniqueSeriesFile, 'w', encoding='utf-8') as f:
f.writelines(uniqueSeriesWarnings)
with open(duplicateIssueFile, 'w', encoding='utf-8') as f:
f.writelines(duplicateIssues)
return
def extract_years_from_filename(filename):
# Define the regular expression pattern to find years in the string with brackets
year1 = 2019
year2 = 2024
#patternYearFileName = r'\[(\d{4})\s*-\s*(\d{4})\]' # Matches years in the format [YYYY - YYYY]
#patternYearFileName = r'(\d{4} - \d{4})|([0-9]{4} - Present)|(\d{4})'
# Find all matches of the pattern in the input string
#matches = re.findall(patternYearFileName, filename)
#yearRangeMatch = re.findall(r'\[(\d{4}-\d{4})\]', filename)
yearRangeMatch = re.findall(r'(\d{4}-\d{4})', filename)
yearRangeMatchPresent = re.findall(r'\[(\d{4}-Present)\]|\((\d{4}-Present)\)', filename)
#yearRangeMatchSingleYear = re.findall(r'\[(\d{4})\]', filename)
yearRangeMatchSingleYear = re.findall(r'\[(\d{4})\]|\((\d{4})\)',filename)
#if re.match(r'\[(\d{4}-\d{4})\]', filename):
if yearRangeMatch:
print(f" Found date range.")
#year1year2Pattern = r'\[(\d{4})-(\d{4})\]'
year1year2Pattern = r'(\d{4})-(\d{4})'
yearRange = re.findall(year1year2Pattern, filename)
year1 = yearRange[0][0]
year2 = yearRange[0][1]
# Do something specific for date range like storing or processing
elif yearRangeMatchPresent:
print(f" Found 'Present' date range.")
year1year2Pattern = r'\[(\d{4})-Present'
yearRange = re.findall(year1year2Pattern, filename)
year1 = yearRange[0]
year2 = datetime.now().year
# Handle the case when 'Present' is matched
elif yearRangeMatchSingleYear:
print(f" Found single year match")
year1year2Pattern = r'\d{4}'
yearRange = re.findall(year1year2Pattern, filename)
year1 = yearRange[0]
year2 = yearRange[0]
# Handle the case when only a single year is matched
'''
if matches:
# Extract years from the matched pattern groups
year1 = matches.group(1)
year2 = matches.group(2)
print(filename)
print(year1)
print(year2)
'''
return year1, year2
def checkDirectories():
directories = [
dataDirectory,
readingListDirectory,
resultsDirectory,
outputDirectory,
IMAGE_DIR,
#jsonOutputDirectory,
#cblOutputDirectory
]
for directory in directories:
if not os.path.exists(directory):
os.makedirs(directory)
def importJSON(inputfile):
print(inputfile)
with open(inputfile) as json_file:
data = json.load(json_file)
issue_data = data['Issues']
dfo = pd.DataFrame.from_dict(data['Issues'], orient='index')#, columns=columns)
dfo.reset_index(drop=True, inplace=True)
df = dfo.join(pd.json_normalize(dfo['Database']))#.drop('Database', axis='columns')
df = df.join(pd.json_normalize(df['Name'])).fillna(0)#, inplace=True)
df.reset_index(drop=True, inplace=True)
#print(df)
rowlist = df['Database'].values.tolist()
for i in range(len(rowlist)):
y = i+1
df.loc[i,'Name'] = rowlist[i]['Name']
if rowlist[i]['SeriesID'] == None or rowlist[i]['SeriesID'] == '':
rowlist[i]['SeriesID'] = 0
if rowlist[i]['IssueID'] == None or rowlist[i]['IssueID'] == '':
rowlist[i]['IssueID'] = 0
df.loc[i,'SeriesID'] = rowlist[i]['SeriesID']
df.loc[i,'IssueID'] = rowlist[i]['IssueID']
#print(rowlist[i]['IssueID'])
#print(df[i, 'IssueID'])
df.fillna({'SeriesID':0, 'IssueID':0}, inplace=True)
#df = df.astype({'SeriesID':float,'IssueID':float}).astype({'SeriesID':int,'IssueID':int})#.fillna(0)#,errors='ignore')#.fillna(0)#,'IssueID':'int'})
df = df.astype({'SeriesID':int,'IssueID':int})#.fillna(0)#,errprint\([A-Z].*ors='ignore')#.fillna(0)#,'IssueID':'int'})
df = df.drop('Database', axis='columns')
df['CV Series Name'] = ''
df['CV Series Year'] = ''
df['CV Issue Number'] = df['IssueNum']
df['CV Series Publisher'] = ''
df['CV Cover Image'] = ''
df['CV Issue URL'] = ''
return(df)
def importCBL(inputfile):
bookList = []
# print("Checking CBL files in %s" % (READINGLIST_DIR),2)
# for root, dirs, files in os.walk(READINGLIST_DIR):
# for file in files:
# if file.endswith(".cbl"):
# try:
# filename = os.path.join(root, file)
# #print("Parsing %s" % (filename))
# tree = ET.parse(filename)
# fileroot = tree.getroot()
# cblinput = fileroot.findall("./Books/Book")
# for entry in cblinput:
# book = {'seriesName':entry.attrib['Series'],'seriesYear':entry.attrib['Volume'],'issueNumber':entry.attrib['Number']}#,'issueYear':entry.attrib['Year']}
# bookList.append(book)
# except Exception as e:
# print("Unable to process file at %s" % ( os.path.join(str(root), str(file)) ),3)
# print(repr(e),3)
try:
tree = ET.parse(inputfile)
fileroot = tree.getroot()
cblinput = fileroot.findall("./Books/Book")
for entry in cblinput:
try:
book = {'seriesName':entry.attrib['Series'],'seriesYear':entry.attrib['Volume'],'issueNumber':entry.attrib['Number'], 'seriesID':entry[0].attrib['Series'], 'issueID':entry[0].attrib['Issue']}#,'issueYear':entry.attrib['Year']}
except:
book = {'seriesName':entry.attrib['Series'],'seriesYear':entry.attrib['Volume'],'issueNumber':entry.attrib['Number'], 'issueID':0, 'seriesID':0}#,'issueYear':entry.attrib['Year']}
bookList.append(book)
except Exception as e:
print("Unable to process file at %s" % (str(inputfile)))
print(repr(e))
#bookSet = set()
finalBookList = []
for book in bookList:
curSeriesName = book['seriesName']
curSeriesYear = book['seriesYear']
curIssueNumber = book['issueNumber']
curSeriesID = book['seriesID']
curIssueID = book['issueID']
#bookSet.add((curSeriesName,curSeriesYear,curIssueNumber))
finalBookList.append([curSeriesName,curSeriesYear,curIssueNumber,curSeriesID, curIssueID])
#df = pd.DataFrame(bookSet, columns =['seriesName', 'seriesYear', 'issueNumber'])
df = pd.DataFrame(finalBookList, columns =['seriesName', 'seriesYear', 'issueNumber', 'seriesID', 'issueID'])
#print(df)
# print(bookSet)
# #Iterate through unique list of series
# if VERBOSE: print('Compiling set of issueNumbers from CBLs',2)
# for series in bookSet:
# curSeriesName = series[0]
# curSeriesYear = series[1]
# curSeriesIssues = []
# #Check every book for matches with series
# for book in bookList:
# if book['seriesName'] == curSeriesName and book['seriesYear'] == curSeriesYear:
# #Book matches current series! Add issueNumber to list
# curSeriesIssues.append({'issueNumber':book['issueNumber'],'issueID':"Unknown"})
# finalBookList.append({'seriesName':curSeriesName,'seriesYear':curSeriesYear,'issueNumberList':curSeriesIssues})
# print(finalBookList[1]['issueNumberList'])
# #print(type(finalBookList[1]['issueNumberList'][issueID]))
# issuedict = finalBookList[1]['issueNumberList']
# print(issuedict[issueID])
# #print(finalBookList)
# #print(type(finalBookList))
# df = pd.DataFrame(finalBookList, columns =['seriesName', 'seriesYear', 'issueNumberList'])
# #df = pd.DataFrame(finalBookList['issueNumberList'], columns =['issueNumber', 'fissueID'])
# #df = pd.DataFrame(finalBookList, columns =['SeriesName', 'SeriesStartYear', 'IssueNum'])
# #print(df['issueNumberList'].values.tolist())
# #print(finalBookList[0]['issueNumberList']['issueNumber'])
# #rowlist =
# #print(rowlist['issueID'])
# #print(rowlist[2]['issueNumberList'])
# #print(len(finalBookList))
# for i in range(len(finalBookList)):
# # y = i+1
# # #df.loc[i,'issueNumberList'] = rowlist[i]['issueNumberList']
# # if finalBookList[i]['issueNumberList'] == None or finalBookList[i]['issueNumberList'] == '':
# # finalBookList[i]['issueNumberList'] = 0
# # if rowlist[i]['issueID'] == None or rowlist[i]['issueID'] == '':
# # rowlist[i]['issueID'] = 0
# #print(finalBookList[i]['issueNumberList'][0])
# #print(finalBookList[i]['issueNumberList'][1])
# df.loc[i,'issueNumber'] = finalBookList[i]['issueNumberList'][0]
# df.loc[i,'issueID'] = finalBookList[i]['issueNumberList'][1]
# #print(rowlist[i]['IssueID'])
# #print(df[i, 'IssueID'])
# ###df.fillna({'issueNumber':0, 'issueID':0}, inplace=True)
# #df = df.astype({'SeriesID':float,'IssueID':float}).astype({'SeriesID':int,'IssueID':int})#.fillna(0)#,errors='ignore')#.fillna(0)#,'IssueID':'int'})
# ###df = df.astype({'issueNumber':int,'issueID':int})#.fillna(0)#,errors='ignore')#.fillna(0)#,'IssueID':'int'})
# df = df.drop('issueNumberList', axis='columns')
# print(df)
#df['issueID'] = 0