File size: 8,523 Bytes
1d797bd
 
81fd211
1d797bd
 
81fd211
1d797bd
 
 
06cc068
 
1d797bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9aaef0
2433f69
 
 
e9aaef0
 
 
 
 
 
06cc068
e9aaef0
 
06cc068
e9aaef0
06cc068
 
 
 
 
e9aaef0
 
0d86e63
 
1d797bd
 
2433f69
1d797bd
 
 
 
2433f69
1d797bd
 
 
 
 
 
 
e9aaef0
1d797bd
e9aaef0
32d8822
 
 
06cc068
32d8822
 
 
 
 
e9aaef0
1d797bd
06cc068
1d797bd
 
 
e9aaef0
 
1d797bd
0d86e63
81fd211
 
 
 
 
e9aaef0
81fd211
e9aaef0
81fd211
e9aaef0
 
 
81fd211
e9aaef0
81fd211
 
06cc068
81fd211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9aaef0
81fd211
 
 
 
 
e9aaef0
81fd211
 
e9aaef0
06cc068
 
 
81fd211
 
e9aaef0
81fd211
 
e9aaef0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""CPU speech recognition and stateful shot direction."""
import base64
import http.client
import io
import json
import logging
import threading
import wave

from camera_direction import camera_direction

import numpy as np
import onnx_asr
import onnxruntime as ort
from huggingface_hub import hf_hub_download, snapshot_download
from llama_cpp import Llama, LlamaGrammar

ASR_REPO = "FluidVoice-Labs/fluid-speech-pro-onnx"
ASR_REV = "fa588e9f87f1b9ad0ca2e2d8f7eaf84dc3803581"
QWEN = "unsloth/Qwen3-4B-Instruct-2507-GGUF"
QWEN_REV = "a06e946bb6b655725eafa393f4a9745d460374c9"
_options = ort.SessionOptions()
_options.intra_op_num_threads = 2
_options.inter_op_num_threads = 1
_dir = snapshot_download(ASR_REPO, revision=ASR_REV, allow_patterns=["*int8*", "vocab.txt", "config.json"])
asr = onnx_asr.load_model("nemo-conformer-tdt", _dir, quantization="int8", sess_options=_options)
llm = Llama(model_path=hf_hub_download(QWEN, "Qwen3-4B-Instruct-2507-Q4_K_M.gguf", revision=QWEN_REV),
            n_ctx=2048, n_threads=2, n_threads_batch=2, verbose=False)
model_lock = threading.Lock()
asr_lock = threading.Lock()
OPS = ("append", "redo_last", "clarify")
# A 45-second spoken cue plus the microphone's short lead-in and word-ending buffer.
MAX_AUDIO_FRAMES = 46 * 16_000
MAX_ENCODED_BYTES = 4 * ((44 + 2 * MAX_AUDIO_FRAMES + 2) // 3)
INTENT = """Decide what the speaker wants to do on the timeline. append adds a following clip.
redo_last makes another version of the last completed clip. clarify means either timing is plausible.
Respect explicit timing, negation and self-corrections. Distinguish a character repeating a movement
from the director asking to reshoot. "Garde cette prise, ensuite il refait le mouvement" is append.
"Pas la suite, le même passage en plan large" is redo_last. "Un peu moins de neige" with no timing is clarify.
When a fixed operation is provided, use it. In all cases, write the resulting full visual shot in English,
preserving established details and applying the visual change. Omit timeline commands from the visual prompt."""
SYSTEM = INTENT + """
Reply in four fields separated by vertical bars:
operation|target|2-7 word English description of the change|updated complete English shot (at most 45 words).
Camera speed and subject speed are distinct. An elliptical change refers to the last directed element."""
ANGLE_GUIDE = " French contre-plongée means looking up from below; plongée means looking down from above. Preserve both camera travel and angle in the shot."

def angle_guide(cue):
    return ANGLE_GUIDE if "plong" in cue.casefold() else ""

GRAMMAR = ('root ::= operation "|" target "|" text "|" text\n'
           'operation ::= "append" | "redo_last" | "clarify"\n'
           'target ::= "scene" | "subject" | "camera" | "weather" | "subject+weather" | "camera+weather" | "subject+camera"\n'
           'text ::= [^\\n|]+')

def transcribe(encoded):
    if not isinstance(encoded, str) or not 40 < len(encoded) <= MAX_ENCODED_BYTES:
        raise ValueError("audio")
    with wave.open(io.BytesIO(base64.b64decode(encoded, validate=True)), "rb") as wav:
        if (wav.getframerate(), wav.getnchannels(), wav.getsampwidth()) != (16000, 1, 2):
            raise ValueError("audio")
        if not 2400 <= wav.getnframes() <= MAX_AUDIO_FRAMES:
            raise ValueError("duration")
        samples = np.frombuffer(wav.readframes(wav.getnframes()), dtype="<i2").astype(np.float32) / 32768
    if len(samples) == 0 or np.max(np.abs(samples)) < .004:
        return ""
    with asr_lock:
        return str(asr.recognize(samples, sample_rate=16000) or "").strip()[:1200]

def local_direction(heard, old, selected):
    data = {"previous_visual_prompt": old["prompt"], "previous_instruction": old["last"],
            "last_directed_element": old["focus"], "new_instruction": heard, "fixed_operation": selected}
    if not old["prompt"]:
        with model_lock:
            first = llm.create_chat_completion(messages=[
                {"role":"system","content":"Translate the scene, including any camera directions, into one short English shot description. Preserve details, add nothing. If already in English, copy it. French contre-plongée means low-angle looking up; plongée means high-angle looking down."},
                {"role":"user","content":heard}],temperature=0,max_tokens=90)
        choice = first["choices"][0]
        opening = choice["message"]["content"].strip()
        if not opening or choice["finish_reason"] == "length":
            raise ValueError("opening")
        return "append", "scene", opening, opening
    with model_lock:
        result = llm.create_chat_completion(messages=[{"role":"system","content":SYSTEM + angle_guide(heard)},
            {"role":"user","content":json.dumps(data, ensure_ascii=False)}], temperature=0,
            grammar=LlamaGrammar.from_string(GRAMMAR, verbose=False), max_tokens=110)
    choice = result["choices"][0]
    parts = [s.strip() for s in choice["message"]["content"].split("|", 3)]
    if len(parts) != 4 or parts[0] not in OPS or not all(parts) or choice["finish_reason"] == "length":
        raise ValueError("direction")
    return tuple(parts)

FLAGS = ("subject_changed", "camera_changed", "weather_changed")
SCHEMA = {
    "type": "object",
    "properties": {**{k: {"type": "boolean"} for k in FLAGS},
                   "operation": {"type": "string", "enum": list(OPS)},
                   "summary": {"type": "string"}, "shot": {"type": "string"}},
    "required": [*FLAGS, "operation", "summary", "shot"], "additionalProperties": False,
}
DIRECTOR = INTENT + """
Edit a continuous video shot. Return three change flags, a 2–7 word English summary and the complete updated English shot (at most 45 words). For an opening, translate the scene faithfully and leave all flags false. Preserve established details. Apply every requested change. Distinguish camera speed from subject speed. An elliptical instruction refers to the previous target. Flag only changes requested to subject (including motion), camera or weather. Summarize all changes."""
def provider_direction(instruction, old, token, selected):
    context = {"shot": old["prompt"], "last_target": old["focus"],
               "last_instruction": old["last"], "instruction": instruction, "fixed_operation": selected}
    body = {"model": "thinkingmachines/Inkling-2-Mini", "temperature": 0,
            "max_tokens": 256, "reasoning": {"effort": "none"},
            "messages": [{"role": "system", "content": DIRECTOR + angle_guide(instruction)},
                         {"role": "user", "content": json.dumps(context, ensure_ascii=False)}],
            "response_format": {"type": "json_schema", "json_schema":
                                {"name": "shot_edit", "strict": True, "schema": SCHEMA}}}
    conn = http.client.HTTPSConnection("router.huggingface.co", timeout=6)
    try:
        conn.request("POST", "/v1/chat/completions", json.dumps(body).encode(),
                     {"Authorization": "Bearer " + token, "Content-Type": "application/json"})
        response = conn.getresponse()
        if response.status != 200:
            raise ValueError(f"Provider HTTP {response.status}")
        choice = json.loads(response.read(65536))["choices"][0]
    finally:
        conn.close()
    edit = json.loads(choice["message"]["content"])
    if (choice.get("finish_reason") != "stop" or not isinstance(edit, dict)
            or edit.get("operation") not in OPS
            or any(type(edit.get(k)) is not bool for k in FLAGS)
            or any(not isinstance(edit.get(k), str) or not edit[k].strip() for k in ("summary","shot"))):
        raise ValueError("Incomplete provider direction")
    prompt = edit["shot"].strip()
    focus = "+".join(k.split("_")[0] for k in FLAGS if edit[k]) or "scene"
    return (edit["operation"], focus, edit["summary"].strip(), prompt) if old["prompt"] else ("append", "scene", prompt, prompt)


def direct(instruction, old, token=None, selected="append"):
    camera = camera_direction(instruction, old, selected)
    if camera:
        return (*camera, "Camera cue")
    if token:
        try:
            return (*provider_direction(instruction, old, token, selected), "Inkling 2 Mini")
        except (OSError, http.client.HTTPException, ValueError, KeyError, IndexError, TypeError) as exc:
            logging.getLogger("studio").warning("Provider unavailable (%s), using Qwen", type(exc).__name__)
    return (*local_direction(instruction, old, selected), "Qwen")