Repository navigation
Expand file tree
/
Copy pathweb_ui.py
More file actions
3768 lines (3372 loc) · 132 KB
/
Copy pathweb_ui.py
File metadata and controls
3768 lines (3372 loc) · 132 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
"""
web_ui.py — WebUI API, static assets, and generation orchestration for ltx-ws.
Used by server.py (--web-ui) and optionally by web_server.py (standalone).
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import uuid
from contextlib import asynccontextmanager
from dataclasses import asdict, dataclass, field
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Any, AsyncIterator, Callable, Optional
from starlette.requests import Request
from starlette.websockets import WebSocket
from ltx_media import media_available, probe_audio_duration, trim_audio_to_temp
REPO_ROOT = Path(__file__).resolve().parent
log = logging.getLogger("web_ui")
KNOWN_MODELS = [
{"id": "auto", "label": "Auto (RAM-based)", "repo": "auto"},
{"id": "dgrauet/ltx-2.3-mlx", "label": "MLX bf16 (full quality)", "repo": "dgrauet/ltx-2.3-mlx"},
{"id": "dgrauet/ltx-2.3-mlx-q8", "label": "MLX int8 (balanced)", "repo": "dgrauet/ltx-2.3-mlx-q8"},
{"id": "dgrauet/ltx-2.3-mlx-q4", "label": "MLX int4 (smallest)", "repo": "dgrauet/ltx-2.3-mlx-q4"},
]
RESOLUTION_PRESETS = [
{"id": "704x480", "width": 704, "height": 480, "label": "704 × 480"},
{"id": "1024x576", "width": 1024, "height": 576, "label": "1024 × 576 (16:9)"},
{"id": "576x1024", "width": 576, "height": 1024, "label": "576 × 1024 (9:16)"},
{"id": "1280x720", "width": 1280, "height": 720, "label": "1280 × 720 (HD)"},
]
GENERATION_MODES = [
{"id": "generate", "label": "Text to video"},
{"id": "i2v", "label": "Image to video (i2v)"},
{"id": "a2v", "label": "Audio to video (a2v)"},
{"id": "v2v", "label": "V2V (reference ± optional LoRA)"},
{"id": "retake", "label": "Retake (edit region)"},
{"id": "extend", "label": "Extend video"},
{"id": "keyframe", "label": "Keyframe interpolation"},
{"id": "lipdub", "label": "LipDub (experimental)"},
{"id": "ic_lora", "label": "IC-LoRA (HDR / Union Control)"},
{"id": "face_swap", "label": "Face swap (LTX 2.3)"},
]
CHAIN_METHODS = [
{
"id": "autocontinue",
"label": "Autocontinue (last frame → i2v)",
"description": "Extract last frame and feed as start image for clip 2+",
},
{
"id": "native_extend",
"label": "Extend video (ltx-2-mlx)",
"description": "Clip 1 generate/i2v; clip 2+ native extend_from_video on prior MP4",
},
]
PIPELINE_PROFILES = [
{"id": "distilled", "label": "Distilled (fast, default)"},
{"id": "two_stage", "label": "Two-stage (dev + upscale)"},
{"id": "hq", "label": "HQ (res_2s + CFG)"},
{"id": "one_stage", "label": "One-stage (full-res CFG)"},
]
CLIP_MULTIPLIER_MAX = 10
IC_LORA_PRESET_ID = "ic_lora_hdr"
IC_LORA_MOTION_PRESET_ID = "ic_lora_union_motion"
IC_LORA_DEFAULT_SPEC = (
"https://huggingface.co/buckets/audiohacking/LTX-2.3-22b-IC-LoRA-HDR-bucket/"
"resolve/ltx-2.3-22b-ic-lora-hdr-0.9.safetensors"
)
IC_LORA_UNION_MOTION_SPEC = (
"https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control/"
"resolve/main/ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors"
)
IC_LORA_DEFAULT_SCALE = 1.0
IC_LORA_BUILTIN_SPECS = frozenset({IC_LORA_DEFAULT_SPEC, IC_LORA_UNION_MOTION_SPEC})
FACE_SWAP_PRESET_ID = "face_swap_head"
FACE_SWAP_DEFAULT_SPEC = (
"https://huggingface.co/Alissonerdx/BFS-Best-Face-Swap-Video/"
"resolve/main/ltx-2.3/head_swap_v3_rank_adaptive_fro_098.safetensors"
)
FACE_SWAP_DEFAULT_SCALE = 0.98
LIPDUB_PRESET_ID = "lipdub_ic_lora"
LIPDUB_OFFICIAL_REPO = "Lightricks/LTX-2.3-22b-IC-LoRA-LipDub"
LIPDUB_OFFICIAL_FILENAME = "ltx-2.3-22b-ic-lora-lipdub-0.9.safetensors"
LIPDUB_OFFICIAL_GATED_SPEC = (
f"https://huggingface.co/{LIPDUB_OFFICIAL_REPO}/resolve/main/{LIPDUB_OFFICIAL_FILENAME}"
)
LIPDUB_PUBLIC_BUCKET_SPEC = (
"https://huggingface.co/buckets/audiohacking/LTX-2.3-22b-IC-LoRA-LipDub-bucket/"
f"resolve/{LIPDUB_OFFICIAL_FILENAME}"
)
LIPDUB_DEFAULT_SPEC = LIPDUB_PUBLIC_BUCKET_SPEC
ENV_LIPDUB_LORA = "LTX_WS_LIPDUB_LORA"
LIPDUB_DEFAULT_SCALE = 1.0
DEFAULT_OUTPUT_DIR = REPO_ROOT / "web_outputs"
def _builtin_lipdub_spec() -> str:
"""Built-in LipDub LoRA URL/path: ``LTX_WS_LIPDUB_LORA`` env override, else public bucket."""
return os.environ.get(ENV_LIPDUB_LORA, "").strip() or LIPDUB_DEFAULT_SPEC
def _pose_control_available() -> bool:
try:
from ltx_ic_lora_preprocess import pose_control_available
return pose_control_available()
except ImportError:
return False
DEFAULT_UPLOAD_DIR = REPO_ROOT / "web_uploads"
INDEX_FILE = "index.json"
SETTINGS_FILE = "settings.json"
FPS = 24
PROGRESS_KEEPALIVE_INTERVAL_S = 1.0
def snap_frames(raw: int) -> int:
k = max(0, round((int(raw) - 1) / 8))
return 8 * k + 1
def duration_to_frames(seconds: float) -> int:
return snap_frames(int(seconds * FPS))
def _duration_preset(preset_id: str, seconds: float, num_frames: int) -> dict[str, Any]:
"""One UI duration option with explicit 8k+1 frame count (LTX VAE temporal compression)."""
nf = int(num_frames)
return {
"id": preset_id,
"seconds": float(seconds),
"num_frames": nf,
"label": f"~{seconds:g} s ({nf} frames @ {FPS} fps)",
}
# 8k+1 frame counts @ 24 fps (see ltx-2-mlx / AGENTS.md frame reference).
DURATION_PRESETS = [
_duration_preset("2s", 2.0, 49),
_duration_preset("4s", 4.0, 97),
_duration_preset("5s", 5.0, 121),
_duration_preset("6s", 6.0, 145),
_duration_preset("8s", 8.0, 193),
_duration_preset("10s", 10.0, 241),
_duration_preset("15s", 15.0, 361),
_duration_preset("20s", 20.0, 481),
_duration_preset("24s", 24.0, 577),
]
def _label_for_lora_spec(spec: str) -> str:
name = spec.rsplit("/", 1)[-1] if "/" in spec else spec
if name.endswith(".safetensors"):
name = name[:-12]
return name or spec
def _read_custom_loras(output_dir: Path) -> list[dict[str, Any]]:
from ltx_mlx_backend import _normalize_lora_spec
raw = read_web_settings(output_dir).get("custom_loras")
if not isinstance(raw, list):
return []
out: list[dict[str, Any]] = []
dirty = False
for item in raw:
if not isinstance(item, dict):
continue
spec = _normalize_lora_spec(str(item.get("spec") or "").strip())
if not spec:
continue
original = str(item.get("spec") or "").strip()
if spec != original:
dirty = True
lid = str(item.get("id") or "").strip() or f"custom_{uuid.uuid4().hex[:8]}"
try:
scale = float(item.get("scale", 1.0))
except (TypeError, ValueError):
scale = 1.0
label = str(item.get("label") or "").strip() or _label_for_lora_spec(spec)
out.append({"id": lid, "label": label, "spec": spec, "scale": scale, "custom": True})
if dirty:
# Persist repaired URLs (Path()-mangled https:/… → https://…).
_write_custom_loras(
output_dir,
[{"id": e["id"], "label": e["label"], "spec": e["spec"], "scale": e["scale"]} for e in out],
)
return out
def _write_custom_loras(output_dir: Path, entries: list[dict[str, Any]]) -> None:
data = read_web_settings(output_dir)
data["custom_loras"] = entries
write_web_settings(output_dir, data)
def _read_hidden_lora_ids(output_dir: Path) -> set[str]:
raw = read_web_settings(output_dir).get("hidden_lora_preset_ids")
if not isinstance(raw, list):
return set()
return {str(x).strip() for x in raw if str(x).strip()}
def _persist_hidden_lora_ids(output_dir: Path, ids: set[str]) -> None:
data = read_web_settings(output_dir)
data["hidden_lora_preset_ids"] = sorted(ids)
write_web_settings(output_dir, data)
def _frames_dir(output_dir: Path) -> Path:
return output_dir / "frames"
def _read_frame_library(output_dir: Path) -> list[dict[str, Any]]:
raw = read_web_settings(output_dir).get("frame_library")
if not isinstance(raw, list):
return []
out: list[dict[str, Any]] = []
for item in raw:
if not isinstance(item, dict):
continue
path = str(item.get("path") or "").strip()
if not path:
continue
fid = str(item.get("id") or "").strip() or f"frame_{uuid.uuid4().hex[:8]}"
label = str(item.get("label") or "").strip() or "Frame"
filename = str(item.get("filename") or Path(path).name)
entry: dict[str, Any] = {
"id": fid,
"label": label,
"path": path,
"filename": filename,
"created_at": str(item.get("created_at") or datetime.now().isoformat()),
}
for key in ("width", "height", "source_clip_id", "time_s"):
if item.get(key) is not None:
entry[key] = item[key]
out.append(entry)
return out
def _write_frame_library(output_dir: Path, entries: list[dict[str, Any]]) -> None:
data = read_web_settings(output_dir)
data["frame_library"] = entries
write_web_settings(output_dir, data)
def _frame_for_api(entry: dict[str, Any]) -> dict[str, Any]:
filename = str(entry.get("filename") or Path(str(entry.get("path") or "")).name)
out = dict(entry)
out["image_url"] = f"/api/frames/files/{filename}"
return out
def _remove_lora_preset_entry(output_dir: Path, preset_id: str) -> None:
"""Drop a custom LoRA entry or hide a built-in/env preset from the Web UI."""
lid = (preset_id or "").strip()
if not lid or lid == "none":
raise ValueError("cannot remove the none preset")
if lid.startswith("custom_"):
kept = [e for e in _read_custom_loras(output_dir) if e["id"] != lid]
if len(kept) == len(_read_custom_loras(output_dir)):
raise LookupError("LoRA preset not found")
_write_custom_loras(
output_dir,
[
{"id": e["id"], "label": e["label"], "spec": e["spec"], "scale": e["scale"]}
for e in kept
],
)
return
hidden = _read_hidden_lora_ids(output_dir)
if lid in hidden:
raise LookupError("LoRA preset not found")
hidden.add(lid)
_persist_hidden_lora_ids(output_dir, hidden)
def _lora_catalog(output_dir: Path | None = None) -> tuple[list[dict[str, Any]], str]:
"""
LoRA presets for the Web UI (default from LTX_WS_DEFAULT_LORA / server defaults).
Returns (presets including a None entry, default_preset_id).
"""
from server import (
DEFAULT_GLOBAL_LORA_PATH,
DEFAULT_GLOBAL_LORA_SCALE,
DEFAULT_LORA_URL,
ENV_DEFAULT_LORA,
ENV_DEFAULT_LORA_SCALE,
_default_loras_from_env,
)
def _label_for_spec(spec: str) -> str:
return _label_for_lora_spec(spec)
seen: set[str] = set()
presets: list[dict[str, Any]] = [
{"id": "none", "label": "None (no LoRA)", "spec": "", "scale": 0.0},
]
default_id = "none"
def _add(id_: str, label: str, spec: str, scale: float, is_default: bool = False) -> None:
nonlocal default_id
key = f"{spec}:{scale}"
if not spec or key in seen:
return
seen.add(key)
presets.append({"id": id_, "label": label, "spec": spec, "scale": scale})
if is_default:
default_id = id_
default_path = os.environ.get(ENV_DEFAULT_LORA, DEFAULT_GLOBAL_LORA_PATH).strip()
if not default_path:
default_path = DEFAULT_LORA_URL
scale_raw = os.environ.get(ENV_DEFAULT_LORA_SCALE, str(DEFAULT_GLOBAL_LORA_SCALE)).strip()
try:
default_scale = float(scale_raw)
except ValueError:
default_scale = DEFAULT_GLOBAL_LORA_SCALE
if default_path:
label = (
"OmniNFT RL LoRA (default)"
if default_path == DEFAULT_LORA_URL
else f"Default — {_label_for_spec(default_path)}"
)
_add(
"default",
label,
default_path,
default_scale,
is_default=True,
)
for i, (path, scale) in enumerate(_default_loras_from_env()):
if path == default_path and scale == default_scale:
continue
_add(f"env_{i}", f"Env LoRA — {_label_for_spec(path)}", path, scale)
_add(
"ic_lora_hdr",
"IC-LoRA HDR",
IC_LORA_DEFAULT_SPEC,
1.0,
)
_add(
"ic_lora_union_motion",
"IC-LoRA Union Control (motion transfer)",
IC_LORA_UNION_MOTION_SPEC,
1.0,
)
_add(
FACE_SWAP_PRESET_ID,
"Face swap — head swap LoRA (LTX 2.3)",
FACE_SWAP_DEFAULT_SPEC,
FACE_SWAP_DEFAULT_SCALE,
)
lipdub_spec = _builtin_lipdub_spec()
_add(
LIPDUB_PRESET_ID,
"LipDub — IC-LoRA (LTX 2.3)",
lipdub_spec,
LIPDUB_DEFAULT_SCALE,
)
# Customs last, keyed by unique id so they always appear in the menu even when
# the same URL/scale already exists as a builtin or earlier custom entry.
if output_dir is not None:
existing_ids = {str(p.get("id") or "") for p in presets}
for entry in _read_custom_loras(output_dir):
eid = str(entry.get("id") or "").strip()
spec = str(entry.get("spec") or "").strip()
if not eid or not spec or eid in existing_ids:
continue
try:
scale = float(entry.get("scale", 1.0))
except (TypeError, ValueError):
scale = 1.0
label = str(entry.get("label") or "").strip() or _label_for_spec(spec)
presets.append(
{
"id": eid,
"label": label,
"spec": spec,
"scale": scale,
"custom": True,
}
)
existing_ids.add(eid)
if output_dir is not None:
hidden = _read_hidden_lora_ids(output_dir)
if hidden:
presets = [presets[0]] + [p for p in presets[1:] if p.get("id") not in hidden]
if default_id in hidden:
default_id = "none"
return presets, default_id
def _ensure_lora_downloaded(spec: str) -> dict[str, Any]:
from ltx_mlx_backend import _lora_cached_path, _normalize_lora_spec, _resolve_lora_path
normalized = _normalize_lora_spec(spec)
cached_path = _lora_cached_path(normalized)
if cached_path is not None:
return {
"ok": True,
"spec": normalized,
"path": str(cached_path),
"cached": True,
}
path, _ = _resolve_lora_path(normalized)
return {"ok": True, "spec": normalized, "path": path, "cached": False}
_lora_ensure_locks: dict[str, asyncio.Lock] = {}
_RUN_BODIES: dict[str, dict[str, Any]] = {}
def resolve_web_dist() -> Path:
return REPO_ROOT / "web" / "dist"
def web_dist_stale() -> bool:
"""True when built assets are missing or older than web/src sources."""
dist = resolve_web_dist()
if not dist.is_dir():
return True
assets = dist / "assets"
js_files = list(assets.glob("index-*.js")) if assets.is_dir() else []
if not js_files:
return True
newest_js = max(js_files, key=lambda path: path.stat().st_mtime)
src_root = REPO_ROOT / "web" / "src"
if not src_root.is_dir():
return False
try:
newest_src = max(
path.stat().st_mtime for path in src_root.rglob("*") if path.is_file()
)
except ValueError:
return False
return newest_src > newest_js.stat().st_mtime
def ensure_web_dist_built(*, auto_build: bool = True) -> bool:
"""Rebuild web/dist when missing/stale so git pulls show UI changes.
``web/dist`` is gitignored, so pulling source alone leaves a stale UI.
Returns True when a usable dist exists after this call.
"""
dist = resolve_web_dist()
if dist.is_dir() and not web_dist_stale():
return True
if not auto_build:
return dist.is_dir() and not web_dist_stale()
web_dir = REPO_ROOT / "web"
pkg = web_dir / "package.json"
if not pkg.is_file():
log.warning("Web UI package.json missing at %s — cannot auto-build", pkg)
return False
npm = shutil.which("npm")
if not npm:
log.warning(
"web/dist is stale/missing and npm was not found — run: cd web && npm run build"
)
return False
cmd = [npm, "run", "build"]
if not (web_dir / "node_modules").is_dir():
cmd = [npm, "install", "--no-fund", "--no-audit"]
log.info("Installing Web UI deps (node_modules missing)…")
try:
subprocess.run(cmd, cwd=str(web_dir), check=True)
except (OSError, subprocess.CalledProcessError) as exc:
log.warning("Web UI npm install failed: %s", exc)
return False
cmd = [npm, "run", "build"]
log.info("Building Web UI (web/dist missing or older than web/src)…")
try:
subprocess.run(cmd, cwd=str(web_dir), check=True)
except (OSError, subprocess.CalledProcessError) as exc:
log.warning("Web UI build failed: %s — run: cd web && npm run build", exc)
return False
ok = dist.is_dir() and not web_dist_stale()
if ok:
log.info("Web UI build ready at %s", dist)
return ok
def resolve_favicon_path() -> Path | None:
"""Locate favicon for embedded Web UI (built dist, then source public/)."""
for candidate in (
resolve_web_dist() / "favicon.ico",
REPO_ROOT / "web" / "public" / "favicon.ico",
REPO_ROOT / "web" / "favicon.ico",
):
if candidate.is_file():
return candidate
return None
def _upload_extension(kind: str, filename: str | None) -> str:
"""Pick a safe suffix for an uploaded file."""
ext = Path(filename or "").suffix.lower()
allowed: dict[str, set[str]] = {
"image": {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"},
"audio": {".mp3", ".wav", ".m4a", ".aac", ".flac", ".ogg", ".opus", ".webm"},
"video": {".mp4", ".mov", ".webm", ".mkv", ".avi"},
}
if ext and ext in allowed.get(kind, set()):
return ext
defaults = {"image": ".jpg", "audio": ".mp3", "video": ".mp4"}
return defaults.get(kind, ".bin")
async def _save_upload_file(
request: Request,
upload_dir: Path,
*,
kind: str = "image",
) -> dict[str, str]:
"""Persist multipart upload; avoids FastAPI UploadFile annotations (PEP 563 ForwardRef)."""
form = await request.form()
upload_file = form.get("file")
if upload_file is None:
raise ValueError("file is required")
read = getattr(upload_file, "read", None)
if read is None:
raise ValueError("file is required")
filename = getattr(upload_file, "filename", None) or "upload.bin"
ext = _upload_extension(kind, filename)
uid = str(uuid.uuid4())
dest = upload_dir / f"{uid}{ext}"
content = await read()
dest.write_bytes(content)
return {"path": str(dest), "filename": filename, "kind": kind}
def local_hostname() -> str:
"""Short machine hostname (like ``hostname -s``)."""
try:
name = socket.gethostname().strip().split(".")[0]
if name:
return name
except OSError:
pass
return "localhost"
def public_host(bind_host: str) -> str:
host = (bind_host or "").strip()
if host in ("0.0.0.0", "::", "[::]"):
return local_hostname()
return host
def urls_from_request(request: Any) -> tuple[str, str]:
"""Build ws/http URLs from the incoming HTTP request (browser host)."""
host = (
request.headers.get("x-forwarded-host")
or request.headers.get("host")
or ""
).split(",")[0].strip()
proto = (
request.headers.get("x-forwarded-proto") or "http"
).split(",")[0].strip().lower()
if not host:
return "", ""
ws_proto = "wss" if proto == "https" else "ws"
return f"{ws_proto}://{host}/ws", f"{proto}://{host}/"
def build_server_urls(bind_host: str, port: int) -> tuple[str, str]:
host = public_host(bind_host)
ws_url = f"ws://{host}:{port}/ws"
http_url = f"http://{host}:{port}/"
return ws_url, http_url
def bind_all_http_hint(port: int, bind_host: str = "0.0.0.0") -> str:
return f"http://{public_host(bind_host)}:{port}/"
def num_frames_to_extend_latent(
num_frames: int | None,
*,
duration_seconds: float | None = None,
video_path: Path | str | None = None,
) -> int:
"""Latent frame count for native_extend (~one segment of new footage)."""
from videofentanyl import resolve_extend_latent_frames
return resolve_extend_latent_frames(
video_path=video_path,
num_frames=num_frames,
duration_seconds=duration_seconds,
fps=float(FPS),
)
def _clip_settings_from_body(body: dict[str, Any]) -> dict[str, Any]:
duration_s = float(body.get("duration_seconds") or 5.0)
clip_count = int(body.get("clip_count") or 1)
audiocontinue = bool(body.get("audiocontinue", False))
autocontinue = bool(body.get("autocontinue", False)) or clip_count > 1 or audiocontinue
autoconcat = bool(body.get("autoconcat", False)) or clip_count > 1 or audiocontinue
return {
"num_frames": body.get("num_frames") or duration_to_frames(duration_s),
"width": body.get("width"),
"height": body.get("height"),
"seed": body.get("seed"),
"num_steps": body.get("num_steps"),
"duration_seconds": duration_s,
"clip_count": clip_count,
"autocontinue": autocontinue,
"autoconcat": autoconcat,
"audiocontinue": audiocontinue,
}
def scan_local_models() -> list[dict[str, str]]:
found: list[dict[str, str]] = []
models_dir = REPO_ROOT / "models"
if not models_dir.is_dir():
return found
for child in sorted(models_dir.iterdir()):
if child.is_dir():
found.append(
{
"id": str(child),
"label": f"Local: {child.name}",
"repo": str(child),
}
)
return found
def _all_model_ids(local: list[dict[str, str]] | None = None) -> set[str]:
local = local or scan_local_models()
return {m["id"] for m in KNOWN_MODELS + local}
def default_model_preference(
local: list[dict[str, str]] | None = None,
cli_default: str = "auto",
) -> str:
"""Prefer the first local weights directory when present, else CLI/env default."""
local = local or scan_local_models()
if local:
return local[0]["id"]
return (cli_default or "auto").strip() or "auto"
def resolve_model_preference(
saved: str,
local: list[dict[str, str]] | None = None,
cli_default: str = "auto",
) -> str:
local = local or scan_local_models()
saved = (saved or "").strip()
ids = _all_model_ids(local)
if saved and saved in ids:
return saved
return default_model_preference(local, cli_default)
def read_web_settings(output_dir: Path) -> dict[str, Any]:
path = output_dir / SETTINGS_FILE
if not path.is_file():
return {}
try:
data = json.loads(path.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except (json.JSONDecodeError, OSError, TypeError):
return {}
def write_web_settings(output_dir: Path, data: dict[str, Any]) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
path = output_dir / SETTINGS_FILE
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
def _upload_paths_from_body(body: dict[str, Any], upload_dir: Path) -> list[Path]:
"""Collect upload-dir files referenced by a generate request body."""
paths: list[Path] = []
try:
upload_root = upload_dir.resolve()
except OSError:
return paths
for key in ("image_path", "audio_path", "video_path", "end_image_path", "conditioning_video_path"):
raw = body.get(key)
if not raw:
continue
try:
candidate = Path(str(raw)).resolve()
except (OSError, ValueError):
continue
if not candidate.is_file():
continue
try:
if candidate.is_relative_to(upload_root):
paths.append(candidate)
except AttributeError:
if str(candidate).startswith(str(upload_root)):
paths.append(candidate)
for item in body.get("video_conditioning") or []:
if not isinstance(item, list) or not item:
continue
raw = item[0]
if not raw:
continue
try:
candidate = Path(str(raw)).resolve()
except (OSError, ValueError):
continue
if not candidate.is_file():
continue
try:
if candidate.is_relative_to(upload_root):
paths.append(candidate)
except AttributeError:
if str(candidate).startswith(str(upload_root)):
paths.append(candidate)
return paths
def _delete_upload_paths(paths: list[Path]) -> None:
for path in paths:
try:
path.unlink(missing_ok=True)
except OSError as exc:
log.warning("Could not delete upload %s: %s", path, exc)
def _cleanup_run_uploads(state: AppState, gen_body: dict[str, Any]) -> None:
"""Delete upload-dir files from a finished run (session clear uses :meth:`clear_upload_dir`)."""
paths = _upload_paths_from_body(gen_body, state.upload_dir)
if paths:
log.info("Web UI: cleaning %d upload file(s)", len(paths))
_delete_upload_paths(paths)
def clear_upload_dir(upload_dir: Path) -> int:
"""Remove all files in the Web UI upload directory."""
deleted = 0
if not upload_dir.is_dir():
return deleted
for path in upload_dir.iterdir():
if not path.is_file():
continue
try:
path.unlink(missing_ok=True)
deleted += 1
except OSError as exc:
log.warning("Could not delete upload %s: %s", path, exc)
return deleted
def _validate_request_media_paths(body: dict[str, Any]) -> None:
"""Fail fast when the client references uploads that are no longer on disk."""
from fastapi import HTTPException
for key, label in (
("audio_path", "Audio"),
("image_path", "Image"),
("end_image_path", "End image"),
("video_path", "Video"),
("conditioning_video_path", "Conditioning video"),
):
raw = body.get(key)
if not raw:
continue
path = Path(str(raw)).expanduser()
if not path.is_file():
raise HTTPException(
400,
f"{label} file not found: {raw}. Re-upload the file and try again.",
)
for item in body.get("video_conditioning") or []:
if not isinstance(item, list) or not item:
continue
raw = item[0]
if not raw:
continue
path = Path(str(raw)).expanduser()
if not path.is_file():
raise HTTPException(
400,
f"Conditioning video file not found: {raw}. Re-upload the file and try again.",
)
def _clip_audio_duration_seconds(body: dict[str, Any]) -> float:
duration_s = body.get("duration_seconds")
if duration_s is not None:
return max(0.25, float(duration_s))
num_frames = body.get("num_frames")
if num_frames is not None:
return max(0.25, int(num_frames) / float(FPS))
return 5.0
def _apply_audio_start_offset(body: dict[str, Any]) -> tuple[dict[str, Any], list[Path]]:
"""Crop a2v audio from ``audio_start_seconds`` before generation."""
temps: list[Path] = []
try:
start = float(body.get("audio_start_seconds") or 0)
except (TypeError, ValueError):
start = 0.0
if start <= 0:
return body, temps
audio_path = str(body.get("audio_path") or "").strip()
if not audio_path:
return body, temps
ui_mode = (body.get("mode") or "generate").strip().lower()
if ui_mode != "a2v":
return body, temps
if not media_available():
raise ValueError("Audio start offset requires PyAV — install with: pip install av")
client_duration = body.get("audio_source_duration_seconds")
try:
client_duration_s = float(client_duration) if client_duration is not None else None
if client_duration_s is not None and client_duration_s <= 0:
client_duration_s = None
except (TypeError, ValueError):
client_duration_s = None
clip_need = _clip_audio_duration_seconds(body)
source_duration = client_duration_s if client_duration_s is not None else probe_audio_duration(audio_path)
if source_duration is not None and source_duration - start + 0.05 < clip_need:
raise ValueError(
f"Only {max(0.0, source_duration - start):.1f}s remains after {start:.1f}s offset, "
f"but this clip needs ~{clip_need:.1f}s — lower the start offset or "
"shorten the clip"
)
out_file, temp_dir = trim_audio_to_temp(audio_path, start)
temps.append(temp_dir)
trimmed_duration = probe_audio_duration(out_file)
if trimmed_duration is None or trimmed_duration <= 0:
raise ValueError("Audio crop produced empty output — check the source file")
if trimmed_duration + 0.05 < clip_need:
raise ValueError(
f"Cropped audio is only {trimmed_duration:.1f}s long, "
f"but this clip needs ~{clip_need:.1f}s — lower the start offset or "
"shorten the clip"
)
new_body = dict(body)
new_body["audio_path"] = str(out_file)
new_body["audio_start_seconds"] = 0
log.info(
"Web UI: audio cropped from %.2fs — %.1fs segment at %s",
start,
trimmed_duration,
out_file,
)
return new_body, temps
@dataclass
class _RunTempFiles:
"""Tracks per-run scratch dirs/files; always cleaned in ``cleanup()``."""
dirs: list[Path] = field(default_factory=list)
def add_dir(self, path: Path | None) -> None:
if path is not None:
self.dirs.append(path)
def add_dirs(self, paths: list[Path]) -> None:
for path in paths:
self.add_dir(path)
def cleanup(self) -> None:
seen: set[Path] = set()
for raw in self.dirs:
path = Path(raw)
if path in seen:
continue
seen.add(path)
try:
if path.is_dir():
shutil.rmtree(path, ignore_errors=True)
elif path.is_file():
path.unlink(missing_ok=True)
except OSError as exc:
log.warning("Could not remove run temp %s: %s", path, exc)
self.dirs.clear()
def _finish_run_teardown(state: AppState, temps: _RunTempFiles) -> None:
temps.cleanup()
state.set_active_run(None)
vs = state.video_server
if vs is not None:
gen = getattr(vs, "generator", None)
if gen is not None:
if hasattr(gen, "clear_cancel"):
gen.clear_cancel()
cleanup = getattr(gen, "cleanup_after_generation", None)
if callable(cleanup):
cleanup()
def resolve_source_video_path(state: AppState, body: dict[str, Any]) -> str | None:
"""Resolve ``source_clip_id`` (library) or ``video_path`` (upload) to a local MP4 path."""
clip_id = str(body.get("source_clip_id") or "").strip()
if clip_id:
clip = state.clips.get(clip_id)
if not clip:
raise ValueError(f"Source clip not found: {clip_id}")
if clip.status != RunStatus.DONE.value:
raise ValueError(f"Source clip is not ready (status={clip.status})")
if not clip.filename:
raise ValueError("Source clip has no video file")
path = state.output_dir / clip.filename
if not path.is_file():
raise ValueError(f"Source clip file missing on disk: {clip.filename}")
return str(path.resolve())
raw = body.get("video_path")
if not raw:
return None
path = Path(str(raw)).expanduser()
if not path.is_file():
raise ValueError(f"Video file not found: {raw}")
return str(path.resolve())
def _validate_source_video_request(state: AppState, body: dict[str, Any], ui_mode: str) -> None:
if ui_mode not in ("retake", "extend", "lipdub", "face_swap"):
return
if not body.get("video_path") and not body.get("source_clip_id"):
raise HTTPException(400, f"{ui_mode} mode requires a source video (upload or library clip)")
try:
resolved = resolve_source_video_path(state, body)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
if not resolved:
raise HTTPException(400, f"{ui_mode} mode requires a source video (upload or library clip)")
def _chain_clip_count(run: RunRecord) -> int:
return len(run.prompts) or len(run.clip_ids)
def _should_stream_clip_video(run: RunRecord, clip_index: int, total_clips: int) -> bool:
"""Whether the client should receive/stream this clip's MP4 during a chain run."""
if total_clips <= 1:
return True
if run.autoconcat:
return False
if run.autocontinue:
return clip_index == total_clips - 1
return True
def _build_clip_done_event(
run: RunRecord,
clip_id: str,
clip: ClipRecord,
index: int,
total_clips: int,
) -> dict[str, Any]:
event: dict[str, Any] = {
"type": "clip_done",
"clip_id": clip_id,
"index": index,