-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
2720 lines (2427 loc) · 110 KB
/
Copy pathgui.py
File metadata and controls
2720 lines (2427 loc) · 110 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
#!/usr/bin/env python3
"""
gui.py — Material Design desktop GUI for the auto_note pipeline.
Requires: pip install flet
Usage: python gui.py
"""
from __future__ import annotations
import json
import os
import re
import subprocess
import sys
import threading
import time
from pathlib import Path
import flet as ft
# ── Project layout ────────────────────────────────────────────────────────────
PROJECT_DIR = Path(__file__).parent
# The ML venv is always at ~/.auto_note/venv/ regardless of frozen/dev mode.
# (The installer creates it there; dev mode uses it directly.)
_VENV_SUBPATH = "Scripts/python.exe" if sys.platform == "win32" else "bin/python"
ML_VENV_DIR = Path.home() / ".auto_note" / "venv"
ML_VENV_PYTHON = str(ML_VENV_DIR / _VENV_SUBPATH)
# Initial Python: prefer the managed venv if already installed; otherwise
# fall back to sys.executable (dev mode) or system python3 (frozen/AppImage).
if Path(ML_VENV_PYTHON).exists():
PYTHON = ML_VENV_PYTHON
elif getattr(sys, "frozen", False):
import shutil as _shutil
if sys.platform == "win32":
PYTHON = _shutil.which("python") or "python"
else:
PYTHON = _shutil.which("python3") or _shutil.which("python") or "python3"
else:
PYTHON = sys.executable
# User data directory: persistent across app restarts.
# When running as a PyInstaller bundle (AppImage / .exe), __file__ resolves to
# a temporary extraction folder that is deleted on exit — any files written
# there are lost. Use ~/.auto_note/ instead so credentials and config survive.
if getattr(sys, "frozen", False):
DATA_DIR = Path.home() / ".auto_note"
else:
DATA_DIR = PROJECT_DIR
DATA_DIR.mkdir(parents=True, exist_ok=True)
# Pipeline scripts are installed to ~/.auto_note/scripts/ in AppImage mode.
# In dev mode the scripts live directly in PROJECT_DIR (no scripts/ subdir).
SCRIPTS_DIR = DATA_DIR / "scripts"
def _install_scripts() -> None:
"""Copy bundled pipeline scripts from AppImage to ~/.auto_note/scripts/."""
if not getattr(sys, "frozen", False):
return # dev mode: use files in place
import shutil as _sh
SCRIPTS_DIR.mkdir(parents=True, exist_ok=True)
for fname in [
"downloader.py", "extract_caption.py", "frame_extractor.py",
"semantic_alignment.py", "alignment_parser.py", "note_generation.py",
]:
src = PROJECT_DIR / fname
dst = SCRIPTS_DIR / fname
if src.exists():
_sh.copy2(str(src), str(dst))
def _script(name: str) -> Path:
"""Return the path to a pipeline script, falling back to PROJECT_DIR in dev mode."""
installed = SCRIPTS_DIR / name
if installed.exists():
return installed
return PROJECT_DIR / name # dev mode: scripts are in the project root
# Lazily-resolved script paths. In AppImage mode, _install_scripts() copies
# scripts to SCRIPTS_DIR *after* module load, so we must re-resolve on first
# access rather than caching stale paths from module-init time.
class _ScriptDict(dict):
"""Dict that re-resolves script paths on every access."""
_NAMES = {
"downloader": "downloader.py",
"transcribe": "extract_caption.py",
"frame_extractor": "frame_extractor.py",
"align": "semantic_alignment.py",
"generate": "note_generation.py",
}
def __getitem__(self, key: str) -> Path:
return _script(self._NAMES[key])
def __contains__(self, key: object) -> bool:
return key in self._NAMES
SCRIPTS = _ScriptDict()
_DEFAULT_PYTHON = PYTHON # auto-detected fallback; may be overridden by user config
# ML packages needed by the pipeline scripts (GUI requirements are bundled separately)
_ML_PACKAGES = [
"tqdm",
"faster-whisper",
"sentence-transformers",
"faiss-cpu",
"pymupdf",
"python-pptx",
"python-docx",
"openai",
"anthropic",
"google-generativeai",
"requests",
"pillow",
"httpx",
"playwright",
"canvasapi",
# PanoptoDownloader is not on PyPI; install from GitHub.
# Its declared version pins (requests~=2.27, tqdm~=4.62, yarl~=1.7) are
# conservative — newer versions work fine.
"ffmpeg-progress-yield",
"pycryptodomex",
"git+https://github.com/Panopto-Video-DL/Panopto-Video-DL-lib.git",
]
def _find_base_python(log_fn: callable) -> str:
"""Find a Python 3 with ssl+venv support.
Tries (in order):
1. Login-shell probe via bash/zsh (Unix only)
2. Common conda/system install locations (platform-specific)
Returns the executable path or '' if nothing is found.
"""
import shutil as _sh
home = Path.home()
# 1) Login shell probe — bash/zsh don't exist on Windows
if sys.platform != "win32":
log_fn("► Probing login shell for Python …")
for shell_cmd in [
["bash", "-l", "-c",
"python3 -c 'import ssl,venv,sys; print(sys.executable)'"],
["zsh", "-l", "-c",
"python3 -c 'import ssl,venv,sys; print(sys.executable)'"],
]:
try:
r = subprocess.run(shell_cmd, capture_output=True,
text=True, timeout=15)
if r.returncode == 0:
for line in reversed(r.stdout.strip().splitlines()):
line = line.strip()
if line and Path(line).exists():
return line
except Exception:
pass
# 2) Common install locations (platform-specific)
if sys.platform == "win32":
_candidates = [
str(home / "miniconda3" / "python.exe"),
str(home / "Miniconda3" / "python.exe"),
str(home / "anaconda3" / "python.exe"),
str(home / "Anaconda3" / "python.exe"),
str(home / "miniforge3" / "python.exe"),
str(home / "mambaforge" / "python.exe"),
# Standard Windows Python installer locations
str(home / "AppData" / "Local" / "Programs" / "Python" / "Python313" / "python.exe"),
str(home / "AppData" / "Local" / "Programs" / "Python" / "Python312" / "python.exe"),
str(home / "AppData" / "Local" / "Programs" / "Python" / "Python311" / "python.exe"),
str(home / "AppData" / "Local" / "Programs" / "Python" / "Python310" / "python.exe"),
str(Path("C:/miniconda3/python.exe")),
str(Path("C:/anaconda3/python.exe")),
str(Path("C:/ProgramData/miniconda3/python.exe")),
str(Path("C:/ProgramData/anaconda3/python.exe")),
_sh.which("python") or "",
]
else:
_candidates = [
str(home / "miniconda3/bin/python3"),
str(home / "miniconda3/bin/python"),
str(home / "anaconda3/bin/python3"),
str(home / "anaconda3/bin/python"),
str(home / "miniforge3/bin/python3"),
str(home / "miniforge3/bin/python"),
str(home / "mambaforge/bin/python3"),
str(home / "mambaforge/bin/python"),
str(home / ".local/share/mamba/bin/python3"),
"/opt/conda/bin/python3",
"/opt/miniconda3/bin/python3",
"/opt/anaconda3/bin/python3",
_sh.which("python3") or "",
_sh.which("python") or "",
"/usr/bin/python3",
"/usr/local/bin/python3",
]
for cand in _candidates:
if not cand or not Path(cand).exists():
continue
r = subprocess.run([cand, "-c", "import ssl, venv"],
capture_output=True, timeout=5)
if r.returncode == 0:
return cand
return ""
def _detect_cuda() -> tuple[int, int] | None:
"""Return (major, minor) CUDA version from nvidia-smi, or None if no GPU."""
try:
r = subprocess.run(
["nvidia-smi"], capture_output=True, text=True, timeout=10
)
if r.returncode == 0:
m = re.search(r"CUDA Version:\s*(\d+)\.(\d+)", r.stdout)
if m:
return (int(m.group(1)), int(m.group(2)))
return (12, 0) # nvidia-smi works but version unreadable → assume 12.x
except Exception:
pass
return None
def _torch_index_url(cuda: tuple[int, int] | None) -> str | None:
"""Return the PyTorch extra-index-url for the detected CUDA version."""
if cuda is None:
return None # CPU build from PyPI
major, minor = cuda
version = major * 10 + minor # 12.8 → 128
if version >= 128:
return "https://download.pytorch.org/whl/cu128"
if version >= 126:
return "https://download.pytorch.org/whl/cu126"
if version >= 124:
return "https://download.pytorch.org/whl/cu124"
return "https://download.pytorch.org/whl/cu121"
def _load_python_from_config() -> None:
"""Override PYTHON global with the user-configured path or the managed venv."""
global PYTHON
config_file = DATA_DIR / "config.json"
if config_file.exists():
try:
cfg = json.load(open(config_file))
p = cfg.get("PYTHON_PATH", "").strip()
if p:
PYTHON = p
return
except Exception:
pass
# Auto-use managed venv if it exists and no explicit path is configured
if Path(ML_VENV_PYTHON).exists():
PYTHON = ML_VENV_PYTHON
OUTPUT_DIR: Path = Path.home() / "AutoNote"
def _load_output_dir_from_config() -> None:
"""Load user-configured output directory from config.json."""
global OUTPUT_DIR
config_file = DATA_DIR / "config.json"
if config_file.exists():
try:
cfg = json.load(open(config_file))
p = cfg.get("OUTPUT_DIR", "").strip()
if p:
OUTPUT_DIR = Path(p)
except Exception:
pass
def _get_output_dir() -> Path:
"""Return current output directory, creating it if needed."""
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
return OUTPUT_DIR
COURSES: dict[int, str] = {} # populated from Canvas API after token is entered
_SKIP_KEYWORDS = [
"training", "pdp", "rmcpdp", "osa", "soct", "travel",
"essentials", "respect", "consent", "osh",
]
def _load_courses_from_canvas() -> str:
"""Fetch active courses from Canvas and update the global COURSES dict.
Returns "" on success, or a human-readable error string on failure."""
COURSES.clear()
token_file = DATA_DIR / "canvas_token.txt"
config_file = DATA_DIR / "config.json"
token = token_file.read_text().strip() if token_file.exists() else ""
if not token:
return "Canvas token not saved — enter it in Settings → API Keys."
cfg = json.load(open(config_file)) if config_file.exists() else {}
canvas_url = cfg.get("CANVAS_URL", "").strip().rstrip("/")
if canvas_url and not canvas_url.startswith(("http://", "https://")):
canvas_url = "https://" + canvas_url
if not canvas_url:
return "Canvas URL not saved — enter it in Settings → Connection."
try:
import requests
resp = requests.get(
f"{canvas_url}/api/v1/courses",
headers={"Authorization": f"Bearer {token}"},
params={"enrollment_state": "active", "per_page": 100},
timeout=10,
)
if resp.status_code == 401:
return "401 Unauthorized — Canvas token is invalid or expired. Generate a new one in Canvas → Account → Settings → New Access Token."
resp.raise_for_status()
for c in resp.json():
name = c.get("name") or c.get("course_code") or ""
if not name:
continue
if any(kw in name.lower() for kw in _SKIP_KEYWORDS):
continue
COURSES[c["id"]] = name
return ""
except Exception as exc:
return str(exc)
# ── Palette ───────────────────────────────────────────────────────────────────
C_PRIMARY = ft.Colors.CYAN_400
C_SECONDARY = ft.Colors.AMBER_400
C_SUCCESS = ft.Colors.GREEN_400
C_ERROR = ft.Colors.RED_400
C_WARN = ft.Colors.ORANGE_400
C_SURFACE = "#1E2A2A"
C_CARD = "#1A2626"
C_RAIL = "#111E1E"
C_OUTPUT_BG = "#0D1515"
MONO = "Courier New"
# ── Pipeline state helpers ────────────────────────────────────────────────────
def _manifest() -> dict:
p = DATA_DIR / "manifest.json"
return json.loads(p.read_text()) if p.exists() else {}
def _video_status(course_id: int) -> tuple[int, int]:
m = _manifest()
items = [v for v in m.values() if str(course_id) in v.get("path", "")]
done = sum(1 for v in items if v.get("status") == "done")
return done, len(items)
def _caption_count(course_id: int) -> int:
d = DATA_DIR / str(course_id) / "captions"
return len(list(d.glob("*.json"))) if d.exists() else 0
def _alignment_count(course_id: int) -> int:
d = DATA_DIR / str(course_id) / "alignment"
return len([f for f in d.glob("*.json")
if "compact" not in f.name]) if d.exists() else 0
def _notes_path(course_id: int) -> Path | None:
d = DATA_DIR / str(course_id) / "notes"
if d.exists():
mds = list(d.glob("*.md"))
return mds[0] if mds else None
return None
def _course_name_from_notes(course_id: int) -> str:
base = COURSES.get(course_id, f"Course {course_id}")
d = DATA_DIR / str(course_id) / "notes"
if d.exists():
for md in d.glob("*.md"):
stem = md.stem.replace("_notes", "").replace("_", " ")
if stem:
return stem
return base
def _read_constant(script_key: str, name: str) -> str:
src = SCRIPTS[script_key].read_text(errors="ignore")
m = re.search(rf"^{name}\s*=\s*(.+)", src, re.MULTILINE)
if m:
return re.sub(r"\s*#.*$", "", m.group(1)).strip().strip('"')
return "?"
def _write_constant(script_key: str, name: str, new_display_val: str) -> bool:
"""Write a constant back to its source file with the correct Python literal type."""
path = SCRIPTS[script_key]
try:
src = path.read_text(errors="ignore")
def _format_val() -> str:
# None keyword → bare None
if new_display_val == "None":
return "None"
# Numeric → bare (int or float)
try:
float(new_display_val)
return new_display_val
except ValueError:
pass
# String → always quoted
return f'"{new_display_val}"'
formatted = _format_val()
# Match: NAME = VALUE [# optional comment]
# The value part may be a quoted string, bare identifier, or number.
# Preserve any inline comment that follows.
new_src, n = re.subn(
rf'^({name}\s*=\s*)([^\n#]+)(#[^\n]*)?$',
lambda m: m.group(1) + formatted + (" " + m.group(3) if m.group(3) else ""),
src, count=1, flags=re.MULTILINE,
)
if n == 0:
# Fallback: value might be glued to comment (e.g. "None# comment")
new_src, n = re.subn(
rf'^({name}\s*=\s*)(\S+)(#[^\n]*)?$',
lambda m: m.group(1) + formatted + (" " + m.group(3) if m.group(3) else ""),
src, count=1, flags=re.MULTILINE,
)
if n == 0:
return False
path.write_text(new_src)
return True
except Exception:
return False
# ── Shared state ──────────────────────────────────────────────────────────────
class AppState:
def __init__(self) -> None:
self.running = False
self.proc: subprocess.Popen | None = None
def stop(self) -> None:
if self.proc and self.proc.poll() is None:
self.proc.terminate()
self.running = False
state = AppState()
# ── Output console ────────────────────────────────────────────────────────────
class OutputConsole:
"""
Pinned-bottom terminal panel.
- Streams subprocess stdout+stderr live
- Stop button kills the running process
- Expand fills all available vertical space
"""
def __init__(self, page: ft.Page) -> None:
self.page = page
self._lines = ft.ListView(
expand=True,
spacing=0,
auto_scroll=True,
padding=ft.Padding.symmetric(horizontal=8, vertical=6),
)
self._badge = ft.Text("", size=11, color=C_PRIMARY)
self._stop_btn = ft.IconButton(
icon=ft.Icons.STOP_CIRCLE_OUTLINED,
icon_color=C_ERROR,
tooltip="Stop process",
visible=False,
icon_size=18,
on_click=self._on_stop,
)
self._clear_btn = ft.IconButton(
icon=ft.Icons.DELETE_SWEEP_OUTLINED,
icon_color=ft.Colors.with_opacity(0.45, ft.Colors.WHITE),
tooltip="Clear output",
icon_size=16,
on_click=lambda _: self.clear(),
)
self.container = ft.Column(
controls=[
# Header bar
ft.Container(
content=ft.Row(
controls=[
ft.Icon(ft.Icons.TERMINAL, color=C_PRIMARY, size=14),
ft.Text(" Output", size=12, color=C_PRIMARY,
weight=ft.FontWeight.BOLD),
ft.Container(expand=True),
self._badge,
self._stop_btn,
self._clear_btn,
],
),
padding=ft.Padding.only(top=8, bottom=4),
),
# Scrollable text area — fixed height so form area gets the rest
ft.Container(
content=self._lines,
height=220,
bgcolor=C_OUTPUT_BG,
border_radius=6,
border=ft.border.all(
1, ft.Colors.with_opacity(0.12, ft.Colors.WHITE)
),
),
],
spacing=0,
)
# ── internal ──────────────────────────────────────────────────────────────
def _on_stop(self, _) -> None:
state.stop()
self.write("\n[stopped by user]", color=C_WARN)
self._stop_btn.visible = False
self.set_status("■ stopped", C_WARN)
self.page.update()
# ── public API ─────────────────────────────────────────────────────────────
def write(self, text: str, color: str | None = None) -> None:
for line in text.splitlines():
self._lines.controls.append(
ft.Text(
line,
size=11,
font_family=MONO,
color=color or ft.Colors.with_opacity(0.88, ft.Colors.WHITE),
no_wrap=False,
selectable=True,
)
)
self.page.update()
def clear(self) -> None:
self._lines.controls.clear()
self._badge.value = ""
self.page.update()
def set_status(self, msg: str, color: str = C_PRIMARY) -> None:
self._badge.value = msg
self._badge.color = color
self.page.update()
def run(self, cmd: list[str], on_done: callable | None = None) -> None:
"""Run cmd, streaming stdout+stderr into the console."""
if state.running:
self.write("⚠ Already running — stop it first.", color=C_WARN)
return
state.running = True
self.clear()
self._stop_btn.visible = True
self.set_status("● running…", C_WARN)
# Show full command (script name + all args)
display_cmd = " ".join(
str(c) for c in cmd[1:] # skip python path, keep script + args
)
self.write(f"$ {display_cmd}\n",
color=ft.Colors.with_opacity(0.40, ft.Colors.WHITE))
_UPDATE_INTERVAL = 0.1 # seconds between UI refreshes while streaming
_default_color = ft.Colors.with_opacity(0.88, ft.Colors.WHITE)
def _append_line(text: str, color: str | None = None) -> None:
for line in text.splitlines():
self._lines.controls.append(
ft.Text(
line, size=11, font_family=MONO,
color=color or _default_color,
no_wrap=False, selectable=True,
)
)
def _worker() -> None:
rc = -1
try:
import io as _io
_ANSI_RE = re.compile(
r"\x1b\[[0-9;]*[mABCDEFGHJKST]|\x1b\][^\x07]*\x07"
)
_MAX_LINES = 500
_last_update = time.monotonic()
buf = "" # current line being assembled
def _cur() -> ft.Text:
"""Return (or create) the last Text item — the live line."""
if not self._lines.controls:
t = ft.Text("", size=11, font_family=MONO,
color=_default_color, no_wrap=False,
selectable=True)
self._lines.controls.append(t)
return self._lines.controls[-1]
def _new_line() -> None:
"""Append a blank Text item; trim oldest if over cap."""
self._lines.controls.append(
ft.Text("", size=11, font_family=MONO,
color=_default_color, no_wrap=False,
selectable=True)
)
excess = len(self._lines.controls) - _MAX_LINES
if excess > 0:
del self._lines.controls[:excess]
def _process_chunk(raw: bytes) -> None:
nonlocal buf
text = _ANSI_RE.sub(
"", raw.decode("utf-8", errors="replace")
)
for ch in text:
if ch == "\r":
buf = ""
elif ch == "\n":
if not buf.startswith("<frozen importlib"):
item = _cur()
item.value = buf
low = buf.lower().lstrip()
if low.startswith(
("error", "traceback", "exception")):
item.color = C_ERROR
elif low.startswith("warning"):
item.color = C_WARN
_new_line()
buf = ""
else:
buf += ch
# ── Launch subprocess ─────────────────────────────────────
# On Unix use a pty so tqdm/rich see a real terminal and use
# \r for in-place refresh. On Windows pty is unavailable so
# fall back to a plain pipe (progress bars produce extra lines
# but work correctly).
env = {
**os.environ,
"PYTHONUNBUFFERED": "1",
"PYTHONIOENCODING": "utf-8",
"PYTHONUTF8": "1",
}
_use_pty = False
if sys.platform != "win32":
try:
import pty as _pty
master_fd, slave_fd = _pty.openpty()
env.update({"TERM": "xterm-256color", "COLUMNS": "100"})
state.proc = subprocess.Popen(
cmd,
stdout=slave_fd, stderr=slave_fd,
close_fds=True,
cwd=str(_get_output_dir()),
env=env,
)
os.close(slave_fd)
_use_pty = True
except Exception:
_use_pty = False
if not _use_pty:
state.proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=str(_get_output_dir()),
env=env,
)
# ── Stream output ─────────────────────────────────────────
if _use_pty:
try:
with _io.open(master_fd, "rb", closefd=True) as master:
while True:
try:
chunk = master.read(4096)
except OSError:
break
if not chunk:
break
_process_chunk(chunk)
now = time.monotonic()
if now - _last_update >= _UPDATE_INTERVAL:
if buf:
_cur().value = buf
self.page.update()
_last_update = now
except OSError:
pass
else:
for line in state.proc.stdout:
_process_chunk(line)
now = time.monotonic()
if now - _last_update >= _UPDATE_INTERVAL:
if buf:
_cur().value = buf
self.page.update()
_last_update = now
if buf:
_cur().value = buf
self.page.update()
state.proc.wait()
rc = state.proc.returncode
if rc == 0:
_append_line("\n✓ Completed successfully.", C_SUCCESS)
self.set_status("✓ done", C_SUCCESS)
elif rc == -15:
pass # user stopped it
else:
_append_line(f"\n✗ Exited with code {rc}.", C_ERROR)
self.set_status(f"✗ code {rc}", C_ERROR)
except Exception as exc:
_append_line(f"\n✗ {exc}", C_ERROR)
self.set_status("✗ error", C_ERROR)
finally:
state.running = False
state.proc = None
self._stop_btn.visible = False
self.page.update()
# Only advance the pipeline chain when the step succeeded.
# On failure rc != 0 — stop the chain so the user sees the error.
if on_done and rc == 0:
on_done()
threading.Thread(target=_worker, daemon=True).start()
# ── UI helpers ────────────────────────────────────────────────────────────────
def _card(content: ft.Control, padding: int = 16) -> ft.Card:
return ft.Card(
content=ft.Container(content=content, padding=padding, bgcolor=C_CARD),
elevation=2,
)
def _section_title(text: str, icon: str | None = None) -> ft.Row:
controls: list[ft.Control] = []
if icon:
controls += [ft.Icon(icon, color=C_PRIMARY, size=18), ft.Container(width=8)]
controls.append(
ft.Text(text, size=15, weight=ft.FontWeight.BOLD, color=C_PRIMARY)
)
return ft.Row(controls=controls)
def _label(text: str) -> ft.Text:
return ft.Text(text, size=12, color=ft.Colors.with_opacity(0.60, ft.Colors.WHITE))
def _chip(label: str, color: str) -> ft.Container:
return ft.Container(
content=ft.Text(label, size=10, color=color, weight=ft.FontWeight.BOLD),
bgcolor=ft.Colors.with_opacity(0.12, color),
border_radius=12,
padding=ft.Padding.symmetric(horizontal=8, vertical=3),
)
def _status_chip(done: int, total: int) -> ft.Container:
if total == 0:
return _chip("○ none", ft.Colors.with_opacity(0.35, ft.Colors.WHITE))
if done >= total:
return _chip(f"✓ {done}/{total}", C_SUCCESS)
return _chip(f"◐ {done}/{total}", C_WARN)
def _course_dropdown(value: str, on_select: callable,
include_all: bool = False) -> ft.Dropdown:
"""
Bug fix: use `on_select` (Flet 0.82+) and read value from `e.data`
rather than `e.control.value` (which may not be updated yet).
"""
options = []
if include_all:
options.append(ft.dropdown.Option(key="0", text="All courses"))
for cid, name in COURSES.items():
options.append(ft.dropdown.Option(key=str(cid), text=f"{name} ({cid})"))
if not options:
options.append(ft.dropdown.Option(
key="", text="— no courses, add Canvas token in Settings —"))
return ft.Dropdown(
options=options,
value=value if COURSES else None,
on_select=on_select,
bgcolor=C_SURFACE,
border_color=ft.Colors.with_opacity(0.25, ft.Colors.WHITE),
focused_border_color=C_PRIMARY,
color=ft.Colors.WHITE,
label="Course",
label_style=ft.TextStyle(color=C_PRIMARY),
expand=True,
)
def _text_field(label: str, value: str = "", hint: str = "",
expand: bool | int = True) -> ft.TextField:
return ft.TextField(
label=label,
value=value,
hint_text=hint,
bgcolor=C_SURFACE,
border_color=ft.Colors.with_opacity(0.25, ft.Colors.WHITE),
focused_border_color=C_PRIMARY,
color=ft.Colors.WHITE,
label_style=ft.TextStyle(color=C_PRIMARY),
cursor_color=C_PRIMARY,
expand=expand,
)
def _run_btn(text: str, icon: str, on_click: callable) -> ft.FilledButton:
return ft.FilledButton(
content=ft.Row(
controls=[ft.Icon(icon, size=16), ft.Text(text, size=13)],
tight=True, spacing=6,
),
style=ft.ButtonStyle(
bgcolor=C_PRIMARY,
color=ft.Colors.BLACK,
padding=ft.Padding.symmetric(horizontal=16, vertical=10),
),
on_click=on_click,
)
def _outlined_btn(text: str, icon: str, on_click: callable) -> ft.OutlinedButton:
return ft.OutlinedButton(
content=ft.Row(
controls=[ft.Icon(icon, size=16, color=C_PRIMARY),
ft.Text(text, size=13, color=C_PRIMARY)],
tight=True, spacing=6,
),
style=ft.ButtonStyle(
side=ft.BorderSide(1, C_PRIMARY),
padding=ft.Padding.symmetric(horizontal=14, vertical=10),
),
on_click=on_click,
)
def _page_layout(scroll_controls: list[ft.Control]) -> ft.Column:
"""Scrollable form area that fills its allotted space."""
return ft.Column(
controls=scroll_controls,
spacing=12,
scroll=ft.ScrollMode.AUTO,
expand=True,
)
# ── Page: Dashboard ───────────────────────────────────────────────────────────
def build_dashboard(page: ft.Page, console: OutputConsole,
navigate: callable | None = None,
on_refresh: callable | None = None) -> ft.Column:
def _course_card(cid: int, name: str) -> ft.Card:
vd, vt = _video_status(cid)
caps = _caption_count(cid)
aligns = _alignment_count(cid)
notes_p = _notes_path(cid)
short = name.split()[0]
note_info = (
ft.Text(notes_p.name, size=10,
color=ft.Colors.with_opacity(0.5, ft.Colors.WHITE))
if notes_p else
ft.Text("no notes yet", size=10,
color=ft.Colors.with_opacity(0.3, ft.Colors.WHITE))
)
return ft.Card(
content=ft.Container(
content=ft.Column(controls=[
ft.Row(controls=[
ft.Text(short, size=18, weight=ft.FontWeight.BOLD,
color=C_PRIMARY),
ft.Container(expand=True),
_chip("✓ notes", C_SUCCESS) if notes_p
else _chip("○ pending",
ft.Colors.with_opacity(0.4, ft.Colors.WHITE)),
]),
ft.Text(name, size=11,
color=ft.Colors.with_opacity(0.55, ft.Colors.WHITE)),
ft.Divider(height=10,
color=ft.Colors.with_opacity(0.08, ft.Colors.WHITE)),
ft.Row(controls=[
ft.Column(controls=[_label("Videos"), _status_chip(vd, vt)], spacing=4),
ft.Column(controls=[_label("Captions"), _status_chip(caps, max(caps, vd))], spacing=4),
ft.Column(controls=[_label("Aligned"), _status_chip(aligns, max(aligns, caps))], spacing=4),
], spacing=20),
ft.Container(height=4),
note_info,
], spacing=6),
padding=16,
bgcolor=C_CARD,
),
elevation=3,
expand=True,
)
def _quick(label: str, icon: str, idx: int) -> ft.ElevatedButton:
def _go(_):
if navigate:
navigate(idx)
return ft.ElevatedButton(
content=ft.Row(
controls=[ft.Icon(icon, size=15), ft.Text(label, size=12)],
tight=True, spacing=6,
),
style=ft.ButtonStyle(
bgcolor=ft.Colors.with_opacity(0.08, ft.Colors.WHITE),
color=ft.Colors.WHITE,
side=ft.BorderSide(1, ft.Colors.with_opacity(0.12, ft.Colors.WHITE)),
padding=ft.Padding.symmetric(horizontal=12, vertical=8),
),
on_click=_go,
)
if COURSES:
items = list(COURSES.items())
course_rows = [
ft.Row(controls=[_course_card(cid, name)
for cid, name in items[i:i+2]], spacing=12)
for i in range(0, len(items), 2)
]
else:
course_rows = [_card(ft.Column(controls=[
ft.Container(height=8),
ft.Icon(ft.Icons.SCHOOL_OUTLINED, size=52,
color=ft.Colors.with_opacity(0.25, ft.Colors.WHITE)),
ft.Text("No courses loaded", size=15,
color=ft.Colors.with_opacity(0.45, ft.Colors.WHITE),
weight=ft.FontWeight.W_500),
ft.Text(
"Go to Settings → enter your Canvas URL and API token,\n"
"then save to load your courses automatically.",
size=12, text_align=ft.TextAlign.CENTER,
color=ft.Colors.with_opacity(0.35, ft.Colors.WHITE),
),
ft.Container(height=8),
], horizontal_alignment=ft.CrossAxisAlignment.CENTER, spacing=10))]
refresh_btn = ft.IconButton(
icon=ft.Icons.REFRESH,
tooltip="Refresh courses from Canvas",
icon_color=C_PRIMARY,
on_click=lambda _: on_refresh() if on_refresh else None,
)
scroll_content = [
ft.Row(controls=[
_section_title("Course Overview", ft.Icons.DASHBOARD_OUTLINED),
ft.Container(expand=True),
refresh_btn,
]),
*course_rows,
ft.Container(height=4),
_section_title("Quick Actions", ft.Icons.BOLT_OUTLINED),
ft.Row(controls=[
_quick("Full Pipeline", ft.Icons.PLAY_CIRCLE_OUTLINE, 1),
_quick("Download", ft.Icons.DOWNLOAD_OUTLINED, 2),
_quick("Transcribe", ft.Icons.MIC_NONE, 3),
_quick("Align", ft.Icons.LINK_OUTLINED, 4),
_quick("Generate Notes", ft.Icons.ARTICLE_OUTLINED, 5),
], spacing=8, wrap=True),
]
return _page_layout(scroll_content)
# ── Page: Full Pipeline ───────────────────────────────────────────────────────
def build_pipeline(page: ft.Page, console: OutputConsole) -> ft.Column:
course_val = {"v": str(next(iter(COURSES), ""))}
course_dd = _course_dropdown(
value=course_val["v"],
# Bug fix: read e.data, not e.control.value
on_select=lambda e: course_val.update({"v": e.data}),
)
step_checks = {
"dl_material": ft.Checkbox(label="Download materials", value=True, fill_color=C_PRIMARY),
"dl_video": ft.Checkbox(label="Download videos", value=True, fill_color=C_PRIMARY),
"transcribe": ft.Checkbox(label="Transcribe videos", value=True, fill_color=C_PRIMARY),
"align": ft.Checkbox(label="Align transcripts", value=True, fill_color=C_PRIMARY),
"generate": ft.Checkbox(label="Generate study notes", value=True, fill_color=C_PRIMARY),
}
secretly_sw = ft.Switch(label="Slack mode for downloads",
value=False, active_color=C_PRIMARY)
course_name_f = _text_field("Course name for notes")
detail_label = ft.Text("7", size=22, weight=ft.FontWeight.BOLD, color=C_PRIMARY)
detail_slider = ft.Slider(
min=0, max=10, value=7, divisions=10,
active_color=C_PRIMARY,
on_change=lambda e: (
setattr(detail_label, "value", str(int(e.control.value))),
page.update(),
),
)
lec_filter_f = _text_field("Lecture filter", hint="1-5 or 1,3,5 (blank=all)")
force_sw = ft.Switch(label="Force regenerate", value=False, active_color=C_PRIMARY)
# Per-video notes are the default (one note per video, named after the
# video). Toggle off to merge everything into one course-wide file.
per_video_sw = ft.Switch(label="Per-video notes", value=True, active_color=C_PRIMARY)
# Image source: video screenshots (frames) by default, or PDF slide renders.
# Falls back to the other source if the chosen one isn't available.