-
Notifications
You must be signed in to change notification settings - Fork 139
/
obsidian_to_anki.py
1777 lines (1633 loc) · 58.3 KB
/
obsidian_to_anki.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
"""Script for adding cards to Anki from Obsidian."""
import re
import json
import urllib.request
import configparser
import os
import collections
import webbrowser
import markdown
import base64
import argparse
import html
import time
import socket
import subprocess
import logging
import hashlib
try:
import gooey
GOOEY = True
except ModuleNotFoundError:
print("Gooey not installed, switching to cli...")
GOOEY = False
logging.basicConfig(
filename='obsidian_to_anki_log.log',
level=logging.DEBUG,
format='%(asctime)s:::%(levelname)s:::%(funcName)s:::%(message)s'
)
MEDIA = dict()
ID_PREFIX = "ID: "
TAG_PREFIX = "Tags: "
TAG_SEP = " "
Note_and_id = collections.namedtuple('Note_and_id', ['note', 'id'])
NOTE_DICT_TEMPLATE = {
"deckName": "",
"modelName": "",
"fields": dict(),
"options": {
"allowDuplicate": False,
"duplicateScope": "deck"
},
"tags": ["Obsidian_to_Anki"],
# ^So that you can see what was added automatically.
"audio": list()
}
CONFIG_PATH = os.path.expanduser(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"obsidian_to_anki_config.ini"
)
)
CONFIG_DATA = dict()
DATA_PATH = os.path.expanduser(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"obsidian_to_anki_data.json"
)
)
md_parser = markdown.Markdown(
extensions=[
'fenced_code',
'footnotes',
'md_in_html',
'tables',
'nl2br',
'sane_lists'
]
)
ANKI_PORT = 8765
ANKI_CLOZE_REGEXP = re.compile(r'{{c\d+::[\s\S]+?}}')
def has_clozes(text):
"""Checks whether text actually has cloze deletions."""
return bool(ANKI_CLOZE_REGEXP.search(text))
def note_has_clozes(note):
"""Checks whether a note has cloze deletions in any of its fields."""
return any(has_clozes(field) for field in note["fields"].values())
def write_safe(filename, contents):
"""
Write contents to filename while keeping a backup.
If write fails, a backup 'filename.bak' will still exist.
"""
with open(filename + ".tmp", "w", encoding='utf_8') as temp:
temp.write(contents)
os.rename(filename, filename + ".bak")
os.rename(filename + ".tmp", filename)
with open(filename, encoding='utf_8') as f:
success = (f.read() == contents)
if success:
os.remove(filename + ".bak")
def string_insert(string, position_inserts):
"""
Insert strings in position_inserts into string, at indices.
position_inserts will look like:
[(0, "hi"), (3, "hello"), (5, "beep")]
"""
offset = 0
position_inserts = sorted(list(position_inserts))
for position, insert_str in position_inserts:
string = "".join(
[
string[:position + offset],
insert_str,
string[position + offset:]
]
)
offset += len(insert_str)
return string
def file_encode(filepath):
"""Encode the file as base 64."""
with open(filepath, 'rb') as f:
return base64.b64encode(f.read()).decode('utf-8')
def spans(pattern, string):
"""Return a list of span-tuples for matches of pattern in string."""
return [match.span() for match in pattern.finditer(string)]
def contained_in(span, spans):
"""Return whether span is contained in spans (+- 1 leeway)"""
return any(
span[0] >= start - 1 and span[1] <= end + 1
for start, end in spans
)
def findignore(pattern, string, ignore_spans):
"""Yield all matches for pattern in string not in ignore_spans."""
return (
match
for match in pattern.finditer(string)
if not contained_in(match.span(), ignore_spans)
)
def wait_for_port(port, host='localhost', timeout=5.0):
"""Wait until a port starts accepting TCP connections.
Args:
port (int): Port number.
host (str): Host address on which the port should exist.
timeout (float): In seconds. How long to wait before raising errors.
Raises:
TimeoutError: The port isn't accepting connection after time specified
in `timeout`.
"""
start_time = time.perf_counter()
while True:
try:
with socket.create_connection((host, port), timeout=timeout):
break
except OSError as ex:
time.sleep(0.01)
if time.perf_counter() - start_time >= timeout:
raise TimeoutError(
'Waited too long for the port {} on host {} to'
'start accepting connections.'.format(port, host)
) from ex
def load_anki():
"""Attempt to load anki in the correct profile."""
try:
Config.load_config()
except Exception as e:
print("Error when loading config:", e)
print("Please open Anki before running script again.")
return False
if CONFIG_DATA["Path"] and CONFIG_DATA["Profile"]:
print("Anki Path and Anki Profile provided.")
print("Attempting to open Anki in selected profile...")
subprocess.Popen(
[CONFIG_DATA["Path"], "-p", CONFIG_DATA["Profile"]]
)
try:
wait_for_port(ANKI_PORT)
except TimeoutError:
print(
"Opened Anki, but can't connect! Is AnkiConnect working?"
)
return False
else:
print("Opened and connected to Anki successfully!")
return True
else:
print(
"Must provide both Anki Path and Anki Profile",
"in order to open Anki automatically"
)
return False
def main():
"""Main functionality of script."""
if not os.path.exists(CONFIG_PATH):
Config.update_config()
App()
class AnkiConnect:
"""Namespace for AnkiConnect functions."""
def request(action, **params):
"""Format action and parameters into Ankiconnect style."""
return {'action': action, 'params': params, 'version': 6}
def invoke(action, **params):
"""Do the action with the specified parameters."""
requestJson = json.dumps(
AnkiConnect.request(action, **params)
).encode('utf-8')
response = json.load(urllib.request.urlopen(
urllib.request.Request('http://localhost:8765', requestJson)))
return AnkiConnect.parse(response)
def parse(response):
"""Parse the received response."""
if len(response) != 2:
raise Exception('response has an unexpected number of fields')
if 'error' not in response:
raise Exception('response is missing required error field')
if 'result' not in response:
raise Exception('response is missing required result field')
if response['error'] is not None:
raise Exception(response['error'])
return response['result']
class FormatConverter:
"""Converting Obsidian formatting to Anki formatting."""
OBS_INLINE_MATH_REGEXP = re.compile(
r"(?<!\$)\$(?=[\S])(?=[^$])[\s\S]*?\S\$"
)
OBS_DISPLAY_MATH_REGEXP = re.compile(r"\$\$[\s\S]*?\$\$")
OBS_CODE_REGEXP = re.compile(
r"(?<!`)`(?=[^`])[\s\S]*?`"
)
OBS_DISPLAY_CODE_REGEXP = re.compile(
r"```[\s\S]*?```"
)
ANKI_INLINE_START = r"\("
ANKI_INLINE_END = r"\)"
ANKI_DISPLAY_START = r"\["
ANKI_DISPLAY_END = r"\]"
ANKI_MATH_REGEXP = re.compile(r"(\\\[[\s\S]*?\\\])|(\\\([\s\S]*?\\\))")
MATH_REPLACE = "OBSTOANKIMATH"
INLINE_CODE_REPLACE = "OBSTOANKICODEINLINE"
DISPLAY_CODE_REPLACE = "OBSTOANKICODEDISPLAY"
IMAGE_REGEXP = re.compile(r'<img alt=".*?" src="(.*?)"')
SOUND_REGEXP = re.compile(r'\[sound:(.+)\]')
CLOZE_REGEXP = re.compile(
r'(?:(?<!{){(?:c?(\d+)[:|])?(?!{))((?:[^\n][\n]?)+?)(?:(?<!})}(?!}))'
)
URL_REGEXP = re.compile(r'https?://')
PARA_OPEN = "<p>"
PARA_CLOSE = "</p>"
CLOZE_UNSET_NUM = 1
@staticmethod
def format_note_with_url(note, url):
for key in note["fields"]:
note["fields"][key] += "<br>" + "".join([
'<a',
' href="{}" class="obsidian-link">Obsidian</a>'.format(url)
])
break # So only does first field
@staticmethod
def format_note_with_frozen_fields(note, frozen_fields_dict):
for field in note["fields"].keys():
note["fields"][field] += frozen_fields_dict[
note["modelName"]
][field]
@staticmethod
def inline_anki_repl(matchobject):
"""Get replacement string for Obsidian-formatted inline math."""
found_string = matchobject.group(0)
# Strip Obsidian formatting by removing first and last characters
found_string = found_string[1:-1]
# Add Anki formatting
result = FormatConverter.ANKI_INLINE_START + found_string
result += FormatConverter.ANKI_INLINE_END
return result
@staticmethod
def display_anki_repl(matchobject):
"""Get replacement string for Obsidian-formatted display math."""
found_string = matchobject.group(0)
# Strip Obsidian formatting by removing first two and last two chars
found_string = found_string[2:-2]
# Add Anki formatting
result = FormatConverter.ANKI_DISPLAY_START + found_string
result += FormatConverter.ANKI_DISPLAY_END
return result
@staticmethod
def obsidian_to_anki_math(note_text):
"""Convert Obsidian-formatted math to Anki-formatted math."""
return FormatConverter.OBS_INLINE_MATH_REGEXP.sub(
FormatConverter.inline_anki_repl,
FormatConverter.OBS_DISPLAY_MATH_REGEXP.sub(
FormatConverter.display_anki_repl, note_text
)
)
@staticmethod
def cloze_repl(match):
id, content = match.group(1), match.group(2)
if id is None:
result = "{{{{c{!s}::{}}}}}".format(
FormatConverter.CLOZE_UNSET_NUM,
content
)
FormatConverter.CLOZE_UNSET_NUM += 1
return result
else:
return "{{{{c{}::{}}}}}".format(id, content)
@staticmethod
def curly_to_cloze(text):
"""Change text in curly brackets to Anki-formatted cloze."""
text = FormatConverter.CLOZE_REGEXP.sub(
FormatConverter.cloze_repl,
text
)
FormatConverter.CLOZE_UNSET_NUM = 1
return text
@staticmethod
def markdown_parse(text):
"""Apply markdown conversions to text."""
text = md_parser.reset().convert(text)
return text
@staticmethod
def is_url(text):
"""Check whether text looks like a url."""
return bool(
FormatConverter.URL_REGEXP.match(text)
)
@staticmethod
def get_images(html_text):
"""Get all the images that need to be added."""
for match in FormatConverter.IMAGE_REGEXP.finditer(html_text):
path = match.group(1)
if FormatConverter.is_url(path):
continue # Skips over images web-hosted.
path = urllib.parse.unquote(path)
filename = os.path.basename(path)
if filename not in App.ADDED_MEDIA and filename not in MEDIA:
MEDIA[filename] = file_encode(path)
# Adds the filename and data to media_names
@staticmethod
def get_audio(html_text):
"""Get all the audio that needs to be added."""
for match in FormatConverter.SOUND_REGEXP.finditer(html_text):
path = match.group(1)
filename = os.path.basename(path)
if filename not in App.ADDED_MEDIA and filename not in MEDIA:
MEDIA[filename] = file_encode(path)
# Adds the filename and data to media_names
@staticmethod
def path_to_filename(matchobject):
"""Replace the src in matchobject appropriately."""
found_string, found_path = matchobject.group(0), matchobject.group(1)
if FormatConverter.is_url(found_path):
return found_string # So urls should not be altered.
found_string = found_string.replace(
found_path, os.path.basename(urllib.parse.unquote(found_path))
)
return found_string
@staticmethod
def fix_image_src(html_text):
"""Fix the src of the images so that it's relative to Anki."""
return FormatConverter.IMAGE_REGEXP.sub(
FormatConverter.path_to_filename,
html_text
)
@staticmethod
def fix_audio_src(html_text):
"""Fix the audio filenames so that it's relative to Anki."""
return FormatConverter.SOUND_REGEXP.sub(
FormatConverter.path_to_filename,
html_text
)
@staticmethod
def format(note_text, cloze=False):
"""Apply all format conversions to note_text."""
note_text = FormatConverter.obsidian_to_anki_math(note_text)
# Extract the parts that are anki math
math_matches = [
math_match.group(0)
for math_match in FormatConverter.ANKI_MATH_REGEXP.finditer(
note_text
)
]
# Replace them to be later added back, so they don't interfere
# with markdown parsing
note_text = FormatConverter.ANKI_MATH_REGEXP.sub(
FormatConverter.MATH_REPLACE, note_text
)
# Now same with code!
inline_code_matches = [
code_match.group(0)
for code_match in FormatConverter.OBS_CODE_REGEXP.finditer(
note_text
)
]
note_text = FormatConverter.OBS_CODE_REGEXP.sub(
FormatConverter.INLINE_CODE_REPLACE, note_text
)
display_code_matches = [
code_match.group(0)
for code_match in FormatConverter.OBS_DISPLAY_CODE_REGEXP.finditer(
note_text
)
]
note_text = FormatConverter.OBS_DISPLAY_CODE_REGEXP.sub(
FormatConverter.DISPLAY_CODE_REPLACE, note_text
)
if cloze:
note_text = FormatConverter.curly_to_cloze(note_text)
for code_match in inline_code_matches:
note_text = note_text.replace(
FormatConverter.INLINE_CODE_REPLACE,
code_match,
1
)
for code_match in display_code_matches:
note_text = note_text.replace(
FormatConverter.DISPLAY_CODE_REPLACE,
code_match,
1
)
note_text = FormatConverter.markdown_parse(note_text)
# Add back the parts that are anki math
for math_match in math_matches:
note_text = note_text.replace(
FormatConverter.MATH_REPLACE,
html.escape(math_match),
1
)
FormatConverter.get_images(note_text)
FormatConverter.get_audio(note_text)
note_text = FormatConverter.fix_image_src(note_text)
note_text = FormatConverter.fix_audio_src(note_text)
note_text = note_text.strip()
# Remove unnecessary paragraph tag
if note_text.startswith(
FormatConverter.PARA_OPEN
) and note_text.endswith(
FormatConverter.PARA_CLOSE
):
note_text = note_text[len(FormatConverter.PARA_OPEN):]
note_text = note_text[:-len(FormatConverter.PARA_CLOSE)]
return note_text
class Note:
"""Manages parsing notes into a dictionary formatted for AnkiConnect.
Input must be the note text.
Does NOT deal with finding the note in the file.
"""
ID_REGEXP = re.compile(
r"(?:<!--)?" + ID_PREFIX + r"(\d+)"
)
def __init__(self, note_text):
"""Set up useful variables."""
self.text = note_text
self.lines = self.text.splitlines()
self.current_field_num = 0
if Note.ID_REGEXP.match(self.lines[-1]):
self.identifier = int(
Note.ID_REGEXP.match(self.lines.pop()).group(1)
)
# The above removes the identifier line, for convenience of parsing
else:
self.identifier = None
if self.lines[-1].startswith(TAG_PREFIX):
self.tags = self.lines.pop()[len(TAG_PREFIX):].split(
TAG_SEP
)
else:
self.tags = list()
self.note_type = self.lines[0]
self.field_names = App.FIELDS_DICT[self.note_type]
self.current_field = self.field_names[0]
def field_from_line(self, line):
"""From a given line, determine the next field to add text into.
Then, return the stripped line, and the field."""
for field in self.field_names:
if line.startswith(field + ":"):
return (line[len(field + ":"):], field)
return (line, self.current_field)
@property
def fields(self):
"""Get the fields of the note into a dictionary."""
fields = {field: "" for field in self.field_names}
for line in self.lines[1:]:
line, self.current_field = self.field_from_line(line)
fields[self.current_field] += line + "\n"
fields = {
key: FormatConverter.format(
value.strip(),
cloze=(
"Cloze" in self.note_type
and CONFIG_DATA["CurlyCloze"]
)
)
for key, value in fields.items()
}
return {key: value.strip() for key, value in fields.items()}
def parse(self, deck, url=None, frozen_fields_dict=None):
"""Get a properly formatted dictionary of the note."""
template = NOTE_DICT_TEMPLATE.copy()
template["modelName"] = self.note_type
template["fields"] = self.fields
if all([
CONFIG_DATA["Add file link"],
CONFIG_DATA["Vault"],
url
]):
FormatConverter.format_note_with_url(template, url)
if frozen_fields_dict:
FormatConverter.format_note_with_frozen_fields(
template, frozen_fields_dict
)
template["tags"] = template["tags"] + self.tags
template["deckName"] = deck
return Note_and_id(note=template, id=self.identifier)
class InlineNote(Note):
ID_REGEXP = re.compile(r"(?:<!--)?" + ID_PREFIX + r"(\d+)")
TAG_REGEXP = re.compile(TAG_PREFIX + r"(.*)")
TYPE_REGEXP = re.compile(r"\[(.*?)\]") # So e.g. [Basic]
def __init__(self, note_text):
self.text = note_text.strip()
self.current_field_num = 0
ID = InlineNote.ID_REGEXP.search(self.text)
if ID is not None:
self.identifier = int(ID.group(1))
self.text = self.text[:ID.start()] # Removes identifier
else:
self.identifier = None
TAGS = InlineNote.TAG_REGEXP.search(self.text)
if TAGS is not None:
self.tags = TAGS.group(1).split(TAG_SEP)
self.text = self.text[:TAGS.start()]
else:
self.tags = list()
TYPE = InlineNote.TYPE_REGEXP.search(self.text)
self.note_type = TYPE.group(1)
self.text = self.text[TYPE.end():]
self.field_names = App.FIELDS_DICT[self.note_type]
self.current_field = self.field_names[0]
@property
def fields(self):
"""Get the fields of the note into a dictionary."""
fields = {field: "" for field in self.field_names}
for word in self.text.split(" "):
for field in self.field_names:
if word == field + ":":
self.current_field = field
word = ""
fields[self.current_field] += word + " "
fields = {
key: FormatConverter.format(
value,
cloze=(
"Cloze" in self.note_type
and CONFIG_DATA["CurlyCloze"]
)
)
for key, value in fields.items()
}
return {key: value.strip() for key, value in fields.items()}
class RegexNote:
ID_REGEXP_STR = r"\n?(?:<!--)?(?:" + ID_PREFIX + r"(\d+).*)"
TAG_REGEXP_STR = r"(" + TAG_PREFIX + r".*)"
def __init__(self, matchobject, note_type, tags=False, id=False):
self.match = matchobject
self.note_type = note_type
self.groups = list(self.match.groups())
self.group_num = len(self.groups)
if id:
# This means id is last group
self.identifier = int(self.groups.pop())
else:
self.identifier = None
if tags:
# Even if id were present, tags is now last group
self.tags = self.groups.pop()[len(TAG_PREFIX):].split(
TAG_SEP
)
else:
self.tags = list()
self.field_names = App.FIELDS_DICT[self.note_type]
@property
def fields(self):
fields = dict.fromkeys(self.field_names, "")
for name, match in zip(self.field_names, self.groups):
if match:
fields[name] = match
fields = {
key: FormatConverter.format(
value,
cloze=(
"Cloze" in self.note_type
and CONFIG_DATA["CurlyCloze"]
)
)
for key, value in fields.items()
}
return {key: value.strip() for key, value in fields.items()}
def parse(self, deck, url=None, frozen_fields_dict=None):
"""Get a properly formatted dictionary of the note."""
template = NOTE_DICT_TEMPLATE.copy()
template["modelName"] = self.note_type
template["fields"] = self.fields
if all([
CONFIG_DATA["Add file link"],
CONFIG_DATA["Vault"],
url
]):
FormatConverter.format_note_with_url(template, url)
if frozen_fields_dict:
FormatConverter.format_note_with_frozen_fields(
template, frozen_fields_dict
)
template["tags"] = template["tags"] + self.tags
template["deckName"] = deck
if "Cloze" in self.note_type and CONFIG_DATA[
"CurlyCloze"
] and not note_has_clozes(template):
return 1 # Like an error code, only for this note type
# Since we can accidentally recognise { in the wrong places.
return Note_and_id(note=template, id=self.identifier)
class Config:
"""Deals with saving and loading the configuration file."""
@staticmethod
def setup_syntax(config):
"""Sets up default syntax in the config object."""
config.setdefault("Syntax", dict())
config["Syntax"].setdefault(
"Begin Note", "START"
)
config["Syntax"].setdefault(
"End Note", "END"
)
config["Syntax"].setdefault(
"Begin Inline Note", "STARTI"
)
config["Syntax"].setdefault(
"End Inline Note", "ENDI"
)
config["Syntax"].setdefault(
"Target Deck Line", "TARGET DECK"
)
config["Syntax"].setdefault(
"File Tags Line", "FILE TAGS"
)
config["Syntax"].setdefault(
"Delete Note Line", "DELETE"
)
config["Syntax"].setdefault(
"Frozen Fields Line", "FROZEN"
)
@staticmethod
def setup_defaults(config):
"""Sets up default values in the config file, not to do with syntax."""
config.setdefault("Obsidian", dict())
config["Obsidian"].setdefault("Vault name", "")
config["Obsidian"].setdefault("Add file link", "False")
config["DEFAULT"] = dict() # Removes DEFAULT if it's there.
config.setdefault("Defaults", dict())
config["Defaults"].setdefault(
"Tag", "Obsidian_to_Anki"
)
config["Defaults"].setdefault(
"Deck", "Default"
)
config["Defaults"].setdefault(
"CurlyCloze", "False"
)
config["Defaults"].setdefault(
"GUI", "True"
)
config["Defaults"].setdefault(
"Regex", "False"
)
config["Defaults"].setdefault(
"ID Comments", "True"
)
config["Defaults"].setdefault(
"Anki Path", ""
)
config["Defaults"].setdefault(
"Anki Profile", ""
)
def update_config():
"""Update config with new notes."""
print("Updating configuration file...")
config = configparser.ConfigParser()
config.optionxform = str
if os.path.exists(CONFIG_PATH):
print("Config file exists, reading...")
config.read(CONFIG_PATH, encoding='utf-8-sig')
note_types = AnkiConnect.invoke("modelNames")
config.setdefault("Custom Regexps", dict())
for note in note_types:
config["Custom Regexps"].setdefault(note, "")
Config.setup_syntax(config)
Config.setup_defaults(config)
with open(CONFIG_PATH, "w", encoding='utf_8') as configfile:
config.write(configfile)
print("Configuration file updated!")
@staticmethod
def load_syntax(config):
"""Reads and loads syntax from the config object."""
CONFIG_DATA["NOTE_PREFIX"] = re.escape(
config["Syntax"]["Begin Note"]
)
CONFIG_DATA["NOTE_SUFFIX"] = re.escape(
config["Syntax"]["End Note"]
)
CONFIG_DATA["INLINE_PREFIX"] = re.escape(
config["Syntax"]["Begin Inline Note"]
)
CONFIG_DATA["INLINE_SUFFIX"] = re.escape(
config["Syntax"]["End Inline Note"]
)
CONFIG_DATA["DECK_LINE"] = re.escape(
config["Syntax"]["Target Deck Line"]
)
CONFIG_DATA["TAG_LINE"] = re.escape(
config["Syntax"]["File Tags Line"]
)
RegexFile.EMPTY_REGEXP = re.compile(
re.escape(
config["Syntax"]["Delete Note Line"]
) + RegexNote.ID_REGEXP_STR
)
CONFIG_DATA["EMPTY_REGEXP"] = re.compile(
re.escape(
config["Syntax"]["Delete Note Line"]
) + RegexNote.ID_REGEXP_STR
)
CONFIG_DATA["FROZEN_LINE"] = re.escape(
config["Syntax"]["Frozen Fields Line"]
)
@staticmethod
def load_defaults(config):
"""Loads default values not to do with syntax from config object."""
NOTE_DICT_TEMPLATE["tags"] = [config["Defaults"]["Tag"]]
NOTE_DICT_TEMPLATE["deckName"] = config["Defaults"]["Deck"]
CONFIG_DATA["CurlyCloze"] = config.getboolean(
"Defaults", "CurlyCloze"
)
CONFIG_DATA["GUI"] = config.getboolean(
"Defaults", "GUI"
)
CONFIG_DATA["Regex"] = config.getboolean(
"Defaults", "Regex"
)
CONFIG_DATA["Comment"] = config.getboolean(
"Defaults", "ID Comments"
)
CONFIG_DATA["Path"] = config["Defaults"]["Anki Path"]
CONFIG_DATA["Profile"] = config["Defaults"]["Anki Profile"]
CONFIG_DATA["Vault"] = config["Obsidian"]["Vault name"]
CONFIG_DATA["Add file link"] = config.getboolean(
"Obsidian", "Add file link"
)
def load_config():
"""Load from an existing config file (assuming it exists)."""
print("Loading configuration file...")
config = configparser.ConfigParser()
config.optionxform = str # Allows for case sensitivity
config.read(CONFIG_PATH, encoding='utf-8-sig')
Config.load_syntax(config)
Config.load_defaults(config)
CONFIG_DATA["CUSTOM_REGEXPS"] = config["Custom Regexps"]
print("Loaded successfully!")
class Data:
"""Class for managing the data file (not meant to be changed by users.)"""
def create_data_file():
"""Creates the data file for the script."""
print("Creating data file...")
with open(DATA_PATH, "w") as f:
json.dump(dict(), f)
def update_data_file(data):
"""Updates the data file for the script with the given data."""
print("Updating data file...")
with open(DATA_PATH, "w") as f:
json.dump(data, f)
def load_data_file():
"""Loads the data file into memory"""
with open(DATA_PATH, "r") as f:
data = json.load(f)
App.ADDED_MEDIA = data.get("Added Media", list())
App.FILE_HASHES = data.get("File Hashes", dict())
class App:
"""Master class that manages the application."""
SUPPORTED_EXTS = [".md", ".txt"]
def __init__(self):
"""Execute the main functionality of the script."""
try:
Config.load_config()
except Exception as e:
print("Error:", e)
print("Attempting to fix config file...")
Config.update_config()
Config.load_config()
try:
Data.load_data_file()
except Exception as e:
print("Error:", e)
Data.create_data_file()
Data.load_data_file()
self.get_fields()
self.get_ids()
if CONFIG_DATA["GUI"] and GOOEY:
self.setup_gui_parser()
else:
self.setup_cli_parser()
args = self.parser.parse_args()
if CONFIG_DATA["GUI"] and GOOEY:
if args.directory:
args.path = args.directory
elif args.file:
args.path = args.file
else:
args.path = False
no_args = True
if args.update:
no_args = False
Config.update_config()
Config.load_config()
if args.mediaupdate:
no_args = False
Data.create_data_file()
self.gen_regexp()
if args.config:
no_args = False
webbrowser.open(CONFIG_PATH)
return
if args.path:
no_args = False
current = os.getcwd()
self.path = args.path
directories = list()
if os.path.isdir(self.path):
os.chdir(self.path)
if args.recurse:
directories = list()
for root, dirs, files in os.walk(os.getcwd()):
directories.append(
Directory(root, regex=args.regex)
)
for dir in dirs:
if dir.startswith("."):
dirs.remove(dir)
# So, ignore . folders
else:
directories = [
Directory(
os.getcwd(), regex=args.regex
)
]
os.chdir(current)
else:
# Still need to get to directory of file for image resolving
# So, go to directory where file is (hopefully)
# But, if just file name is given (e.g. cli), don't want to
# Break anything.
if os.path.dirname(self.path):
file_dir = os.path.dirname(self.path)
else:
file_dir = current
directories = [
Directory(
file_dir, regex=args.regex, onefile=self.path
)
]
requests = list()
print("Getting tag list")
requests.append(
AnkiConnect.request(
"getTags"
)
)
print("Adding media with these filenames...")
print(list(MEDIA.keys()))
requests.append(self.get_add_media())
print("Adding directory requests...")
for directory in directories:
requests.append(directory.requests_1())
result = AnkiConnect.invoke(
"multi",
actions=requests
)
tags = AnkiConnect.parse(result[0])
directory_responses = result[2:]
for directory, response in zip(directories, directory_responses):
directory.parse_requests_1(AnkiConnect.parse(response), tags)
requests = list()
for directory in directories:
requests.append(directory.requests_2())
AnkiConnect.invoke(
"multi",
actions=requests
)
App.ADDED_MEDIA = set(App.ADDED_MEDIA)
App.ADDED_MEDIA.update(MEDIA.keys())
App.ADDED_MEDIA = list(App.ADDED_MEDIA)
for directory in directories:
App.FILE_HASHES.update(directory.hashes())
Data.update_data_file(
{
"Added Media": App.ADDED_MEDIA,
"File Hashes": App.FILE_HASHES
}
)
if no_args:
self.parser.print_help()
def setup_parser_optionals(self):
"""Set up optional arguments for the parser."""
self.parser.add_argument(
"-c", "--config",
action="store_true",