-
Notifications
You must be signed in to change notification settings - Fork 0
/
KJZZ-db.py
2596 lines (2204 loc) · 114 KB
/
KJZZ-db.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
# BiasBuster
# author: AudioscavengeR
# license: GPLv2
# version: 0.9.11 release iframe
# BUG: jpeg produced by plt.savefig have a wide border
# Object: Identify and challenge bias in language wording, primarily directed at KJZZ's radio broadcast.
# BiasBuster provides an automated stream downloader, a SQLite database, and Python functions to output visual statistics.
# BiasBuster will produce:
# - CUDA word transcription from any audio files, based on Whisper-Faster
# - Words cloud, based on amueller/word_cloud
# - Gender bias statistics, based on auroracramer/language-model-bias
# - Misinformation analysis heatmap, based on PDXBek/Misinformation
# https://kjzz.org/kjzz-print-schedule
# python KJZZ-db.py -i -f kjzz\44
# python KJZZ-db.py -i -f kjzz\45
# python KJZZ-db.py -q title
# python KJZZ-db.py -q chunkLast10 -p
# python KJZZ-db.py -g chunk="KJZZ_2023-10-13_Fri_1700-1730_All Things Considered" -v --wordCloud
# python KJZZ-db.py -g title="All Things Considered" -v --wordCloud
# python KJZZ-db.py -g title="All Things Considered" -v --wordCloud
# python KJZZ-db.py -g title="All Things Considered" -v --wordCloud
# python KJZZ-db.py -g title="BBC Newshour" -v --wordCloud
# python KJZZ-db.py -g title="BBC World Business Report" -v --wordCloud
# python KJZZ-db.py -g title="BBC World Service" -v --wordCloud
# python KJZZ-db.py -g title="Fresh Air" -v --wordCloud
# python KJZZ-db.py -g title="Here and Now" -v --wordCloud
# python KJZZ-db.py -g title="Marketplace" -v --wordCloud
# python KJZZ-db.py -g title="Morning Edition" -v --wordCloud
# python KJZZ-db.py -g title="The Show" -v --wordCloud
# python KJZZ-db.py -g week=42+Day=Mon+title="The Show" -v --wordCloud --stopLevel 3
# python KJZZ-db.py -g week=42+Day=Mon+title="All Things Considered" --wordCloud --stopLevel 3 --show
# python KJZZ-db.py -g week=42 --wordCloud --stopLevel 3 --show --max_words=10000
# python KJZZ-db.py -g week=43 --wordCloud --stopLevel 3 --show --max_words=10000
# python KJZZ-db.py -g week=44 --wordCloud --stopLevel 3 --show --max_words=1000 --inputStopWordsFiles data\stopWords.ranks.nl.uniq.txt --inputStopWordsFiles data\stopWords.Wordlist-Adjectives-All.txt
# python KJZZ-db.py -g week=43+title="TED Radio Hour" --wordCloud --stopLevel 3 --show --max_words=1000 --inputStopWordsFiles data\stopWords.ranks.nl.uniq.txt --inputStopWordsFiles data\stopWords.Wordlist-Adjectives-All.txt
# example: week=42+title="Freakonomics"+Day=Sun is about men/women
# python KJZZ-db.py -g week=42+title="Freakonomics"+Day=Sun --wordCloud --stopLevel 3 --show --max_words=1000 --inputStopWordsFiles data\stopWords.ranks.nl.uniq.txt --inputStopWordsFiles data\stopWords.Wordlist-Adjectives-All.txt
# for /l %a in (40,1,45) DO python KJZZ-db.py -g week=%a+title="TED Radio Hour" --wordCloud --stopLevel 3 --show --max_words=1000 --inputStopWordsFiles data\stopWords.ranks.nl.uniq.txt --inputStopWordsFiles data\stopWords.Wordlist-Adjectives-All.txt
# python KJZZ-db.py -g week=42+title="Freakonomics"+Day=Sun --wordCloud --stopLevel 3 --show --max_words=1000 --inputStopWordsFiles data\stopWords.ranks.nl.uniq.txt --inputStopWordsFiles data\stopWords.Wordlist-Adjectives-All.txt
# python KJZZ-db.py --gettext week=42+title="Morning Edition"+Day=Mon --misInformation --graph pie --show
# python KJZZ-db.py --gettext week=42+title="Morning Edition"+Day=Mon --misInformation --noMerge --show
# python KJZZ-db.py --html 42 --byChunk
# python KJZZ-db.py --rebuildThumbnails 41
# for /l %a in (40,1,47) DO python KJZZ-db.py --html %a --autoGenerate --inputStopWordsFiles data\stopWords.ranks.nl.uniq.txt --inputStopWordsFiles data\stopWords.Wordlist-Adjectives-All.txt
# TODO: enable closed-captions by default: nothing works, asked on stackoverflow
# similar question: https://stackoverflow.com/questions/17247931/video-js-how-do-i-make-subtitle-visible-by-default
# my question: https://stackoverflow.com/questions/77581173/how-to-enable-closed-captions-by-default-with-openplayerjs-video-js
# TODO: improve file read fd with list = set(map(str.strip, open(os.path.join(inputFolder, fileName)).readlines()))
# TODO: somehow find way to always include --inputStopWordsFiles data\stopWords.ranks.nl.uniq.txt --inputStopWordsFiles data\stopWords.Wordlist-Adjectives-All.txt
# TODO: add --force to regenerate existing pictures
# TODO: handle same program at differnt time of the day such as Sat: BBC World Service morning and evening - currently we can only generate one same wordCloud for both
# TODO: heatMap: do we keep stopWords or not, brfore the counting occurs?
# TODO: https://github.com/auroracramer/language-model-bias
# TODO: export all configuration into external json files or yaml
# TODO: explore stopWords from https://github.com/taikuukaits/SimpleWordlists/
# TODO: analyse gender bias
# TODO: analyse language bias
# egrep -i "trans[gsv]|\bgay\b|\blesb|\bbisex|\btransg|\bqueer|gender|LGBT" *text
# egrep -i "diversity|equity|inclusion" *text
import getopt, sys, os, re, regex, io, inspect, string, copy
import glob, time, datetime, json, urllib, random, sqlite3
from dateutil import parser
from pathlib import Path
from collections import Counter
# 3rd party modules:
# https://github.com/Textualize/rich
from rich import print
from rich.progress import track, Progress
# we do not preload this bunch unless we need them:
# -------------------------------------------------
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
# import matplotlib.dates as mdates
# from matplotlib import style
# from matplotlib.patches import Rectangle
# import seaborn
# import pngquant
# pngquant.config(min_quality=1, max_quality=20, speed=1, ndeep=2)
# -------------------------------------------------
# def root():
# parent()
# def parent():
# child()
# def child(stack=''):
# for i in reversed(range(0, len(inspect.stack())-1)): stack += "%s: " %(inspect.stack()[i][3])
# print("%s: " %(stack))
# # example of progress bar:
# with Progress() as progress:
# task = progress.add_task("twiddling thumbs", total=10)
# inputFiles = [1,2,3,4,5,6,7,8,9,0]
# for inputFile in inputFiles:
# progress.console.print(f"Working on job #{inputFile}")
# time.sleep(0.2)
# progress.advance(task)
# exit()
verbose = 1
progress = ""
importChunks = False
inputFolder = None
inputFiles = []
inputJsonFile = None
inputTextFile = None
localSqlDb = Path("kjzz.db")
# the db connection is global
conn = None
model = "small"
sqlQuery = None
pretty = False
wordCloud = False
misInformation = False
gettext = None
listTitleWords2Exclude = ["Jazz", "Blues"]
gettextKeys = ["date", "datetime", "week", "Day", "time", "title", "chunk"]
gettextDict = {}
mergeRecords = True
removeStopwords = True
showPicture = False
inputStopWords = []
outputFolder = Path("./kjzz")
dataFolder = Path("./data")
thesaurusFolder = Path("./data/SimpleWordlists")
graphs = [] # bar pie line
weekNumber = 0
jsonScheduleFile = os.path.realpath("kjzz/KJZZ-schedule.json")
indexTemplateFile = os.path.realpath("kjzz/index_template.html")
indexFile = os.path.realpath("kjzz/index.html")
byChunk = False
printOut = False
listLevel = []
silent = False
autoGenerate = False
dryRun = False
noPics = False
missingPic = "../missingPic.png"
missingCloud = "../missingCloud.png"
voidPic = "../1x1.png"
rebuildThumbnail = False
usePngquant = True
useJpeg = False
jpegQuality = 50
force = False
# when uncertainty/sourcing >= BSoMeterTrigger then highlight it
BSoMeterTrigger = 0.9
BSoMeterLevel2 = 0.93
defaultGraphs = ["bar", "pie"]
withSynonyms = True
minChunkSize = 20000
dictHeatMapBlank = {
"explanatory":{"words":set(),"heatCount":0,"heat":None},
"retractors":{"words":set(),"heatCount":0,"heat":None},
"sourcing":{"words":set(),"heatCount":0,"heat":None},
"uncertainty":{"words":set(),"heatCount":0,"heat":None},
}
# busybox sed -E "s/^.{,3}$//g" stopWords.ranks.nl.txt | busybox sort | busybox uniq >stopWords.ranks.nl.txt
# wordcloud internal STOPWORDS: https://github.com/amueller/word_cloud/blob/main/wordcloud/stopwords
# https://www.ranks.nl/stopwords
# https://gist.github.com/sebleier/554280
# https://github.com/taikuukaits/SimpleWordlists/blob/master/Wordlist-Adjectives-All.txt
# wget https://raw.githubusercontent.com/taikuukaits/SimpleWordlists/master/Wordlist-Adjectives-All.txt -OstopWords.Wordlist-Adjectives-All.txt
stopLevel = 3
# after merging 0+1 we get this:
# stopwordsDict = {
# 0: ['up', 'ever', 'yourself', 'therefore', 'cannot', 'could', 'new', "they've", 'theirs', "who's", 'u', 'an', 'am', 'get', 're', 'where', 'herself', 'same', 'was', "you'd", 'www', 'some', 'through', 'each', 'himself', 'once', 'me', 'have', 'our', 'this', 'or', "i'm", 'they', "hasn't", 'which', 'why', 'to', "how's", 'can', 'com', 'we', 'did', 'yours', 'the', "we're", 'more', 'shall', 'about', 'are', 'so', "they're", "he'd", 'otherwise', 'below', 'else', 'further', 'has', 'most', 'ours', 'ourselves', "why's", 'a', 'at', "we'd", 'between', "isn't", 'that', 'one', 'since', "doesn't", 'her', 'into', 'k', "couldn't", 'before', "she'd", "wasn't", 'it', "don't", 'during', 'only', 'hers', "when's", "shouldn't", "she's", 'in', 'my', 'no', 'however', 'r', "they'll", 'above', 'if', 'he', 'of', 'how', 'over', 'say', 'whom', "we've", "here's", 'been', "hadn't", 's', 'be', 'these', 'own', 'both', 'doing', 'itself', 'but', 'against', 'ought', 'http', 'nor', "weren't", "he's", 'does', 'i', 'and', "what's", "wouldn't", 'myself', 'just', 'out', "they'd", 'on', 'than', 'hence', 'themselves', 'then', 'very', "we'll", 'she', "it's", "you'll", 'its', 'is', "let's", 'were', "won't", 'what', 'by', "that's", 'again', 'had', 'too', "mustn't", "i've", "there's", 'as', "she'll", 'few', 'being', 'when', "aren't", 'should', "shan't", 'all', 'under', 'your', 'here', 'down', 'with', 'also', 'after', "you're", 'like', 'you', "where's", 'not', 'any', 'him', 'until', "you've", 'says', "didn't", 'such', "i'd", "i'll", 'them', 'do', 'while', "haven't", 'there', 'their', 'who', 'because', "he'll", "can't", 'from', 'having', 'for', 'off', 'other', 'would', 'those', 'yourselves', 'his'],
# }
# build from https://github.com/amueller/word_cloud/blob/master/wordcloud/wordcloud.py
wordCloudDict = {
"max_words": {
"input": True,
"default": 200,
"value": 1000,
"usage": "int (default=1000)\n The maximum number of words in the Cloud.",
},
"width": {
"input": True,
"default": 400,
"value": 2000,
"usage": "int (default=2000)\n Width of the canvas.",
},
"height": {
"input": True,
"default": 200,
"value": 1000,
"usage": "int (default=1000)\n Height of the canvas.",
},
"min_word_length": {
"input": True,
"default": 0,
"value": 3,
"usage": "int, default=3\n Minimum number of letters a word must have to be included.",
},
"min_font_size": {
"input": True,
"default": 4,
"value": 4,
"usage": "int (default=4)\n Smallest font size to use. Will stop when there is no more room in this size.",
},
"max_font_size": {
"input": True,
"default": 0,
"value": 400,
"usage": " int or None (default=400)\n Maximum font size for the largest word. If None, height of the image is used.",
},
"scale": {
"input": True,
"default": 1.0,
"value": 1.0,
"usage": "float (default=1.0)\n Scaling between computation and drawing. For large word-cloud images,\n using scale instead of larger canvas size is significantly faster, but\n might lead to a coarser fit for the words.",
},
"relative_scaling": {
"input": True,
"default": 0.0,
"value": 'auto',
"usage": "float (default='auto')\n Importance of relative word frequencies for font-size. With\n relative_scaling=0, only word-ranks are considered. With\n relative_scaling=1, a word that is twice as frequent will have twice\n the size. If you want to consider the word frequencies and not only\n their rank, relative_scaling around .5 often looks good.\n If 'auto' it will be set to 0.5 unless repeat is true, in which\n case it will be set to 0.",
},
"background_color": {
"input": True,
"default": 'black',
"value": 'white',
"usage": "color value (default='white')\n Background color for the word cloud image.",
},
"normalize_plurals": {
"input": True,
"default": True,
"value": True,
"usage": "bool, default=True\n Whether to remove trailing 's' from words. If True and a word\n appears with and without a trailing 's', the one with trailing 's'\n is removed and its counts are added to the version without\n trailing 's' -- unless the word ends with 'ss'. Ignored if using\n generate_from_frequencies.",
},
"inputStopWordsFiles": {
"input": True,
"default": [],
"value": [],
"usage": "file, default=None\n Text file containing one stopWord per line.\n You can pass --inputStopWordsFiles multiple times.",
},
"inputStopWords": {
"input": False,
"default": [],
"value": [],
"usage": "list, default=[]\n Consolidated list of stopWords from inputStopWordsFiles.",
},
"font_path": {
"input": True,
"default": None,
"value": "fonts\\Quicksand-Bold.ttf",
"usage": "str, default='fonts\\Quicksand-Bold.ttf'\n Font path to the font that will be used (OTF or TTF).",
},
"collocation_threshold": {
"input": True,
"default": 30,
"value": 30,
"usage": "int, default=30\n Bigrams must have a Dunning likelihood collocation score greater than this\n parameter to be counted as bigrams. Default of 30 is arbitrary.\n See Manning, C.D., Manning, C.D. and Schütze, H., 1999. Foundations of\n Statistical Natural Language Processing. MIT press, p. 162\n https://nlp.stanford.edu/fsnlp/promo/colloc.pdf#page=22",
},
}
sqlListLast10text = """ SELECT text from schedule LIMIT 10 """
sqlLastText = """ SELECT text from schedule LIMIT 1 """
sqlFirstText = """ SELECT text from schedule ORDER BY start DESC LIMIT 1 """
# BUG: what we want is order by iso week day = %u but only %w (Sunday first) works
sqlCountsByDay = """ SELECT Day, title, count(start)
from schedule
GROUP BY Day, title
ORDER BY strftime('%w',start)
"""
# [
# ('Fri', 'All Things Considered', 5),
# ('Fri', 'BBC Newshour', 2),
# ('Fri', 'BBC World Service', 4),
# ('Fri', 'Here and Now', 4),
# ('Fri', 'Morning Edition', 12),
# ('Fri', 'Science Friday', 2),
# ('Fri', 'The Show', 2),
sqlTitles = """ SELECT title
from schedule
GROUP BY title
ORDER BY title, strftime('%w',start)
"""
sqlCountsByTitle = """ SELECT title, Day, count(title)
from schedule
GROUP BY title, Day
ORDER BY title, strftime('%w',start)
"""
# [
# ('All Things Considered', 'Fri', 5),
# ('All Things Considered', 'Thu', 6),
# ('All Things Considered', 'Tue', 1),
# ('All Things Considered', 'Wed', 6),
# ('BBC Newshour', 'Fri', 2),
# spit out chunk names, useful list what's available
# KJZZ_2023-10-09_Mon_0000-0030_BBC World Service
# https://www.sqlite.org/lang_datefunc.html
# https://www.sqlshack.com/sql-convert-date-functions-and-formats/
# python KJZZ-db.py -q chunkLast10 -p
# %w day of week 0-6 with Sunday==0 but we want Mon Tue etc
sqlListChunksLast10 = """ SELECT 'KJZZ_' || strftime('%Y-%m-%d_%w_%H%M-',start) || strftime('%H%M_',stop) || title
from schedule
ORDER BY start DESC
LIMIT 10
"""
# [
# ('KJZZ_2023-10-13_41_1700-1730_All Things Considered',),
# ('KJZZ_2023-10-13_41_1630-1700_All Things Considered',),
# ('KJZZ_2023-10-13_41_1600-1630_All Things Considered',),
# ('KJZZ_2023-10-13_41_1530-1600_All Things Considered',),
# ('KJZZ_2023-10-13_41_1500-1530_All Things Considered',),
# ('KJZZ_2023-10-13_41_1330-1400_BBC Newshour',),
sqlCountsByWord = """ SELECT title, Day, count(start)
from schedule
GROUP BY title, Day
ORDER BY title
"""
# [
# ('All Things Considered', 'Fri', 5), <- insert word count after the 5
# ('All Things Considered', 'Thu', 6),
# ('All Things Considered', 'Tue', 1),
# ('All Things Considered', 'Wed', 6),
# ('BBC Newshour', 'Fri', 2),
# https://www.datacamp.com/tutorial/wordcloud-python
# https://github.com/amueller/word_cloud/blob/main/examples/simple.py
class TimeDict:
def __init__(self, dateTime):
# dateTime = YYYY-MM-DD HH:MM:SS.SSS
self.dateTime = dateTime
self.split = re.split(r"[ -]", dateTime) # ['2023', '10', '09', 'HH:MM:SS.SSS']
self.week = datetime.date(int(self.split[0]),int(self.split[1]),int(self.split[2])).isocalendar().week
self.YYYYMMDD = dateTime[:10]
self.Day = datetime.date(int(self.split[0]),int(self.split[1]),int(self.split[2])).strftime('%a')
self.time = self.split[3]
self.HHMM = self.split[3][:5]
# class TimeDict
class Chunk:
def __init__(self, inputFile, model=model, loadText=True, progress=""):
self.inputFile = Path(inputFile)
self.model = model
self.dirname = os.path.dirname(self.inputFile)
self.basename = os.path.basename(self.inputFile)
self.stem = Path(self.basename).stem
self.ext = Path(self.basename).suffix
self.split = re.split(r"[_-]", self.stem) # ['KJZZ', '2023', '10', '09', 'Mon', '1330', '1400', 'BBC Newshour']
if len(self.split) != 8:
raise ValueError("Chunk: invalid name: %s" % (self.inputFile))
self.week = datetime.date(int(self.split[1]),int(self.split[2]),int(self.split[3])).isocalendar().week
self.YYYYMMDD = '-'.join([self.split[1],self.split[2],self.split[3]])
self.Day = self.split[4]
# we want YYYY-MM-DD HH:MM:SS.SSS
self.startHHMM = ':'.join([self.split[5][:2],self.split[5][2:]])
self.startTime = ':'.join([self.split[5][:2],self.split[5][2:]]) + ":00.000"
self.start = ' '.join([self.YYYYMMDD, self.startTime])
self.stopHHMM = ':'.join([self.split[6][:2],self.split[6][2:]])
self.stopTime = ':'.join([self.split[6][:2],self.split[6][2:]]) + ":00.000"
self.stop = ' '.join([self.YYYYMMDD, self.stopTime])
self.title = self.split[-1]
# generally for 30mn chunks, text files are 25k on average
if os.path.isfile(self.inputFile):
self.size = os.path.getsize(self.inputFile)
if self.size < minChunkSize:
warning("%s [%.1fk] small size is sus" %(self.inputFile, self.size/1024), 0, progress)
if loadText:
with open(self.inputFile, 'r', encoding="utf-8") as pointer:
# with io.open(self.inputFile, mode="r", encoding="utf-8") as pointer:
# separate sentences properly:
text = pointer.read().replace('\n',' ')
self.text = text.replace('. ','.\n')
# ddebug(self.text)
else:
raise ValueError("Chunk: file not found: %s" % (self.inputFile))
# class Chunk
# TODO: update table for missing columns when this script is updated
# TODO: defind columns in a dict and compare to records from this command:
# pragma table_info('schedule')
# 0 start TEXT 0 1
# 1 stop TEXT 1 0
# 2 week INTEGER 0 0
# 3 day TEXT 1 0
# 4 title TEXT 1 0
# 5 text TEXT 0 0
# 6 model TEXT 0 0
# TODO: check indexes exist and create them if not:
# SELECT * FROM sqlite_master WHERE type= 'index' and tbl_name = 'schedule' and name = 'IFK_ScheduleStartStop';
# index IFK_ScheduleStartStop schedule 13436 CREATE UNIQUE INDEX "IFK_ScheduleStartStop" ON "schedule" (
# "start",
# "stop"
# )
# TEST if index is used: https://stackoverflow.com/questions/35625812/sqlite-use-autoindex-instead-my-own-index
# analyze schedule;
# explain query plan SELECT start, text from schedule where 1=1 and week = 40 and title = 'Classic Jazz with Chazz Rayburn' and Day = 'Mon';
# 4 0 0 SEARCH TABLE schedule USING INDEX IFK_ScheduleWeekTitleDay (week=? AND title=? AND day=?)
# yes it is!!!
# If you use the TEXT storage class to store date and time value, you need to use the ISO8601 string format as follows:
# YYYY-MM-DD HH:MM:SS.SSS
def db_init(localSqlDb):
localSqlDb.touch()
# localSqlDb.unlink()
conn = sqlite3.connect(localSqlDb)
cur = conn.cursor()
queryScheduleTable = """
CREATE TABLE schedule (
start TEXT PRIMARY KEY
, stop TEXT NOT NULL
, week INTEGER
, Day TEXT NOT NULL
, title TEXT NOT NULL
, text TEXT
, model TEXT
, misInfo TEXT
);
CREATE UNIQUE INDEX [IFK_ScheduleStartStop] ON "schedule" ([start],[stop]);
CREATE INDEX [IFK_ScheduleWeekTitleDay] ON "schedule" ([week],[title],[Day]);
"""
try:
cur.execute(queryScheduleTable)
info("queryScheduleTable %s: success" %(localSqlDb), 1)
except Exception as error:
if not str(error).find("already exists"):
info("queryScheduleTable %s: %s" %(localSqlDb, error), 1)
else:
records = cursor(localSqlDb, conn, """SELECT count(start) from schedule""")
info("%s chunks found in schedule %s" %(records[0][0], localSqlDb), 1)
queryStatsTable = """
CREATE TABLE statistics (
week INTEGER NOT NULL
, Day TEXT NOT NULL
, title TEXT NOT NULL
, top100tuples TEXT
, PRIMARY KEY (week, day, title)
);
"""
try:
cur.execute(queryStatsTable)
info("queryStatsTable %s: success" %(localSqlDb), 1)
except Exception as error:
if not str(error).find("already exists"):
info("queryStatsTable %s: %s" %(localSqlDb, error), 1)
else:
records = cursor(localSqlDb, conn, """SELECT count(*) from statistics""")
info("%s lines found in statistics %s" %(records[0][0], localSqlDb), 1)
return conn
#
#
# with Progress() as progress:
# task = progress.add_task("twiddling thumbs", total=10)
# inputFiles = [1,2,3,4,5,6,7,8,9,0]
# for inputFile in inputFiles:
# progress.console.print(f"Working on job #{inputFile}")
# time.sleep(0.2)
# progress.advance(task)
def db_update(table, column, value, textConditions, localSqlDb, conn, commit, progress=""):
# db_update('schedule', 'misInfo', str(misInfo), textConditions, localSqlDb, conn)
if not conn:
conn = sqlite3.connect(localSqlDb)
# if isinstance(value,str):
sqlText = """ UPDATE ${table} SET ${column}='${value}' where 1=1 ${textConditions}; """
sql = string.Template((sqlText)).substitute(dict(table=table, column=column, value=value, textConditions=textConditions))
info(sql, 3, progress)
# records is always [] for an update
records = cursor(localSqlDb, conn, sql)
if commit and not dryRun: conn.commit()
# db_update
def db_load(inputFiles, localSqlDb, conn, model, commit, progress=""):
importedFiles = []
if inputFiles:
info("%s files found" %(len(inputFiles)), 1)
if not conn:
conn = sqlite3.connect(localSqlDb)
# tentative to use BEGIN+COMMIT to speed up loading at the expense of memory
# sqlLoad = """ BEGIN; """
with Progress() as progress:
task = progress.add_task("Loading inputFiles", total=len(inputFiles))
# KJZZ_2023-10-08_Sun_2300-2330_BBC World Service.text
for inputFile in inputFiles:
info('Chunk init: "%s"' % (inputFile), 3, progress)
try:
# first we do not read the file:
chunk = Chunk(inputFile, model, False, progress)
# time.sleep(0.2)
except Exception as error:
error('Chunk error: "%s": %s' % (chunk.basename, error), 11)
# check if exist in db:
sqlCheck = """ SELECT * from schedule where start = ?; """
records = cursor(localSqlDb, conn, sqlCheck, (chunk.start,), progress)
# exit()
if len(records) == 0 or force:
# recreate chunk and actually read the file:
try:
chunk = Chunk(inputFile, model, True, progress)
info('Chunk read: "%s" [%.1fk]' % (chunk.basename, chunk.size/1024), 3, progress)
# time.sleep(0.2)
except Exception as error:
error('Chunk error: "%s": %s' % (chunk.basename, error), 11)
# load Chunk in db:
if len(records) == 0:
sqlLoad = """ INSERT INTO schedule(start, stop , week, Day, title, text, model) VALUES(?,?,?,?,?,?,?); """
records = cursor(localSqlDb, conn, sqlLoad, (chunk.start, chunk.stop , chunk.week, chunk.Day, chunk.title, chunk.text, chunk.model), progress)
else:
# you can only use ? in this case: VALUES(?,?,?,?,?,?,?) - not in a WHERE clause or anything else
sqlUpdate = """ UPDATE schedule set (text, model) = (?,?) WHERE start = '%s'; """ %(chunk.start)
records = cursor(localSqlDb, conn, sqlUpdate, (chunk.text, chunk.model), progress)
importedFiles += [inputFile]
info('Chunk imported: "%s" [%.1fk]' % (chunk.basename, chunk.size/1024), 2, progress)
else:
info('Chunk exist: "%s"' % (chunk.basename), 2, progress)
progress.advance(task)
# BEGIN+COMMIT cannot work like this unfortunately: You can only execute one statement at a time.
# records = cursor(localSqlDb, conn, sqlLoad, None, progress)
if commit and not dryRun: conn.commit()
info("Done loading %s/%s files" %(len(importedFiles), len(inputFiles)), 1, progress)
#
def cursor(localSqlDb, conn, sql, data=None, progress=""):
if not conn:
conn = sqlite3.connect(localSqlDb)
cur = conn.cursor()
records = []
try:
if data is not None:
info("cur.execute(%s) ... %s ..." %(sql, data[0]), 4, progress)
# ddebug(sql, data)
cur.execute(sql, data)
else:
info("cur.execute(%s) ..." %(sql), 4, progress)
cur.execute(sql)
records = cur.fetchall()
info("%s records" %(len(records)), 4, progress)
except Exception as error:
error("cur.execute(%s) ..." %(sql))
error("%s" %(error))
return records
#
def sqlQueryPrintExec(sqlQuery, pretty=pretty):
info("sqlQuery: %s" % (sqlQuery), 2)
records = cursor(localSqlDb, conn, sqlQuery)
# SQLite: %w = day of week 0-6 with Sunday==0
# But we want Mon Tue etc so we replace text in each tuple.
# Oh yeah, sqlite3 fetchall returns a list of tuples.
# Each record is a tuple: ('KJZZ_2023-10-13_5_1630-1700_All Things Considered',),
if sqlQuery.find('_%w_') > -1:
# replaceNum2Days will output the same input format: str or tuple: 0->Sun 1->Mon etc
# What we should do is grab the recursive replace function I wrote 10 years ago, pfff where is it
records = [replaceNum2Days(record) for record in records]
# records[0] = map(lambda x: str.replace(x, "[br]", "<br/>"), records[0])
if pretty:
for record in records:
print(('"%s"') %(record))
else:
print(records)
#
return records
#
# # this works only with full key replacement
# subs = { "Houston": "HOU", "L.A. Clippers": "LAC", }
# my_lst = ['LAC', 'HOU', '03/03 06:11 PM', '2.13', '1.80', 'LAC']
# my_lst[:] = map(dict(zip(subs.values(), subs)).get, my_lst[:])
# print (my_lst)
# # just started modifying but this is impossible
# invertWeekDays = { "Sun": "_0_", "Mon": "_1_", "Tue": "2", "Wed": "3", "Thu": "4", "Fri": "5", "Sat": "6", }
# my_lst = ['zzz_0_xxx', 'yy_1_33', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']
# my_lst = map(dict(zip(invertWeekDays.values(), invertWeekDays)).get, my_lst)
# print(my_lst)
def replaceNum2Days(record):
# crap multi replace function but it's cheap
if isinstance(record,str):
newRecord = record
else:
newRecord = record[0]
newRecord = newRecord.replace('_0_','_Sun_')
newRecord = newRecord.replace('_1_','_Mon_')
newRecord = newRecord.replace('_2_','_Tue_')
newRecord = newRecord.replace('_3_','_Wed_')
newRecord = newRecord.replace('_4_','_Thu_')
newRecord = newRecord.replace('_5_','_Fri_')
newRecord = newRecord.replace('_6_','_Sat_')
if isinstance(record,str):
return newRecord
else:
return (newRecord,)
#
def checkChunk(getTextDict, progress=""):
# gettextDict = {'start': '%Y-%m-%d %H:%M'}
# gettextDict = {'week': '40', 'title': 'Classic Jazz with Chazz Rayburn', 'Day': 'Mon'}
sqlGettext = "SELECT count(*) from schedule where 1=1"
# build the actual query
for key in gettextDict.keys():
# build the SQL query:
sqlGettext += (" and %s = '%s'" % (key, gettextDict[key]))
# reformat start time for the fileName: chunk has been build if the key is "chunk"
if key == "start":
gettextDict[key] = parser.parse(gettextDict[key]).strftime("%Y-%m-%d %H:%M")
info("sqlGettext: %s" %(sqlGettext), 3, progress)
records = cursor(localSqlDb, conn, sqlGettext)
if len(records) == 0:
info("0 records for %s" %(gettextDict), 4, progress)
return records[0][0]
# gettext
# the db has: start stop week day title text model misInfo
# and we want: start stop KJZZ_YYYY-mm-DD_Ddd_HHMM-HHMM_Title misInfo
def getChunks(getTextDict, withText=False, progress=""):
# gettextDict = {'start': '%Y-%m-%d %H:%M'}
# gettextDict = {'week': '40', 'title': 'Classic Jazz with Chazz Rayburn', 'Day': 'Mon'}
selectText = ''
if withText: selectText = ', text'
textConditions = ''
for column, value in gettextDict.items():
textConditions += " and %s='%s'" %(column, value)
# strftime('%%H:%%M',start)
# , strftime('%%H:%%M',stop)
# let's return actual times instead, it's more useful
sqlListChunks = """ SELECT
start
, stop
, 'KJZZ_' || strftime('%%Y-%%m-%%d_',start) || Day || strftime('_%%H%%M-',start) || strftime('%%H%%M_',stop) || title
, misInfo
%s
from schedule
where 1=1
%s
ORDER BY start ASC;
""" %(selectText, textConditions)
info("sqlListChunks: %s" %(sqlListChunks), 4, progress)
records = cursor(localSqlDb, conn, sqlListChunks)
if len(records) == 0:
info("0 records for %s" %(gettextDict), 3, progress)
return records
# records = [
# ('2023-10-14 01:00.000', '2023-10-14 01:30.000', 'KJZZ_2023-10-14_Sat_0100-0130_BBC World Service', '[0.7, 0.4, 0.4, 2.9]'),
# ('2023-10-14 01:30.000', '2023-10-14 02:00.000', 'KJZZ_2023-10-14_Sat_0130-0200_BBC World Service', '[0.7, 0.4, 0.4, 2.9]', 'text...'),
# ...
# gettext
def printOutGetText(records, mergeRecords, pretty, dryRun):
if mergeRecords:
mergedText = ''
for record in records: mergedText += record[1]
if pretty:
print(('"%s"') %(mergedText))
else:
print(mergedText)
else:
for record in records:
if pretty:
print(('"%s"') %(record[1]))
else:
print(record)
#
def genWordClouds(records, wordCloudTitle, mergeRecords, showPicture, wordCloudDict, outputFolder=outputFolder, dryRun=False, progress=""):
# gettext = "week=43+title=Classic Jazz with Chazz Rayburn+Day=Mon"
# gettextDict = {'week': '43', 'title': 'Classic Jazz with Chazz Rayburn', 'Day': 'Mon'}
# records = (('2023-10-14 01:00.000', '2023-10-14 01:30.000', 'KJZZ_2023-10-14_Sat_0100-0130_BBC World Service', '[0.7, 0.4, 0.4, 2.9]', 'text...'),..)
# wordCloudTitle = "KJZZ week=43 title=BBC World Service Day=Sat"
if len(records) == 0: return []
genWordCloudDicts = []
mergedText = ''
if mergeRecords:
for record in records: mergedText += record[4]
genWordCloudDicts.append(genWordCloud(mergedText, wordCloudTitle, removeStopwords, stopLevel, wordCloudDict, showPicture, outputFolder, dryRun, progress))
else:
i = 1
for record in records:
info("wordCloud: image %s" % (i), 1, progress)
info("wordCloud: record = \n %s" %(record), 2, progress)
genWordCloudDicts += genWordCloud(record[4], wordCloudTitle, removeStopwords, stopLevel, wordCloudDict, showPicture, outputFolder, dryRun, progress)
i += 1
return genWordCloudDicts
# wordCloud
def genWordCloud(text, wordCloudTitle, removeStopwords=True, level=0, wordCloudDict=wordCloudDict, showPicture=False, outputFolder=outputFolder, dryRun=False, progress=""):
# wordCloudTitle = "KJZZ week=43 title=BBC World Service Day=Sat"
info("Now generating: %s" %(wordCloudTitle), 2, progress)
import numpy as np
import pandas as pd
import matplotlib
# https://stackoverflow.com/questions/27147300/matplotlib-tcl-asyncdelete-async-handler-deleted-by-the-wrong-thread
if not showPicture: matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style
from matplotlib.patches import Rectangle
import seaborn
from wordcloud import WordCloud
# from wordcloud import STOPWORDS
# print(STOPWORDS)
genWordCloudDict = {
"cleanWordsList": [],
"fileName": "",
"level": level,
"numWords": 0,
"outputFile": "",
"removeStopwords": removeStopwords,
"stopWords": [],
"text": text,
"top100tuples": [],
"wordCloudDict": wordCloudDict,
"wordCloudTitle": "",
"wordCloudTitle": wordCloudTitle,
"wordsList": [],
}
# https://github.com/amueller/word_cloud/blob/main/examples/simple.py
# we start by removing words from the wordCloudTitle of the show itself
# for a typical week schedule, normally wordCloudTitle would be == "KJZZ week= title= Day="
genWordCloudDict["stopWords"] = wordCloudTitle.replace("=", " ").split()
genWordCloudDict["wordsList"] = text.split()
genWordCloudDict["numWords"] = len(genWordCloudDict["wordsList"])
genWordCloudDict["wordCloudTitle"] = "%s words=%s maxw=%s minf=%s maxf=%s scale=%s relscale=%s" % (
genWordCloudDict["wordCloudTitle"],
genWordCloudDict["numWords"],
wordCloudDict["max_words"]["value"],
wordCloudDict["min_font_size"]["value"],
wordCloudDict["max_font_size"]["value"],
wordCloudDict["scale"]["value"],
wordCloudDict["relative_scaling"]["value"],
)
genWordCloudDict["fileName"] = genWordCloudDict["wordCloudTitle"].replace(": ", "=").replace(":", "")
genWordCloudDict["outputFileName"] = ""
genWordCloudDict["outputFile"] = ""
if dryRun: return genWordCloudDict
if removeStopwords:
stopwordsDict = loadStopWordsDict()
for i in range(level + 1): genWordCloudDict["stopWords"] += stopwordsDict[i]
genWordCloudDict["stopWords"] += wordCloudDict["inputStopWords"]["value"]
# print(len(STOPWORDS))
# STOPWORDS.update(genWordCloudDict["stopWords"]) # STOPWORDS is now listLevel 0 == stopwordsDict[0]
# print(len(STOPWORDS))
# print(len(stopWords))
# print(stopWords)
# WordCloud can remove stopWords by itself just fine, but we do it just have a count
info("most 10 common words before: \n%s" % (Counter(genWordCloudDict["wordsList"]).most_common(10)), 2, progress)
genWordCloudDict["cleanWordsList"] = [word for word in re.split("\W+",text) if word.lower() not in genWordCloudDict["stopWords"]]
info("most 10 common words after: \n%s" % (Counter(genWordCloudDict["cleanWordsList"]).most_common(10)), 2, progress)
genWordCloudDict["top100tuples"] = Counter(genWordCloudDict["cleanWordsList"]).most_common(100)
info("%s words - %s stopWords (%s words removed) == %s total words" %(genWordCloudDict["numWords"], len(genWordCloudDict["stopWords"]), genWordCloudDict["numWords"] - len(genWordCloudDict["cleanWordsList"]), len(genWordCloudDict["cleanWordsList"])), 2, progress)
info("stopWords = %s" %(str(genWordCloudDict["stopWords"])), 3, progress)
else:
info("%s words" %(genWordCloudDict["numWords"]), 1, progress)
# image 1: Display the generated image:
# font_path="fonts\\Quicksand-Regular.ttf"
# class WordCloud: https://github.com/amueller/word_cloud/blob/fa7ac29c6c96c713f51585818e289e8f99c0f211/wordcloud/wordcloud.py#L154C25-L154C25
wordcloud = WordCloud(
stopwords=genWordCloudDict["stopWords"],
background_color=wordCloudDict["background_color"]["value"],
max_words=wordCloudDict["max_words"]["value"],
width=wordCloudDict["width"]["value"],
height=wordCloudDict["height"]["value"],
relative_scaling=wordCloudDict["relative_scaling"]["value"],
normalize_plurals=wordCloudDict["normalize_plurals"]["value"],
font_path=wordCloudDict["font_path"]["value"],
min_word_length=wordCloudDict["min_word_length"]["value"],
min_font_size=wordCloudDict["min_font_size"]["value"],
max_font_size=wordCloudDict["max_font_size"]["value"],
scale=wordCloudDict["scale"]["value"],
collocation_threshold=wordCloudDict["collocation_threshold"]["value"],
).generate(text)
# wordcloud.generate_from_frequencies(Counter(genWordCloudDict["cleanWordsList"]))
# stopwords=genWordCloudDict["stopWords"],
# background_color=wordCloudDict["background_color"]["value"],
# max_words=wordCloudDict["max_words"]["value"],
# width=wordCloudDict["width"]["value"],
# height=wordCloudDict["height"]["value"],
# relative_scaling=wordCloudDict["relative_scaling"]["value"],
# normalize_plurals=wordCloudDict["normalize_plurals"]["value"],
# font_path=wordCloudDict["font_path"]["value"],
# min_word_length=wordCloudDict["min_word_length"]["value"],
# min_font_size=wordCloudDict["min_font_size"]["value"],
# max_font_size=wordCloudDict["max_font_size"]["value"],
# scale=wordCloudDict["scale"]["value"],
# collocation_threshold=wordCloudDict["collocation_threshold"]["value"],
# ).generate_from_frequencies(Counter(genWordCloudDict["cleanWordsList"]))
# # trying to save image + add legend 1
# plt.figure()
# plt.imshow(wordcloud, interpolation='bilinear')
# plt.axis("off")
# # plt.switch_backend('Agg')
# # plt.savefig(genWordCloudDict["wordCloudTitle"] + ".png")
# # trying to save image + add legend 2
# fig, ax = plt.subplots()
# ax.imshow(wordcloud, interpolation='bilinear')
# ax.axis("off")
# # plt.switch_backend('Agg')
# fig.savefig(genWordCloudDict["wordCloudTitle"] + ".png")
# plt.title(genWordCloudDict["wordCloudTitle"])
# # supported values are 'best', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'
# # plt.legend(loc='best', fancybox=True, shadow=True) # does not show in saved file
# # fig.legend(fancybox=True, shadow=True)
# trying to save image + add legend 3 - that one works
# plt.subplots(figsize=(8, 4)) # 800 x 400
plt.subplots(figsize=(20, 10)) # 2000 x 1000
plt.title(genWordCloudDict["wordCloudTitle"])
plt.axis("off")
# plt.subplots_adjust(
# top=0.931,
# bottom=0.049,
# left=0.017,
# right=0.981,
# hspace=0.2,
# wspace=0.2
# )
# plt.tight_layout(pad=1)
# self.layout_ = list(zip(frequencies, font_sizes, positions, orientations, colors))
# print(wordcloud.layout_)
# [
# (('museum', 1.0), 399, (594, 254), None, 'rgb(69, 55, 129)'),
# (('women', 0.92), 383, (32, 286), None, 'rgb(72, 37, 118)'),
# (('stories', 0.88), 375, (247, 345), None, 'rgb(41, 121, 142)'),
# (('history', 0.76), 197, (812, 8), None, 'rgb(54, 92, 141)'),
# (('music', 0.68), 187, (844, 1189), None, 'rgb(59, 82, 139)'),
# (('tree', 0.68), 187, (37, 1611), None, 'rgb(58, 83, 139)'),
# (('find', 0.56), 171, (364, 1672), None, 'rgb(239, 229, 28)'),
# (('hand', 0.56), 171, (820, 781), None, 'rgb(189, 223, 38)'),
# (('project', 0.56), 171, (4, 131), 2, 'rgb(54, 92, 141)'),
# (('records', 0.56), 123, (498, 1539), None, 'rgb(152, 216, 62)'),
# ...
# self.words_ = dict(frequencies)
# print(wordcloud.words_)
# {
# 'museum': 1.0,
# 'women': 0.92,
# 'stories': 0.88,
# 'history': 0.76,
# 'music': 0.68,
# 'tree': 0.68,
# 'find': 0.56,
# 'hand': 0.56,
# 'project': 0.56,
# 'records': 0.56,
# ...
plt.imshow(wordcloud, interpolation='bilinear')
# # image 2: lower max_font_size
# wordcloud = WordCloud(max_font_size=40).generate(text)
# plt.figure()
# plt.imshow(wordcloud, interpolation="bilinear")
# plt.axis("off")
# The pil way (if you don't have matplotlib)
# image = wordcloud.to_image()
# image.show()
# always save BEFORE show
if genWordCloudDict["fileName"]: genWordCloudDict["outputFile"] = saveImage(outputFolder, genWordCloudDict["fileName"], plt, usePngquant, progress)
if genWordCloudDict["outputFile"]:
genWordCloudDict["outputFileName"] = os.path.basename(genWordCloudDict["outputFile"])
genWordCloudDict["outputThumbnailFile"] = saveThumbnail(genWordCloudDict["outputFile"], outputFolder, "thumbnail-" + genWordCloudDict["outputFileName"], usePngquant)
if showPicture: plt.show()
plt.close()
return genWordCloudDict
# genWordCloud
def loadStopWordsDict():
from wordcloud import STOPWORDS
# https://stackoverflow.com/questions/2831212/python-sets-vs-lists
# z=set()
# for word in stopwordsDict[4]:
# if word not in STOPWORDS: z.add(word) --> now you have a cleaned set of words not already in STOPWORDS
# each stopwords list is actually a set. it's faster to check for word in set then in list, or so they say
stopwordsDict = {
0: STOPWORDS,
}
# TODO: what do we do with stopWords.Wordlist-Adjectives-All.txt? it also contains words, not just adjectives
stopWordsFileNames = ['dummy', 'stopWords.1.txt', 'stopWords.kjzz.txt', 'stopWords.ranks.nl.uniq.txt']
for index, stopWordsFileName in enumerate(stopWordsFileNames):
info("index=%s, stopWordsFileName=%s" %(index, stopWordsFileName), 2)
stopWordsFile = os.path.join(dataFolder, stopWordsFileName)
if os.path.isfile(stopWordsFile):
stopwordsDict[index] = set()
with open(stopWordsFile, 'r', encoding="utf-8") as fd:
for line in fd:
word = line.strip()
stopwordsDict[index].add(word)
return stopwordsDict
# loadStopWordsDict
def loadDictHeatMap(dictHeatMap, withSynonyms=withSynonyms):
synonymsFile = os.path.join(thesaurusFolder, 'Thesaurus-Synonyms-Common.txt')
# only the synonyms of sourcing and uncertainty seem to make sense, and look the most closely related
heatFactorSynonymsFor = set({"sourcing", "uncertainty"})
# load the sets of heat words
for heatFactor in dictHeatMap.keys():
heatFactorFile = os.path.join(dataFolder, 'heatMap.'+heatFactor+'.csv')
heatFactorWSynonymsFile = os.path.join(dataFolder, 'heatMap.'+heatFactor+'+synonyms.csv')
synonymsList = set()
# synonyms wanted and available:
if heatFactor in heatFactorSynonymsFor and withSynonyms:
if not force and os.path.isfile(heatFactorWSynonymsFile) and os.path.getsize(heatFactorWSynonymsFile) > os.path.getsize(heatFactorFile):
info("%s: open file %s" %( heatFactor, heatFactorWSynonymsFile), 3)
with open(heatFactorWSynonymsFile, 'r', encoding="utf-8") as fd:
# BUGFIX: split() also splits compound words like "according to" so we resort to .strip().split('\n')
dictHeatMap[heatFactor]["words"].update(fd.read().strip().split('\n'))
else:
# load the whole synonyms file only once
if not synonymsList:
info("%s: open file %s" %( heatFactor, synonymsFile), 3)
with open(synonymsFile, 'r', encoding="utf-8") as fd: synonymsList.update(fd.read().strip().split('\n'))
info("%s: open file %s" %( heatFactor, heatFactorFile), 3)