-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1280 lines (1151 loc) · 42.3 KB
/
Copy pathcli.py
File metadata and controls
1280 lines (1151 loc) · 42.3 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
"""CLI dispatcher for the docgen tool."""
from __future__ import annotations
import json
import os
from pathlib import Path
import click
import yaml
from docgen.config import Config
from docgen.yaml_generate import DEFAULT_LLM_MODEL
def _parse_env_file_pairs(env_path: Path) -> list[tuple[str, str]]:
pairs: list[tuple[str, str]] = []
for line in env_path.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, val = line.partition("=")
k = key.strip()
if not k:
continue
v = val.strip().strip('"').strip("'")
pairs.append((k, v))
return pairs
def _docgen_env_override_mode() -> str | set[str] | None:
"""Return None (shell wins), 'all' (.env overwrites every key), or a set of keys."""
raw = (os.environ.get("DOCGEN_ENV_OVERRIDES") or "").strip()
if not raw:
return None
lower = raw.lower()
if lower in ("1", "true", "yes", "*", "all"):
return "all"
keys = {p.strip() for p in raw.split(",") if p.strip()}
return keys if keys else None
def _load_env(cfg: Config | None) -> None:
"""Load .env file from config if specified, so OPENAI_API_KEY etc. are available.
By default **shell environment wins**: ``os.environ.setdefault`` does not
replace keys already exported. Set ``DOCGEN_ENV_OVERRIDES=1`` so every key
from the file overwrites, or ``DOCGEN_ENV_OVERRIDES=KEY1,KEY2`` for selected
keys only.
"""
if not cfg or not cfg.env_file or not cfg.env_file.exists():
return
pairs = _parse_env_file_pairs(cfg.env_file)
mode = _docgen_env_override_mode()
if mode == "all":
for k, v in pairs:
os.environ[k] = v
return
override_keys = mode if isinstance(mode, set) else set()
for k, v in pairs:
if k in override_keys:
os.environ[k] = v
continue
if (
k == "OPENAI_API_KEY"
and v
and os.environ.get("OPENAI_API_KEY")
):
click.echo(
"[docgen] OPENAI_API_KEY already set in the process environment; "
"env_file value is ignored for this key (shell wins). "
"Unset OPENAI_API_KEY or set DOCGEN_ENV_OVERRIDES=1 to load all keys "
"from env_file, or DOCGEN_ENV_OVERRIDES=OPENAI_API_KEY to override just "
"this key.",
err=True,
)
os.environ.setdefault(k, v)
def _cli_version_string(ctx: click.Context, param: click.Parameter, value: bool) -> None:
if not value or ctx.resilient_parsing:
return
from docgen.install_spec import DOCGEN_PIP_SPEC, package_version
click.echo(f"docgen {package_version()}")
click.echo(f"install: pip install '{DOCGEN_PIP_SPEC}'")
ctx.exit()
@click.group()
@click.option(
"--config",
"config_path",
default=None,
type=click.Path(exists=False),
help="Path to docgen.yaml (parents of cwd are searched when omitted).",
)
@click.option(
"--version",
is_flag=True,
callback=_cli_version_string,
expose_value=False,
is_eager=True,
help="Show installed docgen version and the recommended pip install line.",
)
@click.pass_context
def main(ctx: click.Context, config_path: str | None) -> None:
"""docgen — demo generation pipeline (install as an external tool; keep only the bundle in-repo).
Environment: keys already set in the shell are not replaced by ``env_file``
(see ``DOCGEN_ENV_OVERRIDES``). If no docgen.yaml is found, pass ``--config``.
"""
ctx.ensure_object(dict)
try:
cfg = Config.from_yaml(config_path) if config_path else Config.discover()
except FileNotFoundError:
cfg = None
click.echo(
"[docgen] No docgen.yaml found in this directory tree; pass "
"`--config PATH/to/docgen.yaml` or `cd` to your demos bundle directory.",
err=True,
)
ctx.obj["config"] = cfg
_load_env(cfg)
@main.command()
@click.argument("target_dir", required=False, default=None, type=click.Path())
@click.option(
"--defaults",
is_flag=True,
help="Non-interactive: detect git root, infer segments from narration/*.md (or 01-intro), then write docgen.yaml.",
)
@click.option(
"--segments-file",
"segments_file",
default=None,
type=click.Path(exists=True, dir_okay=False, path_type=Path),
help=(
"Path to a plain-text file listing one segment stem per line "
"(e.g. ``01-overview``). Used instead of scanning ``narration/*.md``. "
"Lets a reset wipe narration completely and still recreate the same "
"segment list deterministically. Requires --defaults."
),
)
@click.pass_context
def init(
ctx: click.Context,
target_dir: str | None,
defaults: bool,
segments_file: Path | None,
) -> None:
"""Scaffold a new project: docgen.yaml, wrapper scripts, directories.
Optionally pass a target directory (defaults to the current directory for interactive mode,
or ``<repo>/docs/demos`` for ``--defaults`` with no argument).
**Start clean:** ``docgen init PATH --defaults`` then ``docgen yaml-generate``.
"""
from docgen.init import build_defaults_plan, generate_files, print_summary, run_wizard
td = Path(target_dir).resolve() if target_dir else None
if defaults:
plan = build_defaults_plan(
td,
segments_file=segments_file.resolve() if segments_file else None,
)
else:
if segments_file is not None:
raise click.ClickException("--segments-file requires --defaults.")
plan = run_wizard(target_dir=td)
created = generate_files(plan)
print_summary(plan, created)
@main.command("gui")
@click.option("--port", default=0, help="Bind port (0 = ephemeral).")
@click.option(
"--view",
default="benchmark",
show_default=True,
help="Initial view: benchmark, setup, production, or tool.",
)
@click.option(
"--browser",
is_flag=True,
help="Open the system browser instead of a pywebview window.",
)
@click.pass_context
def gui(ctx: click.Context, port: int, view: str, browser: bool) -> None:
"""Desktop GUI (Vue). Prefer `pip install 'docgen[gui]'` for a native window.
This is the entry PyInstaller freezes (see packaging/docgen-gui.spec).
"""
from docgen.gui.__main__ import main as gui_main
args: list[str] = ["--view", view]
if port:
args.extend(["--port", str(port)])
if browser:
args.append("--browser")
cfg = ctx.obj.get("config") if ctx.obj else None
if cfg is not None and getattr(cfg, "yaml_path", None) and Path(cfg.yaml_path).is_file():
args.extend(["--config", str(cfg.yaml_path)])
gui_main(args)
@main.command()
@click.option("--port", default=8501, help="Port for the wizard web server.")
@click.pass_context
def wizard(ctx: click.Context, port: int) -> None:
"""Launch the production wizard (local web GUI)."""
from docgen.wizard import create_app
cfg = ctx.obj["config"]
app = create_app(cfg)
click.echo(f"Starting docgen wizard on http://localhost:{port}")
app.run(host="127.0.0.1", port=port, debug=False)
@main.command()
@click.option("--segment", default=None, help="Generate TTS for a single segment.")
@click.option("--dry-run", is_flag=True, help="Show stripped text without calling TTS API.")
@click.pass_context
def tts(ctx: click.Context, segment: str | None, dry_run: bool) -> None:
"""Generate TTS audio from narration markdown."""
from docgen.tts import TTSGenerator
cfg = ctx.obj["config"]
gen = TTSGenerator(cfg)
gen.generate(segment=segment, dry_run=dry_run)
@main.command()
@click.option(
"--engine",
default=None,
type=click.Choice(["local", "whisper"]),
help=(
"Timing engine (default: timestamps.engine in docgen.yaml, local). "
"local = offline narration-text alignment via ffmpeg silencedetect; "
"whisper = OpenAI whisper-1 transcription."
),
)
@click.pass_context
def timestamps(ctx: click.Context, engine: str | None) -> None:
"""Extract word/segment timestamps from TTS audio -> timing.json."""
from docgen.timestamps import TimestampExtractor
cfg = ctx.obj["config"]
try:
TimestampExtractor(cfg).extract_all(engine=engine)
except RuntimeError as exc:
raise click.ClickException(str(exc)) from exc
@main.command()
@click.option("--scene", default=None, help="Render a single Manim scene.")
@click.pass_context
def manim(ctx: click.Context, scene: str | None) -> None:
"""Render Manim animations."""
from docgen.manim_runner import ManimRunner
cfg = ctx.obj["config"]
runner = ManimRunner(cfg)
runner.render(scene=scene)
@main.command()
@click.argument("segments", nargs=-1)
@click.option(
"--ffmpeg-timeout",
default=None,
type=int,
help="Override ffmpeg timeout in seconds (default from docgen.yaml compose.ffmpeg_timeout_sec).",
)
@click.option(
"--only-visual-type",
"only_visual_types",
multiple=True,
help=(
"Only compose segments whose visual_map type matches (repeatable). "
"Useful after refreshing pre-recorded captures without re-muxing "
"Manim segments, e.g. --only-visual-type still."
),
)
@click.pass_context
def compose(
ctx: click.Context,
segments: tuple[str, ...],
ffmpeg_timeout: int | None,
only_visual_types: tuple[str, ...],
) -> None:
"""Compose segments (audio + video via ffmpeg).
Pass segment IDs to compose specific ones, or omit for the default set.
"""
from docgen.compose import Composer, filter_segments_by_visual_types
cfg = ctx.obj["config"]
comp = Composer(cfg, ffmpeg_timeout_sec=ffmpeg_timeout)
target = list(segments) if segments else list(cfg.segments_default)
target = filter_segments_by_visual_types(cfg, target, only_visual_types)
if only_visual_types and not target:
raise click.ClickException(
"[compose] No segments left after --only-visual-type filter "
f"({', '.join(only_visual_types)})."
)
click.echo(f"=== Composing {len(target)} segments ===")
comp.compose_segments(target)
@main.command()
@click.option("--max-drift", default=None, type=float, help="Max A/V drift in seconds.")
@click.option("--pre-push", is_flag=True, help="Run all checks; exit non-zero on any failure.")
@click.pass_context
def validate(ctx: click.Context, max_drift: float | None, pre_push: bool) -> None:
"""Run validation checks on composed videos (streams, drift, narration lint)."""
from docgen.validate import Validator
cfg = ctx.obj["config"]
v = Validator(cfg)
if pre_push:
v.run_pre_push()
else:
report = v.run_all(max_drift_override=max_drift)
v.print_report(report)
@main.command()
@click.option("--segment", default=None, help="Lint a single segment.")
@click.pass_context
def lint(ctx: click.Context, segment: str | None) -> None:
"""Run narration lint on all (or one) segment narration files."""
from docgen.narration_lint import NarrationLinter
cfg = ctx.obj["config"]
linter = NarrationLinter(cfg)
segments = [segment] if segment else cfg.segments_all
issues_total = 0
for seg_id in segments:
seg_name = cfg.resolve_segment_name(seg_id)
narr_dir = cfg.narration_dir
if not narr_dir.exists():
continue
path = narr_dir / f"{seg_name}.md"
if not path.exists():
candidates = list(narr_dir.glob(f"{seg_id}-*.md"))
path = candidates[0] if candidates else None
if not path or not path.exists():
click.echo(f" [{seg_id}] no narration file")
continue
result = linter.lint_text(path.read_text(encoding="utf-8"))
status = "PASS" if result.passed else "FAIL"
click.echo(f" [{seg_id}] {status} {seg_name}")
for issue in result.issues:
click.echo(f" {issue}")
issues_total += 1
if issues_total:
raise SystemExit(1)
@main.command("narration-generate")
@click.option(
"--segment",
default=None,
help="Segment id (e.g. 01). Mutually exclusive with --all.",
)
@click.option(
"--all",
"all_segments",
is_flag=True,
help="Generate narration for every id in segments.all (use --force to overwrite).",
)
@click.option(
"--extra-path",
"extra_paths",
multiple=True,
type=str,
help="Repo-root-relative source file to include (repeatable). Adds to narration_from_source.context.paths.",
)
@click.option(
"--hint",
"extra_hints",
multiple=True,
type=str,
help="Project-owner hint for the model (repeatable). Adds to YAML hints.",
)
@click.option(
"--dry-run",
is_flag=True,
help="Print generated markdown to stdout; do not write narration/*.md.",
)
@click.option(
"--force",
is_flag=True,
help="Overwrite an existing narration file for this segment.",
)
@click.option(
"--revise",
is_flag=True,
help="Edit existing narration.md in place (requires --revision-notes; implies --force).",
)
@click.option(
"--revision-notes",
default="",
show_default=False,
help="Feedback for --revise, or soft notes appended to a full generate.",
)
@click.pass_context
def narration_generate(
ctx: click.Context,
segment: str | None,
all_segments: bool,
extra_paths: tuple[str, ...],
extra_hints: tuple[str, ...],
dry_run: bool,
force: bool,
revise: bool,
revision_notes: str,
) -> None:
"""Generate or revise narration ``.md`` from repo sources + owner hints via OpenAI chat.
Configure ``narration_from_source`` in docgen.yaml (context paths/globs, hints, model).
Requires ``OPENAI_API_KEY`` unless using a future offline stub.
Use ``--segment <id>`` to drive a single segment, or ``--all`` to iterate
every id in ``segments.all`` (used by full-reset orchestration).
``--revise`` reads the current narration file and applies ``--revision-notes``
with minimal edits (same contract as the wizard Revise button).
"""
if ctx.obj.get("config") is None:
raise click.ClickException("No docgen.yaml found (use --config PATH).")
if all_segments and segment:
raise click.ClickException("--all and --segment are mutually exclusive")
if not all_segments and not segment:
raise click.ClickException("provide --segment <id> or --all")
if revise and not str(revision_notes or "").strip():
raise click.ClickException("--revise requires --revision-notes")
from docgen.narrate_from_source import generate_narration_markdown, write_narration_markdown
cfg = ctx.obj["config"]
mode = "revise" if revise else "generate"
# Revising always overwrites the existing script.
write_force = force or revise
def _one(seg_str: str) -> None:
try:
body = generate_narration_markdown(
cfg,
seg_str,
extra_paths=list(extra_paths),
extra_hints=list(extra_hints),
revision_notes=revision_notes,
mode=mode,
)
except ValueError as exc:
raise click.ClickException(f"segment {seg_str}: {exc}") from exc
if dry_run:
click.echo(body)
return
try:
out = write_narration_markdown(cfg, seg_str, body, force=write_force)
except FileExistsError as exc:
raise click.ClickException(f"segment {seg_str}: {exc} (use --force)") from exc
click.echo(f" -> {out}" if all_segments else f"[narration-generate] wrote {out}")
if all_segments:
ids = list((cfg.raw.get("segments") or {}).get("all") or [])
if not ids:
raise click.ClickException("segments.all is empty in docgen.yaml")
for seg_id in ids:
seg_str = str(seg_id)
click.echo(f"=== narration-generate --segment {seg_str} ===")
_one(seg_str)
return
assert segment is not None # for type-checker
_one(segment)
@main.command("scene-compile")
@click.argument(
"spec_path",
required=False,
default=None,
type=click.Path(path_type=Path, exists=True, dir_okay=False),
)
@click.option(
"--all",
"all_specs",
is_flag=True,
help="Compile every animations/specs/*.scene.yaml (mutually exclusive with SPEC_PATH).",
)
@click.option(
"--retime",
is_flag=True,
help=(
"Re-derive wait_word indices from current timing.json (no OpenAI) and fail if "
"labels do not match spoken words. Implied by --all when timing exists; safe to "
"pass explicitly after `docgen timestamps`."
),
)
@click.option(
"--dry-run",
is_flag=True,
help="Print generated Python only; do not write animations/scenes.py.",
)
@click.pass_context
def scene_compile(
ctx: click.Context,
spec_path: Path | None,
all_specs: bool,
retime: bool,
dry_run: bool,
) -> None:
"""Compile a declarative ``*.scene.yaml`` into ``animations/scenes.py``.
Deterministic layout (rows of ``_box`` mobjects) — use for reliable diagrams
or after an LLM emits **only** YAML. Schema: :mod:`docgen.scene_spec`.
``timing_key`` defaults from ``segment_names`` in docgen.yaml when omitted.
After TTS/timestamps, prefer ``docgen scene-compile --all --retime`` (or
``generate-all``, which retimes existing specs automatically) so beat sync
uses fresh ``timing.json`` without calling OpenAI.
"""
if ctx.obj.get("config") is None:
raise click.ClickException("No docgen.yaml found (use --config PATH).")
if all_specs and spec_path is not None:
raise click.ClickException("Pass SPEC_PATH or --all, not both.")
if not all_specs and spec_path is None:
raise click.ClickException("Pass SPEC_PATH or --all.")
from docgen.manim_scene_support import SceneGenerationError
from docgen.scene_retime import list_scene_spec_paths, retime_compile_spec
from docgen.scene_spec import SceneSpecError
cfg = ctx.obj["config"]
# --retime is the same compile path (label sync + pacing gate); the flag
# documents intent and is the recommended post-timestamps invocation.
_ = retime
paths = list_scene_spec_paths(cfg) if all_specs else [spec_path]
if not paths:
raise click.ClickException("No animations/specs/*.scene.yaml files found.")
failures: list[str] = []
for path in paths:
assert path is not None
try:
result = retime_compile_spec(cfg, path, dry_run=dry_run)
except (SceneGenerationError, SceneSpecError) as exc:
if all_specs:
click.echo(f"[scene-compile] FAIL {path.name}: {exc}", err=True)
failures.append(path.name)
continue
raise click.ClickException(str(exc)) from exc
if dry_run:
click.echo(result["class_block"], nl=False)
if all_specs:
click.echo(f"\n--- end {path.name} ---\n")
continue
click.echo(
f"[scene-compile] wrote {result['class_name']} to {result['scenes_path']} "
f"(segment {result['segment_id']} → timing_key {result['timing_key']!r}"
f"{', retime' if retime or all_specs else ''})"
)
if failures:
raise click.ClickException(
f"scene-compile --all: {len(failures)} failed: " + ", ".join(failures)
)
@main.command("scene-spec-generate")
@click.option(
"--segment",
"segment",
default=None,
help="Segment id (e.g. 01). Mutually exclusive with --all.",
)
@click.option(
"--all",
"all_segments",
is_flag=True,
help="Generate a scene spec for every segment in segments.all whose visual_map "
"type is manim (or unset) and that has no scripts/*<id>*.py. "
"--class-name is ignored with --all.",
)
@click.option(
"--class-name",
"class_name_override",
default=None,
help="Override class name (default: manim_scene_generation.segments.<id>.class_name or CamelCase+Scene). Ignored with --all.",
)
@click.option(
"--extra-path",
"extra_paths",
multiple=True,
type=str,
help="Repo-root-relative source file (repeatable); added to manim context.paths.",
)
@click.option(
"--hint",
"extra_hints",
multiple=True,
type=str,
help="Extra owner hint for the model (repeatable).",
)
@click.option(
"--dry-run",
is_flag=True,
help="Print prompts only; do not call OpenAI.",
)
@click.option(
"--print-only",
is_flag=True,
help="Call OpenAI and print YAML to stdout; do not write a spec file by default.",
)
@click.option(
"--output",
"output_path",
default=None,
type=click.Path(path_type=Path, dir_okay=False),
help="Write spec YAML here (default: <animations_dir>/specs/<segment_stem>.scene.yaml).",
)
@click.option(
"--compile",
"do_compile",
is_flag=True,
help="After success, inject the compiled class into animations/scenes.py (same as scene-compile).",
)
@click.option(
"--model",
default=None,
help="OpenAI chat model override (default: manim_scene_generation.model in docgen.yaml).",
)
@click.pass_context
def scene_spec_generate_cmd(
ctx: click.Context,
segment: str | None,
all_segments: bool,
class_name_override: str | None,
extra_paths: tuple[str, ...],
extra_hints: tuple[str, ...],
dry_run: bool,
print_only: bool,
output_path: Path | None,
do_compile: bool,
model: str | None,
) -> None:
"""Generate a declarative ``*.scene.yaml`` via OpenAI, then optionally compile.
The model outputs YAML only (see :mod:`docgen.scene_spec`); layout is
deterministic in :func:`docgen.scene_spec.compile_scene_class`.
"""
if ctx.obj.get("config") is None:
raise click.ClickException("No docgen.yaml found (use --config PATH).")
if dry_run and print_only:
raise click.ClickException("--dry-run and --print-only are mutually exclusive")
if all_segments and segment:
raise click.ClickException("--all and --segment are mutually exclusive")
if not all_segments and not segment:
raise click.ClickException("provide --segment <id> or --all")
if all_segments and class_name_override:
raise click.ClickException("--class-name cannot be combined with --all")
if all_segments and output_path:
raise click.ClickException("--output cannot be combined with --all (per-segment paths are used)")
from docgen.manim_scene_support import SceneGenerationError
from docgen.scene_spec_generate import (
generate_scene_spec,
inject_class_block_into_scenes_py,
linted_class_block_from_spec,
)
cfg = ctx.obj["config"]
def _one_sid(sid: str) -> None:
try:
res = generate_scene_spec(
cfg,
sid,
extra_paths=list(extra_paths),
extra_hints=list(extra_hints),
class_name_override=class_name_override,
dry_run=dry_run,
model_override=model,
)
except SceneGenerationError as exc:
raise click.ClickException(f"segment {sid}: {exc}") from exc
if dry_run:
click.echo(res.prompt)
return
if print_only:
click.echo(res.yaml_text, nl=False)
else:
specs_dir = cfg.animations_dir / "specs"
specs_dir.mkdir(parents=True, exist_ok=True)
wpath = specs_dir / f"{res.seg_name}.scene.yaml"
wpath.write_text(res.yaml_text, encoding="utf-8")
click.echo(f"[scene-spec-generate] wrote {wpath}")
if do_compile:
try:
class_block, merged = linted_class_block_from_spec(
cfg, res.spec, timing_key=res.seg_name
)
inject_class_block_into_scenes_py(
cfg,
seg_id=merged["segment_id"],
class_name=merged["class_name"],
class_block=class_block,
)
except SceneGenerationError as exc:
raise click.ClickException(str(exc)) from exc
click.echo(
f"[scene-spec-generate] compiled → {cfg.animations_dir / 'scenes.py'} "
f"({res.class_name}, timing_key {res.seg_name!r})"
)
if all_segments:
ids = list((cfg.raw.get("segments") or {}).get("all") or [])
if not ids:
raise click.ClickException("segments.all is empty in docgen.yaml")
names = (cfg.raw.get("segment_names") or {})
scripts_dir = cfg.base_dir / "scripts"
failures: list[str] = []
for seg_id in ids:
sid = str(seg_id)
name = names.get(sid) or names.get(seg_id) or sid
script_match = (
list(scripts_dir.glob(f"*{sid}*.py")) if scripts_dir.is_dir() else []
)
if script_match:
click.echo(
f"[scene-spec-generate --all] skip {sid} ({name}): existing capture script"
)
continue
vm_row = cfg.visual_map.get(sid)
if isinstance(vm_row, dict):
vtype = str(vm_row.get("type", "")).strip().lower()
if vtype and vtype != "manim":
click.echo(
f"[scene-spec-generate --all] skip {sid} ({name}): "
f"visual_map type is {vtype!r} (not manim)"
)
continue
click.echo(f"=== scene-spec-generate --segment {sid} ===")
try:
_one_sid(sid)
except click.ClickException as exc:
click.echo(f"[scene-spec-generate --all] FAIL {sid}: {exc}", err=True)
failures.append(sid)
if failures:
raise click.ClickException(
f"scene-spec-generate --all: {len(failures)} segment(s) failed: "
+ ", ".join(failures)
)
return
assert segment is not None # type-checker
try:
result = generate_scene_spec(
cfg,
segment,
extra_paths=list(extra_paths),
extra_hints=list(extra_hints),
class_name_override=class_name_override,
dry_run=dry_run,
model_override=model,
)
except SceneGenerationError as exc:
raise click.ClickException(str(exc)) from exc
if dry_run:
click.echo(result.prompt)
return
if print_only:
click.echo(result.yaml_text, nl=False)
write_path: Path | None = None
if not print_only:
specs_dir = cfg.animations_dir / "specs"
specs_dir.mkdir(parents=True, exist_ok=True)
write_path = output_path or (specs_dir / f"{result.seg_name}.scene.yaml")
elif output_path:
write_path = output_path
if write_path is not None:
write_path.parent.mkdir(parents=True, exist_ok=True)
write_path.write_text(result.yaml_text, encoding="utf-8")
click.echo(f"[scene-spec-generate] wrote {write_path}")
if do_compile:
try:
class_block, merged = linted_class_block_from_spec(cfg, result.spec, timing_key=result.seg_name)
inject_class_block_into_scenes_py(
cfg,
seg_id=merged["segment_id"],
class_name=merged["class_name"],
class_block=class_block,
)
except SceneGenerationError as exc:
raise click.ClickException(str(exc)) from exc
click.echo(
f"[scene-spec-generate] compiled → {cfg.animations_dir / 'scenes.py'} "
f"({result.class_name}, timing_key {result.seg_name!r})"
)
@main.command("image-generate")
@click.option(
"--segment",
default=None,
help="Segment id (e.g. 01) — uses animations/specs/<stem>.scene.yaml. Mutually exclusive with --all/--spec.",
)
@click.option(
"--all",
"all_segments",
is_flag=True,
help="Process every animations/specs/*.scene.yaml in the bundle.",
)
@click.option(
"--spec",
"spec_path",
default=None,
type=click.Path(path_type=Path, exists=True, dir_okay=False),
help="Explicit path to one *.scene.yaml.",
)
@click.option("--force", is_flag=True, help="Regenerate assets that already exist.")
@click.option("--dry-run", is_flag=True, help="List prompts and target paths; do not call OpenAI.")
@click.option(
"--model",
default=None,
help="OpenAI image model override (default: image_generation.model in docgen.yaml, gpt-image-1).",
)
@click.option(
"--size",
default=None,
help="Image size override (default: image_generation.size in docgen.yaml, 1536x1024).",
)
@click.pass_context
def image_generate_cmd(
ctx: click.Context,
segment: str | None,
all_segments: bool,
spec_path: Path | None,
force: bool,
dry_run: bool,
model: str | None,
size: str | None,
) -> None:
"""Generate scene-spec image assets via the OpenAI Images API.
Scene specs may declare **image elements** (``image:`` + ``prompt:`` on a
box). This command writes the referenced PNG under the bundle directory so
``docgen manim`` can render them. Existing assets are kept unless --force.
"""
if ctx.obj.get("config") is None:
raise click.ClickException("No docgen.yaml found (use --config PATH).")
chosen = [bool(segment), all_segments, spec_path is not None]
if sum(chosen) != 1:
raise click.ClickException("provide exactly one of --segment, --all, or --spec")
from docgen.image_generate import (
ImageGenerationError,
generate_images_for_spec,
spec_files_for_bundle,
)
from docgen.scene_spec import SceneSpecError
cfg = ctx.obj["config"]
if spec_path is not None:
targets = [spec_path]
elif all_segments:
targets = spec_files_for_bundle(cfg)
if not targets:
click.echo("[image-generate] no *.scene.yaml specs found in animations/specs/")
return
else:
stem = cfg.resolve_segment_name(str(segment))
candidate = cfg.animations_dir / "specs" / f"{stem}.scene.yaml"
if not candidate.is_file():
raise click.ClickException(
f"spec not found: {candidate} — run `docgen scene-spec-generate --segment {segment}` "
"or author the spec by hand."
)
targets = [candidate]
total = 0
for target in targets:
try:
results = generate_images_for_spec(
cfg,
target,
force=force,
dry_run=dry_run,
model_override=model,
size_override=size,
)
except (ImageGenerationError, SceneSpecError) as exc:
raise click.ClickException(str(exc)) from exc
if not results:
click.echo(f"[image-generate] {target.name}: no image elements")
continue
for res in results:
if res.status == "dry-run":
click.echo(f"[image-generate] {target.name}: would generate {res.relpath}")
click.echo(f" prompt: {res.prompt}")
elif res.status == "exists":
click.echo(f"[image-generate] {target.name}: {res.relpath} exists (skip; use --force)")
else:
click.echo(f"[image-generate] {target.name}: wrote {res.path}")
total += 1
if not dry_run:
click.echo(f"[image-generate] generated {total} asset(s)")
@main.command("yaml-generate")
@click.option(
"--merge-defaults/--no-merge-defaults",
default=True,
help="Merge safe defaults (archive exclude, optional skeleton blocks).",
)
@click.option(
"--llm",
is_flag=True,
help="Call OpenAI to refresh tts.instructions and wizard.system_prompt from README/AGENTS.",
)
@click.option(
"--model",
default=None,
help=f"Chat model for --llm (default: {DEFAULT_LLM_MODEL}).",
)
@click.option(
"--dry-run",
is_flag=True,
help="Print actions and merged YAML to stdout; do not write docgen.yaml.",
)
@click.option(
"--list-gaps",
is_flag=True,
help="Print narration segment ids missing from segments.all; exit 1 if any.",
)
@click.option(
"--merge-hint-segments/--no-merge-hint-segments",
default=True,
show_default=True,
help="Merge segment ids from hints/*.md YAML front matter (docgen.segment.create).",
)
@click.pass_context
def yaml_generate_cmd(
ctx: click.Context,
merge_defaults: bool,
llm: bool,
model: str | None,
dry_run: bool,
list_gaps: bool,
merge_hint_segments: bool,
) -> None:
"""Merge structural defaults and optionally LLM-authored TTS/wizard prose into docgen.yaml.
Rewrites the config file with PyYAML (comments are not preserved). Use Git to review.
"""
if ctx.obj.get("config") is None:
raise click.ClickException("No docgen.yaml found (use --config PATH).")
from docgen import yaml_generate as yg
cfg = ctx.obj["config"]
path = cfg.yaml_path
raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
if list_gaps:
gaps = yg.narration_not_in_segments(raw, cfg.narration_dir)
if not gaps:
click.echo("[yaml-generate] no narration segments missing from segments.all")
return
for seg_id, stem in gaps:
click.echo(f"gap: {seg_id} ({stem}.md) not in segments.all")
raise SystemExit(1)
changes: list[str] = []
if merge_defaults:
changes.extend(yg.merge_defaults(raw, cfg, merge_hint_segments=merge_hint_segments))
if llm:
try:
hints = yg.generate_llm_hints(cfg, model=model)
except ValueError as exc:
raise click.ClickException(str(exc)) from exc
except RuntimeError as exc:
raise click.ClickException(str(exc)) from exc
yg.apply_llm_hints(raw, hints)
changes.append("tts.instructions + wizard.system_prompt: refreshed via OpenAI")