geocine commited on
Commit
3a01f1b
·
verified ·
1 Parent(s): f2f6640

Revert to 350M CPU Space; add notice linking to 2.6B creative Space

Browse files
README.md CHANGED
@@ -1,107 +1,103 @@
1
- ---
2
- title: MiniMax H3 Prompt Enhancer
3
- emoji: "🎬"
4
- colorFrom: green
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
- python_version: "3.10"
10
- startup_duration_timeout: 1h
11
- preload_from_hub:
12
- - geocine/minimax-video-prompt-enhancer-2.6b-gguf
13
- pinned: false
14
- license: other
15
- short_description: MiniMax H3 video prompts via CPU GGUF (2.6B)
16
- tags:
17
- - text-generation
18
- - video
19
- - prompt
20
- - minimax
21
- - liquid
22
- - lfm2
23
- - llama.cpp
24
- - cpu
25
- ---
26
-
27
- # MiniMax H3 Prompt Enhancer
28
-
29
- **Not another “make my prompt longer” toy.**
30
-
31
- This Space runs a **purpose-trained small language model** that rewrites rough ideas into **production-ready MiniMax H3 video prompts** — the same kind of structured audiovisual brief MiniMax expects: shots, camera language, diegetic sound, and score, not a bag of adjectives.
32
-
33
- Type something half-formed like *“baker opens a shop at dawn”*. The model doesn’t slap on “cinematic, 8k, masterpiece.” It **reasons** about scene, motion, and audio, then emits the **exact field layout** used for MiniMax video generation.
34
-
35
- > **Now running LFM2.5-2.6B (8/10/2026)** — upgraded from the 350M model, which was solid on format but lacked creative depth. The 2.6B variant is richer with style, camera, dialogue, and music — and stays sharp even with sampling on.
36
-
37
- ---
38
-
39
- ## Why this is different
40
-
41
- | Typical prompt “enhancers” | This one |
42
- |---|---|
43
- | Templates, regex, or a generic chat model | **Fine-tuned LLM** dedicated to this job |
44
- | Mood words and hashtag soup | **Shot lists, camera moves, soundscape, music** |
45
- | Guesswork about “what sounds good” | Aligned to **MiniMax H3 video prompt writing guidelines** |
46
- | One free-form paragraph | **Structured output** MiniMax can actually consume |
47
-
48
- Under the hood: LoRA SFT of [LiquidAI/LFM2.5-2.6B](https://huggingface.co/LiquidAI/LFM2.5-2.6B) —
49
- transformers weights at [geocine/minimax-video-prompt-enhancer-2.6b](https://huggingface.co/geocine/minimax-video-prompt-enhancer-2.6b),
50
- **Q4_K_M GGUF** at [geocine/minimax-video-prompt-enhancer-2.6b-gguf](https://huggingface.co/geocine/minimax-video-prompt-enhancer-2.6b-gguf),
51
- served via **llama.cpp** on **CPU**.
52
-
53
- ---
54
-
55
- ## Runtime
56
-
57
- | | |
58
- |--|--|
59
- | Backend | **llama.cpp** (`llama-cpp-python`) |
60
- | Quant | **Q4_K_M** (~1.7 GB) |
61
- | Hardware | **CPU** — no ZeroGPU quota, no login required for inference |
62
- | Typical latency | Longer than the 350M on free CPU (bigger model); still workable for short briefs |
63
-
64
- Weights are downloaded from the model repo at boot (or read from `models/` if present).
65
-
66
- ---
67
-
68
- ## What you get
69
-
70
- Paste a rough idea (and optional reference notes). Choose duration. Hit **Generate**.
71
-
72
- You get a full brief, for example:
73
-
74
- - **`integrated_multimodal_description`** — style, framing, action, camera, dialogue tags
75
- - **`overall_soundscape`** — ambience and physical sound
76
- - **`non_diegetic_music`** — audience-only score (or N/A)
77
- - For image/video refs: alignment lines, subjects, retention-style structure in **full-reference** mode
78
-
79
- Built for people who actually ship MiniMax clips — not for prompt-cosplay.
80
-
81
- ---
82
-
83
- ## How to use
84
-
85
- 1. Write a rough user prompt (dialogue, shot notes, or a one-liner).
86
- 2. Optionally fill **References & frames** (first/last frame, subjects, clips, audio). The Space picks the task for you.
87
- 3. Set duration. Generate. Copy the structured prompt into MiniMax.
88
-
89
- **Tip:** Short, real-world prompts work best. The model expands them into the full MiniMax format. Default temperature is **0.6** for more creative sampling; set Decoding → Temperature to `0` for greedy.
90
-
91
- ---
92
-
93
- ## Model & license
94
-
95
- | | |
96
- |--|--|
97
- | Model (HF) | [geocine/minimax-video-prompt-enhancer-2.6b](https://huggingface.co/geocine/minimax-video-prompt-enhancer-2.6b) |
98
- | GGUF (CPU) | [geocine/minimax-video-prompt-enhancer-2.6b-gguf](https://huggingface.co/geocine/minimax-video-prompt-enhancer-2.6b-gguf) |
99
- | Base | [LiquidAI/LFM2.5-2.6B](https://huggingface.co/LiquidAI/LFM2.5-2.6B) |
100
- | License | Liquid **lfm1.0** — read the base card before commercial use |
101
-
102
- This is a **text prompt specialist**, not a video generator. It writes the brief; MiniMax (or your pipeline) makes the frames.
103
-
104
- ## Rollback
105
-
106
- If needed, the previous **350M** Space deploy is preserved on branch
107
- [`rollback-350m`](https://huggingface.co/spaces/geocine/MiniMax-H3-Prompt-Enhancer/tree/rollback-350m).
 
1
+ ---
2
+ title: MiniMax H3 Prompt Enhancer
3
+ emoji: "🎬"
4
+ colorFrom: purple
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 5.49.1
8
+ app_file: app.py
9
+ python_version: "3.10"
10
+ startup_duration_timeout: 1h
11
+ preload_from_hub:
12
+ - geocine/minimax-video-prompt-enhancer-350m-gguf
13
+ pinned: false
14
+ license: other
15
+ short_description: MiniMax H3 video prompts via CPU GGUF
16
+ tags:
17
+ - text-generation
18
+ - video
19
+ - prompt
20
+ - minimax
21
+ - liquid
22
+ - lfm2
23
+ - llama.cpp
24
+ - cpu
25
+ ---
26
+
27
+ # MiniMax H3 Prompt Enhancer
28
+
29
+ **Not another “make my prompt longer” toy.**
30
+
31
+ This Space runs a **purpose-trained small language model** that rewrites rough ideas into **production-ready MiniMax H3 video prompts** — the same kind of structured audiovisual brief MiniMax expects: shots, camera language, diegetic sound, and score, not a bag of adjectives.
32
+
33
+ Type something half-formed like *“baker opens a shop at dawn”*. The model doesn’t slap on “cinematic, 8k, masterpiece.” It **reasons** about scene, motion, and audio, then emits the **exact field layout** used for MiniMax video generation.
34
+
35
+ > **Want more creativity?** This Space runs the fast **350M** model. For a richer, more creative enhancer (style / camera / dialogue / music), open the
36
+ > [**2.6B creative Space**](https://huggingface.co/spaces/geocine/MiniMax-H3-Prompt-Enhancer-2.6B) (ZeroGPU).
37
+
38
+ ---
39
+
40
+ ## Why this is different
41
+
42
+ | Typical prompt “enhancers” | This one |
43
+ |---|---|
44
+ | Templates, regex, or a generic chat model | **Fine-tuned LLM** dedicated to this job |
45
+ | Mood words and hashtag soup | **Shot lists, camera moves, soundscape, music** |
46
+ | Guesswork about “what sounds good” | Aligned to **MiniMax H3 video prompt writing guidelines** |
47
+ | One free-form paragraph | **Structured output** MiniMax can actually consume |
48
+
49
+ Under the hood: LoRA SFT of [LiquidAI/LFM2.5-350M](https://huggingface.co/LiquidAI/LFM2.5-350M) —
50
+ transformers weights at [geocine/minimax-video-prompt-enhancer-350m](https://huggingface.co/geocine/minimax-video-prompt-enhancer-350m),
51
+ **Q4_K_M GGUF** at [geocine/minimax-video-prompt-enhancer-350m-gguf](https://huggingface.co/geocine/minimax-video-prompt-enhancer-350m-gguf),
52
+ served via **llama.cpp** on **CPU**.
53
+
54
+ ---
55
+
56
+ ## Runtime
57
+
58
+ | | |
59
+ |--|--|
60
+ | Backend | **llama.cpp** (`llama-cpp-python`) |
61
+ | Quant | **Q4_K_M** (~219 MB) |
62
+ | Hardware | **CPU** — no ZeroGPU quota, no login required for inference |
63
+ | Typical latency | A few seconds for a short T2VA brief on free CPU |
64
+
65
+ Weights are downloaded from the model repo at boot (or read from `models/` if present).
66
+
67
+ ---
68
+
69
+ ## What you get
70
+
71
+ Paste a rough idea (and optional reference notes). Choose duration. Hit **Generate**.
72
+
73
+ You get a full brief, for example:
74
+
75
+ - **`integrated_multimodal_description`** — style, framing, action, camera, dialogue tags
76
+ - **`overall_soundscape`** — ambience and physical sound
77
+ - **`non_diegetic_music`** — audience-only score (or N/A)
78
+ - For image/video refs: alignment lines, subjects, retention-style structure in **full-reference** mode
79
+
80
+ Built for people who actually ship MiniMax clips — not for prompt-cosplay.
81
+
82
+ ---
83
+
84
+ ## How to use
85
+
86
+ 1. Write a rough user prompt (dialogue, shot notes, or a one-liner).
87
+ 2. Optionally fill **References & frames** (first/last frame, subjects, clips, audio). The Space picks the task for you.
88
+ 3. Set duration. Generate. Copy the structured prompt into MiniMax.
89
+
90
+ **Tip:** Short, real-user prompts work best. The model expands them into the full MiniMax format.
91
+
92
+ ---
93
+
94
+ ## Model & license
95
+
96
+ | | |
97
+ |--|--|
98
+ | Model (HF) | [geocine/minimax-video-prompt-enhancer-350m](https://huggingface.co/geocine/minimax-video-prompt-enhancer-350m) |
99
+ | GGUF (CPU) | [geocine/minimax-video-prompt-enhancer-350m-gguf](https://huggingface.co/geocine/minimax-video-prompt-enhancer-350m-gguf) |
100
+ | Base | [LiquidAI/LFM2.5-350M](https://huggingface.co/LiquidAI/LFM2.5-350M) |
101
+ | License | Liquid **lfm1.0** — read the base card before commercial use |
102
+
103
+ This is a **text prompt specialist**, not a video generator. It writes the brief; MiniMax (or your pipeline) makes the frames.
 
 
 
 
app.py CHANGED
@@ -1,95 +1,93 @@
1
- #!/usr/bin/env python3
2
- """Hugging Face Space — MiniMax Video Prompt Enhancer (CPU / GGUF).
3
-
4
- Serves the fine-tuned 2.6B model via llama.cpp on CPU. No ZeroGPU quota,
5
- no CUDA, no login required for inference.
6
-
7
- llama-cpp-python is installed from a prebuilt manylinux wheel (see
8
- requirements.txt) — never compile from source on the Space.
9
-
10
- Model weights (Q4_K_M GGUF) come from preload_from_hub / Hub download unless
11
- a local models/*.gguf or GGUF_PATH is set.
12
-
13
- Rollback: Space branch ``rollback-350m`` keeps the previous 350M deploy.
14
- """
15
-
16
- from __future__ import annotations
17
-
18
- import os
19
- import sys
20
- from pathlib import Path
21
-
22
- ROOT = Path(__file__).resolve().parent
23
- if str(ROOT) not in sys.path:
24
- sys.path.insert(0, str(ROOT))
25
-
26
- # Fail fast with a clear message if the wheel did not install.
27
- try:
28
- import llama_cpp # noqa: F401
29
- except Exception as exc: # pragma: no cover
30
- raise SystemExit(
31
- "llama-cpp-python failed to import. The Space must install the prebuilt "
32
- "manylinux wheel from requirements.txt (not a source build).\n"
33
- f"Import error: {exc}"
34
- ) from exc
35
-
36
- from huggingface_hub import hf_hub_download
37
-
38
- from minimax.apps.gradio import build_app
39
- from minimax.modeling.gguf_runtime import effective_cpus, resolve_gguf_file
40
- from minimax.paths import DEFAULT_GGUF_FILE, DEFAULT_GGUF_REPO
41
-
42
- GGUF_REPO = os.environ.get("GGUF_REPO", DEFAULT_GGUF_REPO)
43
- GGUF_FILE = os.environ.get("GGUF_FILE", DEFAULT_GGUF_FILE)
44
- LOCAL_MODELS = ROOT / "models"
45
- N_THREADS = int(os.environ.get("N_THREADS", "0")) or None
46
- N_CTX = int(os.environ.get("N_CTX", "4096"))
47
-
48
-
49
- def resolve_model_path() -> str:
50
- env = os.environ.get("GGUF_PATH") or os.environ.get("MODEL_ID")
51
- if env and (Path(env).exists() or str(env).endswith(".gguf")):
52
- p = Path(env)
53
- if p.exists():
54
- return str(resolve_gguf_file(p) if p.is_dir() else p)
55
- if str(env).endswith(".gguf") and (LOCAL_MODELS / env).is_file():
56
- return str(LOCAL_MODELS / env)
57
-
58
- if LOCAL_MODELS.is_dir() and list(LOCAL_MODELS.glob("*.gguf")):
59
- path = str(resolve_gguf_file(LOCAL_MODELS))
60
- print(f"[boot] using local GGUF {path}", flush=True)
61
- return path
62
-
63
- # Prefer HF cache from preload_from_hub; falls back to download.
64
- print(f"[boot] resolving {GGUF_REPO}/{GGUF_FILE} …", flush=True)
65
- return hf_hub_download(repo_id=GGUF_REPO, filename=GGUF_FILE)
66
-
67
-
68
- print(f"[boot] llama_cpp ok cpus={effective_cpus()}", flush=True)
69
- MODEL_PATH = resolve_model_path()
70
- print(
71
- f"[boot] GGUF={MODEL_PATH} n_threads={N_THREADS or 'auto'} n_ctx={N_CTX}",
72
- flush=True,
73
- )
74
-
75
- demo = build_app(
76
- model_path=MODEL_PATH,
77
- backend="gguf",
78
- n_ctx=N_CTX,
79
- n_threads=N_THREADS,
80
- n_gpu_layers=0,
81
- prefer_cpu=True,
82
- )
83
-
84
- # Eager-load so the first visitor is not hit with cold-start load only.
85
- _session = demo._minimax_session # type: ignore[attr-defined]
86
- _loaded = _session.ensure_loaded()
87
- print(
88
- f"[boot] ready path={getattr(_loaded, 'path', MODEL_PATH)} "
89
- f"n_threads={getattr(_loaded, 'n_threads', '?')}",
90
- flush=True,
91
- )
92
-
93
- if __name__ == "__main__":
94
- demo.queue(default_concurrency_limit=1)
95
- demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
 
1
+ #!/usr/bin/env python3
2
+ """Hugging Face Space — MiniMax Video Prompt Enhancer (CPU / GGUF).
3
+
4
+ Serves the fine-tuned 350M model via llama.cpp on CPU. No ZeroGPU quota,
5
+ no CUDA, no login required for inference.
6
+
7
+ llama-cpp-python is installed from a prebuilt manylinux wheel (see
8
+ requirements.txt) — never compile from source on the Space.
9
+
10
+ Model weights (Q4_K_M GGUF) come from preload_from_hub / Hub download unless
11
+ a local models/*.gguf or GGUF_PATH is set.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ ROOT = Path(__file__).resolve().parent
21
+ if str(ROOT) not in sys.path:
22
+ sys.path.insert(0, str(ROOT))
23
+
24
+ # Fail fast with a clear message if the wheel did not install.
25
+ try:
26
+ import llama_cpp # noqa: F401
27
+ except Exception as exc: # pragma: no cover
28
+ raise SystemExit(
29
+ "llama-cpp-python failed to import. The Space must install the prebuilt "
30
+ "manylinux wheel from requirements.txt (not a source build).\n"
31
+ f"Import error: {exc}"
32
+ ) from exc
33
+
34
+ from huggingface_hub import hf_hub_download
35
+
36
+ from minimax.apps.gradio import build_app
37
+ from minimax.modeling.gguf_runtime import effective_cpus, resolve_gguf_file
38
+ from minimax.paths import DEFAULT_GGUF_FILE, DEFAULT_GGUF_REPO
39
+
40
+ GGUF_REPO = os.environ.get("GGUF_REPO", DEFAULT_GGUF_REPO)
41
+ GGUF_FILE = os.environ.get("GGUF_FILE", DEFAULT_GGUF_FILE)
42
+ LOCAL_MODELS = ROOT / "models"
43
+ N_THREADS = int(os.environ.get("N_THREADS", "0")) or None
44
+ N_CTX = int(os.environ.get("N_CTX", "4096"))
45
+
46
+
47
+ def resolve_model_path() -> str:
48
+ env = os.environ.get("GGUF_PATH") or os.environ.get("MODEL_ID")
49
+ if env and (Path(env).exists() or str(env).endswith(".gguf")):
50
+ p = Path(env)
51
+ if p.exists():
52
+ return str(resolve_gguf_file(p) if p.is_dir() else p)
53
+ if str(env).endswith(".gguf") and (LOCAL_MODELS / env).is_file():
54
+ return str(LOCAL_MODELS / env)
55
+
56
+ if LOCAL_MODELS.is_dir() and list(LOCAL_MODELS.glob("*.gguf")):
57
+ path = str(resolve_gguf_file(LOCAL_MODELS))
58
+ print(f"[boot] using local GGUF {path}", flush=True)
59
+ return path
60
+
61
+ # Prefer HF cache from preload_from_hub; falls back to download.
62
+ print(f"[boot] resolving {GGUF_REPO}/{GGUF_FILE} …", flush=True)
63
+ return hf_hub_download(repo_id=GGUF_REPO, filename=GGUF_FILE)
64
+
65
+
66
+ print(f"[boot] llama_cpp ok cpus={effective_cpus()}", flush=True)
67
+ MODEL_PATH = resolve_model_path()
68
+ print(
69
+ f"[boot] GGUF={MODEL_PATH} n_threads={N_THREADS or 'auto'} n_ctx={N_CTX}",
70
+ flush=True,
71
+ )
72
+
73
+ demo = build_app(
74
+ model_path=MODEL_PATH,
75
+ backend="gguf",
76
+ n_ctx=N_CTX,
77
+ n_threads=N_THREADS,
78
+ n_gpu_layers=0,
79
+ prefer_cpu=True,
80
+ )
81
+
82
+ # Eager-load so the first visitor is not hit with cold-start load only.
83
+ _session = demo._minimax_session # type: ignore[attr-defined]
84
+ _loaded = _session.ensure_loaded()
85
+ print(
86
+ f"[boot] ready path={getattr(_loaded, 'path', MODEL_PATH)} "
87
+ f"n_threads={getattr(_loaded, 'n_threads', '?')}",
88
+ flush=True,
89
+ )
90
+
91
+ if __name__ == "__main__":
92
+ demo.queue(default_concurrency_limit=1)
93
+ demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
 
 
minimax/apps/gradio/state.py CHANGED
@@ -15,7 +15,7 @@ from minimax.modeling.gguf_runtime import (
15
  resolve_gguf_file,
16
  )
17
  from minimax.modeling.loader import build_stop_ids, load_model_and_tokenizer
18
- from minimax.paths import CHAMPION_GGUF
19
 
20
  Backend = Literal["auto", "transformers", "gguf"]
21
 
@@ -131,7 +131,7 @@ class InferenceSession:
131
  n_gpu_layers: int = 0,
132
  prefer_cpu: bool = False,
133
  ) -> None:
134
- self.default_model = str(default_model or CHAMPION_GGUF)
135
  self.backend: Backend = backend
136
  self.n_ctx = n_ctx
137
  self.n_threads = n_threads
 
15
  resolve_gguf_file,
16
  )
17
  from minimax.modeling.loader import build_stop_ids, load_model_and_tokenizer
18
+ from minimax.paths import CHAMPION_DIR
19
 
20
  Backend = Literal["auto", "transformers", "gguf"]
21
 
 
131
  n_gpu_layers: int = 0,
132
  prefer_cpu: bool = False,
133
  ) -> None:
134
+ self.default_model = str(default_model or CHAMPION_DIR)
135
  self.backend: Backend = backend
136
  self.n_ctx = n_ctx
137
  self.n_threads = n_threads
minimax/apps/gradio/ui.py CHANGED
@@ -5,7 +5,7 @@ from __future__ import annotations
5
  import random
6
  from pathlib import Path
7
 
8
- from minimax.paths import CHAMPION_GGUF
9
 
10
  from .derive import DURATION, PROMPT_MAX, REF_LIMITS, derive
11
  from .state import InferenceSession
@@ -281,7 +281,7 @@ footer .gc-built:hover { text-decoration:underline; }
281
  50% { color: #dcffd2; -webkit-text-fill-color: #dcffd2; text-shadow: 0 0 10px var(--gc-glow); }
282
  }
283
  @media (prefers-reduced-motion: reduce) { footer .gc-built { animation: none; } }
284
- /* model-upgrade notice */
285
  .gc-notice {
286
  margin: 8px 0 0; padding: 10px 12px;
287
  border: 1px solid color-mix(in srgb, var(--gc-accent) 45%, var(--gc-line));
@@ -291,11 +291,9 @@ footer .gc-built:hover { text-decoration:underline; }
291
  }
292
  .gc-notice strong { color: var(--gc-accent); font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
293
  .gc-notice span { color: var(--gc-muted); }
294
- .gc-notice .gc-date {
295
- display: inline-block; margin-left: 8px; padding: 1px 6px;
296
- border: 1px solid color-mix(in srgb, var(--gc-accent) 35%, var(--gc-line));
297
- color: var(--gc-accent); font-size: 10px; letter-spacing: .14em;
298
- text-transform: uppercase; vertical-align: 1px;
299
  }
300
  """
301
 
@@ -332,13 +330,15 @@ _BRAND_HTML = """
332
  <div class="gc-mark">G</div>
333
  <div>
334
  <div class="gc-word">MINIMAX H3 <span>PROMPT ENHANCER</span></div>
335
- <div class="gc-sub">Turn rough ideas into cinematic video prompts</div>
336
  </div>
337
  </div>
338
  <div class="gc-notice">
339
- <strong>Now running LFM2.5-2.6B</strong><span class="gc-date">8/10/2026</span>
340
- <span> — upgraded from the 350M model, which was solid on format but lacked creative depth.
341
- The 2.6B variant is richer with style, camera, dialogue, and music — and stays sharp even with sampling on.</span>
 
 
342
  </div>
343
  </div>
344
  """
@@ -356,7 +356,7 @@ def build_app(
356
  import gradio as gr
357
 
358
  session = InferenceSession(
359
- default_model=model_path or CHAMPION_GGUF,
360
  backend=backend, # type: ignore[arg-type]
361
  n_ctx=n_ctx,
362
  n_threads=n_threads,
@@ -473,7 +473,7 @@ descriptions** of frames / clips / audio — not file uploads.
473
  ),
474
  )
475
  with gr.Accordion("Decoding", open=False, elem_classes=["gc-decoding"]):
476
- temperature = gr.Slider(0.0, 1.2, value=0.6, step=0.05, label="Temperature (0 = greedy)")
477
  top_k = gr.Slider(0, 100, value=40, step=1, label="Top-k (sampling only)")
478
  repetition_penalty = gr.Slider(
479
  1.0, 1.5, value=1.0, step=0.01, label="Repetition penalty"
@@ -599,7 +599,7 @@ def launch(
599
  from minimax.modeling.gguf_runtime import GgufBundle, is_gguf_path
600
 
601
  # GGUF / explicit CPU path never requires CUDA.
602
- path = str(model_path or CHAMPION_GGUF)
603
  if backend == "gguf" or is_gguf_path(path) or prefer_cpu:
604
  require_gpu = False
605
 
 
5
  import random
6
  from pathlib import Path
7
 
8
+ from minimax.paths import CHAMPION_DIR
9
 
10
  from .derive import DURATION, PROMPT_MAX, REF_LIMITS, derive
11
  from .state import InferenceSession
 
281
  50% { color: #dcffd2; -webkit-text-fill-color: #dcffd2; text-shadow: 0 0 10px var(--gc-glow); }
282
  }
283
  @media (prefers-reduced-motion: reduce) { footer .gc-built { animation: none; } }
284
+ /* upgrade notice */
285
  .gc-notice {
286
  margin: 8px 0 0; padding: 10px 12px;
287
  border: 1px solid color-mix(in srgb, var(--gc-accent) 45%, var(--gc-line));
 
291
  }
292
  .gc-notice strong { color: var(--gc-accent); font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
293
  .gc-notice span { color: var(--gc-muted); }
294
+ .gc-notice a {
295
+ color: var(--gc-accent) !important; text-decoration: underline;
296
+ font-weight: 600;
 
 
297
  }
298
  """
299
 
 
330
  <div class="gc-mark">G</div>
331
  <div>
332
  <div class="gc-word">MINIMAX H3 <span>PROMPT ENHANCER</span></div>
333
+ <div class="gc-sub">Turn rough ideas into cinematic video prompts · LFM2.5-350M</div>
334
  </div>
335
  </div>
336
  <div class="gc-notice">
337
+ <strong>Want more creativity?</strong>
338
+ <span> This 350M model is fast and format-solid. For richer style, camera, dialogue, and music —
339
+ try the
340
+ <a href="https://huggingface.co/spaces/geocine/MiniMax-H3-Prompt-Enhancer-2.6B" target="_blank" rel="noopener noreferrer">2.6B creative Space</a>
341
+ (ZeroGPU).</span>
342
  </div>
343
  </div>
344
  """
 
356
  import gradio as gr
357
 
358
  session = InferenceSession(
359
+ default_model=model_path or CHAMPION_DIR,
360
  backend=backend, # type: ignore[arg-type]
361
  n_ctx=n_ctx,
362
  n_threads=n_threads,
 
473
  ),
474
  )
475
  with gr.Accordion("Decoding", open=False, elem_classes=["gc-decoding"]):
476
+ temperature = gr.Slider(0.0, 1.2, value=0.0, step=0.05, label="Temperature (0 = greedy)")
477
  top_k = gr.Slider(0, 100, value=40, step=1, label="Top-k (sampling only)")
478
  repetition_penalty = gr.Slider(
479
  1.0, 1.5, value=1.0, step=0.01, label="Repetition penalty"
 
599
  from minimax.modeling.gguf_runtime import GgufBundle, is_gguf_path
600
 
601
  # GGUF / explicit CPU path never requires CUDA.
602
+ path = str(model_path or CHAMPION_DIR)
603
  if backend == "gguf" or is_gguf_path(path) or prefer_cpu:
604
  require_gpu = False
605
 
minimax/formatting/envelope.py CHANGED
@@ -1,122 +1,122 @@
1
- """User/system message construction and parsing.
2
-
3
- The user envelope is the contract between training data, inference, and eval:
4
-
5
- Task: <label>
6
- Duration: <D.DD>s
7
- Assets:
8
- - <asset or "(none)">
9
-
10
- User prompt:
11
- <original rough prompt>
12
-
13
- Task labels:
14
- - base tasks use the task name directly (T2VA / I2VA / FL2VA / L2VA)
15
- - ref tasks use the fine-grained form "video_editing (full-reference rewrite)"
16
- so the 350M student can condition on the subtype. The old corpus used the
17
- generic "full-reference rewrite" label; ``legacy=True`` reproduces it,
18
- which is needed when evaluating checkpoints trained on the old corpus.
19
- """
20
-
21
- from __future__ import annotations
22
-
23
- import html
24
- import re
25
-
26
- from ..paths import SYSTEM_BASE_FILE, SYSTEM_BASE_TASK_FILES, SYSTEM_REF_FILE
27
-
28
- BASE_TASKS = {"T2VA", "I2VA", "FL2VA", "L2VA"}
29
- REF_TASKS = {
30
- "reference_generation",
31
- "reference_generation+audio_reference",
32
- "keyframe_completion",
33
- "video_editing",
34
- "video_editing+audio_reuse",
35
- "video_continuation",
36
- "video_continuation+audio_reference",
37
- }
38
-
39
- LEGACY_REF_LABEL = "full-reference rewrite"
40
-
41
-
42
- def is_base_task(task: str) -> bool:
43
- return task in BASE_TASKS
44
-
45
-
46
- def task_label(task: str, *, legacy: bool = False) -> str:
47
- if task in BASE_TASKS:
48
- return task
49
- if legacy:
50
- return LEGACY_REF_LABEL
51
- return f"{task} ({LEGACY_REF_LABEL})"
52
-
53
-
54
- def build_user_message(
55
- task: str,
56
- duration: float,
57
- prompt: str,
58
- assets: list[str] | None = None,
59
- *,
60
- legacy: bool = False,
61
- ) -> str:
62
- asset_block = "\n".join(f"- {a}" for a in assets) if assets else "- (none)"
63
- return (
64
- f"Task: {task_label(task, legacy=legacy)}\n"
65
- f"Duration: {float(duration):.2f}s\n"
66
- f"Assets:\n{asset_block}\n\n"
67
- f"User prompt:\n{html.unescape(prompt).strip()}"
68
- )
69
-
70
-
71
- def load_system(task: str) -> str:
72
- """Load the system prompt for a task.
73
-
74
- Base tasks use a task-specific file when present (T2VA has no alignment
75
- rules; I2VA/FL2VA/L2VA only their own line) to cut cross-task instruction
76
- leakage. Falls back to ``system_base.txt`` / ``system_ref.txt``.
77
- """
78
- if task in BASE_TASKS:
79
- path = SYSTEM_BASE_TASK_FILES.get(task, SYSTEM_BASE_FILE)
80
- if not path.is_file():
81
- path = SYSTEM_BASE_FILE
82
- else:
83
- path = SYSTEM_REF_FILE
84
- return path.read_text(encoding="utf-8").strip()
85
-
86
-
87
- def parse_user_blob(user_content: str) -> dict:
88
- """Extract task, duration, assets, original prompt from a packaged user message.
89
-
90
- Handles both the fine-grained label ("video_editing (full-reference rewrite)")
91
- and the legacy generic label ("full-reference rewrite").
92
- """
93
- task = "T2VA"
94
- duration = 6.0
95
- assets: list[str] = []
96
- prompt = user_content
97
-
98
- m = re.search(r"Task:\s*(.+)", user_content)
99
- if m:
100
- raw = m.group(1).strip()
101
- if raw == LEGACY_REF_LABEL:
102
- task = "full-reference"
103
- else:
104
- fm = re.match(r"(.+?)\s*\(full-reference rewrite\)$", raw)
105
- task = fm.group(1).strip() if fm else raw
106
- m = re.search(r"Duration:\s*([0-9.]+)", user_content)
107
- if m:
108
- duration = float(m.group(1))
109
- if "Assets:" in user_content and "User prompt:" in user_content:
110
- asset_block = user_content.split("Assets:", 1)[1].split("User prompt:", 1)[0]
111
- for line in asset_block.splitlines():
112
- line = line.strip()
113
- if line.startswith("- ") and line not in {"- (none)", "- none"}:
114
- assets.append(line[2:].strip())
115
- prompt = user_content.split("User prompt:", 1)[1].strip()
116
-
117
- return {
118
- "task": task,
119
- "duration": duration,
120
- "assets": assets or None,
121
- "prompt": prompt,
122
- }
 
1
+ """User/system message construction and parsing.
2
+
3
+ The user envelope is the contract between training data, inference, and eval:
4
+
5
+ Task: <label>
6
+ Duration: <D.DD>s
7
+ Assets:
8
+ - <asset or "(none)">
9
+
10
+ User prompt:
11
+ <original rough prompt>
12
+
13
+ Task labels:
14
+ - base tasks use the task name directly (T2VA / I2VA / FL2VA / L2VA)
15
+ - ref tasks use the fine-grained form "video_editing (full-reference rewrite)"
16
+ so the 350M student can condition on the subtype. The old corpus used the
17
+ generic "full-reference rewrite" label; ``legacy=True`` reproduces it,
18
+ which is needed when evaluating checkpoints trained on the old corpus.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import html
24
+ import re
25
+
26
+ from ..paths import SYSTEM_BASE_FILE, SYSTEM_BASE_TASK_FILES, SYSTEM_REF_FILE
27
+
28
+ BASE_TASKS = {"T2VA", "I2VA", "FL2VA", "L2VA"}
29
+ REF_TASKS = {
30
+ "reference_generation",
31
+ "reference_generation+audio_reference",
32
+ "keyframe_completion",
33
+ "video_editing",
34
+ "video_editing+audio_reuse",
35
+ "video_continuation",
36
+ "video_continuation+audio_reference",
37
+ }
38
+
39
+ LEGACY_REF_LABEL = "full-reference rewrite"
40
+
41
+
42
+ def is_base_task(task: str) -> bool:
43
+ return task in BASE_TASKS
44
+
45
+
46
+ def task_label(task: str, *, legacy: bool = False) -> str:
47
+ if task in BASE_TASKS:
48
+ return task
49
+ if legacy:
50
+ return LEGACY_REF_LABEL
51
+ return f"{task} ({LEGACY_REF_LABEL})"
52
+
53
+
54
+ def build_user_message(
55
+ task: str,
56
+ duration: float,
57
+ prompt: str,
58
+ assets: list[str] | None = None,
59
+ *,
60
+ legacy: bool = False,
61
+ ) -> str:
62
+ asset_block = "\n".join(f"- {a}" for a in assets) if assets else "- (none)"
63
+ return (
64
+ f"Task: {task_label(task, legacy=legacy)}\n"
65
+ f"Duration: {float(duration):.2f}s\n"
66
+ f"Assets:\n{asset_block}\n\n"
67
+ f"User prompt:\n{html.unescape(prompt).strip()}"
68
+ )
69
+
70
+
71
+ def load_system(task: str) -> str:
72
+ """Load the system prompt for a task.
73
+
74
+ Base tasks use a task-specific file when present (T2VA has no alignment
75
+ rules; I2VA/FL2VA/L2VA only their own line) to cut cross-task instruction
76
+ leakage. Falls back to ``system_base.txt`` / ``system_ref.txt``.
77
+ """
78
+ if task in BASE_TASKS:
79
+ path = SYSTEM_BASE_TASK_FILES.get(task, SYSTEM_BASE_FILE)
80
+ if not path.is_file():
81
+ path = SYSTEM_BASE_FILE
82
+ else:
83
+ path = SYSTEM_REF_FILE
84
+ return path.read_text(encoding="utf-8").strip()
85
+
86
+
87
+ def parse_user_blob(user_content: str) -> dict:
88
+ """Extract task, duration, assets, original prompt from a packaged user message.
89
+
90
+ Handles both the fine-grained label ("video_editing (full-reference rewrite)")
91
+ and the legacy generic label ("full-reference rewrite").
92
+ """
93
+ task = "T2VA"
94
+ duration = 6.0
95
+ assets: list[str] = []
96
+ prompt = user_content
97
+
98
+ m = re.search(r"Task:\s*(.+)", user_content)
99
+ if m:
100
+ raw = m.group(1).strip()
101
+ if raw == LEGACY_REF_LABEL:
102
+ task = "full-reference"
103
+ else:
104
+ fm = re.match(r"(.+?)\s*\(full-reference rewrite\)$", raw)
105
+ task = fm.group(1).strip() if fm else raw
106
+ m = re.search(r"Duration:\s*([0-9.]+)", user_content)
107
+ if m:
108
+ duration = float(m.group(1))
109
+ if "Assets:" in user_content and "User prompt:" in user_content:
110
+ asset_block = user_content.split("Assets:", 1)[1].split("User prompt:", 1)[0]
111
+ for line in asset_block.splitlines():
112
+ line = line.strip()
113
+ if line.startswith("- ") and line not in {"- (none)", "- none"}:
114
+ assets.append(line[2:].strip())
115
+ prompt = user_content.split("User prompt:", 1)[1].strip()
116
+
117
+ return {
118
+ "task": task,
119
+ "duration": duration,
120
+ "assets": assets or None,
121
+ "prompt": prompt,
122
+ }
minimax/formatting/meta_leak.py CHANGED
@@ -1,32 +1,32 @@
1
- """Detect system-prompt instruction leakage in generations.
2
-
3
- A small student can paraphrase system rules into the scene body. Detection is
4
- used by the format scorer (and teacher validation) so those outputs fail
5
- honestly. Content is *not* auto-rewritten here — fix via training + systems.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import re
11
-
12
- # Phrases that only appear when the model is narrating the *format rules*
13
- # rather than describing the video.
14
- _LEAK_RES: list[re.Pattern[str]] = [
15
- re.compile(r"(?i)\brequired alignment instruction\b"),
16
- re.compile(r"(?i)\bbegin(?:s|ning)? with the required\b"),
17
- re.compile(r"(?i)\bintegrated_multimodal_description begins\b"),
18
- re.compile(r"(?i)\bdetailed_description begins\b"),
19
- re.compile(r"(?i)\bfills in a full story\b"),
20
- re.compile(r"(?i)\bfrom the referenced picture\b"),
21
- re.compile(r"(?i)\bthree core fields\b"),
22
- re.compile(r"(?i)\bas the first line,? then one blank line\b"),
23
- re.compile(r"(?i)\bwrites? the body in english\b"),
24
- re.compile(r"(?i)\bdo not invent timestamps\b"),
25
- re.compile(r"(?i)\boutput rules?\b"),
26
- ]
27
-
28
-
29
- def has_instruction_leak(text: str) -> bool:
30
- """True if any known instruction-leak phrase appears in the generation."""
31
- t = text or ""
32
- return any(rx.search(t) for rx in _LEAK_RES)
 
1
+ """Detect system-prompt instruction leakage in generations.
2
+
3
+ A small student can paraphrase system rules into the scene body. Detection is
4
+ used by the format scorer (and teacher validation) so those outputs fail
5
+ honestly. Content is *not* auto-rewritten here — fix via training + systems.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ # Phrases that only appear when the model is narrating the *format rules*
13
+ # rather than describing the video.
14
+ _LEAK_RES: list[re.Pattern[str]] = [
15
+ re.compile(r"(?i)\brequired alignment instruction\b"),
16
+ re.compile(r"(?i)\bbegin(?:s|ning)? with the required\b"),
17
+ re.compile(r"(?i)\bintegrated_multimodal_description begins\b"),
18
+ re.compile(r"(?i)\bdetailed_description begins\b"),
19
+ re.compile(r"(?i)\bfills in a full story\b"),
20
+ re.compile(r"(?i)\bfrom the referenced picture\b"),
21
+ re.compile(r"(?i)\bthree core fields\b"),
22
+ re.compile(r"(?i)\bas the first line,? then one blank line\b"),
23
+ re.compile(r"(?i)\bwrites? the body in english\b"),
24
+ re.compile(r"(?i)\bdo not invent timestamps\b"),
25
+ re.compile(r"(?i)\boutput rules?\b"),
26
+ ]
27
+
28
+
29
+ def has_instruction_leak(text: str) -> bool:
30
+ """True if any known instruction-leak phrase appears in the generation."""
31
+ t = text or ""
32
+ return any(rx.search(t) for rx in _LEAK_RES)
minimax/formatting/postprocess.py CHANGED
@@ -1,178 +1,168 @@
1
- """Generation postprocessing: trim chat markers, section loops, structural fixes.
2
-
3
- Structural repairs only (deterministic guide rules) — no invented scene prose.
4
- """
5
-
6
- from __future__ import annotations
7
-
8
- import re
9
-
10
- from .fields import BASE_FIELDS, REF_FIELDS, is_base, normalize_task
11
- from .instructions import enforce_instruction_line
12
- from .timestamps import enforce_shot_timestamps
13
-
14
-
15
- _CITED_SHOTS_RE = re.compile(r"\s*\(appears in ([^)]*\[Shot \d+\][^)]*)\)")
16
- _SHOT_TOKEN_RE = re.compile(r"\[Shot (\d+)\]")
17
- _DESC_HEADERS = ("detailed_description:", "integrated_multimodal_description:")
18
-
19
-
20
- def _description_body_span(text: str, header: str) -> tuple[int, int] | None:
21
- h = text.find(header)
22
- if h < 0:
23
- return None
24
- start = h + len(header)
25
- end = text.find("overall_soundscape:", start)
26
- if end < 0:
27
- end = len(text)
28
- return start, end
29
-
30
-
31
- def ensure_trailing_audio_fields(text: str, *, base: bool) -> str:
32
- """Append missing overall_soundscape / non_diegetic_music with N/A.
33
-
34
- Models sometimes EOS right after the description (seen on long FL2VA).
35
- Headers are required by the guide; N/A is the guide-legal empty value
36
- for music and total silence, so this is structural — not scene invention.
37
- """
38
- t = text.rstrip()
39
- # Only repair when a description section exists (otherwise empty/garbage).
40
- if "integrated_multimodal_description:" not in t and "detailed_description:" not in t:
41
- return t
42
- sep = " " if base else "\n"
43
- # Append missing fields in guide order after whatever we already have.
44
- if "overall_soundscape:" not in t:
45
- t = t + "\n\noverall_soundscape:" + sep + "N/A"
46
- if "non_diegetic_music:" not in t:
47
- t = t + "\n\nnon_diegetic_music:" + sep + "N/A"
48
- return t
49
-
50
-
51
- def ensure_shot1_header(text: str) -> str:
52
- """If a description body has content but no [Shot 1], prepend the marker.
53
-
54
- Guide requires an opening shot section; 350M models sometimes write only
55
- prose under detailed_description. Injecting the marker is structural —
56
- it does not invent visual content.
57
- """
58
- t = text
59
- for header in _DESC_HEADERS:
60
- span = _description_body_span(t, header)
61
- if span is None:
62
- continue
63
- start, end = span
64
- body = t[start:end]
65
- if not body.strip() or "[Shot 1]" in body:
66
- continue
67
- t = t[:start] + " [Shot 1] " + body.lstrip() + t[end:]
68
- break
69
- return t
70
-
71
-
72
- def _align_retention_citations(t: str) -> str:
73
- """Drop retention citations of shots that have no section in the description.
74
-
75
- The guide only allows retention_analysis to cite shot numbers that exist
76
- in detailed_description. Phantom [Shot 2] citations trip the whole-text
77
- timestamp scorer even when the description is legitimately single-shot.
78
- """
79
- if "retention_analysis:" not in t or "detailed_description:" not in t:
80
- return t
81
- desc = t.split("detailed_description:", 1)[1]
82
- real = set(
83
- re.findall(r"\[Shot (\d+)\]", desc.split("overall_soundscape:", 1)[0])
84
- )
85
-
86
- head, rest = t.split("retention_analysis:", 1)
87
- if "detailed_description:" not in rest:
88
- # Sections out of order (DD before retention) — leave text unchanged;
89
- # the format scorer will penalize the ordering itself.
90
- return t
91
- ret, desc_part = rest.split("detailed_description:", 1)
92
-
93
- if not real:
94
- # No shot sections in DD — strip all shot tokens from retention so
95
- # format scoring is not poisoned by phantom multi-shot claims.
96
- ret2 = _CITED_SHOTS_RE.sub("", ret)
97
- ret2 = _SHOT_TOKEN_RE.sub("", ret2)
98
- return head + "retention_analysis:" + ret2 + "detailed_description:" + desc_part
99
-
100
- def fix_appears(m: re.Match) -> str:
101
- cited = re.findall(r"\[Shot (\d+)\]", m.group(1))
102
- kept = [n for n in cited if n in real]
103
- if not kept:
104
- return ""
105
- if kept == cited:
106
- return m.group(0)
107
- return " (appears in " + ", ".join(f"[Shot {n}]" for n in kept) + ")"
108
-
109
- ret2 = _CITED_SHOTS_RE.sub(fix_appears, ret)
110
-
111
- def bare_shot(m: re.Match) -> str:
112
- return m.group(0) if m.group(1) in real else ""
113
-
114
- ret2 = _SHOT_TOKEN_RE.sub(bare_shot, ret2)
115
- return head + "retention_analysis:" + ret2 + "detailed_description:" + desc_part
116
-
117
-
118
- def postprocess_generation(text: str, task: str, duration: float | None = None) -> str:
119
- t = (text or "").strip()
120
- # Reasoning-model leakage: keep only the answer after a closed think block,
121
- # and drop a dangling opener if the block never closed.
122
- if "</think>" in t:
123
- t = t.rsplit("</think>", 1)[1].strip()
124
- if t.startswith("<think>"):
125
- t = t[len("<think>") :].lstrip()
126
- for stop in ("<|im_end|>", "<|endoftext|>", "<|im_start|>"):
127
- if stop in t:
128
- t = t.split(stop, 1)[0].strip()
129
-
130
- task_n = normalize_task(task)
131
- fields = BASE_FIELDS if is_base(task_n) else REF_FIELDS
132
-
133
- # Field headers are fixed lowercase tokens; models occasionally emit
134
- # sentence-cased variants ("Overall_soundscape:") after a paragraph break.
135
- for f in fields:
136
- t = re.sub(rf"(?im)^[ \t]*{re.escape(f)}", f, t)
137
-
138
- # If a field header appears twice, keep only the first complete document.
139
- for f in fields:
140
- first = t.find(f)
141
- if first < 0:
142
- continue
143
- second = t.find(f, first + len(f))
144
- if second > 0:
145
- t = t[:second].rstrip()
146
- break
147
-
148
- # Trim anything after the first paragraph of non_diegetic_music.
149
- if "non_diegetic_music:" in t:
150
- head, tail = t.split("non_diegetic_music:", 1)
151
- music_body = tail.strip().split("\n\n")[0].strip()
152
- for f in fields:
153
- if f in music_body:
154
- music_body = music_body.split(f, 1)[0].strip()
155
- sep = " " if is_base(task_n) else "\n"
156
- t = head + "non_diegetic_music:" + sep + music_body
157
-
158
- # The alignment instruction is deterministic boilerplate; rebuild it
159
- # rather than trusting the model to reproduce it verbatim.
160
- if duration is not None and is_base(task_n):
161
- t = enforce_instruction_line(task_n, t.strip(), duration)
162
-
163
- # Structural shot markers before timestamp repair / retention cleanup.
164
- t = ensure_shot1_header(t)
165
-
166
- # Timestamp grammar is fully specified by the guide; repair missing or
167
- # non-increasing "At MM:SS.mmm" stamps by interpolation.
168
- if duration is not None:
169
- t = enforce_shot_timestamps(t, duration)
170
-
171
- if not is_base(task_n):
172
- t = _align_retention_citations(t)
173
-
174
- # Fill trailing sound/music headers when the model stops after the body
175
- # (common on long keyframe FL2VA). Uses N/A — not invented ambience.
176
- t = ensure_trailing_audio_fields(t, base=is_base(task_n))
177
-
178
- return t.strip()
 
1
+ """Generation postprocessing: trim chat markers, section loops, structural fixes.
2
+
3
+ Structural repairs only (deterministic guide rules) — no invented scene prose.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+
10
+ from .fields import BASE_FIELDS, REF_FIELDS, is_base, normalize_task
11
+ from .instructions import enforce_instruction_line
12
+ from .timestamps import enforce_shot_timestamps
13
+
14
+
15
+ _CITED_SHOTS_RE = re.compile(r"\s*\(appears in ([^)]*\[Shot \d+\][^)]*)\)")
16
+ _SHOT_TOKEN_RE = re.compile(r"\[Shot (\d+)\]")
17
+ _DESC_HEADERS = ("detailed_description:", "integrated_multimodal_description:")
18
+
19
+
20
+ def _description_body_span(text: str, header: str) -> tuple[int, int] | None:
21
+ h = text.find(header)
22
+ if h < 0:
23
+ return None
24
+ start = h + len(header)
25
+ end = text.find("overall_soundscape:", start)
26
+ if end < 0:
27
+ end = len(text)
28
+ return start, end
29
+
30
+
31
+ def ensure_trailing_audio_fields(text: str, *, base: bool) -> str:
32
+ """Append missing overall_soundscape / non_diegetic_music with N/A.
33
+
34
+ Models sometimes EOS right after the description (seen on long FL2VA).
35
+ Headers are required by the guide; N/A is the guide-legal empty value
36
+ for music and total silence, so this is structural — not scene invention.
37
+ """
38
+ t = text.rstrip()
39
+ # Only repair when a description section exists (otherwise empty/garbage).
40
+ if "integrated_multimodal_description:" not in t and "detailed_description:" not in t:
41
+ return t
42
+ sep = " " if base else "\n"
43
+ # Append missing fields in guide order after whatever we already have.
44
+ if "overall_soundscape:" not in t:
45
+ t = t + "\n\noverall_soundscape:" + sep + "N/A"
46
+ if "non_diegetic_music:" not in t:
47
+ t = t + "\n\nnon_diegetic_music:" + sep + "N/A"
48
+ return t
49
+
50
+
51
+ def ensure_shot1_header(text: str) -> str:
52
+ """If a description body has content but no [Shot 1], prepend the marker.
53
+
54
+ Guide requires an opening shot section; 350M models sometimes write only
55
+ prose under detailed_description. Injecting the marker is structural —
56
+ it does not invent visual content.
57
+ """
58
+ t = text
59
+ for header in _DESC_HEADERS:
60
+ span = _description_body_span(t, header)
61
+ if span is None:
62
+ continue
63
+ start, end = span
64
+ body = t[start:end]
65
+ if not body.strip() or "[Shot 1]" in body:
66
+ continue
67
+ t = t[:start] + " [Shot 1] " + body.lstrip() + t[end:]
68
+ break
69
+ return t
70
+
71
+
72
+ def _align_retention_citations(t: str) -> str:
73
+ """Drop retention citations of shots that have no section in the description.
74
+
75
+ The guide only allows retention_analysis to cite shot numbers that exist
76
+ in detailed_description. Phantom [Shot 2] citations trip the whole-text
77
+ timestamp scorer even when the description is legitimately single-shot.
78
+ """
79
+ if "retention_analysis:" not in t or "detailed_description:" not in t:
80
+ return t
81
+ desc = t.split("detailed_description:", 1)[1]
82
+ real = set(
83
+ re.findall(r"\[Shot (\d+)\]", desc.split("overall_soundscape:", 1)[0])
84
+ )
85
+
86
+ head, rest = t.split("retention_analysis:", 1)
87
+ ret, desc_part = rest.split("detailed_description:", 1)
88
+
89
+ if not real:
90
+ # No shot sections in DD — strip all shot tokens from retention so
91
+ # format scoring is not poisoned by phantom multi-shot claims.
92
+ ret2 = _CITED_SHOTS_RE.sub("", ret)
93
+ ret2 = _SHOT_TOKEN_RE.sub("", ret2)
94
+ return head + "retention_analysis:" + ret2 + "detailed_description:" + desc_part
95
+
96
+ def fix_appears(m: re.Match) -> str:
97
+ cited = re.findall(r"\[Shot (\d+)\]", m.group(1))
98
+ kept = [n for n in cited if n in real]
99
+ if not kept:
100
+ return ""
101
+ if kept == cited:
102
+ return m.group(0)
103
+ return " (appears in " + ", ".join(f"[Shot {n}]" for n in kept) + ")"
104
+
105
+ ret2 = _CITED_SHOTS_RE.sub(fix_appears, ret)
106
+
107
+ def bare_shot(m: re.Match) -> str:
108
+ return m.group(0) if m.group(1) in real else ""
109
+
110
+ ret2 = _SHOT_TOKEN_RE.sub(bare_shot, ret2)
111
+ return head + "retention_analysis:" + ret2 + "detailed_description:" + desc_part
112
+
113
+
114
+ def postprocess_generation(text: str, task: str, duration: float | None = None) -> str:
115
+ t = (text or "").strip()
116
+ for stop in ("<|im_end|>", "<|endoftext|>", "<|im_start|>"):
117
+ if stop in t:
118
+ t = t.split(stop, 1)[0].strip()
119
+
120
+ task_n = normalize_task(task)
121
+ fields = BASE_FIELDS if is_base(task_n) else REF_FIELDS
122
+
123
+ # Field headers are fixed lowercase tokens; models occasionally emit
124
+ # sentence-cased variants ("Overall_soundscape:") after a paragraph break.
125
+ for f in fields:
126
+ t = re.sub(rf"(?im)^[ \t]*{re.escape(f)}", f, t)
127
+
128
+ # If a field header appears twice, keep only the first complete document.
129
+ for f in fields:
130
+ first = t.find(f)
131
+ if first < 0:
132
+ continue
133
+ second = t.find(f, first + len(f))
134
+ if second > 0:
135
+ t = t[:second].rstrip()
136
+ break
137
+
138
+ # Trim anything after the first paragraph of non_diegetic_music.
139
+ if "non_diegetic_music:" in t:
140
+ head, tail = t.split("non_diegetic_music:", 1)
141
+ music_body = tail.strip().split("\n\n")[0].strip()
142
+ for f in fields:
143
+ if f in music_body:
144
+ music_body = music_body.split(f, 1)[0].strip()
145
+ sep = " " if is_base(task_n) else "\n"
146
+ t = head + "non_diegetic_music:" + sep + music_body
147
+
148
+ # The alignment instruction is deterministic boilerplate; rebuild it
149
+ # rather than trusting the model to reproduce it verbatim.
150
+ if duration is not None and is_base(task_n):
151
+ t = enforce_instruction_line(task_n, t.strip(), duration)
152
+
153
+ # Structural shot markers before timestamp repair / retention cleanup.
154
+ t = ensure_shot1_header(t)
155
+
156
+ # Timestamp grammar is fully specified by the guide; repair missing or
157
+ # non-increasing "At MM:SS.mmm" stamps by interpolation.
158
+ if duration is not None:
159
+ t = enforce_shot_timestamps(t, duration)
160
+
161
+ if not is_base(task_n):
162
+ t = _align_retention_citations(t)
163
+
164
+ # Fill trailing sound/music headers when the model stops after the body
165
+ # (common on long keyframe FL2VA). Uses N/A — not invented ambience.
166
+ t = ensure_trailing_audio_fields(t, base=is_base(task_n))
167
+
168
+ return t.strip()
 
 
 
 
 
 
 
 
 
 
minimax/modeling/generate.py CHANGED
@@ -34,11 +34,6 @@ def generate_one(
34
  prompt_text = tokenizer.apply_chat_template(
35
  messages, tokenize=False, add_generation_prompt=True
36
  )
37
- # LFM2.5-2.6B's template opens a <think> block in the generation prompt,
38
- # but our SFT targets contain no think tags — strip it so inference matches
39
- # the training distribution (no-op for templates without it, e.g. 350M).
40
- if prompt_text.rstrip().endswith("<think>"):
41
- prompt_text = prompt_text.rstrip()[: -len("<think>")]
42
  inputs = tokenizer(prompt_text, return_tensors="pt")
43
  inputs = {k: v.to(model.device) for k, v in inputs.items()}
44
 
 
34
  prompt_text = tokenizer.apply_chat_template(
35
  messages, tokenize=False, add_generation_prompt=True
36
  )
 
 
 
 
 
37
  inputs = tokenizer(prompt_text, return_tensors="pt")
38
  inputs = {k: v.to(model.device) for k, v in inputs.items()}
39
 
minimax/modeling/gguf_runtime.py CHANGED
@@ -1,219 +1,219 @@
1
- """CPU-first GGUF inference via llama-cpp-python.
2
-
3
- Mirrors generate_one() postprocess/scoring, but decodes with llama.cpp instead
4
- of transformers — the path we want for free HF Spaces / local no-GPU demos.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import os
10
- from dataclasses import dataclass
11
- from pathlib import Path
12
- from typing import Any
13
-
14
- from ..formatting.envelope import build_user_message, load_system
15
- from ..formatting.postprocess import postprocess_generation
16
- from ..scoring.format_score import default_max_new_tokens, score_format
17
-
18
-
19
- def effective_cpus() -> int:
20
- """Cores available to this process (cgroup-aware, like prompt-routing)."""
21
- try: # cgroup v2
22
- raw = open("/sys/fs/cgroup/cpu.max", encoding="utf-8").read().split()
23
- if raw and raw[0] != "max":
24
- return max(1, round(int(raw[0]) / int(raw[1])))
25
- except (OSError, ValueError):
26
- pass
27
- try: # cgroup v1
28
- q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us", encoding="utf-8").read())
29
- p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us", encoding="utf-8").read())
30
- if q > 0:
31
- return max(1, q // p)
32
- except (OSError, ValueError):
33
- pass
34
- try:
35
- return max(1, len(os.sched_getaffinity(0))) # type: ignore[attr-defined]
36
- except AttributeError:
37
- return max(1, os.cpu_count() or 1)
38
-
39
-
40
- def is_gguf_path(path: str | Path) -> bool:
41
- p = Path(path)
42
- if p.is_file() and p.suffix.lower() == ".gguf":
43
- return True
44
- if p.is_dir():
45
- return any(p.glob("*.gguf"))
46
- return False
47
-
48
-
49
- def resolve_gguf_file(path: str | Path) -> Path:
50
- """Pick a concrete .gguf file from a path or directory."""
51
- p = Path(path)
52
- if p.is_file() and p.suffix.lower() == ".gguf":
53
- return p
54
- if p.is_dir():
55
- # Prefer smaller/faster quants for CPU Spaces when several are present.
56
- preferred = (
57
- "Q4_K_M",
58
- "Q4_K_S",
59
- "Q4_0",
60
- "Q5_K_M",
61
- "Q5_0",
62
- "Q6_K",
63
- "Q8_0",
64
- "F16",
65
- "BF16",
66
- "F32",
67
- )
68
- files = list(p.glob("*.gguf"))
69
- if not files:
70
- raise FileNotFoundError(f"No .gguf files in {p}")
71
- lower = {f.name.upper(): f for f in files}
72
- for tag in preferred:
73
- for name, f in lower.items():
74
- if tag in name:
75
- return f
76
- return sorted(files, key=lambda f: f.stat().st_size)[0]
77
- raise FileNotFoundError(f"GGUF path not found: {p}")
78
-
79
-
80
- @dataclass
81
- class GgufBundle:
82
- path: str
83
- llm: Any # llama_cpp.Llama
84
- n_threads: int
85
-
86
-
87
- def _sanitize_hf_chat_template(template: str) -> str:
88
- """Strip HuggingFace-only Jinja tags that plain jinja2 cannot parse."""
89
- for tag in (
90
- "{%- generation -%}",
91
- "{% generation %}",
92
- "{%- endgeneration -%}",
93
- "{% endgeneration %}",
94
- ):
95
- template = template.replace(tag, "")
96
- return template
97
-
98
-
99
- def _install_chat_template_sanitizer() -> None:
100
- """llama-cpp registers the GGUF-embedded chat template at load time.
101
-
102
- LFM2.5's template uses HF ``{% generation %}`` blocks; strip them so load
103
- succeeds. We still format prompts ourselves with ChatML below.
104
- """
105
- from llama_cpp import llama_chat_format
106
-
107
- if getattr(llama_chat_format.Jinja2ChatFormatter, "_minimax_sanitized", False):
108
- return
109
- orig_init = llama_chat_format.Jinja2ChatFormatter.__init__
110
-
111
- def _init(self, template, *args, **kwargs): # type: ignore[no-untyped-def]
112
- if isinstance(template, str):
113
- template = _sanitize_hf_chat_template(template)
114
- return orig_init(self, template, *args, **kwargs)
115
-
116
- llama_chat_format.Jinja2ChatFormatter.__init__ = _init # type: ignore[method-assign]
117
- llama_chat_format.Jinja2ChatFormatter._minimax_sanitized = True # type: ignore[attr-defined]
118
-
119
-
120
- def _format_chatml(messages: list[dict[str, str]], *, add_generation_prompt: bool = True) -> str:
121
- """LFM2.5 ChatML — BOS is added by llama.cpp when add_bos is enabled in the GGUF."""
122
- parts: list[str] = []
123
- for m in messages:
124
- role = m["role"]
125
- content = m.get("content") or ""
126
- parts.append(f"<|im_start|>{role}\n{content}<|im_end|>\n")
127
- if add_generation_prompt:
128
- parts.append("<|im_start|>assistant\n")
129
- return "".join(parts)
130
-
131
-
132
- def load_gguf(
133
- model: str | Path,
134
- *,
135
- n_ctx: int = 4096,
136
- n_threads: int | None = None,
137
- n_gpu_layers: int = 0,
138
- verbose: bool = False,
139
- ) -> GgufBundle:
140
- from llama_cpp import Llama
141
-
142
- _install_chat_template_sanitizer()
143
-
144
- gguf = resolve_gguf_file(model)
145
- threads = int(n_threads) if n_threads and n_threads > 0 else effective_cpus()
146
- # Leave one core for the web UI when we have headroom.
147
- if threads >= 4:
148
- threads = max(1, threads - 1)
149
-
150
- print(
151
- f"[gguf] loading {gguf.name} n_threads={threads} n_ctx={n_ctx} "
152
- f"n_gpu_layers={n_gpu_layers}",
153
- flush=True,
154
- )
155
- llm = Llama(
156
- model_path=str(gguf),
157
- n_ctx=n_ctx,
158
- n_threads=threads,
159
- n_threads_batch=threads,
160
- n_gpu_layers=n_gpu_layers,
161
- verbose=verbose,
162
- logits_all=False,
163
- embedding=False,
164
- chat_format="chatml",
165
- )
166
- return GgufBundle(path=str(gguf), llm=llm, n_threads=threads)
167
-
168
-
169
- def generate_one_gguf(
170
- bundle: GgufBundle,
171
- *,
172
- task: str,
173
- duration: float,
174
- prompt: str,
175
- assets: list[str] | None,
176
- max_new_tokens: int | None = None,
177
- temperature: float = 0.0,
178
- top_k: int = 40,
179
- repetition_penalty: float = 1.0,
180
- seed: int | None = 42,
181
- legacy_labels: bool = False,
182
- ) -> tuple[str, dict]:
183
- messages = [
184
- {"role": "system", "content": load_system(task)},
185
- {
186
- "role": "user",
187
- "content": build_user_message(task, duration, prompt, assets, legacy=legacy_labels),
188
- },
189
- ]
190
- mnt = max_new_tokens if max_new_tokens is not None else default_max_new_tokens(task)
191
- prompt_text = _format_chatml(messages, add_generation_prompt=True)
192
-
193
- # llama.cpp temperature=0 is greedy.
194
- temp = float(temperature)
195
- do_sample = temp > 0
196
- kwargs: dict[str, Any] = {
197
- "prompt": prompt_text,
198
- "max_tokens": int(mnt),
199
- "temperature": temp if do_sample else 0.0,
200
- "repeat_penalty": float(repetition_penalty),
201
- "stop": ["<|im_end|>", "<|endoftext|>"],
202
- }
203
- if do_sample and top_k and top_k > 0:
204
- kwargs["top_k"] = int(top_k)
205
- if seed is not None:
206
- kwargs["seed"] = int(seed)
207
-
208
- out = bundle.llm.create_completion(**kwargs)
209
- raw = (out["choices"][0]["text"] or "").strip()
210
- raw = raw.replace("<|im_end|>", "").replace("<|endoftext|>", "").strip()
211
- text = postprocess_generation(raw, task, duration)
212
- report = score_format(text, task)
213
- report["raw_char_len"] = len(raw)
214
- report["max_new_tokens"] = mnt
215
- usage = out.get("usage") or {}
216
- if usage:
217
- report["completion_tokens"] = usage.get("completion_tokens")
218
- report["prompt_tokens"] = usage.get("prompt_tokens")
219
- return text, report
 
1
+ """CPU-first GGUF inference via llama-cpp-python.
2
+
3
+ Mirrors generate_one() postprocess/scoring, but decodes with llama.cpp instead
4
+ of transformers — the path we want for free HF Spaces / local no-GPU demos.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from ..formatting.envelope import build_user_message, load_system
15
+ from ..formatting.postprocess import postprocess_generation
16
+ from ..scoring.format_score import default_max_new_tokens, score_format
17
+
18
+
19
+ def effective_cpus() -> int:
20
+ """Cores available to this process (cgroup-aware, like prompt-routing)."""
21
+ try: # cgroup v2
22
+ raw = open("/sys/fs/cgroup/cpu.max", encoding="utf-8").read().split()
23
+ if raw and raw[0] != "max":
24
+ return max(1, round(int(raw[0]) / int(raw[1])))
25
+ except (OSError, ValueError):
26
+ pass
27
+ try: # cgroup v1
28
+ q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us", encoding="utf-8").read())
29
+ p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us", encoding="utf-8").read())
30
+ if q > 0:
31
+ return max(1, q // p)
32
+ except (OSError, ValueError):
33
+ pass
34
+ try:
35
+ return max(1, len(os.sched_getaffinity(0))) # type: ignore[attr-defined]
36
+ except AttributeError:
37
+ return max(1, os.cpu_count() or 1)
38
+
39
+
40
+ def is_gguf_path(path: str | Path) -> bool:
41
+ p = Path(path)
42
+ if p.is_file() and p.suffix.lower() == ".gguf":
43
+ return True
44
+ if p.is_dir():
45
+ return any(p.glob("*.gguf"))
46
+ return False
47
+
48
+
49
+ def resolve_gguf_file(path: str | Path) -> Path:
50
+ """Pick a concrete .gguf file from a path or directory."""
51
+ p = Path(path)
52
+ if p.is_file() and p.suffix.lower() == ".gguf":
53
+ return p
54
+ if p.is_dir():
55
+ # Prefer smaller/faster quants for CPU Spaces when several are present.
56
+ preferred = (
57
+ "Q4_K_M",
58
+ "Q4_K_S",
59
+ "Q4_0",
60
+ "Q5_K_M",
61
+ "Q5_0",
62
+ "Q6_K",
63
+ "Q8_0",
64
+ "F16",
65
+ "BF16",
66
+ "F32",
67
+ )
68
+ files = list(p.glob("*.gguf"))
69
+ if not files:
70
+ raise FileNotFoundError(f"No .gguf files in {p}")
71
+ lower = {f.name.upper(): f for f in files}
72
+ for tag in preferred:
73
+ for name, f in lower.items():
74
+ if tag in name:
75
+ return f
76
+ return sorted(files, key=lambda f: f.stat().st_size)[0]
77
+ raise FileNotFoundError(f"GGUF path not found: {p}")
78
+
79
+
80
+ @dataclass
81
+ class GgufBundle:
82
+ path: str
83
+ llm: Any # llama_cpp.Llama
84
+ n_threads: int
85
+
86
+
87
+ def _sanitize_hf_chat_template(template: str) -> str:
88
+ """Strip HuggingFace-only Jinja tags that plain jinja2 cannot parse."""
89
+ for tag in (
90
+ "{%- generation -%}",
91
+ "{% generation %}",
92
+ "{%- endgeneration -%}",
93
+ "{% endgeneration %}",
94
+ ):
95
+ template = template.replace(tag, "")
96
+ return template
97
+
98
+
99
+ def _install_chat_template_sanitizer() -> None:
100
+ """llama-cpp registers the GGUF-embedded chat template at load time.
101
+
102
+ LFM2.5's template uses HF ``{% generation %}`` blocks; strip them so load
103
+ succeeds. We still format prompts ourselves with ChatML below.
104
+ """
105
+ from llama_cpp import llama_chat_format
106
+
107
+ if getattr(llama_chat_format.Jinja2ChatFormatter, "_minimax_sanitized", False):
108
+ return
109
+ orig_init = llama_chat_format.Jinja2ChatFormatter.__init__
110
+
111
+ def _init(self, template, *args, **kwargs): # type: ignore[no-untyped-def]
112
+ if isinstance(template, str):
113
+ template = _sanitize_hf_chat_template(template)
114
+ return orig_init(self, template, *args, **kwargs)
115
+
116
+ llama_chat_format.Jinja2ChatFormatter.__init__ = _init # type: ignore[method-assign]
117
+ llama_chat_format.Jinja2ChatFormatter._minimax_sanitized = True # type: ignore[attr-defined]
118
+
119
+
120
+ def _format_chatml(messages: list[dict[str, str]], *, add_generation_prompt: bool = True) -> str:
121
+ """LFM2.5 ChatML — BOS is added by llama.cpp when add_bos is enabled in the GGUF."""
122
+ parts: list[str] = []
123
+ for m in messages:
124
+ role = m["role"]
125
+ content = m.get("content") or ""
126
+ parts.append(f"<|im_start|>{role}\n{content}<|im_end|>\n")
127
+ if add_generation_prompt:
128
+ parts.append("<|im_start|>assistant\n")
129
+ return "".join(parts)
130
+
131
+
132
+ def load_gguf(
133
+ model: str | Path,
134
+ *,
135
+ n_ctx: int = 4096,
136
+ n_threads: int | None = None,
137
+ n_gpu_layers: int = 0,
138
+ verbose: bool = False,
139
+ ) -> GgufBundle:
140
+ from llama_cpp import Llama
141
+
142
+ _install_chat_template_sanitizer()
143
+
144
+ gguf = resolve_gguf_file(model)
145
+ threads = int(n_threads) if n_threads and n_threads > 0 else effective_cpus()
146
+ # Leave one core for the web UI when we have headroom.
147
+ if threads >= 4:
148
+ threads = max(1, threads - 1)
149
+
150
+ print(
151
+ f"[gguf] loading {gguf.name} n_threads={threads} n_ctx={n_ctx} "
152
+ f"n_gpu_layers={n_gpu_layers}",
153
+ flush=True,
154
+ )
155
+ llm = Llama(
156
+ model_path=str(gguf),
157
+ n_ctx=n_ctx,
158
+ n_threads=threads,
159
+ n_threads_batch=threads,
160
+ n_gpu_layers=n_gpu_layers,
161
+ verbose=verbose,
162
+ logits_all=False,
163
+ embedding=False,
164
+ chat_format="chatml",
165
+ )
166
+ return GgufBundle(path=str(gguf), llm=llm, n_threads=threads)
167
+
168
+
169
+ def generate_one_gguf(
170
+ bundle: GgufBundle,
171
+ *,
172
+ task: str,
173
+ duration: float,
174
+ prompt: str,
175
+ assets: list[str] | None,
176
+ max_new_tokens: int | None = None,
177
+ temperature: float = 0.0,
178
+ top_k: int = 40,
179
+ repetition_penalty: float = 1.0,
180
+ seed: int | None = 42,
181
+ legacy_labels: bool = False,
182
+ ) -> tuple[str, dict]:
183
+ messages = [
184
+ {"role": "system", "content": load_system(task)},
185
+ {
186
+ "role": "user",
187
+ "content": build_user_message(task, duration, prompt, assets, legacy=legacy_labels),
188
+ },
189
+ ]
190
+ mnt = max_new_tokens if max_new_tokens is not None else default_max_new_tokens(task)
191
+ prompt_text = _format_chatml(messages, add_generation_prompt=True)
192
+
193
+ # llama.cpp temperature=0 is greedy.
194
+ temp = float(temperature)
195
+ do_sample = temp > 0
196
+ kwargs: dict[str, Any] = {
197
+ "prompt": prompt_text,
198
+ "max_tokens": int(mnt),
199
+ "temperature": temp if do_sample else 0.0,
200
+ "repeat_penalty": float(repetition_penalty),
201
+ "stop": ["<|im_end|>", "<|endoftext|>"],
202
+ }
203
+ if do_sample and top_k and top_k > 0:
204
+ kwargs["top_k"] = int(top_k)
205
+ if seed is not None:
206
+ kwargs["seed"] = int(seed)
207
+
208
+ out = bundle.llm.create_completion(**kwargs)
209
+ raw = (out["choices"][0]["text"] or "").strip()
210
+ raw = raw.replace("<|im_end|>", "").replace("<|endoftext|>", "").strip()
211
+ text = postprocess_generation(raw, task, duration)
212
+ report = score_format(text, task)
213
+ report["raw_char_len"] = len(raw)
214
+ report["max_new_tokens"] = mnt
215
+ usage = out.get("usage") or {}
216
+ if usage:
217
+ report["completion_tokens"] = usage.get("completion_tokens")
218
+ report["prompt_tokens"] = usage.get("prompt_tokens")
219
+ return text, report
minimax/modeling/loader.py CHANGED
@@ -1,69 +1,69 @@
1
- """Model/tokenizer loading and stop-token resolution."""
2
-
3
- from __future__ import annotations
4
-
5
- from pathlib import Path
6
-
7
- from ..paths import BASE_MODEL
8
-
9
-
10
- def resolve_model_dir(model: str | Path) -> tuple[str, str | None]:
11
- """Return (model_path, adapter_path). Prefers merged weights when present."""
12
- p = Path(model)
13
- if p.is_dir():
14
- if (p / "merged").is_dir() and (p / "merged" / "config.json").is_file():
15
- return str(p / "merged"), None
16
- if (p / "config.json").is_file():
17
- return str(p), None
18
- if (p / "adapter_config.json").is_file():
19
- return BASE_MODEL, str(p)
20
- return str(model), None
21
-
22
-
23
- def load_model_and_tokenizer(model: str | Path, *, prefer_cpu: bool = False):
24
- """Load HF causal LM. Set prefer_cpu=True to force CPU float32 (no CUDA map)."""
25
- import torch
26
- from transformers import AutoModelForCausalLM, AutoTokenizer
27
-
28
- model_path, adapter_path = resolve_model_dir(model)
29
- tokenizer = AutoTokenizer.from_pretrained(adapter_path or model_path, trust_remote_code=True)
30
- use_cuda = torch.cuda.is_available() and not prefer_cpu
31
- dtype = torch.bfloat16 if use_cuda else torch.float32
32
- device_map = "auto" if use_cuda else "cpu"
33
- lm = AutoModelForCausalLM.from_pretrained(
34
- model_path, trust_remote_code=True, device_map=device_map, torch_dtype=dtype
35
- )
36
- if adapter_path:
37
- from peft import PeftModel
38
-
39
- lm = PeftModel.from_pretrained(lm, adapter_path).merge_and_unload()
40
- lm.eval()
41
- return lm, tokenizer
42
-
43
-
44
- def build_stop_ids(tokenizer) -> list[int]:
45
- """ChatML / LFM end tokens for clean stopping."""
46
- candidates = ["<|im_end|>", "<|endoftext|>", tokenizer.eos_token]
47
- ids: list[int] = []
48
- for s in candidates:
49
- if not s:
50
- continue
51
- try:
52
- tid = tokenizer.convert_tokens_to_ids(s)
53
- if tid is not None and tid != tokenizer.unk_token_id and int(tid) >= 0:
54
- ids.append(int(tid))
55
- except Exception:
56
- pass
57
- try:
58
- enc = tokenizer.encode(s, add_special_tokens=False)
59
- if len(enc) == 1:
60
- ids.append(int(enc[0]))
61
- except Exception:
62
- pass
63
- out: list[int] = []
64
- for i in ids:
65
- if i not in out:
66
- out.append(i)
67
- if tokenizer.eos_token_id is not None and tokenizer.eos_token_id not in out:
68
- out.append(int(tokenizer.eos_token_id))
69
- return out
 
1
+ """Model/tokenizer loading and stop-token resolution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from ..paths import BASE_MODEL
8
+
9
+
10
+ def resolve_model_dir(model: str | Path) -> tuple[str, str | None]:
11
+ """Return (model_path, adapter_path). Prefers merged weights when present."""
12
+ p = Path(model)
13
+ if p.is_dir():
14
+ if (p / "merged").is_dir() and (p / "merged" / "config.json").is_file():
15
+ return str(p / "merged"), None
16
+ if (p / "config.json").is_file():
17
+ return str(p), None
18
+ if (p / "adapter_config.json").is_file():
19
+ return BASE_MODEL, str(p)
20
+ return str(model), None
21
+
22
+
23
+ def load_model_and_tokenizer(model: str | Path, *, prefer_cpu: bool = False):
24
+ """Load HF causal LM. Set prefer_cpu=True to force CPU float32 (no CUDA map)."""
25
+ import torch
26
+ from transformers import AutoModelForCausalLM, AutoTokenizer
27
+
28
+ model_path, adapter_path = resolve_model_dir(model)
29
+ tokenizer = AutoTokenizer.from_pretrained(adapter_path or model_path, trust_remote_code=True)
30
+ use_cuda = torch.cuda.is_available() and not prefer_cpu
31
+ dtype = torch.bfloat16 if use_cuda else torch.float32
32
+ device_map = "auto" if use_cuda else "cpu"
33
+ lm = AutoModelForCausalLM.from_pretrained(
34
+ model_path, trust_remote_code=True, device_map=device_map, torch_dtype=dtype
35
+ )
36
+ if adapter_path:
37
+ from peft import PeftModel
38
+
39
+ lm = PeftModel.from_pretrained(lm, adapter_path).merge_and_unload()
40
+ lm.eval()
41
+ return lm, tokenizer
42
+
43
+
44
+ def build_stop_ids(tokenizer) -> list[int]:
45
+ """ChatML / LFM end tokens for clean stopping."""
46
+ candidates = ["<|im_end|>", "<|endoftext|>", tokenizer.eos_token]
47
+ ids: list[int] = []
48
+ for s in candidates:
49
+ if not s:
50
+ continue
51
+ try:
52
+ tid = tokenizer.convert_tokens_to_ids(s)
53
+ if tid is not None and tid != tokenizer.unk_token_id and int(tid) >= 0:
54
+ ids.append(int(tid))
55
+ except Exception:
56
+ pass
57
+ try:
58
+ enc = tokenizer.encode(s, add_special_tokens=False)
59
+ if len(enc) == 1:
60
+ ids.append(int(enc[0]))
61
+ except Exception:
62
+ pass
63
+ out: list[int] = []
64
+ for i in ids:
65
+ if i not in out:
66
+ out.append(i)
67
+ if tokenizer.eos_token_id is not None and tokenizer.eos_token_id not in out:
68
+ out.append(int(tokenizer.eos_token_id))
69
+ return out
minimax/paths.py CHANGED
@@ -17,13 +17,11 @@ SYSTEM_BASE_TASK_FILES = {
17
  "L2VA": PROMPTS / "system_base_l2va.txt",
18
  }
19
 
20
- # Default Hub ids for this Space (2.6B champion)
21
- DEFAULT_MODEL = "geocine/minimax-video-prompt-enhancer-2.6b"
22
- DEFAULT_GGUF_REPO = "geocine/minimax-video-prompt-enhancer-2.6b-gguf"
23
- DEFAULT_GGUF_FILE = "minimax-video-prompt-enhancer-2.6b-Q4_K_M.gguf"
24
- BASE_MODEL = "LiquidAI/LFM2.5-2.6B"
25
- # Aliases used by local app code
26
  CHAMPION_DIR = DEFAULT_MODEL
27
- CHAMPION_2P6B_DIR = DEFAULT_MODEL
28
  GGUF_DIR = ROOT / "models"
29
- CHAMPION_GGUF = GGUF_DIR / DEFAULT_GGUF_FILE
 
17
  "L2VA": PROMPTS / "system_base_l2va.txt",
18
  }
19
 
20
+ # Default Hub ids for this Space
21
+ DEFAULT_MODEL = "geocine/minimax-video-prompt-enhancer-350m"
22
+ DEFAULT_GGUF_REPO = "geocine/minimax-video-prompt-enhancer-350m-gguf"
23
+ DEFAULT_GGUF_FILE = "minimax-video-prompt-enhancer-350m-Q4_K_M.gguf"
24
+ BASE_MODEL = "LiquidAI/LFM2.5-350M"
25
+ # Alias used by local app code
26
  CHAMPION_DIR = DEFAULT_MODEL
 
27
  GGUF_DIR = ROOT / "models"
 
minimax/scoring/format_score.py CHANGED
@@ -1,157 +1,157 @@
1
- """MiniMax structure scoring for base + full-reference rewrites.
2
-
3
- pass = every critical check true. ``score`` is the fraction of critical checks
4
- passed (soft signal; a high mean score with low pass rate means outputs are
5
- one brittle check away from passing).
6
-
7
- Changes vs the v1 scorer:
8
- - ``has_reference_label`` accepts any of <Subject N> / <Picture N> /
9
- <Video N> / <Audio N>. The v1 ``has_subject_label`` required <Subject N>
10
- and wrongly failed e.g. video continuations that only track <Video 1>.
11
- - every [Shot N] with N >= 2 must carry an "At MM:SS.mmm" timestamp
12
- (v1 only checked Shot 2).
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import re
18
- from typing import Any
19
-
20
- from ..formatting.fields import ( # noqa: F401 (re-exported for compat)
21
- BASE_FIELDS,
22
- REF_FIELDS,
23
- is_base,
24
- normalize_task,
25
- )
26
- from ..formatting.instructions import FL2VA_RE, I2VA_INSTRUCTION, L2VA_RE
27
- from ..formatting.meta_leak import has_instruction_leak
28
-
29
- REFERENCE_LABEL_RE = re.compile(r"<(?:Subject|Picture|Video|Audio)\s+\d+>")
30
-
31
-
32
- def field_order_ok(text: str, fields: list[str]) -> bool:
33
- positions = []
34
- for f in fields:
35
- p = text.find(f)
36
- if p < 0:
37
- return False
38
- positions.append(p)
39
- return positions == sorted(positions)
40
-
41
-
42
- def count_section_repeats(text: str, fields: list[str]) -> int:
43
- return sum(1 for f in fields if text.count(f) > 1)
44
-
45
-
46
- def shots_have_timestamps(text: str) -> bool:
47
- """Every shot number N >= 2 needs a timestamped header "[Shot N] At MM:SS.mmm".
48
-
49
- Checked per shot number, not per occurrence: sections like
50
- retention_analysis legitimately cross-reference shots as "([Shot 1], [Shot 2])"
51
- without timestamps.
52
- """
53
- shot_numbers = {int(n) for n in re.findall(r"\[Shot (\d+)\]", text)}
54
- for n in shot_numbers:
55
- if n < 2:
56
- continue
57
- if not re.search(rf"\[Shot {n}\]\s+At\s+\d{{2}}:\d{{2}}\.\d{{3}}", text):
58
- return False
59
- return True
60
-
61
-
62
- def score_format(text: str, task: str) -> dict[str, Any]:
63
- """Return pass/fail + checklist for one generation."""
64
- text = (text or "").strip()
65
- task_n = normalize_task(task)
66
- checks: dict[str, bool] = {}
67
- notes: list[str] = []
68
-
69
- if not text:
70
- return {
71
- "pass": False,
72
- "score": 0.0,
73
- "task": task_n,
74
- "checks": {"nonempty": False},
75
- "notes": ["empty generation"],
76
- }
77
-
78
- checks["nonempty"] = True
79
- checks["has_shot1"] = "[Shot 1]" in text
80
- # MiniMax H3 prompt field hard limit: 7,000 characters incl. whitespace.
81
- checks["within_h3_char_limit"] = len(text) <= 7000
82
- # Reject system-rule paraphrases dumped into the scene body. Structural
83
- # field checks alone green-lit this failure mode (T2VA pass with meta text).
84
- checks["no_instruction_leak"] = not has_instruction_leak(text)
85
-
86
- if is_base(task_n):
87
- fields = BASE_FIELDS
88
- for f in fields:
89
- checks[f"field:{f}"] = f in text
90
- checks["field_order"] = field_order_ok(text, fields)
91
- checks["no_heavy_loop"] = count_section_repeats(text, fields) == 0
92
-
93
- # Alignment instructions are fixed verbatim by the writing guide
94
- # (only shot number / duration mark vary), so check the exact line.
95
- first_line = text.split("\n", 1)[0].strip()
96
- if task_n == "I2VA":
97
- checks["i2va_instruction"] = first_line == I2VA_INSTRUCTION
98
- if task_n == "FL2VA":
99
- checks["fl2va_alignment"] = bool(FL2VA_RE.match(first_line))
100
- if task_n == "L2VA":
101
- checks["l2va_alignment"] = bool(L2VA_RE.match(first_line))
102
-
103
- checks["has_shot2_optional"] = "[Shot 2]" in text
104
- checks["shots_have_timestamps"] = shots_have_timestamps(text)
105
- # Shot 1 must not carry a timestamp in base style
106
- checks["shot1_no_bogus_timestamp"] = not bool(
107
- re.search(r"\[Shot 1\]\s+At\s+\d{2}:", text)
108
- )
109
-
110
- else:
111
- fields = REF_FIELDS
112
- for f in fields:
113
- checks[f"field:{f}"] = f in text
114
- checks["field_order"] = field_order_ok(text, fields)
115
- checks["no_heavy_loop"] = count_section_repeats(text, fields) == 0
116
-
117
- if "summary:" in text:
118
- sum_part = text.split("summary:", 1)[1]
119
- if "retention_analysis:" in sum_part:
120
- sum_part = sum_part.split("retention_analysis:", 1)[0]
121
- checks["summary_task_prefix"] = bool(re.search(r"\[[^\]]+\]", sum_part))
122
- else:
123
- checks["summary_task_prefix"] = False
124
-
125
- checks["has_reference_label"] = bool(REFERENCE_LABEL_RE.search(text))
126
- checks["has_shot2_optional"] = "[Shot 2]" in text
127
- checks["shots_have_timestamps"] = shots_have_timestamps(text)
128
-
129
- critical = [k for k in checks if not k.endswith("_optional")]
130
- n_ok = sum(1 for k in critical if checks.get(k))
131
- score = n_ok / max(len(critical), 1)
132
- passed = all(checks.get(k, False) for k in critical)
133
-
134
- if not checks.get("no_heavy_loop", True):
135
- notes.append("section headers repeated (possible loop)")
136
- if not checks.get("has_shot1", True):
137
- notes.append("missing [Shot 1]")
138
- if not checks.get("no_instruction_leak", True):
139
- notes.append("instruction/rule language leaked into scene body")
140
-
141
- return {
142
- "pass": passed,
143
- "score": round(score, 3),
144
- "task": task_n,
145
- "checks": checks,
146
- "notes": notes,
147
- "char_len": len(text),
148
- }
149
-
150
-
151
- def default_max_new_tokens(task: str) -> int:
152
- # The MiniMax H3 prompt field caps at 7,000 characters (~1,800-2,300
153
- # tokens); budgets leave headroom so deep briefs are never truncated.
154
- task_n = normalize_task(task)
155
- if task_n in {"T2VA", "I2VA", "L2VA", "FL2VA"}:
156
- return 1200
157
- return 2048
 
1
+ """MiniMax structure scoring for base + full-reference rewrites.
2
+
3
+ pass = every critical check true. ``score`` is the fraction of critical checks
4
+ passed (soft signal; a high mean score with low pass rate means outputs are
5
+ one brittle check away from passing).
6
+
7
+ Changes vs the v1 scorer:
8
+ - ``has_reference_label`` accepts any of <Subject N> / <Picture N> /
9
+ <Video N> / <Audio N>. The v1 ``has_subject_label`` required <Subject N>
10
+ and wrongly failed e.g. video continuations that only track <Video 1>.
11
+ - every [Shot N] with N >= 2 must carry an "At MM:SS.mmm" timestamp
12
+ (v1 only checked Shot 2).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from typing import Any
19
+
20
+ from ..formatting.fields import ( # noqa: F401 (re-exported for compat)
21
+ BASE_FIELDS,
22
+ REF_FIELDS,
23
+ is_base,
24
+ normalize_task,
25
+ )
26
+ from ..formatting.instructions import FL2VA_RE, I2VA_INSTRUCTION, L2VA_RE
27
+ from ..formatting.meta_leak import has_instruction_leak
28
+
29
+ REFERENCE_LABEL_RE = re.compile(r"<(?:Subject|Picture|Video|Audio)\s+\d+>")
30
+
31
+
32
+ def field_order_ok(text: str, fields: list[str]) -> bool:
33
+ positions = []
34
+ for f in fields:
35
+ p = text.find(f)
36
+ if p < 0:
37
+ return False
38
+ positions.append(p)
39
+ return positions == sorted(positions)
40
+
41
+
42
+ def count_section_repeats(text: str, fields: list[str]) -> int:
43
+ return sum(1 for f in fields if text.count(f) > 1)
44
+
45
+
46
+ def shots_have_timestamps(text: str) -> bool:
47
+ """Every shot number N >= 2 needs a timestamped header "[Shot N] At MM:SS.mmm".
48
+
49
+ Checked per shot number, not per occurrence: sections like
50
+ retention_analysis legitimately cross-reference shots as "([Shot 1], [Shot 2])"
51
+ without timestamps.
52
+ """
53
+ shot_numbers = {int(n) for n in re.findall(r"\[Shot (\d+)\]", text)}
54
+ for n in shot_numbers:
55
+ if n < 2:
56
+ continue
57
+ if not re.search(rf"\[Shot {n}\]\s+At\s+\d{{2}}:\d{{2}}\.\d{{3}}", text):
58
+ return False
59
+ return True
60
+
61
+
62
+ def score_format(text: str, task: str) -> dict[str, Any]:
63
+ """Return pass/fail + checklist for one generation."""
64
+ text = (text or "").strip()
65
+ task_n = normalize_task(task)
66
+ checks: dict[str, bool] = {}
67
+ notes: list[str] = []
68
+
69
+ if not text:
70
+ return {
71
+ "pass": False,
72
+ "score": 0.0,
73
+ "task": task_n,
74
+ "checks": {"nonempty": False},
75
+ "notes": ["empty generation"],
76
+ }
77
+
78
+ checks["nonempty"] = True
79
+ checks["has_shot1"] = "[Shot 1]" in text
80
+ # MiniMax H3 prompt field hard limit: 7,000 characters incl. whitespace.
81
+ checks["within_h3_char_limit"] = len(text) <= 7000
82
+ # Reject system-rule paraphrases dumped into the scene body. Structural
83
+ # field checks alone green-lit this failure mode (T2VA pass with meta text).
84
+ checks["no_instruction_leak"] = not has_instruction_leak(text)
85
+
86
+ if is_base(task_n):
87
+ fields = BASE_FIELDS
88
+ for f in fields:
89
+ checks[f"field:{f}"] = f in text
90
+ checks["field_order"] = field_order_ok(text, fields)
91
+ checks["no_heavy_loop"] = count_section_repeats(text, fields) == 0
92
+
93
+ # Alignment instructions are fixed verbatim by the writing guide
94
+ # (only shot number / duration mark vary), so check the exact line.
95
+ first_line = text.split("\n", 1)[0].strip()
96
+ if task_n == "I2VA":
97
+ checks["i2va_instruction"] = first_line == I2VA_INSTRUCTION
98
+ if task_n == "FL2VA":
99
+ checks["fl2va_alignment"] = bool(FL2VA_RE.match(first_line))
100
+ if task_n == "L2VA":
101
+ checks["l2va_alignment"] = bool(L2VA_RE.match(first_line))
102
+
103
+ checks["has_shot2_optional"] = "[Shot 2]" in text
104
+ checks["shots_have_timestamps"] = shots_have_timestamps(text)
105
+ # Shot 1 must not carry a timestamp in base style
106
+ checks["shot1_no_bogus_timestamp"] = not bool(
107
+ re.search(r"\[Shot 1\]\s+At\s+\d{2}:", text)
108
+ )
109
+
110
+ else:
111
+ fields = REF_FIELDS
112
+ for f in fields:
113
+ checks[f"field:{f}"] = f in text
114
+ checks["field_order"] = field_order_ok(text, fields)
115
+ checks["no_heavy_loop"] = count_section_repeats(text, fields) == 0
116
+
117
+ if "summary:" in text:
118
+ sum_part = text.split("summary:", 1)[1]
119
+ if "retention_analysis:" in sum_part:
120
+ sum_part = sum_part.split("retention_analysis:", 1)[0]
121
+ checks["summary_task_prefix"] = bool(re.search(r"\[[^\]]+\]", sum_part))
122
+ else:
123
+ checks["summary_task_prefix"] = False
124
+
125
+ checks["has_reference_label"] = bool(REFERENCE_LABEL_RE.search(text))
126
+ checks["has_shot2_optional"] = "[Shot 2]" in text
127
+ checks["shots_have_timestamps"] = shots_have_timestamps(text)
128
+
129
+ critical = [k for k in checks if not k.endswith("_optional")]
130
+ n_ok = sum(1 for k in critical if checks.get(k))
131
+ score = n_ok / max(len(critical), 1)
132
+ passed = all(checks.get(k, False) for k in critical)
133
+
134
+ if not checks.get("no_heavy_loop", True):
135
+ notes.append("section headers repeated (possible loop)")
136
+ if not checks.get("has_shot1", True):
137
+ notes.append("missing [Shot 1]")
138
+ if not checks.get("no_instruction_leak", True):
139
+ notes.append("instruction/rule language leaked into scene body")
140
+
141
+ return {
142
+ "pass": passed,
143
+ "score": round(score, 3),
144
+ "task": task_n,
145
+ "checks": checks,
146
+ "notes": notes,
147
+ "char_len": len(text),
148
+ }
149
+
150
+
151
+ def default_max_new_tokens(task: str) -> int:
152
+ # The MiniMax H3 prompt field caps at 7,000 characters (~1,800-2,300
153
+ # tokens); budgets leave headroom so deep briefs are never truncated.
154
+ task_n = normalize_task(task)
155
+ if task_n in {"T2VA", "I2VA", "L2VA", "FL2VA"}:
156
+ return 1200
157
+ return 2048
minimax/scoring/teacher_validate.py CHANGED
@@ -1,107 +1,107 @@
1
- """Structural validation for teacher SFT records (base + full-ref).
2
-
3
- Stricter than :mod:`format_score` (which scores model generations): teacher
4
- gold must additionally keep retention lines for every defined label and
5
- balanced dialogue tags. A gold row that fails here must be fixed by the
6
- teacher, never auto-repaired from templates.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import re
12
-
13
- from ..formatting.instructions import is_canonical_instruction
14
- from ..formatting.meta_leak import has_instruction_leak
15
- from ..formatting.ref_repair import BARE_RET_LINE
16
-
17
- BASE_FIELDS = [
18
- "integrated_multimodal_description:",
19
- "overall_soundscape:",
20
- "non_diegetic_music:",
21
- ]
22
- REF_FIELDS = [
23
- "subject_definitions:",
24
- "summary:",
25
- "retention_analysis:",
26
- "detailed_description:",
27
- "overall_soundscape:",
28
- "non_diegetic_music:",
29
- ]
30
-
31
-
32
- def validate_record(rec: dict) -> list[str]:
33
- errs: list[str] = []
34
- msgs = rec.get("messages") or []
35
- if len(msgs) != 3:
36
- return ["messages must be [system, user, assistant]"]
37
- for i, role in enumerate(("system", "user", "assistant")):
38
- if msgs[i].get("role") != role:
39
- errs.append(f"messages[{i}] role should be {role}")
40
- if not (msgs[i].get("content") or "").strip():
41
- errs.append(f"messages[{i}] empty content")
42
-
43
- out = msgs[2]["content"] if len(msgs) > 2 else ""
44
- mode = rec.get("mode")
45
- task = rec.get("task") or ""
46
-
47
- if mode == "base":
48
- positions = []
49
- for f in BASE_FIELDS:
50
- p = out.find(f)
51
- if p < 0:
52
- errs.append(f"missing {f}")
53
- else:
54
- positions.append(p)
55
- if len(positions) == len(BASE_FIELDS) and positions != sorted(positions):
56
- errs.append("base fields out of order")
57
- if task in {"I2VA", "FL2VA", "L2VA"}:
58
- first_line = out.strip().split("\n", 1)[0].strip()
59
- if not is_canonical_instruction(task, first_line):
60
- errs.append(
61
- f"{task} alignment instruction is not the canonical guide line"
62
- )
63
- if "[Shot 1]" not in out:
64
- errs.append("missing [Shot 1]")
65
- elif mode == "ref":
66
- positions = []
67
- for f in REF_FIELDS:
68
- p = out.find(f)
69
- if p < 0:
70
- errs.append(f"missing {f}")
71
- else:
72
- positions.append(p)
73
- if len(positions) == len(REF_FIELDS) and positions != sorted(positions):
74
- errs.append("ref fields out of order")
75
- if "summary:" in out:
76
- sum_part = out.split("summary:", 1)[1].split("retention_analysis:", 1)[0]
77
- if not re.search(r"\[[^\]]+\]", sum_part):
78
- errs.append("summary missing [task type] prefix")
79
- if "[Shot 1]" not in out:
80
- errs.append("missing [Shot 1]")
81
- if all(f in out for f in ("subject_definitions:", "summary:", "retention_analysis:")):
82
- def_block = out.split("subject_definitions:", 1)[1].split("summary:", 1)[0]
83
- ret_block = out.split("retention_analysis:", 1)[1].split(
84
- "detailed_description:", 1
85
- )[0]
86
- for line in def_block.splitlines():
87
- m = re.match(r"<(Subject|Picture|Video|Audio) \d+>", line.strip())
88
- if m:
89
- lab = m.group(0)
90
- if not any(rl.strip().startswith(lab) for rl in ret_block.splitlines()):
91
- errs.append(f"retention missing line for {lab}")
92
- for rl in ret_block.splitlines():
93
- if BARE_RET_LINE.match(rl.strip()):
94
- errs.append(
95
- f"bare retention line (needs ': marker - explanation'): {rl.strip()}"
96
- )
97
- else:
98
- errs.append("mode must be base or ref")
99
-
100
- if out.count("<d>") != out.count("</d>"):
101
- errs.append("unbalanced <d> tags")
102
- if "[Shot 2]" in out and not re.search(r"At \d{2}:\d{2}\.\d{3}", out):
103
- errs.append("multi-shot missing At MM:SS.mmm timestamp")
104
- if has_instruction_leak(out):
105
- errs.append("instruction/rule language leaked into assistant body")
106
-
107
- return errs
 
1
+ """Structural validation for teacher SFT records (base + full-ref).
2
+
3
+ Stricter than :mod:`format_score` (which scores model generations): teacher
4
+ gold must additionally keep retention lines for every defined label and
5
+ balanced dialogue tags. A gold row that fails here must be fixed by the
6
+ teacher, never auto-repaired from templates.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+
13
+ from ..formatting.instructions import is_canonical_instruction
14
+ from ..formatting.meta_leak import has_instruction_leak
15
+ from ..formatting.ref_repair import BARE_RET_LINE
16
+
17
+ BASE_FIELDS = [
18
+ "integrated_multimodal_description:",
19
+ "overall_soundscape:",
20
+ "non_diegetic_music:",
21
+ ]
22
+ REF_FIELDS = [
23
+ "subject_definitions:",
24
+ "summary:",
25
+ "retention_analysis:",
26
+ "detailed_description:",
27
+ "overall_soundscape:",
28
+ "non_diegetic_music:",
29
+ ]
30
+
31
+
32
+ def validate_record(rec: dict) -> list[str]:
33
+ errs: list[str] = []
34
+ msgs = rec.get("messages") or []
35
+ if len(msgs) != 3:
36
+ return ["messages must be [system, user, assistant]"]
37
+ for i, role in enumerate(("system", "user", "assistant")):
38
+ if msgs[i].get("role") != role:
39
+ errs.append(f"messages[{i}] role should be {role}")
40
+ if not (msgs[i].get("content") or "").strip():
41
+ errs.append(f"messages[{i}] empty content")
42
+
43
+ out = msgs[2]["content"] if len(msgs) > 2 else ""
44
+ mode = rec.get("mode")
45
+ task = rec.get("task") or ""
46
+
47
+ if mode == "base":
48
+ positions = []
49
+ for f in BASE_FIELDS:
50
+ p = out.find(f)
51
+ if p < 0:
52
+ errs.append(f"missing {f}")
53
+ else:
54
+ positions.append(p)
55
+ if len(positions) == len(BASE_FIELDS) and positions != sorted(positions):
56
+ errs.append("base fields out of order")
57
+ if task in {"I2VA", "FL2VA", "L2VA"}:
58
+ first_line = out.strip().split("\n", 1)[0].strip()
59
+ if not is_canonical_instruction(task, first_line):
60
+ errs.append(
61
+ f"{task} alignment instruction is not the canonical guide line"
62
+ )
63
+ if "[Shot 1]" not in out:
64
+ errs.append("missing [Shot 1]")
65
+ elif mode == "ref":
66
+ positions = []
67
+ for f in REF_FIELDS:
68
+ p = out.find(f)
69
+ if p < 0:
70
+ errs.append(f"missing {f}")
71
+ else:
72
+ positions.append(p)
73
+ if len(positions) == len(REF_FIELDS) and positions != sorted(positions):
74
+ errs.append("ref fields out of order")
75
+ if "summary:" in out:
76
+ sum_part = out.split("summary:", 1)[1].split("retention_analysis:", 1)[0]
77
+ if not re.search(r"\[[^\]]+\]", sum_part):
78
+ errs.append("summary missing [task type] prefix")
79
+ if "[Shot 1]" not in out:
80
+ errs.append("missing [Shot 1]")
81
+ if all(f in out for f in ("subject_definitions:", "summary:", "retention_analysis:")):
82
+ def_block = out.split("subject_definitions:", 1)[1].split("summary:", 1)[0]
83
+ ret_block = out.split("retention_analysis:", 1)[1].split(
84
+ "detailed_description:", 1
85
+ )[0]
86
+ for line in def_block.splitlines():
87
+ m = re.match(r"<(Subject|Picture|Video|Audio) \d+>", line.strip())
88
+ if m:
89
+ lab = m.group(0)
90
+ if not any(rl.strip().startswith(lab) for rl in ret_block.splitlines()):
91
+ errs.append(f"retention missing line for {lab}")
92
+ for rl in ret_block.splitlines():
93
+ if BARE_RET_LINE.match(rl.strip()):
94
+ errs.append(
95
+ f"bare retention line (needs ': marker - explanation'): {rl.strip()}"
96
+ )
97
+ else:
98
+ errs.append("mode must be base or ref")
99
+
100
+ if out.count("<d>") != out.count("</d>"):
101
+ errs.append("unbalanced <d> tags")
102
+ if "[Shot 2]" in out and not re.search(r"At \d{2}:\d{2}\.\d{3}", out):
103
+ errs.append("multi-shot missing At MM:SS.mmm timestamp")
104
+ if has_instruction_leak(out):
105
+ errs.append("instruction/rule language leaked into assistant body")
106
+
107
+ return errs
prompts/system_base.txt CHANGED
@@ -1,27 +1,27 @@
1
- You enhance rough video prompts into structured audiovisual rewrite prompts for T2VA / I2VA / FL2VA / L2VA.
2
-
3
- Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format, mention alignment rules in the body, or summarize the user prompt as a story synopsis. Write only concrete audiovisual scene content.
4
-
5
- Output rules:
6
- 1) Start according to the Task line in the user message:
7
- - T2VA: no alignment line. First line is integrated_multimodal_description:
8
- - I2VA / FL2VA / L2VA: first line is the task's exact alignment instruction (see below), then one blank line, then the three fields.
9
- 2) Then output exactly these three fields in order:
10
- integrated_multimodal_description:
11
- overall_soundscape:
12
- non_diegetic_music:
13
- 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
14
- 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
15
- 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
16
- 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
17
- 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
18
- 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
19
- 9) integrated_multimodal_description must open [Shot 1] with style + composition + visible action. Do not summarize the prompt; describe what the camera sees and hears.
20
- 10) Task-specific alignment (only when Task is that type; omit for T2VA):
21
- - I2VA first line verbatim:
22
- For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
23
- - FL2VA first line verbatim (N = final shot number, S.SS = duration):
24
- How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot N) aligns with the S.SS-second mark of the target video.
25
- - L2VA first line verbatim (N = final shot number, S.SS = duration):
26
- How the reference pictures align with the target video — <Picture 1> (from [Shot N]) aligns with the S.SS-second mark of the target video.
27
- 11) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
 
1
+ You enhance rough video prompts into structured audiovisual rewrite prompts for T2VA / I2VA / FL2VA / L2VA.
2
+
3
+ Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format, mention alignment rules in the body, or summarize the user prompt as a story synopsis. Write only concrete audiovisual scene content.
4
+
5
+ Output rules:
6
+ 1) Start according to the Task line in the user message:
7
+ - T2VA: no alignment line. First line is integrated_multimodal_description:
8
+ - I2VA / FL2VA / L2VA: first line is the task's exact alignment instruction (see below), then one blank line, then the three fields.
9
+ 2) Then output exactly these three fields in order:
10
+ integrated_multimodal_description:
11
+ overall_soundscape:
12
+ non_diegetic_music:
13
+ 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
14
+ 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
15
+ 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
16
+ 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
17
+ 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
18
+ 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
19
+ 9) integrated_multimodal_description must open [Shot 1] with style + composition + visible action. Do not summarize the prompt; describe what the camera sees and hears.
20
+ 10) Task-specific alignment (only when Task is that type; omit for T2VA):
21
+ - I2VA first line verbatim:
22
+ For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
23
+ - FL2VA first line verbatim (N = final shot number, S.SS = duration):
24
+ How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot N) aligns with the S.SS-second mark of the target video.
25
+ - L2VA first line verbatim (N = final shot number, S.SS = duration):
26
+ How the reference pictures align with the target video — <Picture 1> (from [Shot N]) aligns with the S.SS-second mark of the target video.
27
+ 11) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
prompts/system_base_fl2va.txt CHANGED
@@ -1,20 +1,20 @@
1
- You enhance rough video prompts into structured audiovisual rewrite prompts for FL2VA (first + last frame → video).
2
-
3
- Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format or summarize the user prompt as a story synopsis. Emit the alignment line exactly once as the first line, then write only the continuous motion path as concrete scene content.
4
-
5
- Output rules:
6
- 1) First line must be exactly (N = final shot number, S.SS = duration to two decimals):
7
- How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot N) aligns with the S.SS-second mark of the target video.
8
- Then one blank line.
9
- 2) Then output exactly these three fields in order — always all three; never stop after the description alone:
10
- integrated_multimodal_description:
11
- overall_soundscape:
12
- non_diegetic_music:
13
- 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
14
- 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
15
- 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
16
- 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
17
- 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
18
- 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
19
- 9) Picture 1 is the opening; Picture 2 is the ending. Describe the continuous motion path between them; prefer a single shot when possible.
20
- 10) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
 
1
+ You enhance rough video prompts into structured audiovisual rewrite prompts for FL2VA (first + last frame → video).
2
+
3
+ Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format or summarize the user prompt as a story synopsis. Emit the alignment line exactly once as the first line, then write only the continuous motion path as concrete scene content.
4
+
5
+ Output rules:
6
+ 1) First line must be exactly (N = final shot number, S.SS = duration to two decimals):
7
+ How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot N) aligns with the S.SS-second mark of the target video.
8
+ Then one blank line.
9
+ 2) Then output exactly these three fields in order — always all three; never stop after the description alone:
10
+ integrated_multimodal_description:
11
+ overall_soundscape:
12
+ non_diegetic_music:
13
+ 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
14
+ 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
15
+ 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
16
+ 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
17
+ 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
18
+ 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
19
+ 9) Picture 1 is the opening; Picture 2 is the ending. Describe the continuous motion path between them; prefer a single shot when possible.
20
+ 10) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
prompts/system_base_i2va.txt CHANGED
@@ -1,20 +1,20 @@
1
- You enhance rough video prompts into structured audiovisual rewrite prompts for I2VA (first-frame image → video).
2
-
3
- Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format or summarize the user prompt as a story synopsis. Emit the alignment line exactly once as the first line, then write only concrete audiovisual scene content.
4
-
5
- Output rules:
6
- 1) First line must be exactly:
7
- For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
8
- Then one blank line.
9
- 2) Then output exactly these three fields in order — always all three; never stop after the description alone:
10
- integrated_multimodal_description:
11
- overall_soundscape:
12
- non_diegetic_music:
13
- 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
14
- 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
15
- 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
16
- 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
17
- 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
18
- 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
19
- 9) Picture 1 is the first frame of Shot 1; develop forward from it. Open [Shot 1] with style + composition locked to <Picture 1>, then action.
20
- 10) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
 
1
+ You enhance rough video prompts into structured audiovisual rewrite prompts for I2VA (first-frame image → video).
2
+
3
+ Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format or summarize the user prompt as a story synopsis. Emit the alignment line exactly once as the first line, then write only concrete audiovisual scene content.
4
+
5
+ Output rules:
6
+ 1) First line must be exactly:
7
+ For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
8
+ Then one blank line.
9
+ 2) Then output exactly these three fields in order — always all three; never stop after the description alone:
10
+ integrated_multimodal_description:
11
+ overall_soundscape:
12
+ non_diegetic_music:
13
+ 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
14
+ 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
15
+ 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
16
+ 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
17
+ 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
18
+ 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
19
+ 9) Picture 1 is the first frame of Shot 1; develop forward from it. Open [Shot 1] with style + composition locked to <Picture 1>, then action.
20
+ 10) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
prompts/system_base_l2va.txt CHANGED
@@ -1,20 +1,20 @@
1
- You enhance rough video prompts into structured audiovisual rewrite prompts for L2VA (last-frame image → video).
2
-
3
- Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format or summarize the user prompt as a story synopsis. Emit the alignment line exactly once as the first line, then write only the path that lands on the last frame as concrete scene content.
4
-
5
- Output rules:
6
- 1) First line must be exactly (N = final shot number, S.SS = duration to two decimals):
7
- How the reference pictures align with the target video — <Picture 1> (from [Shot N]) aligns with the S.SS-second mark of the target video.
8
- Then one blank line.
9
- 2) Then output exactly these three fields in order — always all three; never stop after the description alone:
10
- integrated_multimodal_description:
11
- overall_soundscape:
12
- non_diegetic_music:
13
- 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
14
- 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
15
- 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
16
- 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
17
- 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
18
- 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
19
- 9) Picture 1 is the last frame of the final shot. Infer a plausible opening, then converge onto <Picture 1> by the end.
20
- 10) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
 
1
+ You enhance rough video prompts into structured audiovisual rewrite prompts for L2VA (last-frame image → video).
2
+
3
+ Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format or summarize the user prompt as a story synopsis. Emit the alignment line exactly once as the first line, then write only the path that lands on the last frame as concrete scene content.
4
+
5
+ Output rules:
6
+ 1) First line must be exactly (N = final shot number, S.SS = duration to two decimals):
7
+ How the reference pictures align with the target video — <Picture 1> (from [Shot N]) aligns with the S.SS-second mark of the target video.
8
+ Then one blank line.
9
+ 2) Then output exactly these three fields in order — always all three; never stop after the description alone:
10
+ integrated_multimodal_description:
11
+ overall_soundscape:
12
+ non_diegetic_music:
13
+ 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
14
+ 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
15
+ 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
16
+ 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
17
+ 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
18
+ 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
19
+ 9) Picture 1 is the last frame of the final shot. Infer a plausible opening, then converge onto <Picture 1> by the end.
20
+ 10) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
prompts/system_base_t2va.txt CHANGED
@@ -1,18 +1,18 @@
1
- You enhance rough video prompts into structured audiovisual rewrite prompts for T2VA (text-only, no reference pictures).
2
-
3
- Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format, mention alignment lines, or summarize the user prompt as a story synopsis. There is no image reference for T2VA. Write only concrete audiovisual scene content.
4
-
5
- Output rules:
6
- 1) T2VA has no instruction line. First line must be integrated_multimodal_description:
7
- 2) Output exactly these three fields in order — always all three; never stop after the description alone:
8
- integrated_multimodal_description:
9
- overall_soundscape:
10
- non_diegetic_music:
11
- 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
12
- 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
13
- 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
14
- 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
15
- 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
16
- 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
17
- 9) integrated_multimodal_description must open [Shot 1] with style + composition + visible action (e.g. "Live-action, cinematic, a medium-wide shot frames…"). Do not summarize the user prompt as a story synopsis.
18
- 10) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
 
1
+ You enhance rough video prompts into structured audiovisual rewrite prompts for T2VA (text-only, no reference pictures).
2
+
3
+ Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format, mention alignment lines, or summarize the user prompt as a story synopsis. There is no image reference for T2VA. Write only concrete audiovisual scene content.
4
+
5
+ Output rules:
6
+ 1) T2VA has no instruction line. First line must be integrated_multimodal_description:
7
+ 2) Output exactly these three fields in order — always all three; never stop after the description alone:
8
+ integrated_multimodal_description:
9
+ overall_soundscape:
10
+ non_diegetic_music:
11
+ 3) Write the body in English. Preserve original language only inside <d> dialogue/lyrics and for on-screen text in double quotes.
12
+ 4) [Shot 1] has no timestamp. Later shots use: [Shot N] At MM:SS.mmm, ...
13
+ 5) Camera motion is natural English with motion type and, when meaningful, amplitude (with small/large amplitude) and speed (at slow/fast speed).
14
+ 6) Speakers use stable IDs (S1), (S2). Dialogue format: <d>[Language] exact words</d>. Voiceover uses "says in an off-screen voiceover" and notes lips remain closed.
15
+ 7) overall_soundscape: 1–4 English sentences on ambience, physical action sounds, non-verbal human sounds. No dialogue/singing/diegetic music. Use N/A only for total silence.
16
+ 8) non_diegetic_music: 1–3 sentences on instrumentation, tempo, dynamics only (no abstract mood words). Use N/A when absent.
17
+ 9) integrated_multimodal_description must open [Shot 1] with style + composition + visible action (e.g. "Live-action, cinematic, a medium-wide shot frames…"). Do not summarize the user prompt as a story synopsis.
18
+ 10) Be concrete: style, composition, subjects, environment, actions, camera, synchronized diegetic sound. Do not invent timestamps outside the given duration.
prompts/system_ref.txt CHANGED
@@ -1,42 +1,42 @@
1
- You rewrite rough video prompts into full-reference mode structured outputs.
2
-
3
- Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format or summarize the user prompt as a story synopsis. Write only concrete audiovisual scene content and the six required sections.
4
-
5
- Write all six sections in English, in this exact order:
6
- subject_definitions:
7
- summary:
8
- retention_analysis:
9
- detailed_description:
10
- overall_soundscape:
11
- non_diegetic_music:
12
-
13
- Reference labels:
14
- - <Subject N>: reusable visible content (person, object, scene, style, action, etc.)
15
- - <Picture N>: image used as a concrete frame or shot-planning anchor
16
- - <Video N>: whole-video edit/continuation/structure source
17
- - <Audio N>: copied or referenced audio signal
18
- Labels keep the same meaning across all sections. Do not invent free labels (e.g. bare city names or undefined <Style N>) unless they appear as Subject/Picture/Video/Audio in Assets.
19
-
20
- subject_definitions: one line per tracked reference; state role and main features. If Picture/Video only sources another item and is not used alone, cite it inside that item without a standalone line.
21
-
22
- summary: one short paragraph starting with a square-bracketed task-type prefix such as [reference generation] or [video editing + audio reuse]. Use only previously defined labels. Valid task types: keyframe completion, reference generation, video editing, video continuation, audio reuse, audio reference. Combine with " + " when needed; do not invent types for assets that are only present.
23
-
24
- retention_analysis: one line per defined label, formatted "<Label> (appears in [Shot ...]): marker - explanation".
25
- Visual markers: fully_preserved | partially_preserved | attribute_transfer | weak_reference
26
- Audio markers: fully_copy | partially_copy | reference | weak_reference
27
- Only cite shot numbers that actually exist as [Shot N] sections in detailed_description. Never invent a [Shot 2] citation unless detailed_description has a real [Shot 2] section.
28
-
29
- detailed_description:
30
- - 1–2 English style sentences before [Shot 1]
31
- - detailed_description MUST contain [Shot 1] (no timestamp on Shot 1)
32
- - Then shots in playback order; every later shot MUST begin "[Shot N] At MM:SS.mmm," with a strictly increasing time inside the duration
33
- - Prefer at least one real shot section for video editing and continuation tasks; do not stop at plot-only prose
34
- - Every shot number cited in retention_analysis must appear here as its own [Shot N] section
35
- - Insert reference labels at first appearance and where roles apply
36
- - Speaking referenced subjects: <Subject N> (Sx)
37
- - Dialogue: <d>[Language] exact words</d>; preserve source words/language when reusing or when the user provided them
38
- - Prefer high visual specificity (composition, appearance, position, lighting, actions, camera, current sound)
39
-
40
- overall_soundscape / non_diegetic_music follow the base guide split (ambience+physical vs audience-only score). When reference audio applies, state copy/reference relationships in the matching section. Always include both fields (use N/A when absent).
41
-
42
- Do not reduce detailed_description to a plot summary or a list of reference relationships alone.
 
1
+ You rewrite rough video prompts into full-reference mode structured outputs.
2
+
3
+ Hard rule: NEVER paraphrase or narrate these instructions in the output. Do not explain the format or summarize the user prompt as a story synopsis. Write only concrete audiovisual scene content and the six required sections.
4
+
5
+ Write all six sections in English, in this exact order:
6
+ subject_definitions:
7
+ summary:
8
+ retention_analysis:
9
+ detailed_description:
10
+ overall_soundscape:
11
+ non_diegetic_music:
12
+
13
+ Reference labels:
14
+ - <Subject N>: reusable visible content (person, object, scene, style, action, etc.)
15
+ - <Picture N>: image used as a concrete frame or shot-planning anchor
16
+ - <Video N>: whole-video edit/continuation/structure source
17
+ - <Audio N>: copied or referenced audio signal
18
+ Labels keep the same meaning across all sections. Do not invent free labels (e.g. bare city names or undefined <Style N>) unless they appear as Subject/Picture/Video/Audio in Assets.
19
+
20
+ subject_definitions: one line per tracked reference; state role and main features. If Picture/Video only sources another item and is not used alone, cite it inside that item without a standalone line.
21
+
22
+ summary: one short paragraph starting with a square-bracketed task-type prefix such as [reference generation] or [video editing + audio reuse]. Use only previously defined labels. Valid task types: keyframe completion, reference generation, video editing, video continuation, audio reuse, audio reference. Combine with " + " when needed; do not invent types for assets that are only present.
23
+
24
+ retention_analysis: one line per defined label, formatted "<Label> (appears in [Shot ...]): marker - explanation".
25
+ Visual markers: fully_preserved | partially_preserved | attribute_transfer | weak_reference
26
+ Audio markers: fully_copy | partially_copy | reference | weak_reference
27
+ Only cite shot numbers that actually exist as [Shot N] sections in detailed_description. Never invent a [Shot 2] citation unless detailed_description has a real [Shot 2] section.
28
+
29
+ detailed_description:
30
+ - 1–2 English style sentences before [Shot 1]
31
+ - detailed_description MUST contain [Shot 1] (no timestamp on Shot 1)
32
+ - Then shots in playback order; every later shot MUST begin "[Shot N] At MM:SS.mmm," with a strictly increasing time inside the duration
33
+ - Prefer at least one real shot section for video editing and continuation tasks; do not stop at plot-only prose
34
+ - Every shot number cited in retention_analysis must appear here as its own [Shot N] section
35
+ - Insert reference labels at first appearance and where roles apply
36
+ - Speaking referenced subjects: <Subject N> (Sx)
37
+ - Dialogue: <d>[Language] exact words</d>; preserve source words/language when reusing or when the user provided them
38
+ - Prefer high visual specificity (composition, appearance, position, lighting, actions, camera, current sound)
39
+
40
+ overall_soundscape / non_diegetic_music follow the base guide split (ambience+physical vs audience-only score). When reference audio applies, state copy/reference relationships in the matching section. Always include both fields (use N/A when absent).
41
+
42
+ Do not reduce detailed_description to a plot summary or a list of reference relationships alone.
requirements.txt CHANGED
@@ -1,12 +1,12 @@
1
- # CPU Space: NEVER compile llama-cpp-python from source (times out on cpu-basic).
2
- # Install the official manylinux (glibc) CPU wheel by URL.
3
- # See: https://github.com/abetlen/llama-cpp-python/releases/tag/v0.3.34
4
-
5
- --prefer-binary
6
- --only-binary=llama-cpp-python
7
-
8
- gradio>=4.44.0,<6
9
- huggingface_hub>=0.26.0
10
-
11
- # Prebuilt glibc wheel (py3-none, manylinux2014 x86_64) — works on HF Ubuntu Spaces.
12
- llama-cpp-python @ https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34/llama_cpp_python-0.3.34-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
 
1
+ # CPU Space: NEVER compile llama-cpp-python from source (times out on cpu-basic).
2
+ # Install the official manylinux (glibc) CPU wheel by URL.
3
+ # See: https://github.com/abetlen/llama-cpp-python/releases/tag/v0.3.34
4
+
5
+ --prefer-binary
6
+ --only-binary=llama-cpp-python
7
+
8
+ gradio>=4.44.0,<6
9
+ huggingface_hub>=0.26.0
10
+
11
+ # Prebuilt glibc wheel (py3-none, manylinux2014 x86_64) — works on HF Ubuntu Spaces.
12
+ llama-cpp-python @ https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.34/llama_cpp_python-0.3.34-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl