-
Notifications
You must be signed in to change notification settings - Fork 1
/
AnnA.py
4164 lines (3708 loc) · 180 KB
/
AnnA.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 threading
import pickle
import hashlib
import webbrowser
import textwrap
import traceback
import copy
import beepy
import logging
from logging import handlers
import gc
from datetime import datetime
import time
import random
import signal
import os
import subprocess
import shlex
import json
import urllib.request
import pyfiglet
from pprint import pprint
from tqdm import tqdm
import re
import importlib
from pathlib import Path
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
from plyer import notification
from typing import Callable
import fire
from platformdirs import user_cache_dir
from py_ankiconnect import PyAnkiconnect
import joblib
import pandas as pd
import numpy as np
from rapidfuzz.fuzz import ratio as levratio
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from tokenizers import Tokenizer
from sentence_transformers import SentenceTransformer
import torch
import ftfy
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics import pairwise_distances, pairwise_kernels
from sklearn.decomposition import TruncatedSVD, PCA
from sklearn.preprocessing import normalize
from sklearn import cluster
import umap.umap_
from bertopic import BERTopic
import hdbscan
import networkx as nx
from plotly.colors import qualitative
from plotly.offline import plot as offpy
from plotly.graph_objs import (Scatter, scatter, Figure, Layout, layout)
import ankipandas as akp
import shutil
from utils.greek import greek_alphabet_mapping
akc = PyAnkiconnect(default_host="http://localhost", default_port=8775)
# avoids annoying warning
os.environ["TOKENIZERS_PARALLELISM"] = "true"
# avoid out of memory error
# https://stackoverflow.com/questions/73747731/runtimeerror-cuda-out-of-memory-how-can-i-set-max-split-size-mb
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = "max_split_size_mb:256"
# avoid crash caused by wrong protobuffer version
# os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
# makes the script interuptible, resume it using c+enter
signal.signal(signal.SIGINT, (lambda signal, frame: breakpoint()))
# adds logger file, restrict it to X lines
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
if Path("logs.txt.4").exists():
Path("logs.txt.4").unlink()
file_handler = handlers.RotatingFileHandler(
"logs.txt",
mode='a',
maxBytes=1000000,
backupCount=4,
encoding=None,
delay=0,
)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(log_formatter)
log = logging.getLogger()
log.setLevel(logging.INFO)
log.addHandler(file_handler)
def set_global_logging_level(level=logging.ERROR, prefices=[""]):
"""
To control logging level for various modules used in the application:
https://github.com/huggingface/transformers/issues/3050#issuecomment-682167272
"""
prefix_re = re.compile(fr'^(?:{ "|".join(prefices) })')
for name in logging.root.manager.loggerDict:
if re.search(prefix_re, name):
logging.getLogger(name).setLevel(level)
colors = {
"red": "\033[91m",
"yellow": "\033[93m",
"reset": "\033[0m",
"white": "\033[0m",
"purple": "\033[95m",
}
def get_coloured_logger(color_asked: str) -> Callable:
"""used to print color coded logs"""
col = colors[color_asked]
# all logs are considered "errors" otherwise the datascience libs just
# overwhelm the logs
def printer(string: str, **args) -> str:
inp = string
if isinstance(string, dict):
try:
string = rtoml.dumps(string, pretty=True)
except Exception:
string = json.dumps(string, indent=2)
if isinstance(string, list):
try:
string = ",".join(string)
except:
pass
try:
string = str(string)
except:
try:
string = string.__str__()
except:
string = string.__repr__()
log.info(string)
tqdm.write(col + string + colors["reset"], **args)
return inp
return printer
whi = get_coloured_logger("white")
yel = get_coloured_logger("yellow")
red = get_coloured_logger("red")
set_global_logging_level(logging.ERROR,
["transformers", "nlp", "torch",
"tensorflow", "sklearn", "nltk"])
def _beep(message=None, **args):
sound = "error" # default sound
if message is None:
red(" ############")
red(" ### BEEP ###") # at least produce a written message
red(" ############")
else:
try:
if isinstance(message, list):
message = "".join(message)
elif not isinstance(message, str):
message = str(message)
# create notification with error
red("NOTIF: " + message)
notification.notify(title="AnnA",
message=message,
timeout=-1,
)
except Exception as err:
red(f"Error when creating notification: '{err}'")
try:
#beepy.beep(sound, **args)
pass
except Exception:
# retry sound if failed
time.sleep(1)
try:
#beepy.beep(sound, **args)
pass
except Exception:
red("Failed to beep twice.")
time.sleep(0.5) # avoid too close beeps in a row
class AnnA:
"""
Arguments
---------
-h, --help
show this help message and exit
--deckname DECKNAME
the deck containing the cards you want to review. If
you don't supply this value or make a mistake, AnnA
will ask you to type in the deckname, with
autocompletion enabled (use `<TAB>`). Default is
`None`.
--reference_order: str REF_ORDER
either "relative_overdueness" or "lowest_interval" or
"order_added" or "LIRO_mix". It is the reference used
to sort the card before adjusting them using the
similarity scores. Default is
`"relative_overdueness"`. Keep in mind that my
relative_overdueness is a reimplementation of the
default overdueness of anki and is not absolutely
exactly the same but should be a close approximation.
If you find edge cases or have any idea, please open
an issue. LIRO_mix is simply the the weighted average
of relative overdueness and lowest interval (4 times
more important than RO) (after some post processing).
I created it as a compromise between old and new
courses. My implementation of relative overdueness
includes a boosting feature: if your dues contain
cards with its overdueness several times larger than
its interval, they are urgent. AnnA will add a tag to
them and increase their likelyhood of being part of
the Optideck.
--task TASK: str
can be 'filter_review_cards',
'bury_excess_learning_cards',
'bury_excess_review_cards',
'add_KNN_to_field',
'just_plot',
'plot_and_tag'.
Respectively to
create a filtered deck with the cards,
or bury only the similar learning cards (among other learning cards),
or bury only the similar cards in review (among other review cards),
or just find the nearest neighbors of each note and save it to the field 'Nearest_neighbors' of each note,
or create a 2D plot using BERTopic
or create the 2D plot using BERTopic then add the topics as tags to the cards
Default is `filter_review_cards`.
--bury_after_filter: bool, default False
if --task is set to "filter_review_cards" and this is True: also
bury the cards that were not filtered. This can be handy when dealing
with daily deck limits and schedulers.
--target_deck_size TARGET_SIZE
indicates the size of the filtered deck to create. Can
be the number of due cards like "100", a proportion of
due cards like '80%', the word "all" or "deck_config"
to use the deck's settings for max review. Default is
`deck_config`.
--max_deck_size MAX_DECK_SIZE
Maximum number of cards to put in the filtered deck or
to leave unburied. Default is `None`.
--stopwords_lang STOPLANG [STOPLANG ...]
a comma separated list of languages used to construct
a list of stop words (i.e. words that will be ignored,
like "I" or "be" in English). Default is `english
french`.
--rated_last_X_days RATED_LAST_X_DAYS
indicates the number of passed days to take into
account when fetching past anki sessions. If you rated
500 cards yesterday, then you don't want your today
cards to be too close to what you viewed yesterday, so
AnnA will find the 500 cards you reviewed yesterday,
and all the cards you rated before that, up to the
number of days in rated_last_X_days value. Default is
`4` (meaning rated today, and in the 3 days before
today). A value of 0 or `None` will disable fetching
those cards. A value of 1 will only fetch cards that
were rated today. Not that this will include cards
rated in the last X days, no matter if they are
reviews or learnings. you can change this using
"highjack_rated_query" argument.
--score_adjustment_factor SCORE_ADJUSTMENT_FACTOR [SCORE_ADJUSTMENT_FACTOR ...]
a comma separated list of numbers used to adjust the
value of the reference order compared to how similar
the cards are. Default is `1,5`. For example: '1, 1.3'
means that the algorithm will spread the similar cards
farther apart.
--field_mapping FIELD_MAPPING_PATH
path of file that indicates which field to keep from
which note type and in which order. Default value is
`utils/field_mappings.py`. If empty or if no matching
notetype was found, AnnA will only take into account
the first 2 fields. If you assign a notetype to
`["take_all_fields]`, AnnA will grab all fields of the
notetype in the same order as they appear in Anki's
interface.
--acronym_file ACRONYM_FILE_PATH
a python file containing dictionaries that themselves
contain acronyms to extend in the text of cards. For
example `CRC` can be extended to `CRC (colorectal
cancer)`. (The parenthesis are automatically added.)
Default is `"utils/acronym_example.py"`. The matching
is case sensitive only if the key contains uppercase
characters. The ".py" file extension is not mandatory.
--acronym_list ACRONYM_LIST [ACRONYM_LIST ...]
a comma separated list of name of dictionaries to
extract file supplied in `acronym_file` var. Used to
extend text, for instance
`AI_machine_learning,medical_terms`. Default to None.
--minimum_due MINIMUM_DUE_CARDS
stops AnnA if the number of due cards is inferior to
this value. Default is `5`. If it's an int less or
equal to 2 it will be set to 3 as it makes no sense
otherwise.
--highjack_due_query HIGHJACK_DUE_QUERY
bypasses the browser query used to find the list of
due cards. You can set it for example to
`deck:"my_deck" (is:due OR prop:due=0) -rated:14 flag:1`. Default is
`None`. **Keep in mind that, when highjacking queries,
you have to specify the deck otherwise AnnA will
compare your whole collection.**
--highjack_rated_query HIGHJACK_RATED_QUERY
same idea as above, bypasses the query used to fetch
rated cards in anki. Related to `highjack_due_query`.
Using this will also bypass the function
'iterated_fetcher' which looks for cards rated at each
day until rated_last_X_days instead of querying all of
them at once which removes duplicates (reviews of the
same card but on different days). Note that
'iterated_fetcher' also looks for cards in filtered
decks created by AnnA from the same deck. When
'iterated_fetcher' is used, the importance of reviews
is gradually decreased as the number of days since the
review grows. In short it's doing temporal
discounting. Default is `None`.
--low_power_mode
enable to reduce the computation needed for AnnA,
making it usable for less powerful computers. This can
greatly reduce accuracy. Also removes non necessary
steps that take long like displaying some stats.
Specifically it uses binary mode for TFIDF and has
no effect if another vectorizer is used.
Default to `False`.
--log_level LOG_LEVEL
can be any number between 0 and 2. Default is `3`.
0 to only print errors. 1 to print also useful
information and >=2 to print everything. Messages
are color coded so it might be better to leave it at 3
and just focus on colors.
--replace_greek
if True, all greek letters will be replaced with a
spelled version. For example `σ` becomes `sigma`.
Default is `True`.
--keep_OCR
if True, the OCR text extracted using the great
AnkiOCR addon (https://github.com/cfculhane/AnkiOCR/)
will be included in the card. Default is `True`.
--append_tags
Whether to append the tags to the cards content or to
add no tags. Default to `False`.
--tags_to_ignore [TAGS_TO_IGNORE ...]
a list of regexp of tags to ignore when appending tags
to cards. This is not a list of tags whose card should
be ignored! Default is ['AnnA', 'leech']. Set to None
to disable it.
If a string is supplied, it will be parsed as a list
as a comma separated value.
--add_KNN_to_field
Whether to add a query to find the K nearestneighbor
of a given card to a new field called
'Nearest_neighbors' (only if already present in the
model). Be careful not to overwrite the fields by
running AnnA several times in a row! For example by
first burying learning cards then filtering review
cards. This argument is to be used if you want to find
the KNN only for the cards of the deck in question and
that are currently due. If you want to run this on the
complete deck you should use the 'task' argument.
--filtered_deck_name_template FILTER_DECK_NAME_TEMPLATE
name template of the filtered deck to create. Only
available if task is set to "filter_review_cards".
Default is `None`.
--filtered_deck_at_top_level
If True, the new filtered deck will be a top level
deck, if False: the filtered deck will be next to the
original deck. Default to True.
--filtered_deck_by_batch
To enable creating batch of filtered decks. Default is
`False`.
--filtered_deck_batch_size FILTERED_DECK_BATCH_SIZE
If creating batch of filtered deck, this is the number
of cards in each. Default is `25`.
--show_banner
used to display a nice banner when instantiating the
collection. Default is `True`.
--repick_task REPICK_TASK
Define what happens to cards deemed urgent in
'relative_overdueness' ref mode. If contains 'boost',
those cards will have a boost in priority to make sure
you will review them ASAP. If contains 'addtag' a tag
indicating which card is urgent will be added at the
end of the run. Disable by setting it to None. Default
is `boost`.
--vectorizer VECTORIZER
Either TFIDF or 'embeddings' to use
sentencetransformers. The latter will deduplicate the
field_mapping, mention the name of the field before
it's content before tokenizing, use a cache to avoid
recomputing the embedding for previously seen notes,
ignore stopwords and any TFIDF arguments used.
Default to 'embeddings'.
--sentencetransformers_precision: str, default "float32"
None to use float32, either int8, uint8, binary, ubinary.
Not available for all embedding models.
--sentencetransformers_prompt: str, default "Specific topic of this anki flashcard: "
Prompt to use for the sentence transformers.
--sentencetransformers_device
either "cpu" or "gpu"/"cuda". None to guess. Default to None.
--embed_model EMBED_MODEL
For multilingual use 'paraphrase-multilingual-mpnet-base-v2'
but for anything else use 'all-mpnet-
base-v2'
--ndim_reduc NDIM_REDUC
the number of dimension to keep using TruncatedSVD (if
TFIDF) or PCA (if embeddings). If 'auto' will
automatically find the best number of dimensions to
keep 80% of the variance. If an int, will do like
'auto' but starting from the supplied value. Default
is `auto`, you cannot disable dimension reduction for
TF_IDF because that would result in a sparse matrix.
(More information at https://scikit-learn.org/stable/m
odules/generated/sklearn.decomposition.TruncatedSVD.ht
ml).
--TFIDF_tokenize
default to `True`. Enable sub word tokenization, for
example turn `hypernatremia` to `hyp + er + natr +
emia`. You cannot enable both `TFIDF_tokenize` and
`TFIDF_stem` but should absolutely enable at least
one.
--TFIDF_tknizer_model TFIDF_tknizer_model
default to `GPT`. Model to use for tokenizing the text
before running TFIDF. Possible values are 'bert' and
'GPT' which correspond respectivelly to `bert-base-
multilingual-cased` and `gpt_neox_20B` They should
work on just about any languages. Use 'Both' to
concatenate both tokenizers. (experimental)
--TFIDF_stem
default to `False`. Whether to enable stemming of
words. Currently the PorterStemmer is used, and was
made for English but can still be useful for some
other languages. Keep in mind that this is the longest
step when formatting text.
--plot_2D_embeddings
EXPERIMENTAL AND UNFINISHED. default to `False`. Will
compute 2D embeddins then create a 2D plots at the
end.
--plot_dir PLOT_PATH
Path location for the output plots. Default is 'Plots'.
--dist_metric DIST_METRIC
when computing the distance matrix, whether to use
'cosine' or 'rbf' or 'euclidean' metrics. cosine and
rbf should be fine. Default to 'cosine'
--whole_deck_computation
defaults to `False`. This can only be used with TFIDF
and would not make any sense for sentence-
transformers. Use ankipandas to extract all text from
the deck to feed into the vectorizer. Results in more
accurate relative distances between cards. (more
information at https://github.com/klieret/AnkiPandas)
--enable_fuzz
Disable fuzzing when computing optimal order ,
otherwise a small random vector is added to the
reference_score and distance_score of each card. Note
that this vector is multiplied by the average of the
`score_adjustment_factor` then multiplied by the mean
distance then divided by 10 to make sure that it does
not overwhelm the other factors. Defaults to `True`.
--resort_by_dist RESORT_BY_DIST
Resorting the new filtered deck taking onlyinto
account the semantic distance and not the reference
score. Useful if you are certain to review the
entierety of the filtered deck today as it will
minimize similarity between consecutive cards. If you
are not sure you will finish the deck today, set to
`False` to make sure you review first the most urgent
cards. This feature is active only if you set `task`
to 'filter_review_cards'. Can be either 'farther' or
'closer' or False. 'farther' meaning to spread the
cards as evenly as possible. Default to 'closer'.
--resort_split
If 'resort_by_dist' is not False, set to True to
resort the boosted cards separately from the rest and
make them appear first in the filtered deck. Default
to `False`.
--profile_name PROFILE_NAME
defaults to `None`. Profile named used by ankipandas
to find your collection. If None, ankipandas will use
the most probable collection. Only used if
'whole_deck_computation' is set to `True`
--disable_threading DISABLE_THREADING
defaults to `False`. If True will disable most hackish
multithreading of the code. Needed if you have a
terrible GPU that is slowing you down. This does not
apply to the plotting
--keep_console_open
defaults to `False`. Set to True to open a python
console after running.
--sync_behavior SYNC_BEHAVIOR
If contains 'before', will trigger a sync when AnnA is
run. If contains 'after', will trigger a sync at the
end of the run. Default is `before&after`.
"""
def __init__(self,
# most important arguments:
deckname=None,
reference_order="relative_overdueness",
# any of "lowest_interval", "relative overdueness",
# "order_added", "LIRO_mix"
task="filter_review_cards",
# any of "filter_review_cards",
# "bury_excess_review_cards", "bury_excess_learning_cards"
# "just_add_KNN", "just_plot"
bury_after_filter: bool = False,
bypass_task_just_return=False,
target_deck_size="deck_config",
# format: 80%, "all", "deck_config"
max_deck_size=None,
stopwords_lang=["english", "french"],
rated_last_X_days=4,
score_adjustment_factor=[1, 5],
field_mappings="utils/field_mappings.py",
acronym_file="utils/acronym_example.py",
acronym_list=None,
# others:
minimum_due=5,
highjack_due_query=None,
highjack_rated_query=None,
low_power_mode=False,
log_level=3, # 0, 1, 2
replace_greek=True,
keep_OCR=True,
append_tags=False,
tags_to_ignore=["AnnA", "leech"],
add_KNN_to_field=False,
filtered_deck_name_template=None,
filtered_deck_at_top_level=True,
filtered_deck_by_batch=False,
filtered_deck_batch_size=25,
show_banner=True,
repick_task="boost", # None, "addtag", "boost" or
# "boost&addtag"
enable_fuzz=True,
resort_by_dist="closer",
resort_split=False,
# vectorization:
vectorizer="embeddings",
sentencetransformers_device=None,
sentencetransformers_precision="float32",
sentencetransformers_prompt="Specific topic of this anki flashcard: ",
embed_model="jinaai/jina-embeddings-v3",
#embed_model="jinaai/jina-colbert-v2",
# embed_model="BAAI/bge-m3",
# embed_model="paraphrase-multilingual-mpnet-base-v2",
# left for legacy reason
ndim_reduc="auto",
TFIDF_tokenize=True,
TFIDF_tknizer_model="GPT",
TFIDF_stem=False,
plot_2D_embeddings=False,
plot_dir="Plots",
dist_metric="cosine", # 'RBF' or 'cosine' or 'euclidean"
whole_deck_computation=False,
profile_name=None,
sync_behavior="before&after",
disable_threading=False,
):
if show_banner:
red(pyfiglet.figlet_format("AnnA"))
red("(Anki neuronal Appendix)\n\n")
gc.collect()
# init logging #######################################################
self.log_level = log_level
if log_level == 0:
log.setLevel(logging.ERROR)
elif log_level == 1:
log.setLevel(logging.WARNING)
elif log_level >= 2:
log.setLevel(logging.DEBUG)
else:
log.setLevel(logging.INFO)
self.disable_threading = disable_threading
# loading arguments and proceed to check correct values ##############
assert isinstance(
replace_greek, bool), "Invalid type of `replace_greek`"
self.replace_greek = replace_greek
assert isinstance(keep_OCR, bool), "Invalid type of `keep_OCR`"
self.keep_OCR = keep_OCR
self.OCR_content = "" # used to avoid looking for acronyms
# in OCR content
if isinstance(target_deck_size, int):
assert target_deck_size > 0
target_deck_size = str(target_deck_size)
elif isinstance(target_deck_size, str):
try:
testint = int(target_deck_size)
except Exception:
pass
assert "%" in target_deck_size or target_deck_size in [
"all", "deck_config"] or (
isinstance(testint, int), (
"Invalid value for `target_deck_size`"))
self.target_deck_size = target_deck_size
if target_deck_size in ["all", 1.0, "100%"] and (
task == "bury_excess_review_cards"):
_beep(f"Arguments mean that all cards "
"will be selected and none will be buried. It makes no sense."
" Aborting.")
raise Exception("Arguments mean that all cards will be selected "
"and none will be buried. It makes no sense."
" Aborting.")
assert max_deck_size is None or max_deck_size >= 1, (
"Invalid value for `max_deck_size`")
self.max_deck_size = max_deck_size
assert rated_last_X_days is None or (
rated_last_X_days >= 0, (
"Invalid value for `rated_last_X_days`"))
self.rated_last_X_days = rated_last_X_days
assert minimum_due >= 0, "Invalid value for `minimum_due`"
if minimum_due <= 2:
red(f"Minimum due should not be under 3, setting it to 3")
self.minimum_due = max(minimum_due, 3)
assert isinstance(highjack_due_query, (str, type(None))
), "Invalid type of `highjack_due_query`"
self.highjack_due_query = highjack_due_query
assert isinstance(highjack_rated_query, (str, type(None))
), "Invalid type of `highjack_rated_query`"
self.highjack_rated_query = highjack_rated_query
if isinstance(score_adjustment_factor, tuple):
score_adjustment_factor = list(score_adjustment_factor)
assert (isinstance(score_adjustment_factor, list)
), "Invalid type of `score_adjustment_factor`"
assert len(
score_adjustment_factor) == 2, (
"Invalid length of `score_adjustment_factor`")
for n in range(len(score_adjustment_factor)):
if not isinstance(score_adjustment_factor[n], float):
score_adjustment_factor[n] = float(score_adjustment_factor[n])
self.score_adjustment_factor = score_adjustment_factor
assert reference_order in ["lowest_interval",
"relative_overdueness",
"order_added",
"LIRO_mix"], (
"Invalid value for `reference_order`")
self.reference_order = reference_order
assert isinstance(append_tags, bool), "Invalid type of `append_tags`"
self.append_tags = append_tags
if tags_to_ignore is None:
tags_to_ignore = []
if isinstance(tags_to_ignore, str):
assert "," in tags_to_ignore, f"If tags_to_ignore is a string it must contain a comma to be separated as list"
tags_to_ignore = tags_to_ignore.split(",")
whi(f"tags_to_ignore was parsed as a comma separated list: {tags_to_ignore}")
assert isinstance(tags_to_ignore, list), "tags_to_ignore is not a list"
self.tags_to_ignore = [re.compile(f".*{t.strip()}.*")
if ".*" not in t
else re.compile(t.strip())
for t in tags_to_ignore]
assert len(tags_to_ignore) == len(self.tags_to_ignore)
assert isinstance(add_KNN_to_field, bool), (
"Invalid type of `add_KNN_to_field`")
self.add_KNN_to_field = add_KNN_to_field
assert isinstance(
low_power_mode, bool), "Invalid type of `low_power_mode`"
self.low_power_mode = low_power_mode
assert vectorizer in ["TFIDF", "embeddings"], "Invalid value for `vectorizer`"
self.vectorizer = vectorizer
if vectorizer == "embeddings" and whole_deck_computation:
raise Exception("You can't use whole_deck_computation for embeddings")
assert sentencetransformers_device in [None, "cpu", "gpu", "cuda"], "Unexpected value for sentencetransformers_device"
self.sentencetransformers_device = sentencetransformers_device
assert sentencetransformers_precision in [None, "float32", "int8", "uint8", "binary", "ubinary"], "Unexpected value for sentencetransformers_precision"
self.sentencetransformers_precision = sentencetransformers_precision
self.sentencetransformers_prompt = sentencetransformers_prompt
self.embed_model = embed_model
assert isinstance(
stopwords_lang, list), "Invalid type of var `stopwords_lang`"
self.stopwords_lang = stopwords_lang
assert isinstance(ndim_reduc, (int, type(None), str)
), "Invalid type of `ndim_reduc`"
if isinstance(ndim_reduc, str):
assert ndim_reduc == "auto", "Invalid value for `ndim_reduc`"
self.ndim_reduc = ndim_reduc
assert isinstance(plot_2D_embeddings, bool), (
"Invalid type of `plot_2D_embeddings`")
self.plot_2D_embeddings = plot_2D_embeddings
self.plot_dir = Path(str(plot_dir))
self.plot_dir.mkdir(exist_ok=True)
assert self.plot_dir.exists(), f"Couldn't find or create dir {self.plot_dir}"
assert isinstance(TFIDF_stem, bool), "Invalid type of `TFIDF_stem`"
assert isinstance(
TFIDF_tokenize, bool), "Invalid type of `TFIDF_tokenize`"
assert TFIDF_stem + TFIDF_tokenize not in [0, 2], (
"You have to enable either tokenization or stemming!")
self.TFIDF_stem = TFIDF_stem
self.TFIDF_tokenize = TFIDF_tokenize
assert TFIDF_tknizer_model.lower() in ["bert", "gpt", "both"], (
"Wrong tokenizer model name!")
self.TFIDF_tknizer_model = TFIDF_tknizer_model
assert dist_metric.lower() in ["cosine", "rbf", "euclidean"], (
"Invalid 'dist_metric'")
self.dist_metric = dist_metric.lower()
if bury_after_filter:
assert task == "filter_review_cards", "Can't set bury_after_filter if task ir not filter_review_cards"
self.bury_after_filter = bury_after_filter
assert task in ["filter_review_cards",
"bury_excess_learning_cards",
"bury_excess_review_cards",
"just_add_KNN",
"just_plot",
"plot_and_tag"], "Invalid value for `task`"
if task in ["bury_excess_learning_cards",
"bury_excess_review_cards"]:
if task == "bury_excess_learning_cards":
red("Task : bury some learning cards")
elif task == "bury_excess_review_cards":
red("Task : bury some reviews\n")
elif task == "filter_review_cards":
red("Task : created filtered deck containing review cards")
elif task == "just_add_KNN":
red("Task : find the nearest neighbor of each note and "
"add it to a field.")
elif task == "just_plot":
red("Task : vectorize the cards and create a 2D plot.")
assert plot_2D_embeddings, "argument plot_2D_embeddings should be True"
elif task == "plot_and_tag":
red("Task : vectorize the cards and create a 2D plot then tag the cards with the appropriate topic.")
assert plot_2D_embeddings, "argument plot_2D_embeddings should be True"
else:
raise ValueError()
self.task = task
self.bypass_task_just_return = bypass_task_just_return
self.return_values = None # can contain values than will be returned as the end of instanciation
assert isinstance(filtered_deck_name_template, (str, type(
None))), "Invalid type for `filtered_deck_name_template`"
self.filtered_deck_name_template = filtered_deck_name_template
assert isinstance(filtered_deck_by_batch,
bool), "Invalid type for `filtered_deck_by_batch`"
self.filtered_deck_by_batch = filtered_deck_by_batch
assert isinstance(filtered_deck_at_top_level,
bool), "Invalid type for `filtered_deck_at_top_level`"
self.filtered_deck_at_top_level = filtered_deck_at_top_level
assert isinstance(filtered_deck_batch_size,
int), "Invalid type for `filtered_deck_batch_size`"
self.filtered_deck_batch_size = filtered_deck_batch_size
assert isinstance(whole_deck_computation,
bool), "Invalid type for `whole_deck_computation`"
self.whole_deck_computation = whole_deck_computation
assert isinstance(profile_name, (str, type(None))
), "Invalid type for `profile_name`"
self.profile_name = profile_name
if sync_behavior is None:
sync_behavior = ""
assert isinstance(sync_behavior, str), (
"sync_behavior should be a string!")
assert (
(
"before" in sync_behavior
) or ("after" in sync_behavior
) or (sync_behavior == "")
), (f"Wrong value of 'sync_behavior': '{sync_behavior}'")
self.sync_behavior = sync_behavior
assert isinstance(repick_task, str), "Invalid type for `repick_task`"
self.repick_task = repick_task
assert isinstance(acronym_file, (str, type(None))
), "Invalid type for `acronym_file`"
self.acronym_file = acronym_file
assert isinstance(acronym_list, (list, type(None))
), "Invalid type for `acronym_list`"
self.acronym_list = acronym_list
assert isinstance(field_mappings, (str, type(None))
), "Invalid type for `field_mappings`"
self.field_mappings = field_mappings
assert isinstance(enable_fuzz, bool), "Invalid type for 'enable_fuzz'"
self.enable_fuzz = enable_fuzz
assert isinstance(resort_by_dist, (bool, str)), (
"Invalid type for 'resort_by_dist'")
if isinstance(resort_by_dist, str):
resort_by_dist = resort_by_dist.lower()
self.resort_by_dist = resort_by_dist
assert resort_by_dist in ["farther", "closer", False], (
"Invalid 'resort_by_dist' value")
assert isinstance(resort_split, bool), (
"Invalid type for 'resort_split'")
self.resort_split = resort_split
assert Path(user_cache_dir()).exists(), f"User cache dir not found: '{user_cache_dir()}'"
self.cache_dir = Path(user_cache_dir()) / "AnnA"
self.cache_dir.mkdir(exist_ok=True)
# additional processing of arguments #################################
# load or ask for deckname
self.deckname = self._check_deckname(deckname)
red(f"Selected deck: {self.deckname}\n")
self.deck_config = self._call_anki(action="getDeckConfig",
deck=self.deckname)
global beep
def beep(x):
"simple overloading to display the deckname"
try:
return _beep(f"{self.deckname}: {x}")
except Exception:
return _beep(x)
if task != "filter_review_cards" and (
self.filtered_deck_name_template is not None):
red("Ignoring argument 'filtered_deck_name_template' because "
"'task' is not set to 'filter_review_cards'.")
# load tokenizers
if TFIDF_tokenize:
if self.TFIDF_tknizer_model.lower() in ["bert", "both"]:
yel("Will use BERT as tokenizer.")
self.tokenizer_bert = Tokenizer.from_file(
"./utils/bert-base-multilingual-cased_tokenizer.json")
self.tokenizer_bert.no_truncation()
self.tokenizer_bert.no_padding()
self.tokenize = self._bert_tokenize
if self.TFIDF_tknizer_model.lower() in ["gpt", "both"]:
yel("Will use GPT as tokenizer.")
self.tokenizer_gpt = Tokenizer.from_file(
"./utils/gpt_neox_20B_tokenizer.json")
self.tokenizer_gpt.no_truncation()
self.tokenizer_gpt.no_padding()
self.tokenize = self._gpt_tokenize
if self.TFIDF_tknizer_model.lower() == "both":
yel("Using both GPT and BERT as tokenizers.")
self.tokenize = lambda x: self._gpt_tokenize(
x) + self._bert_tokenize(x)
else:
# create dummy tokenizer
self.tokenize = lambda x: x.replace("<NEWFIELD>", " ").strip(
).split(" ")
# load acronyms
if self.acronym_file is not None and self.acronym_list is not None:
file = Path(acronym_file)
if not file.exists():
beep(f"Acronym file was not "
f"found: {acronym_file}")
raise Exception(f"Acronym file was not found: {acronym_file}")
# importing acronym file
acr_mod = importlib.import_module(
acronym_file.replace("/", ".").replace(".py", "")
)
# getting acronym dictionnary list
acr_dict_list = [x for x in dir(acr_mod)
if not x.startswith("_")]
# if empty file:
if len(acr_dict_list) == 0:
beep(f"No dictionnary found "
f"in {acronym_file}")
raise SystemExit()
if isinstance(self.acronym_list, str):
self.acronym_list = [self.acronym_list]
missing = [x for x in self.acronym_list
if x not in acr_dict_list]
if missing:
beep(f"Mising the following acronym "
"dictionnary in "
f"{acronym_file}: {','.join(missing)}")
raise SystemExit()
acr_dict_list = [x for x in acr_dict_list
if x in self.acronym_list]
if len(acr_dict_list) == 0:
beep(f"No dictionnary from "
f"{self.acr_dict_list} "
f"found in {acronym_file}")
raise SystemExit()
compiled_dic = {}
notifs = []
for item in acr_dict_list:
acronym_dict = eval(f"acr_mod.{item}")
for ac in acronym_dict:
if ac.lower() == ac:
compiled = re.compile(r"\b" + ac + r"\b",
flags=(re.IGNORECASE |
re.MULTILINE |
re.DOTALL))
else:
compiled = re.compile(r"\b" + ac + r"\b",
flags=(
re.MULTILINE |
re.DOTALL))
if compiled in compiled_dic:
notifs.append(
f"Pattern '{compiled}' found "
"multiple times in acronym dictionnary, "
"keeping only the last one.")
compiled_dic[compiled] = acronym_dict[ac]