-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnote_generation.py
More file actions
2520 lines (2219 loc) · 108 KB
/
Copy pathnote_generation.py
File metadata and controls
2520 lines (2219 loc) · 108 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
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
"""
Note Generation
Generates one comprehensive Markdown note file per course, covering all
lectures in sequence, matching the style of example/CS2105_note.md.
Architecture:
- Per lecture: split slides into ~CHAPTER_SIZE chunks, one GPT call per chunk.
- Chunks map to ### N.x sections. Images injected at diagram slides.
- All lectures merged into one file; exam notes appended at the end.
- Self-scoring via heuristics (no extra API call).
Usage:
python note_generation.py --course 85427
python note_generation.py --course 85427 --detail 9 --iterate
python note_generation.py --slides 85427/materials/LectureNotes/L02.pdf \\
--alignment "85427/alignment/L02.json" --lecture-num 2 --course-name "CS3210"
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from datetime import datetime
from pathlib import Path
try:
from tqdm import tqdm
except ImportError as _e:
print(f"[error] Missing dependency: {_e}")
print("[error] Please install the ML environment from Settings → ML Environment in the AutoNote app.")
sys.exit(1)
try:
import alignment_parser
except ImportError as _e:
print(f"[error] Could not import alignment_parser: {_e}")
print(f"[error] Make sure alignment_parser.py is in the same directory as note_generation.py")
sys.exit(1)
PROJECT_DIR = Path(__file__).parent
import sys as _sys
_AUTO_NOTE_DIR = Path.home() / ".auto_note"
import os as _os
if _os.environ.get("AUTONOTE_DATA_DIR"):
DATA_DIR = Path(_os.environ["AUTONOTE_DATA_DIR"])
elif getattr(_sys, "frozen", False) or PROJECT_DIR == _AUTO_NOTE_DIR / "scripts":
DATA_DIR = _AUTO_NOTE_DIR
else:
DATA_DIR = PROJECT_DIR
# Course output directory: defaults to DATA_DIR but can be overridden by
# OUTPUT_DIR in config.json so files land in the user's chosen Output Dir.
_ng_config: dict = (
json.loads((DATA_DIR / "config.json").read_text())
if (DATA_DIR / "config.json").exists() else {}
)
_out_dir = _ng_config.get("OUTPUT_DIR", "").strip()
COURSE_DATA_DIR = Path(_out_dir) if _out_dir else Path.home() / "AutoNote"
# ── Constants ─────────────────────────────────────────────────────────────────
DETAIL_LEVEL = 7
OUTPUT_FORMAT = "md"
NOTE_MODEL = "gpt-5.1"
TRANSLATE_MODEL = "gpt-4o" # Chinese/other translation post-pass — gpt-4o is cheap enough
QUALITY_TARGET = 8.0
IMAGE_RENDER_SCALE = 1.5
NOTE_LANGUAGE = "en" # "en" = English | "zh" = Chinese
SHOW_SCORE = False # dev mode: set via --score flag to show self-scoring
CHAPTER_SIZE = 15 # slides per GPT call
MAX_NOTE_CHARS = 120000 # max total chars in the chunk prompt (transcript + slides + images)
SCORE_WEIGHTS = {"coverage": 0.30, "terminology": 0.35,
"callouts": 0.15, "code_blocks": 0.20}
MIN_NOTE_WORDS_PER_SLIDE = 60 # expected words per slide in final note
# ── Prompts ───────────────────────────────────────────────────────────────────
_PROMPTS: dict[str, dict] = {
"en": dict(
system="""\
You are a teaching assistant at a top university, writing high-quality study notes for computer science courses based on lecture slides and audio transcripts.
Writing guidelines:
1. Write in English. Keep technical terms in English.
2. Never use a third-person narrator perspective. Do not write "the professor said", "the lecturer pointed out", etc. Focus on the knowledge itself — state concepts, principles, and conclusions directly:
- ✗ "The professor explained that…" → ✓ "The key idea is…"
- ✗ "The lecturer used an example…" → ✓ "As an example,…"
3. Structure content as: concept → principle → example → exam focus. Write fluent explanatory paragraphs; do not list slide bullets verbatim.
4. Use LaTeX for math: inline $...$, display $$...$$.
5. Code examples must be complete, compilable/runnable snippets (with necessary includes, function signatures, main, etc.) using correct syntax highlighting (```c, ```cpp, ```python, etc.). Use pseudocode only when no real equivalent exists, tagged as ```pseudo.
6. Mark exam-critical content with:
> [!IMPORTANT]
> content
7. Use italics for interesting analogies or memory aids.
8. Image insertion rules (strictly follow):
- **Insert all and only images that contain visual elements**: diagrams, flowcharts, architecture drawings, code screenshots, mathematical derivations, data visualizations, tables with meaningful structure, annotated figures, or any non-trivial visual illustration. Do NOT insert administrative or non-course elements (course info slides, polling QR codes, attendance prompts, etc.) even if they contain images.
- Pure text slides (bullet points, definitions, titles) do not need images — the notes express text better than a screenshot.
- **Be INCLUSIVE with images**: if a frame/slide shows a diagram, chart, table, code, or any non-trivial visual content, include it. Aim to include most of the content-rich images available, not just a few highlights. It's better to have more images with brief connecting text than to skip images.
- **Each image MUST be placed inline, immediately after the paragraph that directly discusses the concept shown in that image.** If a frame shows content that the transcript doesn't fully cover, briefly describe the frame's content (using the description provided in the image hints) and then insert the image.
- Format for slide images: ` *(one-sentence description)*`
- Format for screen-capture frames: ` *(one-sentence description)*`
(The subdirectory under `images/` is provided in the "Available images" list — copy it verbatim, including any slug suffix, and do not shorten or rewrite it. The caption must be in parentheses wrapped in asterisks exactly as shown.)
9. Never fabricate technical details not present in the source material.
""",
chunk="""\
Write study notes for the following course segment ({course_name} Lecture {lec_num}: {lec_title}).
## Lecture audio transcript (PRIMARY SOURCE — this is the main content to cover)
{transcript_block}
## Slide outline (structural guide — use for topic organization)
{slide_outline}
## Available images (insert relevant ones inline)
{image_hints}
---
Requirements:
- The **transcript is the primary source material**. Cover ALL concepts, explanations, examples, and details the lecturer discusses. The slide outline is a structural guide for organizing topics, but the transcript contains the actual teaching content.
- The section heading for this segment is `### {lec_num}.{chunk_idx} {chunk_title}` (**do not output this line** — it is added by the caller).
- Detail level: {detail}/10. {detail_instruction}
- Images: **insert all images that contain visual elements** (diagrams, charts, graphs, code screenshots, architecture drawings, data visualizations, mathematical derivations, etc.). Skip images of pure text, bullet points, or administrative/non-course elements.
Copy the exact path from the "Available images" list above (including the images/L** subdirectory). Do not invent paths.
**CRITICAL: Be inclusive — aim to include MOST content-rich images (diagrams, charts, code, tables). For each image, ensure a paragraph discusses its content, then insert the image right after that paragraph. If a frame has visual content that the transcript doesn't cover, write a brief paragraph about it based on the image description, then insert the image. NEVER cluster multiple images together consecutively without explanatory text between them.**
Format: ` *(caption)*` or ` *(caption)*`
- Code examples must be complete and compilable (with necessary includes/imports), using the correct language tag (```c, ```cpp, ```python).
- Only cover the content in this segment; do not introduce material from other lectures.
""",
slide_only="""\
Write study notes for {course_name} Lecture {lec_num}: {lec_title} based on the slides below.
(No audio transcript is available — supplement with your CS knowledge where appropriate.)
## Slide content
{slide_outline}
## Available images
{image_hints}
---
Requirements:
- The section heading is `### {lec_num}.{chunk_idx} {chunk_title}` (**do not output this line**).
- Detail level: {detail}/10. {detail_instruction}
- Images: **insert all images that contain visual elements** (diagrams, charts, graphs, code screenshots, architecture drawings, data visualizations, mathematical derivations, etc.). Skip images of pure text, bullet points, or administrative/non-course elements.
Copy the exact path from the "Available images" list above (including the images/L** subdirectory). Do not invent paths.
**CRITICAL: Be inclusive — aim to include MOST content-rich images. For each image, write a paragraph about its content then insert the image. NEVER cluster multiple images together consecutively without explanatory text between them.**
Format: ` *(caption)*` or ` *(caption)*`
- Code examples must be complete and compilable, using the correct language tag (```c, ```cpp, ```python).
""",
exam="""\
Below are the complete lecture notes for {course_name}. Please append a concise exam cheat-sheet section at the end.
Format:
- Heading: `## Exam Notes`
- Each entry: `N. **Topic**: one-sentence summary`
- No more than 30 entries, covering key concepts, formulas, algorithm steps, and common confusion points from all lectures.
Notes summary:
{summary}
""",
no_transcript="(No audio transcript available for this segment.)",
detail_instructions=[
(range(0, 3), "Minimal bullets: one line per concept, no expansion, max 3 bullets per slide."),
(range(3, 6), "Hierarchical bullets: one top-level bullet (`-`) per main concept, "
"at most 2 sub-bullets (` -`) for key details. "
"Max 5 bullets total per slide. No prose paragraphs."),
(range(6, 9), "Detailed paragraphs: cover concepts, principles, the lecturer's examples and analogies in full."),
(range(9, 11), "Maximum detail: include all nuances, edge cases, connections to other chapters, and exam pointers."),
],
), # end en
} # end _PROMPTS
# Language names for the translation instruction
_LANG_NAMES = {"en": "English", "zh": "Chinese", "ja": "Japanese", "ko": "Korean"}
def _P(key: str) -> str:
"""Return the English prompt unchanged. Translation is always a separate
post-generation step via _translate()."""
return _PROMPTS["en"][key]
def _detail_instr(level: int) -> str:
instrs = _PROMPTS["en"]["detail_instructions"]
for rng, txt in instrs:
if level in rng:
return txt
return instrs[2][1]
# ── Image filter constants ────────────────────────────────────────────────────
IMAGE_FILTER_MODEL = "gpt-4o"
IMAGE_FILTER_WORD_MAX = 12 # slides with ≤ this many words → remove without API call
IMAGE_FILTER_HEURISTIC = 80 # slides with > this many words AND no code/desc → remove
# Title/divider patterns that add no visual value
_TITLE_PATTERN = re.compile(
r"^\s*(CS\d+|AY\d+|Lecture\s+\d+|\[.*\]|Part\s+\d+|Section\s+\d+|"
r"Outline|Agenda|Table of Contents|Overview|Summary|Questions\?|Q&A)\s*$",
re.IGNORECASE | re.MULTILINE,
)
# Keywords that indicate a slide description contains visual/diagram content
_VISUAL_KEYWORDS = re.compile(
r"\b(diagram|chart|graph|figure|illustration|flowchart|screenshot|"
r"table|formula|equation|architecture|layout|structure|matrix|tree|"
r"network|circuit|timeline|image|photo|plot|drawing|schematic|visual)\b",
re.IGNORECASE,
)
def _desc_has_visual(desc: str) -> bool:
"""Return True if a cache description mentions diagram/chart/visual content."""
return bool(_VISUAL_KEYWORDS.search(desc))
def _img_ref_pattern() -> re.Pattern:
# Matches slide_001.png / frame_001.png under images/L04/, images/L04_F02/,
# or images/L04_<slug>[_F02]/ — with an optional trailing italic caption.
return re.compile(
r"!\[(?:Slide|Frame) \d+\]\((images/L\d{2}[^/]*/(?:slide|frame)_\d{3}\.png)\)"
r"(?:\s*\*\([^)]*\)\*)?"
)
def _vision_keep(img_path: Path, slide_text: str = "") -> bool:
"""Ask GPT-4o-mini whether the slide image is worth including in notes.
Uses slide_text as context so the model can reason about whether the
visual structure actually explains the lecture content (e.g. a diagram
of a protocol stack/a picture of a biological structure) vs. being an unrelated administrative element
(e.g. a PollEv QR code, a course logo, a participation prompt).
"""
import base64
import io
if not img_path.exists():
return False
try:
from PIL import Image as PILImage
img = PILImage.open(img_path).convert("RGB")
# Downscale to max 800px wide to keep base64 payload small
if img.width > 800:
ratio = 800 / img.width
img = img.resize((800, int(img.height * ratio)), PILImage.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=75)
b64 = base64.b64encode(buf.getvalue()).decode("ascii")
except Exception:
return True # can't load image → default keep
context_block = (
f"\n\nSlide text (OCR):\n\"\"\"\n{slide_text[:400]}\n\"\"\""
if slide_text.strip() else ""
)
_VISION_PROMPT = f"""\
You are a study-notes curator deciding whether a lecture slide image should be \
embedded in written notes.{context_block}
## KEEP the image if the slide contains ANY course-relevant visual element:
- Diagrams: system/architecture diagrams, component boxes connected by arrows
- Flowcharts, state machines, decision trees, sequence/timing diagrams
- Memory layouts, address-space maps, cache/pipeline stage illustrations
- Graphs, plots, bar/line/pie charts, scatter plots showing data or trends
- Tables with a meaningful grid structure (comparing options, relationships)
- Mathematical formulas or derivations where spatial layout matters
- Code screenshots or annotated code with visual highlights
- Annotated screenshots, highlighted output, or callout arrows
- Any non-trivial visual illustration related to the course
## REMOVE only if the slide is clearly non-visual or non-course-related:
- Pure text slides (bullet points, prose, definitions) with absolutely no \
diagram, chart, figure, or visual element
- Title slides, section dividers, agenda/outline, blank slides
- Administrative elements unrelated to the course: polling/quiz prompts \
(PollEv, Mentimeter, Kahoot QR codes), attendance check slides, \
course info graphics, "any questions?" slides, logos, sponsor slides
## Default: when genuinely uncertain, KEEP.
Reply with exactly one word: KEEP or REMOVE."""
try:
openai_client = _get_client_for(IMAGE_FILTER_MODEL)
r = openai_client.chat.completions.create(
model=IMAGE_FILTER_MODEL,
messages=[{"role": "user", "content": [
{"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{b64}", "detail": "low"}},
{"type": "text", "text": _VISION_PROMPT},
]}],
max_tokens=5,
)
return "KEEP" in r.choices[0].message.content.strip().upper()
except Exception:
return True # default: keep on API error
def filter_images_pass(
notes_text: str,
notes_dir: Path,
lectures: list["LectureData"],
) -> tuple[str, int, int]:
"""Post-processing agent: remove low-value image references from merged notes.
Decision priority:
1. Cache-verified AND description mentions visual elements → KEEP
2. Title/divider pattern → REMOVE
3. All other cases → vision API decision
Returns (cleaned_text, n_kept, n_removed).
"""
pattern = _img_ref_pattern()
# Build unified lookup: image rel-path → (SlideInfo, LectureData).
# Path scheme matches render_chunk_images: images/{dir_key}/…, where
# dir_key = L{num:02d}_{slug}[_F{idx:02d}].
slide_ld_lookup: dict[str, tuple[SlideInfo, "LectureData"]] = {}
for ld in lectures:
# Use frame_NNN for screenshare, slide_NNN for traditional
img_prefix = "frame" if ld.source == "screenshare" else "slide"
for s in ld.slides:
key = f"images/{ld.dir_key}/{img_prefix}_{s.index+1:03d}.png"
slide_ld_lookup[key] = (s, ld)
# Collect unique paths and decide keep/remove
decisions: dict[str, bool] = {} # path → True=keep
for m in pattern.finditer(notes_text):
rel = m.group(1)
if rel in decisions:
continue
pair = slide_ld_lookup.get(rel)
slide = pair[0] if pair else None
owner = pair[1] if pair else None
img_path = notes_dir / rel
# ⓪ Screen share frames — always keep (the frame IS the content)
if owner and owner.source == "screenshare":
decisions[rel] = True
continue
# ① Cache-verified AND description mentions visual elements → KEEP
if slide and owner:
desc = owner.img_cache.get(f"page_{slide.index}", "")
if desc and _desc_has_visual(desc):
decisions[rel] = True
continue
# ② Title/divider pattern → REMOVE
if slide and _TITLE_PATTERN.search(slide.text):
decisions[rel] = False
continue
# ③ Vision API — KEEP only if visual AND relevant to lecture content
slide_text = slide.text if slide else ""
decisions[rel] = _vision_keep(img_path, slide_text)
kept = sum(1 for v in decisions.values() if v)
removed = sum(1 for v in decisions.values() if not v)
tqdm.write(f" Image filter: {kept} kept, {removed} removed out of {len(decisions)}")
# Remove lines for filtered-out images; collapse extra blank lines
lines_out: list[str] = []
for line in notes_text.splitlines():
m = pattern.fullmatch(line.strip())
if m and not decisions.get(m.group(1), True):
# Replace filtered image line with nothing (don't emit the line)
continue
lines_out.append(line)
cleaned = "\n".join(lines_out)
# Collapse 3+ consecutive blank lines → 2 (preserves paragraph spacing)
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
return cleaned, kept, removed
def _max_tokens(level: int) -> int:
# Per chunk (CHAPTER_SIZE slides).
# gpt-5.x reasoning models consume tokens for internal thinking,
# so we need larger budgets than the expected output length.
# Token budget directly caps output length — keep it proportional to detail level.
if level < 3: return 2000
if level < 6: return 3500
if level < 9: return 10000
return 16000
# ── Multi-provider LLM helpers ────────────────────────────────────────────────
def _provider(model: str) -> str:
if model == "claude-cli":
return "claude-cli"
if model == "codex-cli":
return "codex-cli"
if model.startswith("gemini"):
return "gemini"
if model.startswith("claude"):
return "anthropic"
if model.startswith("deepseek"):
return "deepseek"
if model.startswith("grok"):
return "grok"
if model.startswith(("mistral", "codestral", "pixtral", "magistral")):
return "mistral"
return "openai"
_client_cache: dict = {}
def _make_client(provider: str):
import os
from openai import OpenAI
def _read_key(env_var: str, filename: str, label: str) -> str:
key = os.environ.get(env_var, "")
if not key:
kf = DATA_DIR / filename
if kf.exists():
key = kf.read_text().strip()
if not key:
raise RuntimeError(
f"No {label} API key found "
f"(set {filename} in ~/.auto_note/ or {env_var} env var)"
)
return key
if provider == "gemini":
return OpenAI(
api_key=_read_key("GEMINI_API_KEY", "gemini_api.txt", "Gemini"),
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
)
elif provider == "anthropic":
from anthropic import Anthropic
return Anthropic(api_key=_read_key("ANTHROPIC_API_KEY", "anthropic_key.txt", "Anthropic"))
elif provider == "deepseek":
return OpenAI(
api_key=_read_key("DEEPSEEK_API_KEY", "deepseek_key.txt", "DeepSeek"),
base_url="https://api.deepseek.com",
)
elif provider == "grok":
return OpenAI(
api_key=_read_key("GROK_API_KEY", "grok_key.txt", "xAI Grok"),
base_url="https://api.x.ai/v1",
)
elif provider == "mistral":
return OpenAI(
api_key=_read_key("MISTRAL_API_KEY", "mistral_key.txt", "Mistral"),
base_url="https://api.mistral.ai/v1",
)
else: # openai
return OpenAI(api_key=_read_key("OPENAI_API_KEY", "openai_api.txt", "OpenAI"))
def _get_client_for(model: str):
"""Return (and cache) the appropriate API client for the given model name."""
p = _provider(model)
if p not in _client_cache:
_client_cache[p] = _make_client(p)
return _client_cache[p]
def _pick_translate_model() -> str:
"""Choose a translator that won't truncate. When the user's NOTE_MODEL
has a much bigger output cap than TRANSLATE_MODEL (e.g. deepseek-v4-*
has 384K, gpt-5.1 has 128K, gpt-4o only 16K), prefer NOTE_MODEL so
long Chinese translations of long English drafts don't get cut off
mid-sentence."""
if NOTE_MODEL in ("claude-cli", "codex-cli"):
return NOTE_MODEL
note_cap = _MODEL_MAX_COMPLETION.get(NOTE_MODEL, 0)
tr_cap = _MODEL_MAX_COMPLETION.get(TRANSLATE_MODEL, 0)
if note_cap and tr_cap and note_cap > tr_cap * 2:
return NOTE_MODEL
return TRANSLATE_MODEL
def _translate(text: str, lang: str) -> str:
"""Translate note text to the target language, preserving all Markdown
formatting, image references, LaTeX formulas, and code blocks verbatim.
Only prose text is translated; technical terms keep English with
translation in parentheses on first use.
On detected truncation (finish_reason=length), the text is split at
paragraph boundaries and translated chunk-by-chunk; the chunks are
concatenated back together. This avoids the silent-truncation bug
where a long English draft turned into a short Chinese fragment that
ended mid-sentence or mid-image-link."""
system = (
f"You are a professional translator for technical study notes. "
f"Translate English prose into {lang} while keeping ALL technical "
f"terminology in its original English form. Do NOT translate "
f"technical terms — readers are studying the subject in English "
f"and need to recognize the exact English terminology from lectures, "
f"exams, and textbooks."
)
prompt = (
f"Translate the following study notes into {lang}.\n\n"
f"Rules:\n"
f"1. Translate ONLY the connecting prose (explanatory sentences, "
f"narrative text) into {lang}.\n"
f"2. Keep ALL technical terminology in ENGLISH, verbatim. This "
f"includes — but is not limited to — protocol names (TCP, UDP, HTTP, "
f"DHCP, ARP, ICMP, DNS, RSA, AES…), networking concepts (subnet mask, "
f"MAC address, broadcast, unicast, frame, packet, segment, hub, "
f"switch, router, bridge, LAN, WAN, VPN…), cryptography terms "
f"(symmetric key, public key, private key, cipher, plaintext, "
f"ciphertext, block cipher, stream cipher, hash, signature, session "
f"key, Diffie-Hellman…), algorithm names (CSMA/CD, Caesar cipher, "
f"monoalphabetic cipher, polyalphabetic cipher), proper nouns "
f"(Alice, Bob, Trudy, Ethernet, Wi-Fi, OSI, NUS…), and anything in "
f"code font `…`. Never translate these into {lang}.\n"
f"3. Do NOT write the {lang} translation next to the English term — "
f"just keep the English term as-is. The reader already understands "
f"English technical vocabulary; they need {lang} only for the "
f"connecting narrative.\n"
f"4. Keep EXACTLY as-is without any modification:\n"
f" - Image lines:  *(caption)* — translate ONLY "
f"the non-technical prose inside *(...)*, keep the path + all "
f"English technical terms unchanged\n"
f" - LaTeX: $...$ and $$...$$\n"
f" - Code blocks: ```...```\n"
f" - Callout markers: > [!IMPORTANT]\n"
f" - Markdown formatting: ###, **, *, ---, etc.\n"
f"5. Do NOT shorten, summarize, or omit any content.\n"
f"6. Output ONLY the translated text.\n\n"
f"Example (for Chinese):\n"
f" IN: The symmetric key cryptography scheme uses the same key "
f"for encryption and decryption.\n"
f" OUT: symmetric key cryptography 方案在 encryption 和 decryption "
f"时使用同一个 key。\n\n"
f"---\n\n{text}"
)
_tmodel = _pick_translate_model()
# Generous output budget — Chinese translation of English text often
# tokenizes 1.5-2x larger than the source on cl100k_base, so naive
# len(text)*3 still bumps gpt-4o's 16K cap on chunks past ~5K chars.
_trunc: list[bool] = []
out = _call(_tmodel, system, prompt, len(text) * 3, _truncated=_trunc)
flagged = _trunc and _trunc[0]
# Some providers (notably DeepSeek's V4 chat completions) return
# finish_reason="stop" even when the output was cut mid-token. Fall
# back to a content-shape heuristic — broken UTF-8, mid-word cuts,
# unbalanced markdown image links — so those silent truncations
# don't end up in the cache.
if not flagged and _looks_truncated(out):
flagged = True
if flagged:
# Split at paragraph boundaries and translate chunk-by-chunk to
# stay under the per-call output cap. Falls back to keeping the
# English source for any chunk that still won't fit, rather than
# caching a truncated translation.
return _translate_chunked(text, lang)
return out
_TRUNC_IMAGE_RE = re.compile(r"!\[[^\]]*\]\([^)\s\n]*\Z")
_SENTENCE_END_RE = re.compile(
r"[.!?。!?]\s*[*_`>]*\s*\Z|[\)\]\*_`>]\s*\Z|[一-鿿][\)\]\*_`>]?\s*\Z"
# Permissive: end with western/CJK terminator, closing markdown
# punctuation, or any Chinese character (Chinese sentences often
# end with the period folded into the last char's metric).
)
def _looks_truncated(text: str) -> bool:
"""Heuristic truncation detector for cases where the provider returns
finish_reason='stop' but the text was actually cut mid-stream.
Conservative — false positives waste a chunk-translate retry but
don't lose data; false negatives cache a broken section, which is
what we just shipped a fix for.
"""
if not text:
return True
s = text.rstrip()
if not s:
return True
# 1. Broken UTF-8 replacement char at the end → certain truncation
if s.endswith("�"):
return True
# 2. Open image-link without closing paren — `:
return True
# 3. Ends mid-ASCII-word (alphabetic char, no sentence end nearby)
last = s[-1]
if last.isascii() and last.isalpha():
# Allow technical term endings ONLY if a closing punct sits
# within the last few chars. `_SENTENCE_END_RE` matches the
# tail with permissive markdown closings; if it doesn't match
# AND we end on a bare letter, assume mid-word truncation.
if not _SENTENCE_END_RE.search(s[-12:]):
return True
return False
def _translate_chunked(text: str, lang: str, max_chunk_chars: int = 3500) -> str:
"""Recursive paragraph-by-paragraph translation. Joined back with the
same separator the splitter used so Markdown structure is preserved."""
paragraphs = text.split("\n\n")
out_parts: list[str] = []
cur: list[str] = []
cur_len = 0
for p in paragraphs:
if cur_len + len(p) + 2 > max_chunk_chars and cur:
out_parts.append("\n\n".join(cur))
cur = [p]
cur_len = len(p)
else:
cur.append(p)
cur_len += len(p) + 2
if cur:
out_parts.append("\n\n".join(cur))
translated: list[str] = []
for part in out_parts:
if not part.strip():
translated.append(part)
continue
try:
t = _translate(part, lang) # depth-limited: chunks are small
translated.append(t)
except Exception:
# Failed to translate this chunk — keep it in English rather
# than dropping content silently.
translated.append(part)
return "\n\n".join(translated)
_MODEL_MAX_COMPLETION = {
# Conservative per-model output-token caps for OpenAI models. The API
# rejects requests where max_tokens exceeds these, so we clamp here.
"gpt-4o": 16384,
"gpt-4o-2024-08-06": 16384,
"gpt-4o-2024-11-20": 16384,
"gpt-4o-mini": 16384,
"gpt-4.1": 32768,
"gpt-4.1-mini": 32768,
"gpt-4.1-nano": 32768,
"gpt-5.1": 128000,
"gpt-5.2": 128000,
"o3": 100000,
"o4-mini": 100000,
# DeepSeek V4 (Pro + Flash) share a 384K max-output cap on the public
# API; legacy deepseek-chat / deepseek-reasoner alias to v4-flash.
"deepseek-v4-pro": 384000,
"deepseek-v4-flash": 384000,
"deepseek-chat": 384000,
"deepseek-reasoner": 384000,
}
def _cap_tokens(model: str, max_tokens: int) -> int:
"""Clamp max_tokens to the model's max completion-token limit."""
cap = _MODEL_MAX_COMPLETION.get(model)
if cap and max_tokens > cap:
return cap
return max_tokens
def _call(model: str, system: str, user: str, max_tokens: int,
_truncated: list | None = None) -> str:
"""Call any supported LLM (OpenAI, Gemini, Anthropic, or Claude CLI).
If *_truncated* is a list, appends True/False to indicate whether the
response was cut short by the token limit.
"""
max_tokens = _cap_tokens(model, max_tokens)
# ── Claude CLI mode: call `claude -p` as subprocess ──────────────────
if _provider(model) == "claude-cli":
import subprocess as _sp
cmd = ["claude", "-p", "--output-format", "text"]
if system:
cmd.extend(["--system-prompt", system])
result = _sp.run(
cmd, input=user, capture_output=True, text=True,
timeout=600,
)
content = result.stdout.strip()
if _truncated is not None:
_truncated.append(False) # CLI handles its own limits
if result.returncode != 0 and not content:
raise RuntimeError(f"claude -p failed (code {result.returncode}): {result.stderr[:500]}")
return content
# ── Codex CLI mode: call `codex exec` as subprocess ──────────────────
# Auth is handled by the `codex` CLI itself (prior `codex login`).
# We run non-interactively, read-only sandbox, outside a git repo, and
# capture only the agent's final message via `-o <file>` so we don't
# have to parse the streaming event log on stdout.
# The caller's ~/.codex/config.toml default (e.g. gpt-5.2-codex) is
# often not available on a ChatGPT-plan login, so we override to
# gpt-5.2 which is broadly available on ChatGPT plans. Set
# AUTONOTE_CODEX_MODEL to pick a different one — gpt-5.1 requires
# an API-key codex login, gpt-5.4 / gpt-5.5 / gpt-5.4-mini work on
# ChatGPT-only accounts.
if _provider(model) == "codex-cli":
import subprocess as _sp
import tempfile as _tf
import os as _os2
out_fd, out_file = _tf.mkstemp(prefix="codex_out_", suffix=".txt")
_os2.close(out_fd)
try:
prompt_text = f"{system}\n\n{user}" if system else user
codex_model = _os2.environ.get("AUTONOTE_CODEX_MODEL", "gpt-5.2")
cmd = [
"codex", "exec",
"-m", codex_model,
"--skip-git-repo-check",
"-s", "read-only",
"-o", out_file,
"-", # read prompt from stdin
]
result = _sp.run(
cmd, input=prompt_text, capture_output=True, text=True,
timeout=1800,
)
try:
content = Path(out_file).read_text(encoding="utf-8").strip()
except Exception:
content = ""
if _truncated is not None:
_truncated.append(False) # CLI handles its own limits
if result.returncode != 0 and not content:
err = (result.stderr or result.stdout or "").strip()
# Surface the real failure at the *tail* of stderr (quota,
# auth, 400s from the provider). The head is usually just
# skill-loader warnings and the session preamble.
tail = err[-600:] if len(err) > 600 else err
raise RuntimeError(
f"codex exec failed (code {result.returncode}): {tail}"
)
return content
finally:
try:
Path(out_file).unlink()
except Exception:
pass
client = _get_client_for(model)
if _provider(model) == "anthropic":
kwargs: dict = {"model": model, "max_tokens": max_tokens,
"messages": [{"role": "user", "content": user}]}
if system:
kwargs["system"] = system
r = client.messages.create(**kwargs)
if _truncated is not None:
_truncated.append(r.stop_reason == "max_tokens")
return r.content[0].text.strip() if r.content else ""
# OpenAI-compatible (OpenAI + Gemini via OpenAI compat layer)
msgs = []
if system:
msgs.append({"role": "system", "content": system})
msgs.append({"role": "user", "content": user})
last_err = None
for tok in ("max_completion_tokens", "max_tokens"):
try:
r = client.chat.completions.create(
model=model, messages=msgs, **{tok: max_tokens})
if _truncated is not None:
reason = getattr(r.choices[0], "finish_reason", None)
_truncated.append(reason == "length")
content = r.choices[0].message.content
return content.strip() if content else ""
except Exception as e:
s = str(e)
if "max_tokens" in s or "max_completion_tokens" in s:
last_err = e
continue
raise
raise RuntimeError(f"Cannot call {model}: {last_err}")
# ── Slide loading & rendering ─────────────────────────────────────────────────
class SlideInfo:
__slots__ = ("index", "label", "text", "has_code", "word_count")
def __init__(self, index: int, label: str, text: str):
self.index = index
self.label = label
self.text = text
self.has_code = bool(re.search(
r"[{};]\s*$|^\s*(int|void|def |class |#include|pthread|malloc)",
text, re.MULTILINE))
self.word_count = len(text.split())
def _load_slides(slide_path: Path) -> list[SlideInfo]:
ext = slide_path.suffix.lower()
if ext == ".pdf":
import fitz
doc = fitz.open(str(slide_path))
out = []
for i, page in enumerate(doc):
text = page.get_text().strip()
label = next((ln.strip() for ln in text.splitlines() if ln.strip()), f"Page {i+1}")
out.append(SlideInfo(i, label[:80], text))
doc.close()
return out
if ext in (".pptx", ".ppt"):
from pptx import Presentation
prs = Presentation(str(slide_path))
out = []
for i, slide in enumerate(prs.slides):
parts = []
for shape in slide.shapes:
if shape.has_text_frame:
for para in shape.text_frame.paragraphs:
ln = para.text.strip()
if ln: parts.append(ln)
try:
notes = slide.notes_slide.notes_text_frame.text.strip()
if notes: parts.append(notes)
except Exception:
pass
text = "\n".join(parts)
label = parts[0][:80] if parts else f"Slide {i+1}"
out.append(SlideInfo(i, label, text))
return out
if ext in (".docx", ".doc"):
from docx import Document
PAGE_PARA = 15
doc = Document(str(slide_path))
paras = [p.text.strip() for p in doc.paragraphs if p.text.strip()]
out = []
for pi, start in enumerate(range(0, max(len(paras), 1), PAGE_PARA)):
chunk = paras[start:start + PAGE_PARA]
text = "\n".join(chunk)
label = chunk[0][:80] if chunk else f"Page {pi+1}"
out.append(SlideInfo(pi, label, text))
return out
raise ValueError(f"Unsupported format: {ext}")
def render_slide_images(slide_path: Path, out_dir: Path,
indices: list[int] | None = None) -> dict[int, Path]:
"""Render PDF pages to PNG. If indices provided, only render those pages."""
if slide_path.suffix.lower() != ".pdf":
return {}
import fitz
from PIL import Image as PILImage
out_dir.mkdir(parents=True, exist_ok=True)
doc = fitz.open(str(slide_path))
mat = fitz.Matrix(IMAGE_RENDER_SCALE, IMAGE_RENDER_SCALE)
mapping: dict[int, Path] = {}
pages = indices if indices is not None else list(range(len(doc)))
for i in pages:
if i >= len(doc):
continue
png = out_dir / f"slide_{i+1:03d}.png"
if not png.exists():
px = doc[i].get_pixmap(matrix=mat)
pil = PILImage.frombytes("RGB", [px.width, px.height], px.samples)
pil.save(str(png))
del px, pil
mapping[i] = png
doc.close()
return mapping
# ── Chunk helpers ─────────────────────────────────────────────────────────────
def _clean_artifacts(text: str) -> str:
"""Remove pipeline artifacts that may leak into generated notes."""
lines = text.splitlines()
cleaned = []
for line in lines:
stripped = line.strip()
if "terminology or factual errors" in stripped:
continue
# Clean section-header artifacts
line = re.sub(r"##\s*NUS Confidential\s*##", "", line)
line = re.sub(r"[©(]\s*c?\)?\s*CS\d+", "", line)
cleaned.append(line)
return "\n".join(cleaned)
def _ensure_frames_embedded(
draft: str,
slides: list,
img_map: dict,
img_cache: dict,
out_dir: Path,
source: str,
) -> str:
"""Append any frames the LLM forgot to include in its draft.
The `_build_chunk_prompt` lists every available frame in the prompt
under "Available images", but DeepSeek V4 (and some other models)
are inconsistent at actually emitting the `` markdown
even when explicitly asked. This safety net keeps the contract:
every extracted frame is given a chance to surface in the final
note. The downstream image-filter pass (`filter_images_pass`) still
runs and can drop junk frames — we just guarantee they reach that
pass instead of being silently dropped by the LLM.
"""
if not img_map:
return draft
appended: list[str] = []
for s in slides:
if s.index not in img_map:
continue
rel = img_map[s.index].relative_to(out_dir)
rel_str = str(rel).replace("\\", "/")
# Already cited somewhere in the draft? Skip.
if rel_str in draft:
continue
cache_key = f"page_{s.index}"
desc = (img_cache.get(cache_key, "") or "").strip()
# First sentence of the description as the caption (max 140 chars).
caption = desc[:140]
for end in ".。!?!?":
idx = caption.find(end)
if 25 < idx < len(caption):
caption = caption[:idx + 1]
break
if not caption:
caption = f"Frame {s.index + 1}" if source == "screenshare" \
else f"Slide {s.index + 1}"
prefix = "Frame" if source == "screenshare" else "Slide"
appended.append(f" *({caption})*")
if not appended:
return draft
return draft.rstrip() + "\n\n" + "\n\n".join(appended) + "\n"
_BAD_LABEL = re.compile(
r"^\s*(\d+|[A-Z]{2,4}\d{4}[\s\-].*|CS\d+.*|AY\d+.*|\[.*\]|"
r".*NUS Confidential.*|.*©\s*CS\d+.*|\(c\)\s*CS\d+.*|Page\s+\d+)\s*$",
re.IGNORECASE,
)
def _dedup_slides(slides: list[SlideInfo], threshold: float = 0.85) -> list[SlideInfo]:
"""Remove near-duplicate slides by comparing text content.
Groups consecutive slides whose text Jaccard similarity exceeds
*threshold* and keeps only the one with the most text (typically
the "fully revealed" version of an incremental slide). Also deduplicates
non-consecutive slides that are very similar (threshold 0.9).
"""
if len(slides) <= 1:
return slides
def _words(s: SlideInfo) -> set[str]:
return set(s.text.lower().split())
# Pass 1: merge consecutive near-duplicates
kept: list[SlideInfo] = [slides[0]]
for s in slides[1:]:
wa, wb = _words(kept[-1]), _words(s)
union = wa | wb
if union and len(wa & wb) / len(union) >= threshold:
# Keep the one with more content
if s.word_count > kept[-1].word_count:
kept[-1] = s
else:
kept.append(s)
# Pass 2: remove non-consecutive near-duplicates (very high threshold)
final: list[SlideInfo] = []
seen_texts: list[set[str]] = []
for s in kept:
ws = _words(s)
is_dup = False
for prev_ws in seen_texts:
union = ws | prev_ws
if union and len(ws & prev_ws) / len(union) >= 0.9:
is_dup = True
break
if not is_dup:
final.append(s)
seen_texts.append(ws)
return final
def _chunk_title(slides_in_chunk: list[SlideInfo]) -> str:
"""Pick a representative title for a chunk of slides.
Prefer short, meaningful slide labels (section headers).
Skip labels that are pure numbers, course codes, or bracket tags.
"""
def _is_good(label: str) -> bool:
if not label or len(label) < 4:
return False
if _BAD_LABEL.match(label):
return False