-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1624 lines (1362 loc) · 55 KB
/
cli.py
File metadata and controls
1624 lines (1362 loc) · 55 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
"""Command-line interface for D&D Session Processor"""
import click
from pathlib import Path
from rich.console import Console
from rich.table import Table
from src.pipeline import DDSessionProcessor
from src.config import Config
from src.logger import get_log_file_path, set_console_log_level, LOG_LEVEL_CHOICES
from src.audit import log_audit_event, audit_enabled
from src.story_notebook import StoryNotebookManager, load_notebook_context_file
console = Console()
def _audit(ctx, action: str, *, status: str = "info", **metadata):
"""Record an audit event when auditing is enabled."""
context = ctx.obj or {}
if not context.get("audit_enabled", audit_enabled()):
return
actor = context.get("audit_actor") or Config.AUDIT_LOG_ACTOR
log_audit_event(
action,
actor=actor,
source="cli",
status=status,
metadata=metadata or {},
)
@click.group()
@click.option(
"--log-level",
type=click.Choice(LOG_LEVEL_CHOICES, case_sensitive=False),
default=None,
help="Set console log verbosity for this CLI session."
)
@click.option(
"--audit-actor",
default=None,
help="Label audit log entries for this session (default: AUDIT_LOG_ACTOR)."
)
@click.option(
"--no-audit",
is_flag=True,
help="Temporarily disable audit logging for this CLI invocation."
)
@click.pass_context
def cli(ctx, log_level, audit_actor, no_audit):
"""D&D Session Transcription & Diarization System"""
ctx.ensure_object(dict)
if log_level:
set_console_log_level(log_level)
ctx.obj["audit_actor"] = audit_actor or Config.AUDIT_LOG_ACTOR
ctx.obj["audit_enabled"] = Config.AUDIT_LOG_ENABLED and not no_audit
@cli.command()
@click.argument('input_file', type=click.Path(exists=True))
@click.option(
'--session-id',
'-s',
help='Unique session identifier (defaults to filename)',
default=None
)
@click.option(
'--party',
help='Party configuration ID (e.g., "default"). Overrides --characters and --players',
default=None
)
@click.option(
'--characters',
'-c',
help='Comma-separated list of character names',
default=None
)
@click.option(
'--players',
'-p',
help='Comma-separated list of player names',
default=None
)
@click.option(
'--output-dir',
'-o',
help='Output directory',
type=click.Path(),
default=None
)
@click.option(
'--skip-diarization',
is_flag=True,
help='Skip speaker diarization (faster but no speaker labels)'
)
@click.option(
'--skip-classification',
is_flag=True,
help='Skip IC/OOC classification (faster but no content separation)'
)
@click.option(
'--skip-snippets',
is_flag=True,
help='Skip exporting per-segment audio snippets'
)
@click.option(
'--num-speakers',
'-n',
type=int,
default=4,
help='Expected number of speakers (default: 4)'
)
@click.pass_context
def process(
ctx,
input_file,
session_id,
party,
characters,
players,
output_dir,
skip_diarization,
skip_classification,
skip_snippets,
num_speakers
):
"""Process a D&D session recording"""
input_path = Path(input_file)
# Default session ID to filename
if session_id is None:
session_id = input_path.stem
# Create processor based on party config or manual entry
if party:
# Use party configuration
console.print(f"[cyan]Using party configuration: {party}[/cyan]")
processor = DDSessionProcessor(
session_id=session_id,
num_speakers=num_speakers,
party_id=party
)
else:
# Parse character and player names
character_names = characters.split(',') if characters else []
player_names = players.split(',') if players else []
processor = DDSessionProcessor(
session_id=session_id,
character_names=character_names,
player_names=player_names,
num_speakers=num_speakers
)
# Process
_audit(
ctx,
"cli.process.start",
session_id=session_id,
input_file=str(input_path),
party=party,
skip_diarization=skip_diarization,
skip_classification=skip_classification,
skip_snippets=skip_snippets,
num_speakers=num_speakers,
)
try:
result = processor.process(
input_file=input_path,
output_dir=output_dir,
skip_diarization=skip_diarization,
skip_classification=skip_classification,
skip_snippets=skip_snippets
)
# Show success message
console.print("\n[bold green][OK] Processing completed successfully![/bold green]")
console.print(f"[dim]Verbose log: {get_log_file_path()}[/dim]")
_audit(
ctx,
"cli.process.complete",
status="success",
session_id=session_id,
output_dir=str(output_dir) if output_dir else None,
stats=(result or {}).get("statistics", {}),
)
except Exception as e:
console.print(f"\n[bold red][FAIL] Processing failed: {e}[/bold red]")
console.print(f"[dim]Inspect log for details: {get_log_file_path()}[/dim]")
_audit(
ctx,
"cli.process.error",
status="error",
session_id=session_id,
error=str(e),
)
raise click.Abort()
@cli.command()
@click.argument('session_id')
@click.argument('speaker_id')
@click.argument('person_name')
@click.pass_context
def map_speaker(ctx, session_id, speaker_id, person_name):
"""
Map a speaker ID to a person name.
Example: python cli.py map-speaker session1 SPEAKER_00 "Alice"
"""
from src.diarizer import SpeakerProfileManager
manager = SpeakerProfileManager()
manager.map_speaker(session_id, speaker_id, person_name)
console.print(f"[green][OK] Mapped {speaker_id} -> {person_name} for session {session_id}[/green]")
_audit(
ctx,
"cli.speakers.map",
status="success",
session_id=session_id,
speaker_id=speaker_id,
person_name=person_name,
)
@cli.command()
@click.argument('session_id')
def show_speakers(session_id):
"""Show speaker mappings for a session"""
from src.diarizer import SpeakerProfileManager
manager = SpeakerProfileManager()
if session_id not in manager.profiles:
console.print(f"[yellow]No speaker profiles found for session: {session_id}[/yellow]")
return
profiles = manager.profiles[session_id]
table = Table(title=f"Speaker Profiles for {session_id}")
table.add_column("Speaker ID", style="cyan")
table.add_column("Person Name", style="green")
for speaker_id, person_name in profiles.items():
table.add_row(speaker_id, person_name)
console.print(table)
@cli.command()
def list_parties():
"""List all available party configurations"""
from src.party_config import PartyConfigManager
manager = PartyConfigManager()
parties = manager.list_parties()
if not parties:
console.print("[yellow]No party configurations found.[/yellow]")
return
table = Table(title="Available Party Configurations")
table.add_column("Party ID", style="cyan")
table.add_column("Party Name", style="green")
table.add_column("Campaign", style="yellow")
table.add_column("Characters", style="magenta")
for party_id in parties:
party = manager.get_party(party_id)
character_names = ", ".join([c.name for c in party.characters])
table.add_row(
party_id,
party.party_name,
party.campaign or "N/A",
character_names
)
console.print(table)
@cli.command()
@click.argument('party_id', default='default')
def show_party(party_id):
"""Show detailed information about a party configuration"""
from src.party_config import PartyConfigManager
manager = PartyConfigManager()
party = manager.get_party(party_id)
if not party:
console.print(f"[red]Party '{party_id}' not found.[/red]")
return
console.print(f"\n[bold cyan]{party.party_name}[/bold cyan]")
console.print(f"[dim]Campaign: {party.campaign or 'N/A'}[/dim]")
console.print(f"[dim]DM: {party.dm_name}[/dim]\n")
table = Table(title="Characters")
table.add_column("Name", style="cyan")
table.add_column("Player", style="green")
table.add_column("Race", style="yellow")
table.add_column("Class", style="magenta")
table.add_column("Aliases", style="dim")
for char in party.characters:
aliases = ", ".join(char.aliases) if char.aliases else "—"
table.add_row(
char.name,
char.player,
char.race,
char.class_name,
aliases
)
console.print(table)
if party.notes:
console.print(f"\n[dim]Notes: {party.notes}[/dim]")
@cli.command()
@click.argument('party_id')
@click.argument('output_file', type=click.Path())
@click.pass_context
def export_party(ctx, party_id, output_file):
"""
Export a party configuration to a JSON file.
Example: python cli.py export-party default my_party.json
"""
from src.party_config import PartyConfigManager
manager = PartyConfigManager()
try:
manager.export_party(party_id, Path(output_file))
console.print(f"[green]SUCCESS: Exported party '{party_id}' to {output_file}[/green]")
_audit(
ctx,
"cli.party.export",
status="success",
party_id=party_id,
output=str(Path(output_file).resolve()),
)
except ValueError as e:
console.print(f"[red]ERROR: {e}[/red]")
_audit(
ctx,
"cli.party.export",
status="error",
party_id=party_id,
output=str(Path(output_file).resolve()),
error=str(e),
)
raise click.Abort()
@cli.command()
@click.argument('input_file', type=click.Path(exists=True))
@click.option('--party-id', help='Override party ID from file')
@click.pass_context
def import_party(ctx, input_file, party_id):
"""
Import a party configuration from a JSON file.
Example: python cli.py import-party my_party.json
Example: python cli.py import-party my_party.json --party-id my_campaign
"""
from src.party_config import PartyConfigManager
manager = PartyConfigManager()
try:
imported_id = manager.import_party(Path(input_file), party_id)
console.print(f"[green]SUCCESS: Imported party as '{imported_id}'[/green]")
_audit(
ctx,
"cli.party.import",
status="success",
imported_id=imported_id,
input=str(Path(input_file).resolve()),
)
except Exception as e:
console.print(f"[red]ERROR: Error importing party: {e}[/red]")
_audit(
ctx,
"cli.party.import",
status="error",
input=str(Path(input_file).resolve()),
override_party_id=party_id,
error=str(e),
)
raise click.Abort()
@cli.command()
@click.argument('output_file', type=click.Path())
@click.pass_context
def export_all_parties(ctx, output_file):
"""
Export all party configurations to a JSON file.
Example: python cli.py export-all-parties backup.json
"""
from src.party_config import PartyConfigManager
manager = PartyConfigManager()
try:
manager.export_all_parties(Path(output_file))
party_count = len(manager.list_parties())
console.print(f"[green]SUCCESS: Exported {party_count} parties to {output_file}[/green]")
_audit(
ctx,
"cli.party.export_all",
status="success",
output=str(Path(output_file).resolve()),
count=party_count,
)
except Exception as e:
console.print(f"[red]ERROR: {e}[/red]")
_audit(
ctx,
"cli.party.export_all",
status="error",
output=str(Path(output_file).resolve()),
error=str(e),
)
raise click.Abort()
@cli.command()
def list_characters():
"""List all character profiles"""
from src.character_profile import CharacterProfileManager
manager = CharacterProfileManager()
characters = manager.list_characters()
if not characters:
console.print("[yellow]No character profiles found.[/yellow]")
return
table = Table(title="Character Profiles")
table.add_column("Character", style="cyan")
table.add_column("Player", style="green")
table.add_column("Race/Class", style="yellow")
table.add_column("Level", style="magenta")
table.add_column("Sessions", style="blue")
for char_name in characters:
profile = manager.get_profile(char_name)
table.add_row(
char_name,
profile.player,
f"{profile.race} {profile.class_name}",
str(profile.level),
str(profile.total_sessions)
)
console.print(table)
@cli.command()
@click.argument('character_name')
@click.option('--format', '-f', type=click.Choice(['markdown', 'text']), default='markdown',
help='Output format')
@click.option('--output', '-o', type=click.Path(), help='Save to file instead of printing')
def show_character(character_name, format, output):
"""Show detailed character profile and overview"""
from src.character_profile import CharacterProfileManager
manager = CharacterProfileManager()
overview = manager.generate_character_overview(character_name, format=format)
if output:
Path(output).write_text(overview, encoding='utf-8')
console.print(f"[green]Saved character overview to {output}[/green]")
else:
from rich.markdown import Markdown
if format == 'markdown':
console.print(Markdown(overview))
else:
console.print(overview)
@cli.command()
@click.argument('character_name')
@click.argument('output_file', type=click.Path())
@click.pass_context
def export_character(ctx, character_name, output_file):
"""Export a character profile to JSON file"""
from src.character_profile import CharacterProfileManager
manager = CharacterProfileManager()
try:
manager.export_profile(character_name, Path(output_file))
console.print(f"[green]SUCCESS: Exported character '{character_name}' to {output_file}[/green]")
_audit(
ctx,
"cli.character.export",
status="success",
character=character_name,
output=str(Path(output_file).resolve()),
)
except ValueError as e:
console.print(f"[red]ERROR: {e}[/red]")
_audit(
ctx,
"cli.character.export",
status="error",
character=character_name,
output=str(Path(output_file).resolve()),
error=str(e),
)
raise click.Abort()
@cli.command()
@click.argument('input_file', type=click.Path(exists=True))
@click.option('--character-name', help='Override character name from file')
@click.pass_context
def import_character(ctx, input_file, character_name):
"""Import a character profile from JSON file"""
from src.character_profile import CharacterProfileManager
manager = CharacterProfileManager()
try:
imported_name = manager.import_profile(Path(input_file), character_name)
console.print(f"[green]SUCCESS: Imported character '{imported_name}'[/green]")
_audit(
ctx,
"cli.character.import",
status="success",
input=str(Path(input_file).resolve()),
imported_name=imported_name,
)
except Exception as e:
console.print(f"[red]ERROR: {e}[/red]")
_audit(
ctx,
"cli.character.import",
status="error",
input=str(Path(input_file).resolve()),
override_name=character_name,
error=str(e),
)
raise click.Abort()
@cli.command()
def config():
"""Show current configuration"""
table = Table(title="Configuration")
table.add_column("Setting", style="cyan")
table.add_column("Value", style="green")
table.add_row("Whisper Model", Config.WHISPER_MODEL)
table.add_row("Whisper Backend", Config.WHISPER_BACKEND)
table.add_row("LLM Backend", Config.LLM_BACKEND)
table.add_row("Chunk Length", f"{Config.CHUNK_LENGTH_SECONDS}s")
table.add_row("Chunk Overlap", f"{Config.CHUNK_OVERLAP_SECONDS}s")
table.add_row("Sample Rate", f"{Config.AUDIO_SAMPLE_RATE} Hz")
table.add_row("Output Directory", str(Config.OUTPUT_DIR))
table.add_row("Temp Directory", str(Config.TEMP_DIR))
console.print(table)
@cli.command()
def check_setup():
"""Check if all dependencies are properly installed"""
console.print("[bold]Checking setup...[/bold]\n")
checks = []
# Check FFmpeg
import subprocess
try:
subprocess.run(['ffmpeg', '-version'], capture_output=True, check=True)
checks.append(("FFmpeg", True, "Installed"))
except (subprocess.CalledProcessError, FileNotFoundError):
checks.append(("FFmpeg", False, "Not found - please install from https://ffmpeg.org"))
# Check PyTorch
try:
import torch
cuda_available = torch.cuda.is_available()
if cuda_available:
checks.append(("PyTorch", True, f"Installed with CUDA"))
else:
checks.append(("PyTorch", True, f"Installed (CPU only)"))
except ImportError:
checks.append(("PyTorch", False, "Not installed"))
# Check faster-whisper
try:
import faster_whisper
checks.append(("faster-whisper", True, "Installed"))
except ImportError:
checks.append(("faster-whisper", False, "Not installed"))
# Check PyAnnote
try:
import pyannote.audio
checks.append(("pyannote.audio", True, "Installed"))
except ImportError:
checks.append(("pyannote.audio", False, "Not installed"))
# Check Ollama connection and model availability
try:
from src.llm_factory import OllamaClientFactory, OllamaConfig
factory = OllamaClientFactory()
ollama_config = OllamaConfig(host=Config.OLLAMA_BASE_URL)
client = factory.create_client(
config=ollama_config,
test_connection=True,
max_retries=1
)
# Check if configured model is available
available_models = factory._fetch_available_models(client)
if available_models and Config.OLLAMA_MODEL in available_models:
checks.append(("Ollama", True, f"Running with model '{Config.OLLAMA_MODEL}'"))
elif available_models:
model_list = ", ".join(available_models[:3])
checks.append(("Ollama", False,
f"Model '{Config.OLLAMA_MODEL}' not found. Available: {model_list}"))
else:
checks.append(("Ollama", True, f"Running at {Config.OLLAMA_BASE_URL} (no models)"))
except Exception as e:
checks.append(("Ollama", False, f"Not running - {str(e)[:50]}"))
# Display results
table = Table(title="Dependency Check")
table.add_column("Component", style="cyan")
table.add_column("Status", style="bold")
table.add_column("Details", style="dim")
for name, success, details in checks:
status = "[green]OK[/green]" if success else "[red]FAIL[/red]"
table.add_row(name, status, details)
console.print(table)
# Overall status
all_ok = all(check[1] for check in checks)
if all_ok:
console.print("\n[bold green][OK] All dependencies are ready![/bold green]")
else:
console.print("\n[bold yellow][WARNING] Some dependencies are missing. Please install them.[/bold yellow]")
console.print("\nRun: pip install -r requirements.txt")
@click.group()
def sessions():
"""Manage and audit processed sessions."""
pass
@sessions.command()
@click.option('--output', '-o', type=click.Path(), help='Save report to markdown file')
@click.pass_context
def audit(ctx, output):
"""Audit all processed sessions for issues."""
from src.session_manager import SessionManager
console.print("[bold]Auditing sessions...[/bold]\n")
manager = SessionManager()
report = manager.audit_sessions()
totals = {
"total": report.total_sessions,
"empty": len(report.empty_sessions),
"incomplete": len(report.incomplete_sessions),
"stale": len(report.stale_checkpoints),
"potential_cleanup_mb": report.potential_cleanup_mb,
}
console.print(f"[bold]Total Sessions:[/bold] {totals['total']}")
console.print(f"[bold]Valid Sessions:[/bold] {len(report.valid_sessions)} ({report.total_size_mb - report.empty_size_mb - report.incomplete_size_mb:.2f} MB)")
console.print(f"[bold]Empty Sessions:[/bold] {totals['empty']} ({report.empty_size_mb:.2f} MB)")
console.print(f"[bold]Incomplete Sessions:[/bold] {totals['incomplete']} ({report.incomplete_size_mb:.2f} MB)")
console.print(f"[bold]Stale Checkpoints:[/bold] {totals['stale']} ({report.stale_checkpoint_size_mb:.2f} MB)")
console.print(f"[bold cyan]Potential Cleanup:[/bold cyan] {report.potential_cleanup_mb:.2f} MB\n")
if not (report.empty_sessions or report.incomplete_sessions or report.stale_checkpoints):
console.print("[bold green][OK] All sessions are in good condition.[/bold green]")
else:
if report.empty_sessions:
table = Table(title="Empty Sessions")
table.add_column("Session ID", style="cyan")
table.add_column("Size", style="yellow")
table.add_column("Created", style="dim")
for session in report.empty_sessions:
table.add_row(
session.session_id,
f"{session.size_mb:.2f} MB",
session.created_time.strftime('%Y-%m-%d')
)
console.print(table)
console.print()
if report.incomplete_sessions:
table = Table(title="Incomplete Sessions")
table.add_column("Session ID", style="cyan")
table.add_column("Size", style="yellow")
table.add_column("Missing Components", style="red")
for session in report.incomplete_sessions:
missing = []
if not session.has_transcript:
missing.append("transcript")
if not session.has_diarized_transcript:
missing.append("diarized")
if not session.has_classified_transcript:
missing.append("classified")
table.add_row(
session.session_id,
f"{session.size_mb:.2f} MB",
", ".join(missing)
)
console.print(table)
console.print()
if report.stale_checkpoints:
table = Table(title="Stale Checkpoints (>7 days)")
table.add_column("Checkpoint ID", style="cyan")
table.add_column("Size", style="yellow")
for checkpoint_name in report.stale_checkpoints:
size_mb = manager._get_directory_size(manager.checkpoint_dir / checkpoint_name) / (1024 * 1024)
table.add_row(checkpoint_name, f"{size_mb:.2f} MB")
console.print(table)
if output:
markdown_report = manager.generate_audit_report_markdown(report)
Path(output).write_text(markdown_report, encoding='utf-8')
console.print(f"\n[bold green][OK] Report saved to:[/bold green] {output}")
report_path = str(Path(output).resolve())
else:
report_path = None
_audit(
ctx,
"cli.sessions.audit",
status="success",
report_path=report_path,
totals=totals,
)
@sessions.command()
@click.option("--empty/--no-empty", default=True, help="Delete empty session directories (default: yes)")
@click.option("--incomplete/--no-incomplete", default=False, help="Delete incomplete sessions (default: no)")
@click.option("--stale-checkpoints/--no-stale-checkpoints", default=True, help="Delete stale checkpoints (default: yes)")
@click.option("--dry-run", is_flag=True, help="Show what would be deleted without actually deleting anything.")
@click.option("--force", is_flag=True, help="Delete without prompting (non-interactive mode).")
@click.option('--output', '-o', type=click.Path(), help='Save cleanup report to markdown file')
@click.pass_context
def cleanup(ctx, empty, incomplete, stale_checkpoints, dry_run, force, output):
"""Clean up empty, incomplete, and stale sessions.
By default, this will:
- Delete empty session directories
- Delete stale checkpoints (>7 days old)
- Keep incomplete sessions (use --incomplete to delete them)
- Prompt before deleting (use --force to skip prompts)
"""
from src.session_manager import SessionManager
if dry_run:
console.print("[bold yellow]DRY RUN MODE - No files will be deleted[/bold yellow]\n")
console.print("[bold]Running cleanup...[/bold]\n")
actor = ctx.obj.get("audit_actor") if ctx.obj else None
manager = SessionManager(audit_actor=actor)
# Run cleanup with specified options
report = manager.cleanup(
delete_empty=empty,
delete_incomplete=incomplete,
delete_stale_checkpoints=stale_checkpoints,
dry_run=dry_run,
interactive=not force
)
# Print summary
console.print(f"\n[bold]Cleanup Summary:[/bold]")
console.print(f" Empty sessions deleted: {report.deleted_empty}")
console.print(f" Incomplete sessions deleted: {report.deleted_incomplete}")
console.print(f" Stale checkpoints deleted: {report.deleted_checkpoints}")
console.print(f" [bold green]Total space freed: {report.total_freed_mb:.2f} MB[/bold green]")
if report.skipped_sessions:
console.print(f"\n[yellow]Skipped sessions: {len(report.skipped_sessions)}[/yellow]")
if report.errors:
console.print(f"\n[bold red]Errors encountered: {len(report.errors)}[/bold red]")
for error in report.errors:
console.print(f" - {error}")
# Save markdown report if requested
if output:
markdown_report = manager.generate_cleanup_report_markdown(report)
Path(output).write_text(markdown_report, encoding='utf-8')
console.print(f"\n[bold green][OK] Report saved to:[/bold green] {output}")
report_path = str(Path(output).resolve())
else:
report_path = None
if dry_run:
console.print("\n[bold yellow]This was a dry run. Run without --dry-run to delete files.[/bold yellow]")
else:
console.print("\n[bold green][OK] Cleanup complete![/bold green]")
_audit(
ctx,
"cli.sessions.cleanup",
status="success",
dry_run=dry_run,
options={
"delete_empty": empty,
"delete_incomplete": incomplete,
"delete_stale_checkpoints": stale_checkpoints,
"forced": force,
},
results={
"deleted_empty": report.deleted_empty,
"deleted_incomplete": report.deleted_incomplete,
"deleted_checkpoints": report.deleted_checkpoints,
"freed_mb": report.total_freed_mb,
"errors": len(report.errors),
},
report_path=report_path,
)
cli.add_command(sessions)
@click.group()
def campaigns():
"""Manage campaigns and migrate existing data."""
pass
@campaigns.command('migrate-sessions')
@click.argument('campaign_id')
@click.option('--dry-run', is_flag=True, help='Preview changes without modifying files')
@click.option('--filter', '-f', help='Filter sessions by glob pattern (e.g., "Session_*")')
@click.option('--output', '-o', type=click.Path(), help='Save report to markdown file')
def migrate_sessions_cmd(campaign_id, dry_run, filter, output):
"""Add campaign_id to existing session metadata files.
Example:
python cli.py campaigns migrate-sessions broken_seekers
python cli.py campaigns migrate-sessions broken_seekers --filter "Session_*"
python cli.py campaigns migrate-sessions broken_seekers --dry-run
"""
from src.campaign_migration import CampaignMigration
console.print(f"\n[bold]{'[DRY RUN] ' if dry_run else ''}Migrating sessions to campaign: {campaign_id}[/bold]\n")
migration = CampaignMigration()
report = migration.migrate_session_metadata(
campaign_id=campaign_id,
dry_run=dry_run,
session_filter=filter
)
# Display results
console.print(f"[bold green][OK] Sessions migrated:[/bold green] {report.sessions_migrated}")
console.print(f"[bold yellow][SKIP] Sessions skipped:[/bold yellow] {report.sessions_skipped}")
if report.errors:
console.print(f"\n[bold red][FAIL] Errors ({len(report.errors)}):[/bold red]")
for error in report.errors:
console.print(f" - {error}")
if output:
markdown_report = migration.generate_migration_report_markdown(sessions_report=report)
Path(output).write_text(markdown_report, encoding='utf-8')
console.print(f"\n[bold green][OK] Report saved to:[/bold green] {output}")
if dry_run and report.sessions_migrated > 0:
console.print(f"\n[bold yellow]This was a dry run. Run without --dry-run to apply changes.[/bold yellow]")
@campaigns.command('migrate-profiles')
@click.argument('campaign_id')
@click.option('--dry-run', is_flag=True, help='Preview changes without saving')
@click.option('--characters', '-c', help='Comma-separated list of character names to migrate')
@click.option('--output', '-o', type=click.Path(), help='Save report to markdown file')
def migrate_profiles_cmd(campaign_id, dry_run, characters, output):
"""Assign campaign_id to character profiles.
Example:
python cli.py campaigns migrate-profiles broken_seekers
python cli.py campaigns migrate-profiles broken_seekers --characters "Sha'ek,Pipira"
python cli.py campaigns migrate-profiles broken_seekers --dry-run
"""
from src.campaign_migration import CampaignMigration
character_filter = characters.split(',') if characters else None
console.print(f"\n[bold]{'[DRY RUN] ' if dry_run else ''}Migrating character profiles to campaign: {campaign_id}[/bold]\n")
migration = CampaignMigration()
report = migration.migrate_character_profiles(
campaign_id=campaign_id,
dry_run=dry_run,
character_filter=character_filter
)
# Display results
console.print(f"[bold green][OK] Profiles migrated:[/bold green] {report.profiles_migrated}")
console.print(f"[bold yellow][SKIP] Profiles skipped:[/bold yellow] {report.profiles_skipped}")
if report.errors:
console.print(f"\n[bold red][FAIL] Errors ({len(report.errors)}):[/bold red]")
for error in report.errors:
console.print(f" - {error}")
if output:
markdown_report = migration.generate_migration_report_markdown(profiles_report=report)
Path(output).write_text(markdown_report, encoding='utf-8')
console.print(f"\n[bold green][OK] Report saved to:[/bold green] {output}")
if dry_run and report.profiles_migrated > 0:
console.print(f"\n[bold yellow]This was a dry run. Run without --dry-run to save changes.[/bold yellow]")
@campaigns.command('migrate-narratives')
@click.argument('campaign_id')
@click.option('--dry-run', is_flag=True, help='Preview changes without modifying files')
@click.option('--output', '-o', type=click.Path(), help='Save report to markdown file')
def migrate_narratives_cmd(campaign_id, dry_run, output):
"""Add YAML frontmatter with campaign metadata to narrative files.
Example:
python cli.py campaigns migrate-narratives broken_seekers
python cli.py campaigns migrate-narratives broken_seekers --dry-run
"""
from src.campaign_migration import CampaignMigration
console.print(f"\n[bold]{'[DRY RUN] ' if dry_run else ''}Adding frontmatter to narratives for campaign: {campaign_id}[/bold]\n")
migration = CampaignMigration()
report = migration.migrate_narrative_frontmatter(
campaign_id=campaign_id,
dry_run=dry_run
)
# Display results
console.print(f"[bold green][OK] Narratives migrated:[/bold green] {report.narratives_migrated}")
console.print(f"[bold yellow][SKIP] Narratives skipped:[/bold yellow] {report.narratives_skipped}")
if report.errors:
console.print(f"\n[bold red][FAIL] Errors ({len(report.errors)}):[/bold red]")
for error in report.errors:
console.print(f" - {error}")
if output:
markdown_report = migration.generate_migration_report_markdown(narratives_report=report)
Path(output).write_text(markdown_report, encoding='utf-8')
console.print(f"\n[bold green][OK] Report saved to:[/bold green] {output}")
if dry_run and report.narratives_migrated > 0:
console.print(f"\n[bold yellow]This was a dry run. Run without --dry-run to apply changes.[/bold yellow]")
cli.add_command(campaigns)
@click.group()
def artifacts():
"""Browse and download session artifacts."""
pass
@artifacts.command('list')
@click.option('--limit', '-n', type=int, default=None, help='Maximum number of sessions to show')
@click.option('--json', 'output_json', is_flag=True, help='Output in JSON format')
@click.pass_context
def artifacts_list(ctx, limit, output_json):
"""List all processed sessions.
Shows session directories sorted by modification time (most recent first).
Displays name, file count, size, and modification date.
Examples:
python cli.py artifacts list
python cli.py artifacts list --limit 10
python cli.py artifacts list --json
"""
from src.api.session_artifacts import list_sessions_api
import json
response = list_sessions_api()