Matthias Nott
3 days ago 9d577bcc3774a70d7dfb53cb9ba68a995dfb208b
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
#!/usr/bin/env python3
"""
Restructure explanation text in SPL exam question files to use markdown bullets
for option analysis sentences.
"""
import re
import os
from pathlib import Path
BASE_DIR = Path("/Users/i052341/Daten/Cloud/04 - Ablage/Ablage 2020 - 2029/Ablage 2025/Hobbies 2025/Segelflug/Theorie/Glidr")
SUBJECT_DIRS = {
    "EN": BASE_DIR / "SPL Exam Questions EN",
    "DE": BASE_DIR / "SPL Exam Questions DE",
    "FR": BASE_DIR / "SPL Exam Questions FR",
}
EXPLANATION_HEADERS = {
    "EN": "#### Explanation",
    "DE": "#### Erklärung",
    "FR": "#### Explication",
}
KEY_TERMS_HEADERS = {
    "EN": "#### Key Terms",
    "DE": "#### Begriffe",
    "FR": "#### Termes clés",
}
# Patterns that identify option-analysis sentences.
# Each pattern must match the START of a sentence (after splitting on sentence boundaries).
# Strategy: a sentence is an option sentence if it STARTS with an option reference.
# This catches all forms: "Option A is...", "Option A (label) contains...", "Options A and B are...", etc.
OPTION_PATTERNS = [
    # EN/DE: sentence starts with "Option" or "Options" followed by one or more letters A-D
    r"^Options?\s+[A-D]",
    # EN/DE: "Die Option A" or "Nur Option A"
    r"^(?:Die|Nur|Only)\s+Options?\s+[A-D]",
    # EN bare letter: "A is wrong", "B is incorrect" (only when followed by a form of "to be")
    r"^[A-D]\s+(?:is|are|was|were|would|can|cannot|does|did|has|have)\b",
    # DE bare letter: "A ist falsch"
    r"^[A-D]\s+(?:ist|sind|war|w\u00e4re)\b",
    # FR: "L'option A" or "L\u2019option A"
    r"^L['\u2019]?options?\s+[A-D]",
    # FR bare letter: "A est incorrecte"
    r"^[A-D]\s+est\b",
    # Generic: "Option A:" or "Option A —" or "Option A–"
    r"^Options?\s+[A-D](?:\s*(?:,|and|und|et)\s*(?:and\s+|und\s+|et\s+)?[A-D])*\s*(?::|—|–)",
    # "Seule l'option C" (FR), "Nur Option C" (DE), "Only Option C" (EN) - correct answer callouts
    r"^(?:Seule\s+l['\u2019]?option|Nur\s+Option|Only\s+Option)\s+[A-D]",
]
# Compiled combined pattern (case-sensitive)
# We split by detecting sentence starts matching any option pattern.
# Strategy: split the explanation text into sentences, then bucket them.
def split_into_sentences(text):
    """
    Split text into sentences. Split on sentence-ending punctuation followed by
    a space and a capital letter. Handles:
      - ". Capital"
      - '." Capital'  (period inside quotes)
      - ".'" / ".»" etc.
    """
    # Split on: period (optionally followed by closing quote/bracket) then whitespace then capital
    parts = re.split(r'(?<=\.)["\'\u201d\u2019»]?\s+(?=[A-Z\xdc\xc4\xd6L\'"«\u201c\u2018])', text.strip())
    return parts
def is_option_sentence(sentence, lang):
    """Return True if the sentence is an option-analysis sentence."""
    s = sentence.strip()
    for pat in OPTION_PATTERNS:
        if re.match(pat, s, re.IGNORECASE):
            return True
    return False
def bold_option_reference(sentence):
    """
    Bold the initial option reference in a sentence.
    e.g. "Option A is wrong..." -> "**Option A** is wrong..."
         "Option A (label) contains..." -> "**Option A** (label) contains..."
         "Options A and B are..." -> "**Options A and B** are..."
         "L'option A est..." -> "**L'option A** est..."
         "Only Option C correctly..." -> "Only **Option C** correctly..."
         "A is wrong" -> "**A** is wrong"
    """
    s = sentence.strip()
    patterns_to_bold = [
        # EN/DE multi: "Options A, B, and C" / "Options A und B"  (must come before single)
        (r'^(Options?\s+[A-D](?:\s*(?:,|and|und)\s*(?:and\s+|und\s+)?[A-D])+)', r'**\1**'),
        # EN/DE single: "Option A"
        (r'^(Options?\s+[A-D])\b', r'**\1**'),
        # FR multi: "L'option A et B"
        (r"^(L['\u2019]?options?\s+[A-D](?:\s*(?:,|et)\s*(?:et\s+)?[A-D])+)", r'**\1**'),
        # FR single: "L'option A"
        (r"^(L['\u2019]?options?\s+[A-D])\b", r'**\1**'),
        # EN "Only Option C" -> "Only **Option C**"
        (r'^(Only\s+)(Options?\s+[A-D])\b', r'\1**\2**'),
        # DE "Nur Option C"
        (r'^(Nur\s+)(Options?\s+[A-D])\b', r'\1**\2**'),
        # FR "Seule l'option C"
        (r"^(Seule\s+)(l['\u2019]?options?\s+[A-D])\b", r'\1**\2**'),
        # DE "Die Option A"
        (r'^(Die\s+)(Options?\s+[A-D])\b', r'\1**\2**'),
        # Bare letter: "A is", "B est"
        (r'^([A-D])(\s+(?:is|are|ist|sind|est|sont|was|w\u00e4re|serait)\b)', r'**\1**\2'),
    ]
    for pat, repl in patterns_to_bold:
        new_s = re.sub(pat, repl, s, count=1, flags=re.IGNORECASE)
        if new_s != s:
            return new_s
    return s
