-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathcloze_utils.py
More file actions
73 lines (53 loc) · 2 KB
/
cloze_utils.py
File metadata and controls
73 lines (53 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import re
from typing import List
CLOZE_REGEX = re.compile(r"{{c\d+::.*?}}", re.MULTILINE | re.DOTALL)
def iscloze(text: str) -> bool:
"returns True or False depending on if the text is a cloze note"
if "}}" not in text:
return False
if not re.sub(CLOZE_REGEX, "", text).strip():
return False
if not re.search(CLOZE_REGEX, text):
return False
return True
def getclozes(text: str) -> List[str]:
"return the cloze found in the text. Should only be called on cloze notes"
assert iscloze(text), f"Text '{text}' does not contain a cloze"
return re.findall(CLOZE_REGEX, text)
def cloze_input_parser(cloze: str) -> str:
"""edits the cloze from anki before sending it to the LLM. This is useful
if you use weird formatting that mess with LLMs"""
assert iscloze(cloze), f"Invalid cloze: {cloze}"
# TODO: What is this?
cloze = cloze.replace("\xa0", " ")
# make newlines consistent
cloze = cloze.replace("<br/>", "<br>")
cloze = cloze.replace("\r", "<br>")
cloze = cloze.replace("<br>", "\n")
# make spaces consitent
cloze = cloze.replace(" ", " ")
# misc
cloze = cloze.replace(">", ">")
cloze = cloze.replace("≥", ">=")
cloze = cloze.replace("<", "<")
cloze = cloze.replace("≤", "<=")
assert iscloze(cloze), f"Invalid cloze: {cloze}"
return cloze
def cloze_output_parser(cloze: str) -> str:
"""
formats the cloze that were made easy to read by the LLM easy to
display and answer in anki"""
# strip
cloze = cloze.strip()
# make sure all newlines are consistent for now
# TODO: You mean <br/>?
cloze = cloze.replace("</br>", "<br>")
cloze = cloze.replace("<br/>", "<br>")
cloze = cloze.replace("\r", "<br>")
# TODO: Not needed
# cloze = cloze.replace("<br>", "\n")
# make sure all spaces are consistent
cloze = cloze.replace(" ", " ")
# now use anki formatting for the newlines
cloze = cloze.replace("\n", "<br>")
return cloze