Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1255 lines (1134 loc) · 57.6 KB
/
Copy pathapp.py
File metadata and controls
1255 lines (1134 loc) · 57.6 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
"""
MiniMax-H3 スタンドアロン検証アプリ (FastAPI)。
diffusers-server (port 8601) とは完全に独立したワークスペース。将来の統合検証のための
先行アプリで、T2VA (テキスト -> 動画+ステレオ音声) と FL2VA (先頭/末尾フレーム指定) を
提供する。生成は同時1件まで (グローバルロック)。
起動: venv/bin/python -m uvicorn app:app --host 0.0.0.0 --port 8611
"""
import core.hubenv # noqa: F401 huggingface_hub を import する前に Windows の symlink 設定を整える
import logging
import tempfile
import threading
import time
import uuid
from pathlib import Path
from typing import Optional
from fastapi import Body, FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from PIL import Image
import core.gallery as gallery
# `runner` はこのモジュールでは MiniMaxH3Runner インスタンスの名前なので、モジュール
# 自体は別名で持つ (`resolve_num_inference_steps()` が H3_TURBO_LORA をモジュール属性
# として読むために必要)。
import core.runner as runner_mod
import core.settings as settings
from core.local_llm import local_llm
from core.llm import (
H3SkillNotFetchedError,
InfeasibleInputError,
LLMConnectionError,
VALID_H3_OFFICIAL_LANGS,
VALID_H3_OFFICIAL_TASKS,
VALID_MODES,
enhance_prompt,
enhance_prompt_checked,
get_llm_url,
last_backend,
llm_status,
)
from core.runner import (
FPS,
H3_LOWVRAM,
H3_TURBO_LORA,
H3_TURBO_STEPS_DEFAULT,
MAX_SECONDS,
MIN_SECONDS,
STILL_FRAME_CHOICES,
GenerationInterrupted,
MiniMaxH3AudioReference,
MiniMaxH3ImageReference,
MiniMaxH3Runner,
MiniMaxH3VideoReference,
ProgressState,
interrupt_controller,
seconds_to_num_frames,
)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("minimax_h3.app")
BASE_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = BASE_DIR / "outputs"
OUTPUT_DIR.mkdir(exist_ok=True)
app = FastAPI(title="MiniMax-H3")
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
app.mount("/outputs", StaticFiles(directory=str(OUTPUT_DIR)), name="outputs")
runner = MiniMaxH3Runner(OUTPUT_DIR)
# 同時1件までのシンプルな排他制御 (diffusers-server の generation_lock と同じ考え方)
_generation_lock = threading.Lock()
_current_progress: Optional[ProgressState] = None
_progress_guard = threading.Lock()
RESOLUTION_PRESETS = {
"768x768": (768, 768),
"768x1344": (768, 1344),
"1344x768": (1344, 768),
}
# 任意サイズ指定のための丸め規則。MiniMax-H3 のキャンバスは 32 の倍数でなければならず
# (`MINIMAX_H3_CANVAS_MULTIPLE`、`MiniMaxH3Ref2VASetupStep._check_inputs` 等が
# 満たさない値を ValueError にする)、ネイティブのキャンバスは短辺 768・最大 768x1344。
# ここでは「エラーにせず丸める」方針を取り、下限/上限でクランプしてから 32 の倍数へ
# 四捨五入する(上限はモデルカードの 2K 記載に合わせた実験用の余地。ネイティブ範囲を
# 超える指定は VRAM も品質も未検証なので UI 側で注意書きを出す)。
CANVAS_MULTIPLE = 32
CANVAS_MIN = 256
CANVAS_MAX = 2048
CANVAS_NATIVE_MAX = 1344 # ネイティブ範囲の目安(超過は実験的)
def round_canvas_value(value: int) -> int:
"""1辺を H3 の規則(32の倍数)へ丸め、[CANVAS_MIN, CANVAS_MAX] にクランプする。"""
value = max(CANVAS_MIN, min(CANVAS_MAX, int(value)))
return int(round(value / CANVAS_MULTIPLE)) * CANVAS_MULTIPLE
# ベースモデル(非蒸留)のステップ既定。
NON_TURBO_NUM_INFERENCE_STEPS = 30
# 後方互換のため残している「起動時の turbo 既定に対応するステップ数」。内部の既定解決は
# 下の `resolve_num_inference_steps()` が担うので、この定数はもう既定値としては使わない
# (README / docs が過去の不具合記録でこの名前を参照している)。
DEFAULT_NUM_INFERENCE_STEPS = H3_TURBO_STEPS_DEFAULT if H3_TURBO_LORA else NON_TURBO_NUM_INFERENCE_STEPS
def resolve_num_inference_steps(num_inference_steps: Optional[int], turbo: Optional[bool]) -> int:
"""`num_inference_steps` 未指定時の既定を、そのリクエストの**実効 turbo** から決める。
turbo はリクエスト単位の即反映設定 (`core/settings.py` の
`resolve_instant_settings()`、LoRA は初回 ON 時に遅延ロードされる) なので、ステップ
既定も同じ粒度で決めないと食い違う。旧実装は起動時の `H3_TURBO_LORA` だけで固定した
`DEFAULT_NUM_INFERENCE_STEPS` を FastAPI の Form 既定値にしていたため、次の2ケースが
壊れていた (2026-08-20 修正。UI 側の同種の食い違いは core/runner.py の
`turbo_steps_default` のコメント参照):
- `H3_TURBO_LORA=0` のサーバへ `turbo=true` だけ送る -> 蒸留モデルに 30 ステップ
(無駄に遅い。4step 蒸留の想定外の領域でもある)
- `H3_TURBO_LORA=1` のサーバへ `turbo=false` だけ送る -> 非 turbo なのに 4 ステップ
(生成が破綻する)
turbo 未指定時の解決規則は `resolve_instant_settings()` と一致させること
(どちらも `core.runner.H3_TURBO_LORA` を見る)。**モジュール属性として読む**のが要点で、
import 時の値を焼き込むと、将来この既定が実行時に変更可能になったとき静かにずれる。
明示指定された値は turbo の状態に関わらず常にそのまま尊重する。
"""
if num_inference_steps is not None:
return num_inference_steps
effective_turbo = turbo if turbo is not None else runner_mod.H3_TURBO_LORA
return H3_TURBO_STEPS_DEFAULT if effective_turbo else NON_TURBO_NUM_INFERENCE_STEPS
@app.get("/")
def index():
# ブラウザが古いindex.htmlをキャッシュしてUI更新が見えなくなる問題の対策
# (diffusers-server の NoCacheStaticFiles と同趣旨。JS/CSSはこのファイルにインライン)
return FileResponse(
str(BASE_DIR / "static" / "index.html"),
headers={"Cache-Control": "no-store"},
)
@app.get("/api/status")
def api_status():
with _progress_guard:
busy = _generation_lock.locked()
progress = _current_progress.snapshot() if _current_progress else None
return {
"busy": busy,
"progress": progress,
"runner": runner.status(),
"llm": llm_status(),
"min_seconds": MIN_SECONDS,
"max_seconds": MAX_SECONDS,
"resolutions": list(RESOLUTION_PRESETS.keys()),
# 任意サイズ/秒数のUI側プレビュー用。丸めの権威はサーバ(下の各エンドポイント)
# だが、UIが同じ規則で「実際に使われる値」を先に見せられるように公開する。
"constraints": {
"canvas_multiple": CANVAS_MULTIPLE,
"canvas_min": CANVAS_MIN,
"canvas_max": CANVAS_MAX,
"canvas_native_max": CANVAS_NATIVE_MAX,
"fps": FPS,
"frame_step": 17, # num_frames は 17n + 5 (align_num_frames)
"frame_offset": 5,
"still_frame_choices": list(STILL_FRAME_CHOICES), # /api/t2i の frames の選択肢
},
}
@app.get("/api/progress")
def api_progress():
with _progress_guard:
if _current_progress is None:
return {"phase": "idle"}
return _current_progress.snapshot()
@app.post("/api/interrupt")
def api_interrupt(job_id: Optional[str] = Body(None, embed=True)):
"""現在実行中の生成に中断を要求する。
`job_id` を**指定した**場合は、現在実行中のジョブと一致するときだけ中断する
(不一致なら何もしない -- 中止を押した直後に次のジョブが始まっていた場合に、
それを巻き添えにしないため)。**省略した場合は「いま動いているものを中断する」**
(呼び出し側がジョブIDを知らないことがあるため。mv_studio_V2 の中止ボタンは
この省略形で呼ぶので、ここを「省略なら何もしない」に変えると中止が効かなくなる)。
反応はステップ境界まで遅延する(H3の1ステップは実測6〜9秒 -- `core/runner.py` の
`GenerationInterrupted` docstring参照)。中断されたリクエストは HTTP 499 で返る。
生成中でなければ `interrupted: false` を返すだけ(エラーにはしない)。
"""
with _progress_guard:
current_job_id = _current_progress.job_id if _current_progress else None
requested = interrupt_controller.request(job_id)
return {
"interrupted": requested,
"current_job_id": current_job_id,
"requested_job_id": job_id,
}
@app.get("/api/settings")
def api_settings():
"""Current instant/reload-group settings + choice lists (see core/settings.py).
The UI reads this once at load to seed its controls with the server's actual
current state, not hardcoded defaults.
"""
return settings.current_settings_snapshot()
@app.post("/api/settings/apply")
def api_settings_apply(
transformer_quant: Optional[str] = Form(None),
te_quant: Optional[str] = Form(None),
te_prune: Optional[bool] = Form(None),
lowvram: Optional[str] = Form(None),
video_vae_fp16: Optional[bool] = Form(None),
te_proj: Optional[bool] = Form(None),
te_proj_quant: Optional[str] = Form(None),
):
"""Apply a new reload-group configuration: unloads every big model and reloads
under the new settings (core.settings.apply_reload_settings -> runner.unload_all()
+ runner.preload_all(), no process restart -- see that function's docstring).
409 while a generation is in progress (same generation_lock as /api/t2va etc, so an
apply can never race an in-flight denoise loop or vice versa). 400 for an invalid/
unverified combination (mirrors core/runner.py's own startup validation).
"""
fields = {}
if transformer_quant is not None:
fields["transformer_quant"] = transformer_quant
if te_quant is not None:
fields["te_quant"] = te_quant
if te_prune is not None:
fields["te_prune"] = te_prune
if lowvram is not None:
fields["lowvram"] = lowvram
if video_vae_fp16 is not None:
fields["video_vae_fp16"] = video_vae_fp16
if te_proj is not None:
fields["te_proj"] = te_proj
if te_proj_quant is not None:
fields["te_proj_quant"] = te_proj_quant
acquired = _generation_lock.acquire(blocking=False)
if not acquired:
raise HTTPException(409, "生成が進行中のため設定を適用できません。完了を待ってから再試行してください。")
global _current_progress
job_id = uuid.uuid4().hex[:12]
progress = ProgressState(job_id=job_id, phase="starting", started_at=time.time())
with _progress_guard:
_current_progress = progress
try:
progress.update(phase="loading", message="設定を適用中(モデル再ロード)...")
result = settings.apply_reload_settings(runner, **fields)
progress.update(phase="done", message="設定適用完了")
return JSONResponse(result)
except ValueError as e:
progress.update(phase="error", error=str(e))
raise HTTPException(400, str(e))
except Exception as e:
logger.exception("settings apply failed")
progress.update(phase="error", error=str(e))
raise HTTPException(500, f"settings apply failed: {e}")
finally:
_generation_lock.release()
@app.post("/api/admin/unload")
def api_admin_unload():
"""Phase 5a(diffusers-movie-server resident 切替)用: プロセスを残したまま
常駐モデルを全て解放する(runner.unload_all()、各 _free_* が gc + empty_cache 済み)。
生成中は 409。解放後も次の生成要求は generate()/generate_ref2va() の冪等な
_ensure_* 群で自動再ロードされる(遅延ロードで自然復帰)が、96gb 常駐構成の
プリロード状態へ戻したい場合は /api/admin/reload を使う。
"""
acquired = _generation_lock.acquire(blocking=False)
if not acquired:
raise HTTPException(409, "生成が進行中のためアンロードできません。完了を待ってから再試行してください。")
try:
runner.unload_all()
return {"result": "unloaded", "runner": runner.status()}
except Exception as e:
logger.exception("admin unload failed")
raise HTTPException(500, f"unload failed: {e}")
finally:
_generation_lock.release()
@app.post("/api/admin/reload")
def api_admin_reload():
"""Phase 5a 用: preload_all() を再実行して定常常駐状態へ戻す(構成は起動時 env の
まま変わらない)。resident 切替の「復帰」で gateway から呼ばれる。生成中は 409。
"""
acquired = _generation_lock.acquire(blocking=False)
if not acquired:
raise HTTPException(409, "生成が進行中のため再ロードできません。完了を待ってから再試行してください。")
global _current_progress
progress = ProgressState(job_id=uuid.uuid4().hex[:12], phase="loading", started_at=time.time())
with _progress_guard:
_current_progress = progress
try:
progress.update(phase="loading", message="モデルを再ロード中(preload_all)...")
t0 = time.time()
runner.preload_all()
progress.update(phase="done", message="再ロード完了")
return {"result": "reloaded", "elapsed_s": round(time.time() - t0, 1),
"runner": runner.status()}
except Exception as e:
logger.exception("admin reload failed")
progress.update(phase="error", error=str(e))
raise HTTPException(500, f"reload failed: {e}")
finally:
_generation_lock.release()
def _run_generation(
prompt: str,
resolution: str,
seconds: float,
num_inference_steps: Optional[int],
seed: Optional[int],
image: Optional[Image.Image],
last_image: Optional[Image.Image],
upscale: int = 0,
height: Optional[int] = None,
width: Optional[int] = None,
cache: Optional[str] = None,
cache_threshold: Optional[float] = None,
attn: Optional[str] = None,
turbo: Optional[bool] = None,
mute: bool = False,
still_frames: Optional[int] = None,
) -> dict:
"""still_frames を指定すると静止画モード (t2i): seconds は無視され、超短尺動画から
中央フレームの PNG を書き出す(core/runner.py の generate(still=True) 参照)。
`num_inference_steps=None` はそのリクエストの実効 turbo から解決する
(`resolve_num_inference_steps()` 参照)。"""
global _current_progress
num_inference_steps = resolve_num_inference_steps(num_inference_steps, turbo)
# height/width を明示指定した場合はプリセットより優先し、H3の規則へ丸める
# (エラーにはしない)。片方だけの指定は誤用なので 400。
if (height is None) != (width is None):
raise HTTPException(400, "height と width は両方指定してください(片方だけの指定は不可)")
if height is not None:
height = round_canvas_value(height)
width = round_canvas_value(width)
else:
if resolution not in RESOLUTION_PRESETS:
raise HTTPException(400, f"unknown resolution preset: {resolution}")
height, width = RESOLUTION_PRESETS[resolution]
# 秒数もモデルの許容範囲へ丸める(エラーにしない)。実際のフレーム数は
# seconds_to_num_frames() が 17n+5 へ切り上げるため、生成尺は要求秒数より
# わずかに長くなることがある(レスポンスの num_frames / duration_s が実値)。
# 静止画モード (still_frames 指定時) は seconds を使わないため丸めもしない。
if still_frames is None:
seconds = max(MIN_SECONDS, min(MAX_SECONDS, float(seconds)))
if not (MIN_SECONDS <= seconds <= MAX_SECONDS):
raise HTTPException(400, f"seconds must be between {MIN_SECONDS} and {MAX_SECONDS}, got {seconds}")
if not prompt or not prompt.strip():
raise HTTPException(400, "prompt is required")
acquired = _generation_lock.acquire(blocking=False)
if acquired:
local_llm.before_generation() # RAM の少ない PC では内蔵 LLM を止めて生成に RAM を回す
if not acquired:
raise HTTPException(409, "別の生成が進行中です。しばらく待ってから再試行してください。")
job_id = uuid.uuid4().hex[:12]
progress = ProgressState(job_id=job_id, phase="starting", started_at=time.time())
with _progress_guard:
_current_progress = progress
# 前回の中断要求が残っていて今回の生成が即死しないよう、開始時に必ずクリアする。
interrupt_controller.begin(job_id)
try:
result = runner.generate(
prompt=prompt.strip(),
height=height,
width=width,
seconds=seconds,
num_inference_steps=num_inference_steps,
seed=seed,
image=image,
last_image=last_image,
progress=progress,
upscale=upscale,
cache=cache,
cache_threshold=cache_threshold,
attn=attn,
turbo=turbo,
mute=mute,
still=still_frames is not None,
still_frames=still_frames if still_frames is not None else 22,
)
result["job_id"] = job_id
result["video_url"] = f"/outputs/{Path(result['mp4_path']).name}"
if result.get("png_filename"):
result["image_url"] = f"/outputs/{result['png_filename']}"
return result
except ValueError as e:
raise HTTPException(400, str(e))
except GenerationInterrupted as e:
logger.info("generation interrupted: %s", e)
progress.update(phase="error", error=str(e))
raise HTTPException(499, f"生成が中断されました: {e}")
except Exception as e:
logger.exception("generation failed")
progress.update(phase="error", error=str(e))
raise HTTPException(500, f"generation failed: {e}")
finally:
interrupt_controller.end()
_generation_lock.release()
@app.post("/api/t2va")
def api_t2va(
prompt: str = Form(...),
resolution: str = Form("768x768"),
seconds: float = Form(5.0),
num_inference_steps: Optional[int] = Form(None),
seed: Optional[int] = Form(None),
upscale: int = Form(0),
height: Optional[int] = Form(None),
width: Optional[int] = Form(None),
cache: Optional[str] = Form(None),
cache_threshold: Optional[float] = Form(None),
attn: Optional[str] = Form(None),
turbo: Optional[bool] = Form(None),
mute: bool = Form(False),
):
"""height/width を指定すると resolution プリセットより優先され、32の倍数へ丸められる。
cache/cache_threshold/attn/turbo は即反映(再ロード不要)の任意パラメータ。
未指定ならサーバの現在の既定(環境変数由来)のまま(core/settings.py 参照)。
"""
result = _run_generation(
prompt=prompt,
resolution=resolution,
seconds=seconds,
num_inference_steps=num_inference_steps,
seed=seed,
image=None,
last_image=None,
upscale=upscale,
height=height,
width=width,
cache=cache,
cache_threshold=cache_threshold,
attn=attn,
turbo=turbo,
mute=mute,
)
return JSONResponse(result)
@app.post("/api/t2i")
def api_t2i(
prompt: str = Form(...),
resolution: str = Form("768x768"),
frames: int = Form(22),
num_inference_steps: Optional[int] = Form(None),
seed: Optional[int] = Form(None),
height: Optional[int] = Form(None),
width: Optional[int] = Form(None),
cache: Optional[str] = Form(None),
cache_threshold: Optional[float] = Form(None),
attn: Optional[str] = Form(None),
turbo: Optional[bool] = Form(None),
mute: bool = Form(False),
):
"""静止画生成 (t2i): 超短尺動画を生成して中央フレームを PNG として書き出す。
frames は 22 (0.917秒、品質検証済みの既定) か 5 (0.208秒、実験的・要
H3_VAE_SMALLCLIP_FIX=1)。速度は固定費 (~55s〜、低VRAMモードではモデル再ロード分
さらに増える) 支配のため専用 T2I モデルには勝てないが、H3 と画風が完全に一致する
静止画を FL2VA の先頭フレームや Ref2VA の参照画像として作れるのが価値
(README「静止画モード」参照)。レスポンスには mp4 (超短尺の元動画) と
png (image_url) の両方が入る。height/width 指定時は resolution より優先。
cache/cache_threshold/attn/turbo は他エンドポイントと同じ即反映パラメータ。
"""
if frames not in STILL_FRAME_CHOICES:
raise HTTPException(400, f"frames は {STILL_FRAME_CHOICES} のいずれかです: {frames}")
result = _run_generation(
prompt=prompt,
resolution=resolution,
seconds=0.0, # still モードでは未使用 (still_frames が尺を決める)
num_inference_steps=num_inference_steps,
seed=seed,
image=None,
last_image=None,
height=height,
width=width,
cache=cache,
cache_threshold=cache_threshold,
attn=attn,
turbo=turbo,
mute=mute,
still_frames=frames,
)
return JSONResponse(result)
# 1バッチの場面数上限。場面ごとに増えるGPU/RAM負担は潜在+prompt_embedsのみ(数十MB/場面)
# なので技術的にはもっと積めるが、1リクエストが長くなりすぎるとHTTPタイムアウトや
# 途中失敗時の損失が大きくなるため、物語用途に十分な数で切る。
STILL_BATCH_MAX = 24
@app.post("/api/t2i_batch")
def api_t2i_batch(
prompts: list[str] = Form(...),
resolution: str = Form("768x768"),
frames: int = Form(22),
num_inference_steps: Optional[int] = Form(None),
seed: Optional[int] = Form(None),
height: Optional[int] = Form(None),
width: Optional[int] = Form(None),
cache: Optional[str] = Form(None),
cache_threshold: Optional[float] = Form(None),
attn: Optional[str] = Form(None),
turbo: Optional[bool] = Form(None),
mute: bool = Form(False),
):
"""静止画のバッチ生成: プロンプト配列 (multipart で `prompts` を複数回送る) から
場面ごとの PNG を連続生成する(物語の場面画像用)。
`H3_LOWVRAM=1` ではモデルロードの固定費 (~120s) をバッチ全体で1回に償却する
位相並べ替え (core/runner.py の generate_still_batch) を使う。それ以外のモードは
大モデルが常駐していて位相並べ替えの利得がないため、逐次 generate() で同じ
レスポンス形式を返す。seed は全場面共通(手動で同一 seed を N 回叩くのと同じ)。
解像度・フレーム数・ステップ数も全場面共通で、変えられるのはプロンプトのみ。
`num_inference_steps=None` はそのリクエストの実効 turbo から解決する
(`resolve_num_inference_steps()` 参照)。バッチ全場面で同じ値を使う。
"""
num_inference_steps = resolve_num_inference_steps(num_inference_steps, turbo)
if frames not in STILL_FRAME_CHOICES:
raise HTTPException(400, f"frames は {STILL_FRAME_CHOICES} のいずれかです: {frames}")
cleaned = [p.strip() for p in prompts if p and p.strip()]
if not cleaned:
raise HTTPException(400, "prompts が空です (空でないプロンプトを1つ以上)")
if len(cleaned) > STILL_BATCH_MAX:
raise HTTPException(400, f"prompts は最大 {STILL_BATCH_MAX} 場面です: {len(cleaned)}")
if (height is None) != (width is None):
raise HTTPException(400, "height と width は両方指定してください(片方だけの指定は不可)")
if height is not None:
height = round_canvas_value(height)
width = round_canvas_value(width)
else:
if resolution not in RESOLUTION_PRESETS:
raise HTTPException(400, f"unknown resolution preset: {resolution}")
height, width = RESOLUTION_PRESETS[resolution]
acquired = _generation_lock.acquire(blocking=False)
if acquired:
local_llm.before_generation() # RAM の少ない PC では内蔵 LLM を止めて生成に RAM を回す
if not acquired:
raise HTTPException(409, "別の生成が進行中です。しばらく待ってから再試行してください。")
global _current_progress
job_id = uuid.uuid4().hex[:12]
progress = ProgressState(job_id=job_id, phase="starting", started_at=time.time())
with _progress_guard:
_current_progress = progress
interrupt_controller.begin(job_id)
try:
if H3_LOWVRAM:
result = runner.generate_still_batch(
prompts=cleaned,
height=height,
width=width,
num_inference_steps=num_inference_steps,
seed=seed,
still_frames=frames,
progress=progress,
cache=cache,
cache_threshold=cache_threshold,
attn=attn,
turbo=turbo,
mute=mute,
)
else:
# 常駐モード (bnb-4bit 既定 / group / none): 逐次 generate() でも固定費は
# ほぼ増えないので、同じレスポンス形式に詰め替えて返す。
t0 = time.time()
scenes = []
for idx, p in enumerate(cleaned):
progress.update(message=f"場面 {idx + 1}/{len(cleaned)} を生成中...")
r = runner.generate(
prompt=p, height=height, width=width, seconds=0.0,
num_inference_steps=num_inference_steps, seed=seed,
progress=progress, cache=cache, cache_threshold=cache_threshold,
attn=attn, turbo=turbo, mute=mute, still=True, still_frames=frames,
)
scenes.append({
"prompt": p,
"png_path": r["png_path"], "png_filename": r["png_filename"],
"mp4_path": r["mp4_path"], "mp4_filename": r["mp4_filename"],
"still_frame_index": r["still_frame_index"],
"denoise_time_s": r["denoise_time_s"],
"avg_step_time_s": r["avg_step_time_s"],
"cache_skipped_steps": r["cache_skipped_steps"],
})
total = time.time() - t0
result = {
"mode": "t2i_batch", "num_scenes": len(cleaned),
"height": height, "width": width,
"num_frames": frames, "still_frames": frames, "duration_s": frames / FPS,
"num_inference_steps": num_inference_steps, "seed": seed,
"total_elapsed_s": round(total, 2),
"per_image_s": round(total / len(cleaned), 2),
"scenes": scenes,
}
result["job_id"] = job_id
for scene in result["scenes"]:
scene["image_url"] = f"/outputs/{scene['png_filename']}"
scene["video_url"] = f"/outputs/{scene['mp4_filename']}"
return JSONResponse(result)
except ValueError as e:
raise HTTPException(400, str(e))
except GenerationInterrupted as e:
logger.info("t2i_batch generation interrupted: %s", e)
progress.update(phase="error", error=str(e))
raise HTTPException(499, f"生成が中断されました: {e}")
except Exception as e:
logger.exception("t2i_batch generation failed")
progress.update(phase="error", error=str(e))
raise HTTPException(500, f"t2i_batch generation failed: {e}")
finally:
interrupt_controller.end()
_generation_lock.release()
@app.post("/api/fl2va")
def api_fl2va(
prompt: str = Form(...),
resolution: str = Form("768x768"),
seconds: float = Form(5.0),
num_inference_steps: Optional[int] = Form(None),
seed: Optional[int] = Form(None),
image: Optional[UploadFile] = File(None),
last_image: Optional[UploadFile] = File(None),
height: Optional[int] = Form(None),
width: Optional[int] = Form(None),
cache: Optional[str] = Form(None),
cache_threshold: Optional[float] = Form(None),
attn: Optional[str] = Form(None),
turbo: Optional[bool] = Form(None),
mute: bool = Form(False),
):
"""height/width を指定すると resolution プリセットより優先され、32の倍数へ丸められる。
cache/cache_threshold/attn/turbo は即反映(再ロード不要)の任意パラメータ。
"""
if image is None and last_image is None:
raise HTTPException(400, "FL2VA には image または last_image のいずれかが必要です")
pil_image = Image.open(image.file).convert("RGB") if image is not None else None
pil_last_image = Image.open(last_image.file).convert("RGB") if last_image is not None else None
result = _run_generation(
prompt=prompt,
resolution=resolution,
seconds=seconds,
num_inference_steps=num_inference_steps,
seed=seed,
image=pil_image,
last_image=pil_last_image,
height=height,
width=width,
cache=cache,
cache_threshold=cache_threshold,
attn=attn,
turbo=turbo,
mute=mute,
)
return JSONResponse(result)
# Content-type / extension -> reference kind ("image" | "video" | "audio"). Video/audio
# containers are decoded by PyAV inside each MiniMaxH3*Reference class's own `from_file`
# classmethod (it accepts a path and decodes it when built, per references.py's module
# docstring) -- this app only needs to classify the upload and hand it a path, never
# touching pixels/samples itself.
_REF_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}
_REF_VIDEO_EXTS = {".mp4", ".webm", ".mov", ".mkv", ".avi"}
_REF_AUDIO_EXTS = {".wav", ".mp3", ".flac", ".ogg", ".m4a", ".aac"}
def _detect_reference_kind(upload: UploadFile) -> str:
content_type = (upload.content_type or "").lower()
if content_type.startswith("image/"):
return "image"
if content_type.startswith("video/"):
return "video"
if content_type.startswith("audio/"):
return "audio"
ext = Path(upload.filename or "").suffix.lower()
if ext in _REF_IMAGE_EXTS:
return "image"
if ext in _REF_VIDEO_EXTS:
return "video"
if ext in _REF_AUDIO_EXTS:
return "audio"
raise HTTPException(
400,
f"references の種別を判定できません(filename={upload.filename!r}, content_type={upload.content_type!r})。"
"画像/動画/音声いずれかの一般的な拡張子・content-typeにしてください。",
)
@app.post("/api/ref2va")
def api_ref2va(
prompt: str = Form(...),
references: list[UploadFile] = File(...),
height: Optional[int] = Form(None),
width: Optional[int] = Form(None),
seconds: Optional[float] = Form(None),
num_inference_steps: Optional[int] = Form(None),
seed: Optional[int] = Form(None),
cache: Optional[str] = Form(None),
cache_threshold: Optional[float] = Form(None),
attn: Optional[str] = Form(None),
turbo: Optional[bool] = Form(None),
mute: bool = Form(False),
still: int = Form(0),
frames: int = Form(22),
reference_image_short_edge: Optional[int] = Form(None),
vocal_lock: Optional[bool] = Form(None),
):
"""ref2va: 画像最大9・動画最大3・音声最大3(計12参照)からの動画+音声生成。
references の送信順が参照順(プロンプト内ラベル・rotary配置に反映される)。種別は
content-type/拡張子から自動判定する。`seconds` を省略できるのは references に音声を
持つ参照(音声単体 or 音声付き動画)がちょうど1本のときのみ(その音声長が生成尺になる、
core/runner.py の `_num_frames_from_audio_reference` の仕様どおり) -- それ以外で
省略すると ValueError を 400 に変換して返す。
cache/cache_threshold/attn/turbo は即反映(再ロード不要)の任意パラメータ
(transformer_ref へ適用される)。
still=1 は参照付き静止画モード (ref2i): seconds を無視して frames (22既定|5) の
超短尺を生成し、中央フレームPNGを書き出す(レスポンスに image_url が付く)。
キャラクター参照から場面ごとの一貫した静止画を作る用途(README
「スパイク: Ref2VA×超短尺」参照)。
`num_inference_steps=None` はそのリクエストの実効 turbo から解決する
(`resolve_num_inference_steps()` 参照)。
`reference_image_short_edge` は任意パラメータ(未指定ならプロセス起動時の
H3_REF_IMAGE_SHORT_EDGE 環境変数の値、既定2048、を使う=挙動は完全に従来どおり)。
参照画像をQwen3-VL-32Bへ通す前に正規化する短辺サイズで、小さいほどプレフィックス
トークン数が減りエンコード・denoiseとも高速化するが、参照の細部再現度が下がる
(トレードオフの実測は core/runner.py の H3_REF_IMAGE_SHORT_EDGE コメント参照)。
不正値(正の整数でない)は400。
`vocal_lock` は任意パラメータ(未指定ならプロセス起動時の H3_VOCAL_LOCK
環境変数の値を使う=挙動は完全に従来どおり)。true/false を指定すると
その環境変数より優先される(このリクエストだけ Vocal Lock を有効/無効にする、
プロセス再起動不要)。詳細は core/runner.py の H3_VOCAL_LOCK コメント参照。
"""
global _current_progress
runner_mod._tl("api_entry")
num_inference_steps = resolve_num_inference_steps(num_inference_steps, turbo)
if not prompt or not prompt.strip():
raise HTTPException(400, "prompt is required")
if not references:
raise HTTPException(400, "references is required (at least one image/video/audio file)")
if still and frames not in STILL_FRAME_CHOICES:
raise HTTPException(400, f"frames は {STILL_FRAME_CHOICES} のいずれかです: {frames}")
if (height is None) != (width is None):
raise HTTPException(400, "height と width は両方指定するか、両方省略してください")
if reference_image_short_edge is not None and reference_image_short_edge <= 0:
raise HTTPException(
400, f"reference_image_short_edge は正の整数で指定してください: {reference_image_short_edge}"
)
# 32の倍数でない値はエラーにせず丸める(t2va/fl2va と同じ方針。省略時はサーバが
# H3 自身の 16:9 キャンバスを解決するので触らない)。
if height is not None:
height = round_canvas_value(height)
width = round_canvas_value(width)
# 秒数も許容範囲へ丸める(省略時は音声参照1本からサーバが導出する)。
# 静止画モードでは seconds は使わない (frames が尺を決める)。
if still:
seconds = None
elif seconds is not None:
seconds = max(MIN_SECONDS, min(MAX_SECONDS, float(seconds)))
# Each upload is spooled to a real temp file: MiniMaxH3ImageReference.from_file(path) /
# MiniMaxH3VideoReference.from_file(path) / MiniMaxH3AudioReference.from_file(path)
# decodes a path itself (PyAV for video/audio, PIL for image), and this app never
# needs the pixels/samples directly. Cleaned up in `finally`, after generate_ref2va()
# has already decoded everything into in-memory MiniMaxH3*Reference objects
# (construction happens before the try block below, so the temp files must outlive
# that construction).
tmp_paths: list[Path] = []
built_references = []
try:
for upload in references:
kind = _detect_reference_kind(upload)
suffix = Path(upload.filename or "").suffix or {"image": ".png", "video": ".mp4", "audio": ".wav"}[kind]
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix, dir=tempfile.gettempdir()) as tmp:
tmp.write(upload.file.read())
tmp_path = Path(tmp.name)
tmp_paths.append(tmp_path)
try:
if kind == "image":
built_references.append(MiniMaxH3ImageReference.from_file(str(tmp_path)))
elif kind == "video":
built_references.append(MiniMaxH3VideoReference.from_file(str(tmp_path)))
else:
built_references.append(MiniMaxH3AudioReference.from_file(str(tmp_path)))
except Exception as e:
raise HTTPException(400, f"references[{len(built_references)}] ({upload.filename}) の読み込みに失敗: {e}")
runner_mod._tl("api_refs_built")
acquired = _generation_lock.acquire(blocking=False)
if acquired:
local_llm.before_generation() # RAM の少ない PC では内蔵 LLM を止めて生成に RAM を回す
if not acquired:
raise HTTPException(409, "別の生成が進行中です。しばらく待ってから再試行してください。")
runner_mod._tl("api_lock_acquired")
job_id = uuid.uuid4().hex[:12]
progress = ProgressState(job_id=job_id, phase="starting", started_at=time.time())
with _progress_guard:
_current_progress = progress
interrupt_controller.begin(job_id)
# H3_DECODE_STREAM=1 のとき、runner が denoise 完了直後 (decode 開始前) に
# `_release_gen_lock()` を呼ぶ。そこで生成ロックと中断コントローラを手放し、decode+mux の
# 間に次の /api/ref2va を受け付けられるようにする。1回だけ実行されるようにガードし、
# 下の finally は「まだ手放していない場合だけ」手放す (二重 release / 次ジョブの
# interrupt 状態の巻き添えを防ぐ)。フラグ OFF (既定) では callback は None で、
# 従来どおり finally が解放する。
_gen_lock_released = False
def _release_gen_lock():
nonlocal _gen_lock_released
if _gen_lock_released:
return
_gen_lock_released = True
interrupt_controller.end()
_generation_lock.release()
try:
result = runner.generate_ref2va(
prompt=prompt.strip(),
references=built_references,
height=height,
width=width,
seconds=seconds,
num_inference_steps=num_inference_steps,
seed=seed,
progress=progress,
cache=cache,
cache_threshold=cache_threshold,
attn=attn,
turbo=turbo,
mute=mute,
still=bool(still),
still_frames=frames,
reference_image_short_edge=reference_image_short_edge,
vocal_lock=vocal_lock,
on_denoise_done=_release_gen_lock if runner.decode_overlap_active() else None,
)
result["job_id"] = job_id
result["video_url"] = f"/outputs/{Path(result['mp4_path']).name}"
if result.get("png_filename"):
result["image_url"] = f"/outputs/{result['png_filename']}"
return JSONResponse(result)
except ValueError as e:
raise HTTPException(400, str(e))
except GenerationInterrupted as e:
logger.info("ref2va generation interrupted: %s", e)
progress.update(phase="error", error=str(e))
raise HTTPException(499, f"生成が中断されました: {e}")
except Exception as e:
logger.exception("ref2va generation failed")
progress.update(phase="error", error=str(e))
raise HTTPException(500, f"ref2va generation failed: {e}")
finally:
_release_gen_lock()
finally:
for tmp_path in tmp_paths:
tmp_path.unlink(missing_ok=True)
def _run_ref_batch(
prompts: list[str],
references: list[UploadFile],
still: bool,
frames: int,
seconds: Optional[float],
num_inference_steps: Optional[int],
seed: Optional[int],
height: Optional[int],
width: Optional[int],
cache: Optional[str],
cache_threshold: Optional[float],
attn: Optional[str],
turbo: Optional[bool],
mute: bool = False,
reference_image_short_edge: Optional[int] = None,
) -> JSONResponse:
"""/api/ref2i_batch (still=True) と /api/ref2va_batch (still=False) の共通実装。
`H3_LOWVRAM=1` ではモデルロード固定費をバッチ全体で1回に償却する位相並べ替え
(core/runner.py の generate_ref_batch) を使い、他モードは逐次 generate_ref2va()
で同じレスポンス形式を返す。参照・seed・解像度・尺・ステップ数は全場面共通
(変えられるのはプロンプトのみ)。reference_image_short_edge も全場面共通
(未指定なら /api/ref2va と同じくプロセスの H3_REF_IMAGE_SHORT_EDGE を使う)。
`num_inference_steps=None` はそのリクエストの実効 turbo から解決する
(`resolve_num_inference_steps()` 参照)。バッチ全場面で同じ値を使う。
"""
global _current_progress
num_inference_steps = resolve_num_inference_steps(num_inference_steps, turbo)
if still and frames not in STILL_FRAME_CHOICES:
raise HTTPException(400, f"frames は {STILL_FRAME_CHOICES} のいずれかです: {frames}")
if not still:
if seconds is None:
raise HTTPException(400, "ref2va_batch では seconds が必須です(全場面共通の尺)")
seconds = max(MIN_SECONDS, min(MAX_SECONDS, float(seconds)))
cleaned = [p.strip() for p in prompts if p and p.strip()]
if not cleaned:
raise HTTPException(400, "prompts が空です (空でないプロンプトを1つ以上)")
if len(cleaned) > STILL_BATCH_MAX:
raise HTTPException(400, f"prompts は最大 {STILL_BATCH_MAX} 場面です: {len(cleaned)}")
if not references:
raise HTTPException(400, "references is required (at least one image/video/audio file)")
if (height is None) != (width is None):
raise HTTPException(400, "height と width は両方指定するか、両方省略してください")
if height is not None:
height = round_canvas_value(height)
width = round_canvas_value(width)
if reference_image_short_edge is not None and reference_image_short_edge <= 0:
raise HTTPException(
400, f"reference_image_short_edge は正の整数で指定してください: {reference_image_short_edge}"
)
# 参照のスプールと構築は /api/ref2va と同じ手順 (tmp ファイル → MiniMaxH3*Reference.from_file)。
tmp_paths: list[Path] = []
built_references = []
try:
for upload in references:
kind = _detect_reference_kind(upload)
suffix = Path(upload.filename or "").suffix or {"image": ".png", "video": ".mp4", "audio": ".wav"}[kind]
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix, dir=tempfile.gettempdir()) as tmp:
tmp.write(upload.file.read())
tmp_path = Path(tmp.name)
tmp_paths.append(tmp_path)
try:
if kind == "image":
built_references.append(MiniMaxH3ImageReference.from_file(str(tmp_path)))
elif kind == "video":
built_references.append(MiniMaxH3VideoReference.from_file(str(tmp_path)))
else:
built_references.append(MiniMaxH3AudioReference.from_file(str(tmp_path)))
except Exception as e:
raise HTTPException(400, f"references[{len(built_references)}] ({upload.filename}) の読み込みに失敗: {e}")
acquired = _generation_lock.acquire(blocking=False)
if acquired:
local_llm.before_generation() # RAM の少ない PC では内蔵 LLM を止めて生成に RAM を回す
if not acquired:
raise HTTPException(409, "別の生成が進行中です。しばらく待ってから再試行してください。")
job_id = uuid.uuid4().hex[:12]
progress = ProgressState(job_id=job_id, phase="starting", started_at=time.time())
with _progress_guard:
_current_progress = progress
interrupt_controller.begin(job_id)
mode_label = "ref2i_batch" if still else "ref2va_batch"
try:
if H3_LOWVRAM:
result = runner.generate_ref_batch(
prompts=cleaned,
references=built_references,
height=height,
width=width,