def restructure_explanation(explanation_text, lang):
    """
    Given the raw explanation text (without the header line), restructure it:
    - Sentences before the first option-analysis sentence -> main paragraph
    - Option-analysis sentences -> bullet points
    Returns (new_text, was_changed: bool)
    """
    text = explanation_text.strip()
    if not text:
        return text, False
    sentences = split_into_sentences(text)
    if not sentences:
        return text, False
    # Find index of first option sentence
    first_option_idx = None
    for i, s in enumerate(sentences):
        if is_option_sentence(s, lang):
            first_option_idx = i
            break
    if first_option_idx is None:
        # No option sentences found, leave as-is
        return text, False
    # Main paragraph: sentences before first option sentence
    main_sentences = sentences[:first_option_idx]
    option_sentences = sentences[first_option_idx:]
    # Verify that option_sentences are indeed all option-like (some trailing sentences might not be)
    # We keep going: once we see an option sentence, everything else goes to bullets
    # (this matches the described format where option analysis is at the end)
    main_paragraph = " ".join(s.strip() for s in main_sentences if s.strip())
    bullets = []
    for s in option_sentences:
        s = s.strip()
        if not s:
            continue
        # Remove trailing period for bullet, then re-add
        s_clean = s.rstrip(".")
        bolded = bold_option_reference(s_clean)
        bullets.append(f"- {bolded}.")
    if not bullets:
        return text, False
    # Build new text
    parts = []
    if main_paragraph:
        parts.append(main_paragraph)
        parts.append("")  # blank line
    parts.extend(bullets)
    new_text = "\n".join(parts)
    # Only report change if something actually changed
    changed = new_text.strip() != text.strip()
    return new_text, changed
def process_file(filepath, lang, explanation_header, key_terms_header):
    """
    Process a single markdown file. Returns (content, count_restructured).
    """
    content = filepath.read_text(encoding="utf-8")
    lines = content.split("\n")
    count = 0
    result_lines = []
    i = 0
    while i < len(lines):
        line = lines[i]
        # Check if this line is the explanation header
        if line.strip() == explanation_header:
            result_lines.append(line)
            i += 1
            # Collect blank lines after header
            while i < len(lines) and lines[i].strip() == "":
                result_lines.append(lines[i])
                i += 1
            # Collect the explanation body until we hit:
            # - key terms header
            # - next question (### Q)
            # - end of file
            explanation_body_lines = []
            while i < len(lines):
                l = lines[i]
                if (l.strip() == key_terms_header or
                        l.strip().startswith("### Q") or
                        l.strip().startswith("#### ")):
                    break
                explanation_body_lines.append(l)
                i += 1
            # The explanation body (trim trailing blanks)
            raw_body = "\n".join(explanation_body_lines).rstrip()
            new_body, changed = restructure_explanation(raw_body, lang)
            if changed:
                count += 1
                result_lines.append(new_body)
                result_lines.append("")  # trailing blank line
            else:
                # Restore original lines
                for bl in explanation_body_lines:
                    result_lines.append(bl)
        else:
            result_lines.append(line)
            i += 1
    new_content = "\n".join(result_lines)
    return new_content, count
def main():
    total_restructured = 0
    total_files = 0
    for lang, dir_path in SUBJECT_DIRS.items():
        explanation_header = EXPLANATION_HEADERS[lang]
        key_terms_header = KEY_TERMS_HEADERS[lang]
        md_files = sorted(dir_path.glob("*.md"))
        for filepath in md_files:
            # Skip the combined file
            if "SPL Exam Questions" in filepath.name:
                continue
            new_content, count = process_file(
                filepath, lang, explanation_header, key_terms_header
            )
            if count > 0:
                filepath.write_text(new_content, encoding="utf-8")
                print(f"  [{lang}] {filepath.name}: {count} explanation(s) restructured")
                total_restructured += count
            else:
                print(f"  [{lang}] {filepath.name}: no changes")
            total_files += 1
    print(f"\nDone. {total_restructured} explanations restructured across {total_files} files.")
if __name__ == "__main__":
    main()