-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
2457 lines (2148 loc) · 94.9 KB
/
cli.py
File metadata and controls
2457 lines (2148 loc) · 94.9 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
# Copyright (c) 2026 Liquid Releasing. Licensed under the MIT License.
# Written by human and Claude AI (Claude Sonnet).
"""FunscriptForge CLI
Full-pipeline shortcut (Steps 1 + 3 + 4 in one command):
python cli.py pipeline path/to/input.funscript --output-dir output/
[--perf performance.json] [--break break.json] [--raw raw.json]
[--beats beats.json] [--transformer-config tc.json]
[--customizer-config cc.json]
Individual steps:
Step 1 — Assess
python cli.py assess path/to/input.funscript [--output assessment.json]
[--config analyzer_config.json]
[--min-phrase-duration SECONDS]
[--amplitude-tolerance FRACTION]
Step 2 — Review [MANUAL] — open assessment.json, inspect bpm_transitions and per-phrase BPMs,
then decide which phrases to edit (use Streamlit UI or phrase-transform command)
Step 3 — Transform (BPM-threshold based)
python cli.py transform path/to/input.funscript \\
--assessment assessment.json \\
[--output output.funscript] \\
[--config transformer_config.json]
Step 4 — Customize (human-defined windows)
python cli.py customize path/to/transformed.funscript \\
--assessment assessment.json \\
[--output customized.funscript] \\
[--config customizer_config.json] \\
[--perf manual_performance.json] \\
[--break manual_break.json] \\
[--raw raw_windows.json] \\
[--beats beats.json]
Step 2b — Phrase Transform (catalog transform on individual phrases)
python cli.py phrase-transform path/to/input.funscript \\
--assessment assessment.json \\
--transform smooth --phrase 3 [--param strength=0.25] # one phrase
--transform normalize --all # all phrases
--suggest [--bpm-threshold 120] # auto-pick per phrase
--dry-run # print plan only
--suggest uses tag-aware rules (highest priority first):
frantic → halve_tempo
giggle / plateau / lazy → amplitude_scale (amplify; scale targets peak hi ≈ 65)
stingy → amplitude_scale (reduce; scale targets peak hi ≈ 65)
drift / half_stroke → recenter (target_center=50)
drone → beat_accent
(no tag) transition → smooth
(no tag) low BPM → passthrough
(no tag) narrow span → normalize
(no tag) high BPM → amplitude_scale
For split-phrase workflows (different transforms in different time ranges within
a single phrase) use the Streamlit Pattern Editor UI — it supports adding split
boundaries, per-segment transform selection, and proportional copy to all
instances of the same behavioral tag.
Additional commands:
python cli.py finalize path/to/transformed.funscript # blend seams + final smooth, then save
[--output finalized.funscript]
[--param seam_max_velocity=0.3] # blend_seams param override
[--param smooth_strength=0.05] # final_smooth param override
[--skip-seams] [--skip-smooth] # disable either pass
python cli.py export-plan path/to/input.funscript # show export-tab transform plan
[--assessment assessment.json] # use cached assessment
[--transforms overrides.json] # per-phrase manual overrides
[--no-recommended] # skip auto-suggestions
[--bpm-threshold 120] # threshold for recommendations
[--format table|json] # output format (default: table)
[--apply] [--output out.funscript] # write the result
[--dry-run] # print plan only
python cli.py catalog [--catalog PATH] # show catalog summary
python cli.py catalog --tag stingy # list all stingy phrases
python cli.py catalog --remove Timeline1.original.funscript # remove one entry
python cli.py catalog --clear # clear all entries
python cli.py visualize path/to/input.funscript --assessment assessment.json [--output viz.png]
python cli.py config --output transformer_config.json # dump default transformer config
python cli.py config --customizer --output cc.json # dump customizer config
python cli.py config --analyzer --output analyzer_config.json # dump analyzer config
python cli.py test # run all tests
Forge metadata / media analysis:
python cli.py meta path/to/input.funscript # print auto-derived metadata table
[--assessment assessment.json] # reuse cached assessment
[--output metadata.json] # also save as JSON
[--format table|json] # output format (default: table)
Derived fields: Pace (BPM), Intensity (avg_speed), Stroke depth (pos range),
Duration category, Dominant mood, Arc type, Variety, auto Hub tags, Tone suggestion.
python cli.py suggest-tone path/to/input.funscript # print tone label + rationale
python cli.py beats path/to/video.mp4 # extract beat timestamps
[--audio path/to/override.wav] # use separate audio track instead
[--output-dir output/] # where to write _beats.json + _beats.csv
Requires: pip install av librosa numpy
python cli.py audio-peaks path/to/media.mp4 # pre-computed waveform sidecar
[--hop-ms 10] # window size (default 10ms)
[--force] # recompute even if sidecar exists
[--no-write] # skip writing <stem>.audio.json
[--format table|json] # output format (default: table)
Writes <stem>.audio.json next to the media file (peaks: 0..1 RMS-per-hop).
Requires: pip install av numpy
python cli.py parse-captions path/to/captions.srt # parse SRT or VTT, save _captions.json
[--output-dir output/] # destination folder
[--print] # also print all cues to stdout
Supports: .srt (SubRip), .vtt (WebVTT)
"""
import argparse
import copy
import dataclasses
import functools
import json
import os
import sys
import tempfile
import time
from pathlib import Path
from typing import Optional
sys.path.insert(0, os.path.dirname(__file__))
from assessment.analyzer import AnalyzerConfig, FunscriptAnalyzer
from assessment.classifier import TAGS
from catalog.pattern_catalog import PatternCatalog
from models import AssessmentResult
from pattern_catalog.config import TransformerConfig
from pattern_catalog.phrase_transforms import (
TRANSFORM_CATALOG, _BUILTIN_KEYS, _validate_recipe_entry, suggest_transform,
)
from pattern_catalog.transformer import FunscriptTransformer
from user_customization.config import CustomizerConfig
from user_customization.customizer import WindowCustomizer
from utils import ms_to_timestamp
from visualizations.motion import HAS_MATPLOTLIB, MotionVisualizer
# ------------------------------------------------------------------
# Error handling
# ------------------------------------------------------------------
def _cli_command(fn):
"""Decorator that gives every CLI command consistent error handling.
Catches FileNotFoundError and ValueError (the two exceptions our pipeline
raises for bad input) and prints a clean one-line message to stderr before
exiting with code 1. KeyboardInterrupt exits with code 130.
"""
@functools.wraps(fn)
def wrapper(args):
try:
fn(args)
except (FileNotFoundError, ValueError) as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
print("\nInterrupted.", file=sys.stderr)
sys.exit(130)
return wrapper
# ------------------------------------------------------------------
# Command implementations
# ------------------------------------------------------------------
def _build_analyzer_config(args):
"""Build an AnalyzerConfig from CLI args and optional --config file."""
config = AnalyzerConfig()
if getattr(args, "config", None):
with open(args.config) as f:
d = json.load(f)
config = AnalyzerConfig(**{
k: v for k, v in d.items()
if k in AnalyzerConfig.__dataclass_fields__
})
if getattr(args, "min_phrase_duration", None) is not None:
config.min_phrase_duration_ms = int(args.min_phrase_duration * 1000)
if getattr(args, "amplitude_tolerance", None) is not None:
config.amplitude_tolerance = args.amplitude_tolerance
return config
@_cli_command
def cmd_pipeline(args):
output_dir = args.output_dir or os.path.join(
os.path.dirname(args.funscript), "output"
)
os.makedirs(output_dir, exist_ok=True)
base = os.path.splitext(os.path.basename(args.funscript))[0]
# Stage 1 — Assess
analyzer = FunscriptAnalyzer(config=_build_analyzer_config(args))
analyzer.load(args.funscript)
t0 = time.time()
assessment = analyzer.analyze(progress_callback=lambda s: print(f" {s}"))
assessment_path = os.path.join(output_dir, f"{base}.assessment.json")
assessment.save(assessment_path)
print(f"Assessment saved: {assessment_path} ({time.time() - t0:.2f}s)")
print(f" BPM: {assessment.bpm} Phrases: {len(assessment.phrases)}"
f" Transitions: {len(assessment.bpm_transitions)}")
# Stage 2 — Transform
tx_config = TransformerConfig.load(args.transformer_config) if args.transformer_config else TransformerConfig()
transformer = FunscriptTransformer(tx_config)
transformer.load_funscript(args.funscript)
transformer.load_assessment(assessment)
t0 = time.time()
transformer.transform()
transformed_path = os.path.join(output_dir, f"{base}.transformed.funscript")
transformer.save(transformed_path)
print(f"Transformed: {transformed_path} ({time.time() - t0:.2f}s)")
# Stage 3 — Customize
cust_config = CustomizerConfig.load(args.customizer_config) if args.customizer_config else CustomizerConfig()
customizer = WindowCustomizer(cust_config)
customizer.load_funscript(transformed_path)
customizer.load_assessment(assessment)
customizer.load_manual_overrides(
perf_path=args.perf,
break_path=args.break_windows,
raw_path=args.raw,
)
if args.beats:
customizer.load_beats_from_file(args.beats)
t0 = time.time()
customizer.customize()
customized_path = os.path.join(output_dir, f"{base}.customized.funscript")
customizer.save(customized_path)
print(f"Customized: {customized_path} ({time.time() - t0:.2f}s)")
@_cli_command
def cmd_assess(args):
json_mode = getattr(args, "format", "table") == "json"
analyzer = FunscriptAnalyzer(config=_build_analyzer_config(args))
analyzer.load(args.funscript)
t0 = time.time()
# JSON mode: stdout is the structured payload — keep progress prints
# off it. Send progress to stderr so the user (and Tauri bridge) can
# still see them but the parser stays clean. The same stage label is
# also pushed onto the structured progress pipe at depth 2 so the
# AcceptBar footer renders a 6-step checklist (matches the
# auto-chapter UX — depth 1 is reserved for the outer command
# wrapper, depth 2+ is what the listener actually surfaces).
_stages_seen: list[str] = []
def _progress(stage: str) -> None:
if json_mode:
print(f" {stage}", file=sys.stderr)
else:
print(f" {stage}")
# Close the previous stage with `done::` before opening the new
# one with `start::`. The analyzer only emits one event per stage
# (no explicit completion), so the next start implicitly marks
# the prior stage done.
if _stages_seen:
_emit_progress(f"done::2::{_stages_seen[-1]}")
_emit_progress(f"start::2::{stage}")
_stages_seen.append(stage)
result = analyzer.analyze(progress_callback=_progress)
# Close the final stage once analyze() returns.
if _stages_seen:
_emit_progress(f"done::2::{_stages_seen[-1]}")
elapsed = time.time() - t0
# Chapter-scoped phrase re-detection — when chapters exist, replace
# the global phrase pass with per-chapter detection so each chapter's
# natural duration drives the analyzer's auto_scale thresholds. Solves
# the previously-observed mashup-vs-individual mismatch: the 93-min
# mashup yielded 37 phrases globally vs 111 across the 16 component
# clips with tight per-chapter scoping. chapter_id is tagged at
# detection time (no midpoint lookup needed).
chapters = _load_chapters_for_phrases(args.funscript)
if chapters:
per_chapter_phrases = []
for ch_idx, ch in enumerate(chapters):
ch_start = int(ch.get("at_ms", 0))
ch_end = int(ch.get("end_ms", 0))
ch_actions = [
a for a in analyzer._actions
if ch_start <= a["at"] < ch_end
]
if not ch_actions:
continue
# Per-chapter sub-analyzer: disable auto-scale. auto_scale targets
# ~15 phrases per analyzed span; applied per-chapter that forces
# 15 phrases into every chapter, over-splitting uniform regions
# and burying real transitions under widened tolerances. Fixed
# defaults (min_phrase_duration_ms=20_000, amplitude_tolerance=0.30)
# split on actual character drift instead of a target count.
sub_config = _build_analyzer_config(args)
sub_config.auto_scale_phrases = False
sub = FunscriptAnalyzer(config=sub_config)
sub._actions = ch_actions
sub._source_file = analyzer._source_file
sub_result = sub.analyze(progress_callback=None)
for p in sub_result.phrases:
p.chapter_id = ch_idx
per_chapter_phrases.extend(sub_result.phrases)
result.phrases = per_chapter_phrases
# Length splitter post-pass — chapter-scoped phrases > 4 min still
# benefit from the splitter (e.g. one long chapter of uniform
# character produces an oversized phrase). Mutates result.phrases so
# the json_mode stdout payload reflects the split too.
result.phrases = _split_long_phrases(result.phrases, args.funscript)
# Step 2 — character-drift splitter. Subdivides on top/bottom/density drift,
# adds beat-aligned drone-grid in long uniform stretches, snaps interior
# boundaries to downbeats when the beats sidecar is available. Validated
# against VictoriaOaks + IPZZ-125 dogfood; user-confirmed direction.
from assessment.character_drift import split_phrases as _drift_split
downbeats_ms = _load_downbeats_for_phrases(args.funscript)
result.phrases = _drift_split(result.phrases, analyzer._actions, downbeats_ms=downbeats_ms)
# Re-classify post-split phrases. _split_long_phrases and _drift_split
# create NEW phrase boundaries; without this pass, tags / metrics /
# shape_label reflect the pre-split phrases, which yields wrong
# labels (e.g. a "swell" that was split into two equal halves would
# carry "swell" on both halves even though each half is now
# structurally different from the original).
from assessment.classifier import annotate_phrases as _annotate_phrases
from assessment.shape_labeler import label_phrases as _label_phrases
_post_split_phrase_dicts = [p.to_dict() for p in result.phrases]
_annotate_phrases(_post_split_phrase_dicts, [], analyzer._actions)
_label_phrases(_post_split_phrase_dicts, analyzer._actions)
for _phrase, _pd in zip(result.phrases, _post_split_phrase_dicts):
_phrase.tags = _pd.get("tags", [])
_phrase.metrics = _pd.get("metrics", {})
_phrase.shape_label = _pd.get("shape_label", "steady")
# Phrase slice sidecar — `<stem>.forge/<stem>.phrases.json`. Read by
# PhrasesTab / PatternsTab. chapter_id comes from the runtime
# attribute set during per-chapter detection above (None when the
# project has no chapters sidecar).
if not getattr(args, "no_save", False):
_write_phrases_slice_sidecar(args.funscript, result)
if json_mode:
# Structured stdout payload for the Tauri bridge (PhrasesTab consumer).
# Phrase shape: at_ms / end_ms / number (1-based global) / bpm / tag
# (primary tag for color) / all_tags (forward-compat) / pattern_label.
# Sidecar file is written too unless --no-save is passed; gives both
# the JS consumer and the existing pipeline what they need.
payload = {
"duration_ms": result.duration_ms,
"bpm": result.bpm,
"action_count": result.action_count,
"phrases": [
{
"at_ms": p.start_ms,
"end_ms": p.end_ms,
"number": i + 1,
"bpm": p.bpm,
"tag": (p.tags[0] if p.tags else None),
"all_tags": list(p.tags),
"pattern_label": p.pattern_label,
}
for i, p in enumerate(result.phrases)
],
}
if not getattr(args, "no_save", False):
output = args.output or _default_path(args.funscript, "_assessment.json")
result.save(output)
print(json.dumps(payload))
return
output = args.output or _default_path(args.funscript, "_assessment.json")
result.save(output)
print(f"Assessment saved: {output} ({elapsed:.2f}s)")
print(f" Duration: {result.duration_ts} ({result.duration_ms} ms)")
print(f" BPM: {result.bpm}")
print(f" Actions: {result.action_count}")
print(f" Phases: {len(result.phases)}")
print(f" Cycles: {len(result.cycles)}")
print(f" Patterns: {len(result.patterns)}")
print(f" Phrases: {len(result.phrases)}")
if result.bpm_transitions:
print(f" BPM transitions ({len(result.bpm_transitions)}):")
for t in result.bpm_transitions:
print(f" {t.description}")
else:
print(" BPM transitions: none detected")
@_cli_command
def cmd_transform(args):
config = TransformerConfig.load(args.config) if args.config else TransformerConfig()
transformer = FunscriptTransformer(config)
transformer.load_funscript(args.funscript)
transformer.load_assessment_from_file(args.assessment)
t0 = time.time()
transformer.transform()
elapsed = time.time() - t0
output = args.output or _default_path(args.funscript, "_transformed.funscript")
transformer.save(output)
for line in transformer.get_log():
print(line)
print(f"\nTransformed funscript saved: {output} ({elapsed:.2f}s)")
@_cli_command
def cmd_customize(args):
config = CustomizerConfig.load(args.config) if args.config else CustomizerConfig()
customizer = WindowCustomizer(config)
customizer.load_funscript(args.funscript)
customizer.load_assessment_from_file(args.assessment)
customizer.load_manual_overrides(
perf_path=args.perf,
break_path=args.break_windows,
raw_path=args.raw,
)
if args.beats:
customizer.load_beats_from_file(args.beats)
t0 = time.time()
customizer.customize()
elapsed = time.time() - t0
output = args.output or _default_path(args.funscript, "_customized.funscript")
customizer.save(output)
for line in customizer.get_log():
print(line)
print(f"\nCustomized funscript saved: {output} ({elapsed:.2f}s)")
@_cli_command
def cmd_visualize(args):
if not HAS_MATPLOTLIB:
print("Error: matplotlib is not installed. Run: pip install matplotlib")
sys.exit(1)
with open(args.funscript) as f:
data = json.load(f)
actions = data["actions"]
assessment = AssessmentResult.load(args.assessment)
output = args.output or _default_path(args.funscript, "_visualization.png")
viz = MotionVisualizer(assessment, actions)
viz.plot(output)
print(f"Visualization saved: {output}")
@_cli_command
def cmd_config(args):
if args.customizer:
cfg = CustomizerConfig()
output = args.output or "customizer_config.json"
cfg.save(output)
print(f"Default customizer config written: {output}")
elif args.analyzer:
cfg = AnalyzerConfig()
output = args.output or "analyzer_config.json"
with open(output, "w") as f:
json.dump(dataclasses.asdict(cfg), f, indent=2)
print(f"Default analyzer config written: {output}")
else:
cfg = TransformerConfig()
output = args.output or "transformer_config.json"
cfg.save(output)
print(f"Default transformer config written: {output}")
print("Edit the values then pass with --config when running the command.")
@_cli_command
def cmd_list_transforms(args):
"""List all available transforms (built-in + user-loaded)."""
catalog = dict(sorted(TRANSFORM_CATALOG.items()))
if args.user_only:
catalog = {k: v for k, v in catalog.items() if k not in _BUILTIN_KEYS}
if args.format == "json":
out = {}
for key, spec in catalog.items():
entry = {
"name": spec.name,
"description": spec.description,
"structural": spec.structural,
"source": "builtin" if key in _BUILTIN_KEYS else "user",
}
if args.verbose:
entry["params"] = {
pkey: {
"label": p.label,
"type": p.type,
"default": p.default,
"min": p.min_val,
"max": p.max_val,
"step": p.step,
"help": p.help,
}
for pkey, p in (spec.params or {}).items()
}
out[key] = entry
print(json.dumps(out, indent=2))
return
# --- table output ---
if not catalog:
print("No transforms found.")
return
for key, spec in catalog.items():
source_tag = "" if key in _BUILTIN_KEYS else " [user]"
struct_tag = " (structural)" if spec.structural else ""
print(f"{key}{source_tag}{struct_tag}")
print(f" {spec.name} — {spec.description}")
if args.verbose and spec.params:
for pkey, p in spec.params.items():
default_str = f", default {p.default}" if p.default is not None else ""
range_str = f" [{p.min_val}–{p.max_val}]" if p.min_val is not None else ""
print(f" --param {pkey}=VALUE {p.label}{range_str}{default_str}")
if p.help:
print(f" {p.help}")
print()
def cmd_validate_plugins(args):
"""Validate JSON recipe files and report Python plugin gate status."""
import glob as _glob
root = os.path.dirname(os.path.abspath(__file__))
recipes_dir = args.recipes_dir or os.path.join(root, "user_transforms")
plugins_dir = args.plugins_dir or os.path.join(root, "plugins")
total_files = 0
total_entries = 0
total_errors = 0
# ---- JSON recipes ----
if os.path.isdir(recipes_dir):
json_files = sorted(_glob.glob(os.path.join(recipes_dir, "*.json")))
for path in json_files:
fname = os.path.relpath(path, root)
total_files += 1
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
except Exception as exc:
print(f" ERROR {fname}: {exc}")
total_errors += 1
continue
entries = data if isinstance(data, list) else [data]
file_ok = True
for i, entry in enumerate(entries):
total_entries += 1
err = _validate_recipe_entry(entry)
if err:
key = entry.get("key", f"entry[{i}]") if isinstance(entry, dict) else f"entry[{i}]"
print(f" ERROR {fname} [{key}]: {err}")
total_errors += 1
file_ok = False
elif args.verbose:
key = entry.get("key", f"entry[{i}]")
print(f" ok {fname} [{key}]")
if file_ok and not args.verbose:
n = len(entries)
print(f" ok {fname} ({n} {'entry' if n == 1 else 'entries'})")
else:
print(f" (no recipes directory at {recipes_dir})")
# ---- Python plugins ----
print()
plugins_enabled = os.environ.get("FUNSCRIPT_PLUGINS_ENABLED", "").lower() in (
"1", "true", "yes",
)
if os.path.isdir(plugins_dir):
py_files = sorted(_glob.glob(os.path.join(plugins_dir, "*.py")))
non_example = [p for p in py_files if not os.path.basename(p).startswith("example_")]
example_files = [p for p in py_files if os.path.basename(p).startswith("example_")]
if not py_files:
print("Python plugins: none found in plugins/")
else:
status = "ENABLED (FUNSCRIPT_PLUGINS_ENABLED is set)" if plugins_enabled else "DISABLED (FUNSCRIPT_PLUGINS_ENABLED not set)"
print(f"Python plugins: {status}")
for p in non_example:
tag = "would load" if plugins_enabled else "skipped — set FUNSCRIPT_PLUGINS_ENABLED=1 to enable"
print(f" {os.path.relpath(p, root)}: {tag}")
for p in example_files:
print(f" {os.path.relpath(p, root)}: skipped (example/template file)")
else:
print("Python plugins: no plugins/ directory found")
# ---- Summary ----
print()
if total_files == 0:
print("No JSON recipe files found.")
elif total_errors == 0:
print(f"All {total_entries} recipe {'entry' if total_entries == 1 else 'entries'} in {total_files} {'file' if total_files == 1 else 'files'} are valid.")
else:
print(f"{total_errors} error(s) found across {total_files} file(s). Fix errors before loading.")
sys.exit(1)
def _coerce(v: str):
"""Parse a string value as int, float, or str."""
try:
i = int(v); f = float(v)
return i if i == f else f
except ValueError:
return v
@_cli_command
def cmd_phrase_transform(args):
"""Apply a catalog transform to one or all phrases of a funscript."""
# --- load inputs ---
with open(args.funscript) as f:
data = json.load(f)
actions = data["actions"]
assessment = AssessmentResult.load(args.assessment)
phrases = [p.__dict__ if hasattr(p, "__dict__") else p for p in assessment.phrases]
# Normalise to plain dicts with the keys phrase_detail expects
phrase_dicts = []
for p in assessment.phrases:
d = p if isinstance(p, dict) else {
"start_ms": p.start_ms,
"end_ms": p.end_ms,
"bpm": getattr(p, "bpm", 0),
"pattern_label": getattr(p, "pattern_label", ""),
"amplitude_span": getattr(p, "amplitude_span", 100),
"cycle_count": getattr(p, "cycle_count", None),
}
phrase_dicts.append(d)
if not phrase_dicts:
print("No phrases found in assessment — nothing to transform.")
sys.exit(1)
# --- resolve which phrases to process ---
if args.all or args.suggest:
indices = list(range(len(phrase_dicts)))
elif args.phrase:
indices = []
for n in args.phrase:
idx = n - 1 # user-facing is 1-based
if idx < 0 or idx >= len(phrase_dicts):
print(f"Error: --phrase {n} is out of range (1–{len(phrase_dicts)}).")
sys.exit(1)
indices.append(idx)
else:
print("Error: specify --phrase N, --all, or --suggest.")
sys.exit(1)
# --- parse --param key=value pairs ---
extra_params = {}
for kv in (args.param or []):
if "=" not in kv:
print(f"Error: --param must be key=value, got: {kv!r}")
sys.exit(1)
k, v = kv.split("=", 1)
extra_params[k.strip()] = _coerce(v.strip())
# --- build transform plan ---
bpm_threshold = args.bpm_threshold or 120.0
plan = [] # list of (phrase_idx, transform_key, param_values)
for idx in indices:
phrase = phrase_dicts[idx]
if args.suggest:
key, _ = suggest_transform(phrase, bpm_threshold)
else:
key = args.transform
if key not in TRANSFORM_CATALOG:
print(f"Error: unknown transform {key!r}. "
f"Available: {', '.join(TRANSFORM_CATALOG)}")
sys.exit(1)
spec = TRANSFORM_CATALOG[key]
params = {k: v.default for k, v in spec.params.items()}
params.update(extra_params)
plan.append((idx, key, params))
# --- print plan ---
print(f"Phrase-transform plan ({len(plan)} phrase{'s' if len(plan) != 1 else ''}):")
for idx, key, params in plan:
ph = phrase_dicts[idx]
param_str = " ".join(f"{k}={v}" for k, v in params.items()) if params else "-"
label = ph.get('pattern_label', '').encode('ascii', errors='replace').decode('ascii')
print(f" P{idx + 1:>2} {key:<18} params: {param_str}"
f" ({ph.get('bpm', 0):.0f} BPM, {label})")
if args.dry_run:
print("\n--dry-run: no file written.")
return
# --- apply ---
result = copy.deepcopy(actions)
for idx, key, params in plan:
spec = TRANSFORM_CATALOG[key]
ph = phrase_dicts[idx]
start = ph["start_ms"]
end = ph["end_ms"]
slice_ = [a for a in result if start <= a["at"] <= end]
transformed = spec.apply(slice_, params)
if spec.structural:
# Replace the phrase slice with the new (potentially shorter) actions
result = [a for a in result if not (start <= a["at"] <= end)]
result = sorted(result + transformed, key=lambda a: a["at"])
else:
t_map = {a["at"]: a["pos"] for a in transformed}
for a in result:
if a["at"] in t_map:
a["pos"] = t_map[a["at"]]
# --- save ---
data["actions"] = result
output = args.output or _default_path(args.funscript, "_phrase_transformed.funscript")
with open(output, "w") as f:
json.dump(data, f, indent=2)
print(f"\nSaved: {output}")
@_cli_command
def cmd_finalize(args):
"""Apply blend_seams + final_smooth to the full action list, then save."""
with open(args.funscript) as f:
data = json.load(f)
result = copy.deepcopy(data["actions"])
seam_spec = TRANSFORM_CATALOG["blend_seams"]
smooth_spec = TRANSFORM_CATALOG["final_smooth"]
# Build optional param overrides from --param seam_* / smooth_* prefixes
seam_params = {}
smooth_params = {}
for kv in (args.param or []):
if "=" not in kv:
print(f"Error: --param must be key=value, got: {kv!r}")
sys.exit(1)
k, v = kv.split("=", 1)
k = k.strip()
val = _coerce(v.strip())
if k.startswith("seam_"):
seam_params[k[5:]] = val
elif k.startswith("smooth_"):
smooth_params[k[7:]] = val
else:
print(f"Error: --param key must start with seam_ or smooth_, got: {k!r}")
sys.exit(1)
if not args.skip_seams:
result = seam_spec.apply(result, seam_params or None)
print(f"Applied blend_seams (max_velocity={seam_spec.params['max_velocity'].default if not seam_params else seam_params.get('max_velocity', seam_spec.params['max_velocity'].default)}, "
f"max_strength={seam_params.get('max_strength', seam_spec.params['max_strength'].default)})")
if not args.skip_smooth:
result = smooth_spec.apply(result, smooth_params or None)
print(f"Applied final_smooth (strength={smooth_params.get('strength', smooth_spec.params['strength'].default)})")
data["actions"] = result
output = args.output or _default_path(args.funscript, "_finalized.funscript")
with open(output, "w") as f:
json.dump(data, f, indent=2)
print(f"\nSaved: {output}")
@_cli_command
def cmd_catalog(args):
"""Inspect or manage the cross-funscript pattern catalog."""
catalog_path = args.catalog or os.path.join(
os.path.dirname(__file__), "output", "pattern_catalog.json"
)
cat = PatternCatalog(catalog_path)
if args.clear:
cat._data["entries"] = []
cat.save()
print("Catalog cleared.")
return
if args.remove:
removed = cat.remove(args.remove)
if removed:
cat.save()
print(f"Removed: {args.remove}")
else:
print(f"Not found in catalog: {args.remove}")
return
if args.tag:
tag = args.tag
meta = TAGS.get(tag)
phrases = cat.get_phrases_for_tag(tag)
label = meta.label if meta else tag
print(f"Tag '{label}' — {len(phrases)} phrase(s) across {len({p['_funscript'] for p in phrases})} file(s)")
if meta:
print(f" Description: {meta.description}")
print(f" Suggested fix: {meta.suggested_transform} — {meta.fix_hint}")
for ph in phrases:
print(f" [{ph['_funscript']}] {ms_to_timestamp(ph['start_ms'])} → {ms_to_timestamp(ph['end_ms'])}"
f" BPM: {ph.get('bpm', 0):.1f}"
f" span: {ph.get('metrics', {}).get('span', 0):.1f}")
return
# Default: summary
s = cat.summary()
print(f"Catalog: {catalog_path}")
print(f" Funscripts indexed : {s['funscripts_indexed']}")
print(f" Tagged phrases : {s['total_tagged_phrases']}")
if s["tags_found"]:
stats = cat.get_tag_stats()
print(f" Tags found : {', '.join(s['tags_found'])}")
print()
print(f" {'Tag':<14} {'Phrases':>7} {'Files':>5} {'BPM':>12} {'Span':>12}")
print(f" {'-'*14} {'-'*7} {'-'*5} {'-'*12} {'-'*12}")
for tag in s["tags_found"]:
st = stats[tag]
label = TAGS[tag].label if tag in TAGS else tag
bpm_range = f"{st['bpm_min']}–{st['bpm_max']}"
span_range = f"{st['span_min']}–{st['span_max']}"
print(f" {label:<14} {st['count']:>7} {st['funscripts']:>5} {bpm_range:>12} {span_range:>12}")
else:
print(" No tagged phrases yet — assess a funscript to populate the catalog.")
@_cli_command
def cmd_export_plan(args):
"""Show (and optionally apply) the export-tab transform plan for a funscript."""
# --- load assessment (run fresh if not provided) ---
if args.assessment:
assessment = AssessmentResult.load(args.assessment)
else:
analyzer = FunscriptAnalyzer(config=_build_analyzer_config(args))
analyzer.load(args.funscript)
assessment = analyzer.analyze()
phrase_dicts = []
for p in assessment.phrases:
d = p if isinstance(p, dict) else {
"start_ms": p.start_ms,
"end_ms": p.end_ms,
"bpm": getattr(p, "bpm", 0),
"cycle_count": getattr(p, "cycle_count", None),
"pattern_label": getattr(p, "pattern_label", ""),
"amplitude_span": getattr(p, "amplitude_span", 100),
"tags": list(getattr(p, "tags", []) or []),
}
phrase_dicts.append(d)
if not phrase_dicts:
print("No phrases found — run an assessment first.")
sys.exit(1)
# --- load per-phrase override file (optional) ---
# Format: {"1": {"transform": "normalize", "params": {...}}, "3": "passthrough", ...}
# Keys are 1-based phrase numbers (strings or ints).
overrides: dict = {}
if args.transforms:
with open(args.transforms) as f:
raw = json.load(f)
for k, v in raw.items():
idx = int(k) - 1 # convert 1-based → 0-based
if isinstance(v, str):
overrides[idx] = {"transform": v, "params": {}}
else:
overrides[idx] = {
"transform": v.get("transform", "passthrough"),
"params": v.get("params", {}),
}
bpm_threshold = args.bpm_threshold or 120.0
include_recommended = not args.no_recommended
# --- build plan ---
plan = [] # list of dicts
for idx, phrase in enumerate(phrase_dicts):
tx_key: str = None
tx_params: dict = {}
source: str = None
# 1. Manual override from --transforms file
if idx in overrides:
entry_tx = overrides[idx]["transform"]
if entry_tx and entry_tx != "passthrough":
tx_key = entry_tx
tx_params = overrides[idx]["params"]
source = "Manual"
# 2. Recommended (untouched phrases)
if not tx_key and include_recommended:
rec, rec_params = suggest_transform(phrase, bpm_threshold)
if rec and rec != "passthrough":
tx_key = rec
tx_params = rec_params
source = "Recommended"
if not tx_key:
continue
if tx_key not in TRANSFORM_CATALOG:
print(f"Warning: unknown transform {tx_key!r} for phrase {idx + 1} — skipping.")
continue
old_bpm = phrase.get("bpm", 0.0)
old_cycles = phrase.get("cycle_count") or 0
new_bpm = (old_bpm / 2) if tx_key == "halve_tempo" else None
new_cycles = (old_cycles // 2) if tx_key == "halve_tempo" else None
spec = TRANSFORM_CATALOG[tx_key]
tx_name = spec.name
plan.append({
"phrase_idx": idx,
"start_ms": phrase["start_ms"],
"end_ms": phrase["end_ms"],
"tx_key": tx_key,
"tx_name": tx_name,
"tx_params": tx_params,
"source": source,
"old_bpm": old_bpm,
"new_bpm": new_bpm,
"old_cycles": old_cycles,
"new_cycles": new_cycles,
})
# --- output ---
if args.format == "json":
out = []
for e in plan:
row = {
"phrase": e["phrase_idx"] + 1,
"start": ms_to_timestamp(e["start_ms"]),
"end": ms_to_timestamp(e["end_ms"]),
"duration_s": round((e["end_ms"] - e["start_ms"]) / 1000, 1),
"transform": e["tx_name"],
"source": e["source"],
"bpm": {
"old": round(e["old_bpm"], 1),
**({"new": round(e["new_bpm"], 1)} if e["new_bpm"] is not None else {}),
},
"cycles": {
"old": e["old_cycles"],
**({"new": e["new_cycles"]} if e["new_cycles"] is not None else {}),
},
}
out.append(row)
print(json.dumps(out, indent=2))
else:
# Human-readable table
n = len(plan)
rec_n = sum(1 for e in plan if e["source"] == "Recommended")
man_n = n - rec_n
print(f"Export plan: {n} transform{'s' if n != 1 else ''}"
f" ({man_n} manual, {rec_n} recommended)")
print(f" BPM threshold for recommendations: {bpm_threshold}")
print()
_W = (3, 29, 7, 24, 13, 18, 8)
_HDR = ("#", "Time", "Dur(s)", "Transform", "Source", "BPM", "Cycles")
_sep = " ".join(f"{h:<{w}}" for h, w in zip(_HDR, _W))
print(_sep)
print("-" * len(_sep))
for e in plan:
time_str = (f"{ms_to_timestamp(e['start_ms'])} -> "
f"{ms_to_timestamp(e['end_ms'])}")
dur_s = f"{(e['end_ms'] - e['start_ms']) / 1000:.1f}"
if e["new_bpm"] is not None:
bpm_str = f"{e['old_bpm']:.1f} -> {e['new_bpm']:.1f}"
else:
bpm_str = f"{e['old_bpm']:.1f}"
if e["new_cycles"] is not None:
cyc_str = f"{e['old_cycles']} -> {e['new_cycles']}"
else:
cyc_str = str(e["old_cycles"])
row = (
str(e["phrase_idx"] + 1),
time_str,
dur_s,
e["tx_name"],
e["source"],
bpm_str,
cyc_str,
)