Download app.py from SecLoTus/mv-brain: direct link, hf CLI and curl.
- Browser
- Download file 6.79 kB
-
https://huggingface.co/spaces/SecLoTus/mv-brain/resolve/main/app.py
- Command line
-
hf download hf://spaces/SecLoTus/mv-brain/app.py
-
curl -L -o app.py https://huggingface.co/spaces/SecLoTus/mv-brain/resolve/main/app.py
6.79 kB
| """MV Studio brain engine: Qwen3.8-27B (vision-language) + Whisper on ZeroGPU. | |
| Two endpoints, both prompt-agnostic (the studio owns every system prompt): | |
| /chat - LLM call with optional images: the music-video director, and the FLUX caption upsampler. | |
| /transcribe - lyrics with word timestamps. | |
| """ | |
| import spaces # noqa: F401 (must come before torch) | |
| import json | |
| import os | |
| import tempfile | |
| import time | |
| import gradio as gr | |
| import torch | |
| from PIL import Image | |
| from transformers import AutoModelForImageTextToText, AutoProcessor, pipeline | |
| token = os.environ.get("HF_TOKEN") | |
| LLM_REPO = os.environ.get("LLM_REPO", "Qwen/Qwen3.8-27B-FP8") | |
| WHISPER_REPO = os.environ.get("WHISPER_REPO", "openai/whisper-large-v3") | |
| # FP8 weights (~29 GB) fit the default half GPU. Set GPU_SIZE=xlarge if the bf16 repo is used instead. | |
| GPU_SIZE = os.environ.get("GPU_SIZE", "large") | |
| TOKENS_PER_SECOND = float(os.environ.get("TOKENS_PER_SECOND", "18")) | |
| print(f"[boot] {LLM_REPO}…", flush=True) | |
| processor = AutoProcessor.from_pretrained(LLM_REPO, token=token) | |
| model = AutoModelForImageTextToText.from_pretrained(LLM_REPO, dtype="auto", token=token).eval() | |
| model.to("cuda") | |
| print(f"[boot] {WHISPER_REPO}…", flush=True) | |
| asr = pipeline("automatic-speech-recognition", model=WHISPER_REPO, dtype=torch.float16, device="cuda", token=token) | |
| print("[boot] ready", flush=True) | |
| def _paths(files): | |
| return [f if isinstance(f, str) else getattr(f, "name", None) or f.get("path") for f in (files or [])] | |
| def _chat_duration(system, user, images=None, thinking=False, max_tokens=1024, temperature=0.7): | |
| budget = int(max_tokens) * (2 if thinking else 1) | |
| return int(min(max(15 + budget / TOKENS_PER_SECOND + 4 * len(images or []), 20), 300)) | |
| def _chat_gpu(system, user, images=None, thinking=False, max_tokens=1024, temperature=0.7): | |
| content = [{"type": "image", "image": Image.open(p).convert("RGB")} for p in _paths(images)] | |
| content.append({"type": "text", "text": user}) | |
| messages = ([{"role": "system", "content": system}] if system else []) + [{"role": "user", "content": content}] | |
| inputs = processor.apply_chat_template( | |
| messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt", | |
| enable_thinking=bool(thinking), | |
| ).to(model.device) | |
| # Sampling settings from the model card: thinking vs. instruct mode. | |
| sampling = dict(temperature=1.0, top_p=0.95, top_k=20) if thinking else \ | |
| dict(temperature=float(temperature), top_p=0.8, top_k=20) | |
| t0 = time.time() | |
| with torch.inference_mode(): | |
| out = model.generate(**inputs, max_new_tokens=int(max_tokens) * (2 if thinking else 1), | |
| do_sample=sampling["temperature"] > 0, **sampling) | |
| new = out[0, inputs["input_ids"].shape[1]:] | |
| text = processor.decode(new, skip_special_tokens=True) | |
| if "</think>" in text: | |
| text = text.split("</think>", 1)[1] | |
| print(f"[timing] chat tokens={len(new)} s={time.time() - t0:.1f} tok/s={len(new) / max(time.time() - t0, 1e-6):.1f}", | |
| flush=True) | |
| return text.strip() | |
| ENGINE_KEY = os.environ.get("ENGINE_KEY", "") | |
| def _guard(request): | |
| """Only the owner's studio may run jobs: it sends the shared ENGINE_KEY in a header.""" | |
| if ENGINE_KEY and (request is None or request.headers.get("x-mv-key") != ENGINE_KEY): | |
| raise gr.Error("This is a private engine.") | |
| def chat(system: str, user: str, images=None, thinking: bool = False, max_tokens: int = 1024, | |
| temperature: float = 0.7, request: gr.Request = None): | |
| """Run the LLM. | |
| Args: | |
| system: system prompt. | |
| user: user message. | |
| images: optional image files, attached before the text in order. | |
| thinking: let the model reason before answering (slower, costs more GPU time). | |
| max_tokens: answer budget (doubled internally when thinking). | |
| temperature: sampling temperature in instruct mode. | |
| Returns: | |
| The model's answer, without its reasoning. | |
| """ | |
| _guard(request) | |
| if not (user or "").strip(): | |
| raise gr.Error("Empty message.") | |
| return _chat_gpu(system or "", user, _paths(images), bool(thinking), int(max_tokens), float(temperature)) | |
| def _transcribe_gpu(audio_path, language): | |
| t0 = time.time() | |
| kwargs = {"task": "transcribe"} | |
| if language: | |
| kwargs["language"] = language | |
| result = asr(audio_path, return_timestamps="word", chunk_length_s=30, batch_size=16, generate_kwargs=kwargs) | |
| print(f"[timing] transcribe s={time.time() - t0:.1f}", flush=True) | |
| return result | |
| def transcribe(audio, language: str = "", request: gr.Request = None): | |
| """Transcribe vocals with word timestamps. | |
| Args: | |
| audio: audio file (isolated vocals work best). | |
| language: optional language code, e.g. "en"; empty to auto-detect. | |
| Returns: | |
| JSON file: {"text": str, "words": [{"word", "start", "end"}]}. | |
| """ | |
| _guard(request) | |
| path = audio if isinstance(audio, str) else getattr(audio, "name", None) or audio.get("path") | |
| result = _transcribe_gpu(path, (language or "").strip() or None) | |
| words = [{"word": c["text"].strip(), "start": c["timestamp"][0], "end": c["timestamp"][1]} | |
| for c in result.get("chunks", []) if c.get("text", "").strip()] | |
| out = os.path.join(tempfile.mkdtemp(), "lyrics.json") | |
| with open(out, "w") as f: | |
| json.dump({"text": result.get("text", "").strip(), "words": words}, f) | |
| return out | |
| with gr.Blocks(title="MV Studio · brain engine") as demo: | |
| gr.Markdown(f"### MV Studio brain engine\n`{LLM_REPO}` + `{WHISPER_REPO}`. Backend for the studio.") | |
| with gr.Tab("Chat"): | |
| system = gr.Textbox(label="System", lines=3) | |
| user = gr.Textbox(label="User", lines=5) | |
| images = gr.File(label="Images", file_count="multiple", file_types=["image"]) | |
| with gr.Row(): | |
| thinking = gr.Checkbox(label="Thinking", value=False) | |
| max_tokens = gr.Slider(64, 4096, value=1024, step=64, label="Max tokens") | |
| temperature = gr.Slider(0.0, 1.5, value=0.7, step=0.05, label="Temperature") | |
| go = gr.Button("Run", variant="primary") | |
| answer = gr.Textbox(label="Answer", lines=12) | |
| go.click(chat, [system, user, images, thinking, max_tokens, temperature], answer, api_name="chat") | |
| with gr.Tab("Transcribe"): | |
| audio = gr.Audio(type="filepath", label="Vocals") | |
| language = gr.Textbox(label="Language (optional)", value="en") | |
| go2 = gr.Button("Transcribe", variant="primary") | |
| lyrics = gr.File(label="lyrics.json") | |
| go2.click(transcribe, [audio, language], lyrics, api_name="transcribe") | |
| demo.queue(max_size=16).launch(show_error=True) | |