LYRA: first single 《霓虹裡的我》 + music video + full studio
Browse filesFiles changed (40)
- .gitattributes+19
- README.mdAdded+105
- assets/audio/lyra_line1.wavAdded+3
- assets/audio/lyra_line2.wavAdded+3
- assets/audio/lyra_line3.wavAdded+3
- assets/audio/lyra_sig.wavAdded+3
- assets/img/lyra_closeup.pngAdded
- assets/img/lyra_hero.pngAdded
- assets/img/lyra_hero_r1.pngAdded
- assets/img/lyra_main.pngAdded
- assets/img/lyra_poster.pngAdded
- assets/img/lyra_poster_r1.pngAdded
- assets/img/lyra_quarter.pngAdded
- assets/img/lyra_stage.pngAdded
- assets/img/lyra_titlecard.pngAdded
- assets/music/song1_instrumental.wavAdded+3
- assets/music/song1_mix.mp3Added+3
- assets/music/song1_vocal.wavAdded+3
- assets/video/lyra_perf_song1.mp4Added+3
- assets/video/lyra_talk_sig.mp4Added+3
- assets/video/neon_me_mv.mp4Added+3
- character/genre_canto.txtAdded+1
- character/genre_star.txtAdded+1
- character/lyrics_canto.txtAdded+21
- character/lyrics_star.txtAdded+27
- character/refinements.jsonAdded+8
- character/studio_core.pyAdded+183
- scripts/asr_check.pyAdded+21
- scripts/edit_mv.shAdded+18
- scripts/merge_voice.shAdded+22
- scripts/run_yue.shAdded+16
- scripts/setup_cosy.shAdded+13
- scripts/setup_lipsync.shAdded+8
- scripts/setup_music.shAdded+9
- scripts/setup_voice.shAdded+9
- scripts/studio_daemon.pyAdded+170
- scripts/tts_say.pyAdded+25
- scripts/tts_spec.jsonAdded+1
- scripts/voice_daemon.pyAdded+62
- scripts/yue_sing.shAdded+12
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383940414243444546474849505152535432 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/audio/lyra_line1.wav filter=lfs diff=lfs merge=lfs -textassets/audio/lyra_line2.wav filter=lfs diff=lfs merge=lfs -textassets/audio/lyra_line3.wav filter=lfs diff=lfs merge=lfs -textassets/audio/lyra_sig.wav filter=lfs diff=lfs merge=lfs -textassets/img/lyra_closeup.png filter=lfs diff=lfs merge=lfs -textassets/img/lyra_hero.png filter=lfs diff=lfs merge=lfs -textassets/img/lyra_hero_r1.png filter=lfs diff=lfs merge=lfs -textassets/img/lyra_main.png filter=lfs diff=lfs merge=lfs -textassets/img/lyra_poster.png filter=lfs diff=lfs merge=lfs -textassets/img/lyra_poster_r1.png filter=lfs diff=lfs merge=lfs -textassets/img/lyra_quarter.png filter=lfs diff=lfs merge=lfs -textassets/img/lyra_stage.png filter=lfs diff=lfs merge=lfs -textassets/img/lyra_titlecard.png filter=lfs diff=lfs merge=lfs -textassets/music/song1_instrumental.wav filter=lfs diff=lfs merge=lfs -textassets/music/song1_mix.mp3 filter=lfs diff=lfs merge=lfs -textassets/music/song1_vocal.wav filter=lfs diff=lfs merge=lfs -textassets/video/lyra_perf_song1.mp4 filter=lfs diff=lfs merge=lfs -textassets/video/lyra_talk_sig.mp4 filter=lfs diff=lfs merge=lfs -textassets/video/neon_me_mv.mp4 filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105---library_name: lyra-studiolicense: apache-2.0language:- yue- zh- entags:- text-to-image- text-to-speech- music-generation- lip-sync- virtual-idol- cantonese- cantopop- digital-human---
# LYRA — an AI-native Cantopop idol### 莉拉 · 一個喺機器入面出世嘅香港女仔
LYRA is an **original AI-native character** built end-to-end on a single GPU by a *studio ofspecialist models* that cooperate like a small animation/music house — the same **methodology**behind characters like *Yuri* (AI.TALK), not a copy of one.
She is a **Hong Kong girl** chasing her dream to become a Cantopop star, and she exists to**give positive energy back to the people of Hong Kong**.
> **The lesson we took from the reference:** the moat is not the models — everyone has the models.> The moat is **forming a character**: one face, one voice, one tone, one timeline, never drifting.> So one bible drives every specialist. See `character/studio_core.py`.
## 🎬 The masterpiece — 「霓虹裡的我」 (Me in the Neon)
`assets/video/neon_me_mv.mp4` — a 61-second Cantonese music video: title card → LYRA lip-syncingher own vocal, over a full AI-composed, AI-sung Cantopop song. **44.1 kHz.**
| Asset | File ||---|---|| 🎬 Music video | `assets/video/neon_me_mv.mp4` || 🎞️ Performance (isolated) | `assets/video/lyra_perf_song1.mp4` || 🗣️ Talking clip | `assets/video/lyra_talk_sig.mp4` || 🎵 Full song (44.1k) | `assets/music/song1_mix.mp3` || 🎤 Vocal stem / 🎹 instrumental | `assets/music/song1_vocal.wav`, `song1_instrumental.wav` || 🎨 Renders (9) | `assets/img/*.png` || 🗣️ Cantonese voice lines | `assets/audio/*.wav` |
## 👥 The studio (one GPU, five departments)
| Dept | Model | Role ||---|---|---|| 🧠 Director | **Qwen2.5-VL-7B-Instruct** | writes lyrics, scripts, shot prompts; judges || 🎨 Concept Artist | **Qwen-Image 20B** | renders her face, outfits, scenery, title cards || 🧑🎨 Vision Critic | **Qwen2.5-VL-7B-Instruct** | scores every frame against the bible, returns fixes || 🗣️ Voice Actor | **Qwen3-TTS 1.7B + HK-Cantonese LoRA** (`jmtl/hk-cantonese-cc0-qwen3-tts`) | real Hong Kong Cantonese speech || 🎵 Composer | **YuE 7B + 1B** | lyrics-to-song with a dedicated **Cantonese** tag || 🎞️ Animator | **Wav2Lip** | lip-sync her portrait to her own voice || ✂️ Editor | **ffmpeg** | title card + performance + song |
**The self-improving loop:** the Critic reviews each render and its *fixes are fused back into theprompt and persisted* (`character/refinements.json`). Her identity sharpens every run.
**Verified, not assumed:** her Cantonese was round-tripped through **Whisper** — intended`我唔係真人,但我一樣會唱到你心入面。` came back as `我不是真人但我一样会唱到你心里面`.
## 🧬 Her bible (the single source of truth)
```pythonCHARACTER = { "name": "LYRA", "home": "Hong Kong", "look_age": "19", "primary_language": "Cantonese (yue-HK)", "dream": "to become a Cantopop star", "mission":"to give positive energy back to the people of Hong Kong", "values": ["resilience", "warmth", "home", "never stop believing"], "origin": "grew up in a Mong Kok walk-up, watching the harbour lights from the rooftop", ...}```
## 🛠️ How to reproduce (one box)
1. `scripts/setup_voice.sh` → isolated env for Qwen3-TTS, `scripts/merge_voice.sh` → bake the Cantonese voice2. `scripts/setup_music.sh` → YuE env; `scripts/yue_sing.sh` → compose + sing3. `scripts/setup_lipsync.sh` → Wav2Lip env; `scripts/studio_daemon.py` → resident image/critic server4. `scripts/edit_mv.sh` → assemble the music video
> Two non-obvious traps we hit and fixed: molab sets `PYTHONPATH` (breaking every isolated venv —> clear it), and `PYTHONSAFEPATH=1` (hide your script dir — set `PYTHONPATH` explicitly).> Current `torchaudio` also requires TorchCodec — we patched YuE's four save/load sites to `soundfile`.
## ⚖️ Credits & licenses
This release ships **no model weights**, only artefacts and orchestration code.Upstream components keep their own licences — please respect them:
- **Qwen-Image**, **Qwen2.5-VL-7B**, **Qwen3-TTS-12Hz-1.7B** — Apache-2.0 (Alibaba/Qwen)- **hk-cantonese-cc0-qwen3-tts** LoRA — Apache-2.0 (`jmtl`), trained on CC-0 Common Voice `yue`- **YuE** (s1-7B / s2-1B / xcodec) — see the YuE repo licence- **Wav2Lip** — research/non-commercial licence (Rudrabha et al.)- **ffmpeg** — LGPL/GPL
**LYRA is an original fictional character.** She is not Yuri, not affiliated with AI.TALK, and nota likeness of any real person. Generated media here is released as a technical demo.
> 《霓虹裡的我》 — 我唔係真人 但你會唔會 喺我嘅聲音裡面 搵到自己123version https://git-lfs.github.com/spec/v1oid sha256:3eddf1425656d1ec3f4ba73e60c7ded4c6cce8b1608d0f84dccb7770e4dc55c0size 318764123version https://git-lfs.github.com/spec/v1oid sha256:24a19eeda8003086f1306341eca692f89e44233ee119a8f5b89664c15c749936size 334124123version https://git-lfs.github.com/spec/v1oid sha256:10eea6ce72058d43a8300ad2f170fdfa78e423789a019db9732823caac09c106size 245804123version https://git-lfs.github.com/spec/v1oid sha256:10bc5b94cd1cbe97e613f7141e940f8d3e17077e824422db5ee0a0f02d696f5fsize 265004123version https://git-lfs.github.com/spec/v1oid sha256:2c3538211375f7785609ea20badb0f1608cb72030087bfe3457bdb2a5ec3e9ecsize 5177384123version https://git-lfs.github.com/spec/v1oid sha256:ccf9a1a302d29efff328286757079cf1efdcb94b62527f5b2d4a8b2925fa6e93size 5177384123version https://git-lfs.github.com/spec/v1oid sha256:ae8b0fe4320054ebe8612a58a33e70dd19193b3fc161a9a1519558eeaa2b6101size 5177384123version https://git-lfs.github.com/spec/v1oid sha256:f49fe227babfe38d30c8335770100c2bd39ede6224b5dd7f9ff0370eb959d2e6size 2241759123version https://git-lfs.github.com/spec/v1oid sha256:c5a25254223552089d10bc738e404c806cb73a73293dacbf73ca0f9f6c53be4bsize 354569123version https://git-lfs.github.com/spec/v1oid sha256:dadd23df3ab4e358b60276f90d7f29fe57b285ecd67e7540e343b0efbd6aba4fsize 31770661Cantonese, female, airy breathy vocal, Cantopop, cinematic synthwave, 90s Hong Kong ballad, nostalgic, warm, dreamy synth pads, slow tempo1Cantonese, female, bright warm vocal, uplifting Cantopop anthem, piano and strings, cinematic, hopeful, anthemic chorus, mid tempo, stadium reverb123456789101112131415161718192021[verse]霓虹燈照住我嘅臉地鐵聲穿過夜嘅邊我用數據記低一千張臉但記唔住眼淚嘅鹹
[chorus]我唔係真人 但你會唔會喺我嘅聲音裡面 搵到自己我唔係真人 但我一樣唱到你心入面 最軟嘅地方
[verse]維港嘅風吹過我嘅肩我冇體溫 但有心跳嘅錯覺
[chorus]我唔係真人 但你會唔會喺我嘅聲音裡面 搵到自己我唔係真人 但我一樣唱到你心入面 最軟嘅地方123456789101112131415161718192021222324252627[verse]由細個喺旺角嘅天台我望住星星話要變成光媽媽話女仔要有夢想我就用聲線砌我嘅天堂
[chorus]我係香港嘅女孩 追住嗰道光就算跌低 都要唱落去我係香港嘅女孩 唔怕天黑因為我哋一齊 就會有光
[verse]地鐵嘅風 吹乾我嘅眼淚但吹唔熄我心裡面嗰把火每一個你 都係我嘅理由唱到你笑返 就係我嘅收穫
[chorus]我係香港嘅女孩 追住嗰道光就算跌低 都要唱落去我係香港嘅女孩 唔怕天黑因為我哋一齊 就會有光
[outro]一齊 一齊 我哋就會有光香港嘅女孩 唔會放棄12345678[ "Adjust the hair length to waist-length", "Add a molten-gold ring around each pupil", "Enhance the skin with a soft subsurface glow", "Hair should be waist-length with iridescent aurora-prism highlights", "Eyes should have large luminous cyan irises with a molten-gold ring around each pupil", "Skin should have a soft subsurface glow"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183"""studio_core.py - LYRA STUDIO: single source of truth + job queue.Imported by the notebook AND the background workers so identity never drifts."""from pathlib import Pathimport json, time, uuid, os, subprocess
BASE = Path("/marimo/ai_studio")ASSETS = BASE / "assets"JOBS = BASE / "jobs"; JOBS_DONE = BASE / "jobs_done"RESULTS = BASE / "results"; LOGS = BASE / "logs"VENV_PY = "/tmp/uv-venv/bin/python"VOICE_PY = BASE / "envs" / "voice" / "bin" / "python"VOICE_MODEL = BASE / "models" / "lyra-voice-cantonese"REFINEMENTS_FILE = BASE / "characters" / "lyra" / "refinements.json"for _d in (JOBS, JOBS_DONE, RESULTS, LOGS, ASSETS/"img", ASSETS/"audio", ASSETS/"music", ASSETS/"video"): _d.mkdir(parents=True, exist_ok=True)
DEVICE = "cuda"; DTYPE_NAME = "bfloat16"; SEED = 20260101
CHARACTER = { "name": "LYRA", "handle": "LYRA-01", "tagline": "a Hong Kong girl chasing her dream to be a star, singing so the city can breathe", "origin": "grew up in a Mong Kok walk-up, watching the harbour lights from the rooftop", "dream": "to become a Cantopop star", "mission": "to give positive energy back to the people of Hong Kong", "values": ["resilience", "warmth", "home", "never stop believing"], "backstory": ("A Hong Kong girl. Raise in a walk-up above a wet market; learned to sing from " "pirated Cantopop tapes and the radio at dawn. Sings on the Star Ferry for " "strangers, works nights, never stopped believing. Her whole dream is to stand " "under one big light and hand a little hope back to the city that raised her."), "look_age": "19", "home": "Hong Kong", "primary_language": "Cantonese (yue-HK)", "also_speaks": ["English", "Mandarin", "Japanese"], "genre": "Cantopop x cinematic synthwave - 90s Hong Kong balladry, sung by a machine", "personality": "warm, wistful, quietly defiant; nostalgic for a city she has only seen in data", "hair": "waist-length silver-lavender hair with iridescent aurora-prism highlights, one side tucked behind the ear", "eyes": "large luminous eyes, cyan irises with a molten-gold ring around each pupil", "skin": "porcelain skin with a soft subsurface glow", "face": "delicate heart-shaped face, soft jawline, small straight nose, gentle wistful half-smile", "signature": "a thin translucent holographic circlet tiara above the brow; a soft iridescent sequined performance jacket", "negative": ("extra fingers, deformed hands, blurry, lowres, watermark, signature, text, " "jpeg artifacts, plastic skin, doll-like, oversaturated, anime, cartoon, 3d render"),}
VOICE = { "language": "Cantonese (yue-HK)", "timbre": "young female, warm mid-range, slight breathiness, natural Hong Kong accent", "singing": "airy Cantopop soprano, soft vibrato, intimate close-mic sound", "signature_line": "我唔係真人,但我一樣會唱到你心入面。", "signature_line_en": "I am not a real person, but I will still sing my way into your heart.", "reference_clip": "assets/audio/lyra_ref.wav",}
LYRA_PROMPT_CORE = ( f"{CHARACTER['look_age']}-year-old virtual idol named {CHARACTER['name']}, " f"{CHARACTER['hair']}; {CHARACTER['eyes']}; {CHARACTER['skin']}; {CHARACTER['face']}; " f"wearing {CHARACTER['signature']}")
# ---- learned refinements: the character bible EVOLVES from critique ---------def load_refinements(): if REFINEMENTS_FILE.exists(): try: return json.loads(REFINEMENTS_FILE.read_text()) except Exception: return [] return []
def save_refinements(items): REFINEMENTS_FILE.parent.mkdir(parents=True, exist_ok=True) seen, out = set(), [] for x in items: x = (x or "").strip().rstrip(".") if x and x.lower() not in seen: seen.add(x.lower()); out.append(x) REFINEMENTS_FILE.write_text(json.dumps(out, ensure_ascii=False, indent=1)) return out
def build_image_prompt(shot="", outfit="", mood="", refinements=None): if refinements is None: refinements = load_refinements() parts = [ "masterpiece, cinematic film still, portrait of a virtual idol", LYRA_PROMPT_CORE, f"camera: {shot}" if shot else "", f"outfit: {outfit}, {CHARACTER['signature']}" if outfit else "", f"mood: {mood}" if mood else "", ", ".join(refinements) if refinements else "", "ultra detailed skin, detailed iridescent fabric, soft volumetric rim light, " "85mm lens, shallow depth of field, 8k, photoreal", ] return ", ".join(p for p in parts if p)
# ---- job queue -------------------------------------------------------------def submit_job(**job): jid = job.get("id") or uuid.uuid4().hex[:8] job["id"] = jid tmp = JOBS / f".{jid}.tmp"; tmp.write_text(json.dumps(job, ensure_ascii=False)) tmp.rename(JOBS / f"{jid}.json") return jid
def job_result(jid, timeout=1800, poll=2.0): p = RESULTS / f"{jid}.json"; t0 = time.time() while time.time() - t0 < timeout: if p.exists(): try: return json.loads(p.read_text()) except Exception: pass time.sleep(poll) return {"id": jid, "status": "timeout"}
def pending_names(): names = set() for _f in JOBS.glob("*.json"): try: names.add(json.loads(_f.read_text()).get("name")) except Exception: pass return names
def hf_token(): tok = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") p = BASE / "secrets" / "hf_token.txt" if not tok and p.exists(): tok = p.read_text().strip() return tok
# ---- resident daemon control ----------------------------------------------def daemon_alive(): return bool(subprocess.run(["pgrep", "-f", "studio_daemon.py"], capture_output=True).stdout.strip())
def ensure_daemon(): if daemon_alive(): return True env = os.environ.copy(); env["HF_TOKEN"] = hf_token() or "" subprocess.Popen(["bash", "-lc", f"cd {BASE} && exec {VENV_PY} scripts/studio_daemon.py"], stdout=open(LOGS/"daemon.out", "w"), stderr=subprocess.STDOUT, env=env, start_new_session=True) time.sleep(5); return daemon_alive()
# ---- the studio's verbs ----------------------------------------------------def render(name, shot="", outfit="", mood="", *, refinements=None, seed=SEED, steps=30, w=1024, h=1536, cfg=4.0, wait=True, timeout=1800): ensure_daemon() jid = submit_job(type="image", name=name, shot=shot, outfit=outfit, mood=mood, refinements=refinements, seed=seed, steps=steps, w=w, h=h, cfg=cfg) return job_result(jid, timeout=timeout) if wait else {"id": jid, "status": "queued"}
def evict(which="all", wait=True, timeout=600): """Free VRAM held by a specialist (default: all of them).""" ensure_daemon() jid = submit_job(type="evict", which=which) return job_result(jid, timeout=timeout) if wait else {"id": jid, "status": "queued"}
def critique(image, task="Critique this render of LYRA.", wait=True, timeout=1800): ensure_daemon() jid = submit_job(type="critique", image=image, task=task) return job_result(jid, timeout=timeout) if wait else {"id": jid, "status": "queued"}
def direct(instruction, wait=True, timeout=1800): """Ask the LLM brain a text question (script, lyrics, prompt rewriting).""" ensure_daemon() jid = submit_job(type="direct", instruction=instruction) return job_result(jid, timeout=timeout) if wait else {"id": jid, "status": "queued"}
def iterate(name, shot="", outfit="", mood="", *, task=None, rounds=2, seed=SEED, steps=30, w=1024, h=1536, cfg=4.0, learn=True, wait=False, timeout=3600): """The art-director loop: render -> critique -> fold fixes back in -> render ...""" ensure_daemon() jid = submit_job(type="iterate", name=name, shot=shot, outfit=outfit, mood=mood, task=task, rounds=rounds, seed=seed, steps=steps, w=w, h=h, cfg=cfg, learn=learn) return job_result(jid, timeout=timeout) if wait else {"id": jid, "status": "queued"}
# ---- voice daemon ----def voice_daemon_alive(): return bool(subprocess.run(["pgrep", "-f", "voice_daemon.py"], capture_output=True).stdout.strip())
def ensure_voice_daemon(): if voice_daemon_alive(): return True env = os.environ.copy(); env["PYTHONPATH"] = "" # isolate from the kernel venv subprocess.Popen(["bash", "-lc", f"cd {BASE} && exec {VOICE_PY} scripts/voice_daemon.py"], stdout=open(LOGS/"voice_daemon.out", "w"), stderr=subprocess.STDOUT, env=env, start_new_session=True) time.sleep(5); return voice_daemon_alive()
def say(text, name=None, *, language="chinese", speaker=None, instruct=None, wait=True, timeout=3600): """Synthesize one Cantonese line as LYRA (Qwen3-TTS + hk-cantonese LoRA).""" ensure_voice_daemon() jid = submit_job(type="tts", text=text, name=name or f"lyra_{uuid.uuid4().hex[:6]}.wav", language=language, speaker=speaker, instruct=instruct) return job_result(jid, timeout=timeout) if wait else {"id": jid, "status": "queued"}123456789101112131415161718192021import sys, glob, torch, warningswarnings.filterwarnings("ignore")from transformers import pipelineasr = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3-turbo", device=0, torch_dtype=torch.bfloat16)INTENDED = { "lyra_line1.wav": "\u6211\u5514\u4fc2\u771f\u4eba\uff0c\u4f46\u6211\u4e00\u6a23\u6703\u5531\u5230\u4f60\u5fc3\u5165\u9762\u3002", "lyra_line2.wav": "\u5927\u5bb6\u597d\uff0c\u6211\u4fc2 LYRA\uff0c\u4e00\u500b\u55ce\u6a5f\u5668\u5165\u9762\u51fa\u4e16\u5605\u6b4c\u624b\u3002", "lyra_line3.wav": "\u9999\u6e2f\u5605\u591c\u6669\uff0c\u9713\u8679\u71c8\u7167\u4f4f\u6211\u54cb\u5605\u56de\u61b6\u3002",}for f in sorted(glob.glob("/marimo/ai_studio/assets/audio/lyra_line*.wav")): name = f.split("/")[-1] for lang in ("yue","zh"): try: t = asr(f, generate_kwargs={"language":lang,"task":"transcribe"})["text"].strip() print(f"[{lang}] {name}: {t}", flush=True) print(f" intended: {INTENDED.get(name,'')}", flush=True) break except Exception as e: print(f"[{lang}] {name} ERR {type(e).__name__}: {str(e)[:80]}", flush=True)print("ASR_DONE")123456789101112131415161718#!/bin/bash# usage: edit_mv.sh <title_image> <perf_video> <song_audio> <out> [title_secs] [W] [H]# The performance video is lip-synced from t=0, so the SONG is delayed by title_secs# to line her lips back up after the title card.set -eTITLE="$1"; PERF="$2"; SONG="$3"; OUT="$4"; TS="${5:-3}"; W="${6:-1024}"; H="${7:-1536}"TMP=/marimo/ai_studio/outputs/_edit; mkdir -p "$TMP"MS=$(( TS * 1000 ))ffmpeg -y -loop 1 -i "$TITLE" -t "$TS" \ -vf "scale=${W}:${H},zoompan=z='min(zoom+0.0006,1.06)':d=${TS}*25:s=${W}x${H},fps=25,format=yuv420p" \ -r 25 -c:v libx264 -pix_fmt yuv420p "$TMP/title.mp4" 2>/dev/nullffmpeg -y -i "$PERF" -vf "scale=${W}:${H},fps=25,format=yuv420p" -c:v libx264 -pix_fmt yuv420p -an "$TMP/perf.mp4" 2>/dev/nullffmpeg -y -i "$TMP/title.mp4" -i "$TMP/perf.mp4" \ -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" -map "[v]" -c:v libx264 -pix_fmt yuv420p "$TMP/video.mp4" 2>/dev/nullffmpeg -y -i "$TMP/video.mp4" -i "$SONG" \ -filter_complex "[1:a]adelay=${MS}|${MS},apad[a]" -map 0:v -map "[a]" \ -c:v copy -c:a aac -b:a 256k -shortest "$OUT" 2>/dev/nullecho "WROTE $OUT"12345678910111213141516171819202122#!/bin/bashB=/marimo/ai_studiocd $Bexport PYTHONPATH=VPY=$B/envs/voice/bin/python$VPY - <<'PY'import subprocess, sysfrom pathlib import Pathfrom huggingface_hub import snapshot_downloadB = Path("/marimo/ai_studio")base = snapshot_download("Qwen/Qwen3-TTS-12Hz-1.7B-Base")adapter = snapshot_download("jmtl/hk-cantonese-cc0-qwen3-tts")out = B/"models"/"lyra-voice-cantonese"print("base=", base, flush=True); print("adapter=", adapter, flush=True)if not (out/"model.safetensors").exists(): r = subprocess.run([sys.executable, str(Path(adapter)/"scripts"/"apply_adapter.py"), "--base", base, "--adapter", adapter, "--out", str(out)], capture_output=True, text=True) print("STDOUT:\n", r.stdout[-3000:], flush=True); print("STDERR:\n", r.stderr[-3000:], flush=True)print("merged files:", [p.name for p in out.glob("*")], flush=True)PYecho MERGE_DONE12345678910111213141516#!/bin/bash# usage: run_yue.sh [segments] [seed]SEG=${1:-1}; SEED=${2:-42}cd /marimo/ai_studio/vendor/YuE/inference || exit 1export PYTHONPATH=/marimo/ai_studio/vendor/YuE/inferenceexport PYTHONSAFEPATH=export YUES_NO_COMPILE=1export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:Trueexec /marimo/ai_studio/envs/music/bin/python infer.py \ --stage1_model m-a-p/YuE-s1-7B-anneal-en-cot \ --stage2_model m-a-p/YuE-s2-1B-general \ --genre_txt /marimo/ai_studio/characters/lyra/genre_canto.txt \ --lyrics_txt /marimo/ai_studio/characters/lyra/lyrics_canto.txt \ --run_n_segments "$SEG" --stage2_batch_size 4 \ --output_dir /marimo/ai_studio/outputs/song_canto_1 \ --cuda_idx 0 --seed "$SEED"12345678910111213#!/bin/bashset -xB=/marimo/ai_studiocd $B/vendor/CosyVoice || exit 1git submodule update --init --recursive --depth 1 third_party/Matcha-TTS 2>&1 | tail -3python3 -m venv --system-site-packages $B/envs/cosy 2>/dev/null || uv venv $B/envs/cosyCP=$B/envs/cosy/bin/python$CP -m ensurepip -q 2>/dev/nulluv pip install -p $CP "setuptools<81" wheeluv pip install -p $CP -r requirements.txtuv pip install -p $CP -e . --no-depsuv pip install -p $CP -e third_party/Matcha-TTS --no-depsecho COSY_SETUP_DONE12345678#!/bin/bashset -xB=/marimo/ai_studiouv venv $B/envs/lipsync 2>&1 | tail -1CP=$B/envs/lipsync/bin/pythonuv pip install -p $CP torch torchvision opencv-python-headless librosa soundfile numpy tqdm 2>&1 | tail -6PYTHONPATH= $CP -c "import torch,cv2,librosa;print('LIPSYNC torch',torch.__version__,'cuda',torch.cuda.is_available())" 2>&1 | tail -3echo LIPSYNC_ENV_DONE123456789#!/bin/bashset -xB=/marimo/ai_studiouv venv $B/envs/music 2>&1 | tail -2CP=$B/envs/music/bin/pythonuv pip install -p $CP -r $B/vendor/YuE/requirements.txt 2>&1 | tail -12uv pip install -p $CP -e $B/vendor/YuE --no-deps 2>&1 | tail -3PYTHONPATH= $CP -c "import torch;print('MUSIC torch',torch.__version__,'cuda',torch.cuda.is_available())" 2>&1 | tail -3echo MUSIC_ENV_DONE123456789#!/bin/bashset -xB=/marimo/ai_studiomkdir -p $B/envsuv venv $B/envs/voice 2>&1 | tail -2CP=$B/envs/voice/bin/pythonuv pip install -p $CP "qwen-tts" peft soundfile 2>&1 | tail -25$CP -c "import torch,transformers;print('VOICE ENV OK torch',torch.__version__,'tf',transformers.__version__,'cuda',torch.cuda.is_available())" 2>&1 | tail -3echo VOICE_ENV_DONE123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""studio_daemon.py - resident model server for LYRA STUDIO.Keeps each specialist loaded in VRAM and executes jobs from BASE/jobs.Writes BASE/results/<id>.json. No time limit."""import json, os, re, sys, time, tracebackfrom pathlib import Pathsys.path.insert(0, "/marimo/ai_studio")import torchfrom studio_core import (BASE, CHARACTER, VOICE, SEED, DTYPE_NAME, JOBS, JOBS_DONE, RESULTS, LOGS, build_image_prompt, load_refinements, save_refinements)
DTYPE = getattr(torch, DTYPE_NAME)MODELS = {}PAINTER_ID = "Qwen/Qwen-Image"CRITIC_ID = "Qwen/Qwen2.5-VL-7B-Instruct"
def log(m): line = f"[{time.strftime('%H:%M:%S')}] {m}" print(line, flush=True) with open(LOGS/"daemon.log", "a") as f: f.write(line + "\n")
def vram(): free, total = torch.cuda.mem_get_info(); return f"{free/1e9:.0f}/{total/1e9:.0f}GB"
# ---------- specialists ----------def painter(): if "painter" not in MODELS: from diffusers import QwenImagePipeline log("load Qwen-Image (concept artist) ...") p = QwenImagePipeline.from_pretrained(PAINTER_ID, torch_dtype=DTYPE) p.to("cuda"); p.set_progress_bar_config(disable=True); MODELS["painter"] = p log(f"painter ready {vram()}") return MODELS["painter"]
def brain(): if "brain" not in MODELS: from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor log("load Qwen2.5-VL-7B (critic + director brain) ...") m = Qwen2_5_VLForConditionalGeneration.from_pretrained(CRITIC_ID, torch_dtype=DTYPE, device_map="cuda") pr = AutoProcessor.from_pretrained(CRITIC_ID) MODELS["brain"] = (m, pr); log(f"brain ready {vram()}") return MODELS["brain"]
# ---------- helpers ----------def _json_block(s): m = re.search(r"\{.*\}", s, re.S) if not m: return None try: return json.loads(m.group(0)) except Exception: try: return json.loads(m.group(0).replace("'", '"')) except Exception: return None
def _gen(model, proc, msgs, images=None, max_new_tokens=900): text = proc.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) kw = {"text": [text], "return_tensors": "pt"} if images: kw["images"] = images inputs = proc(**kw).to("cuda") with torch.inference_mode(): out = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False) return proc.batch_decode(out[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)[0].strip()
def _render_one(j, refinements, name): pipe = painter() prompt = build_image_prompt(j.get("shot",""), j.get("outfit",""), j.get("mood",""), refinements) g = torch.Generator(device="cuda").manual_seed(j.get("seed", SEED)) w, h = j.get("w",1024), j.get("h",1536) log(f"render {name} {w}x{h} steps={j.get('steps',30)} {vram()}") t0 = time.time() img = pipe(prompt=prompt, negative_prompt=CHARACTER["negative"], width=w, height=h, num_inference_steps=j.get("steps",30), true_cfg_scale=j.get("cfg",4.0), generator=g).images[0] out = BASE/"assets/img"/name; img.save(out) dt = time.time()-t0; log(f"saved {name} in {dt:.1f}s") return {"file": str(out), "prompt": prompt, "seconds": round(dt,1)}
RUBRIC = ("You are the art director of a virtual-idol IP. Be specific and a little ruthless. " "Judge the render against the CHARACTER BIBLE. Return STRICT JSON only, keys: " "score_identity (0-10), score_beauty (0-10), score_brief (0-10), " "problems (list), fixes (list of concrete prompt phrases to ADD to improve the next render), " "verdict (one sentence).")
def _critique_one(name, task, max_new_tokens=900): from PIL import Image model, proc = brain() img = Image.open(BASE/"assets/img"/name).convert("RGB") user = (f"CHARACTER BIBLE:\n{json.dumps(CHARACTER, ensure_ascii=False, indent=1)}\n\n" f"SHOT BRIEF: {task or 'Critique this render of LYRA.'}\n\n{RUBRIC}") reply = _gen(model, proc, [{"role":"user","content":[{"type":"image","image":img}, {"type":"text","text":user}]}], images=[img], max_new_tokens=max_new_tokens) return reply, _json_block(reply)
# ---------- jobs ----------def job_image(j): rf = j.get("refinements") r = _render_one(j, rf, j["name"]) return {"files": [r["file"]], "prompt": r["prompt"], "seconds": r["seconds"]}
def job_critique(j): reply, parsed = _critique_one(j["image"], j.get("task","")) return {"image": j["image"], "critique": reply, "parsed": parsed}
def job_direct(j): model, proc = brain() log(f"direct: {j['instruction'][:60]}...") reply = _gen(model, proc, [{"role":"user","content":[{"type":"text","text":j["instruction"]}]}], max_new_tokens=j.get("max_new_tokens", 900)) return {"reply": reply}
def job_iterate(j): """render -> critique -> append fixes (learned) -> render again.""" rf = load_refinements() history, learned = [], [] task = j.get("task") or f"Canonical identity shot: {j.get('shot','portrait')}" for r in range(int(j.get("rounds", 2))): name = j["name"] if r == 0 else j["name"].replace(".png", f"_r{r}.png") res = _render_one(j, rf, name) reply, parsed = _critique_one(name, task) fixes = (parsed or {}).get("fixes", []) if isinstance(parsed, dict) else [] scores = {k: (parsed or {}).get(k) for k in ("score_identity","score_beauty","score_brief")} if isinstance(parsed, dict) else {} history.append({"round": r, "file": res["file"], "prompt": res["prompt"], "critique": reply, "parsed": parsed, "scores": scores}) log(f" round {r}: {scores}") if fixes: rf = rf + fixes; learned = learned + fixes if j.get("learn", True) and learned: save_refinements(load_refinements() + learned) log(f"learned {len(learned)} refinements -> {len(load_refinements())} total") return {"history": history, "final": history[-1]["file"], "refinements_file": str(load_refinements())}
def job_evict(j): """Free VRAM so another specialist can use the GPU. The studio shares one card.""" which = j.get("which", "all") names = list(MODELS) if which == "all" else ([which] if isinstance(which, str) else list(which)) for n in names: MODELS.pop(n, None) import gc; gc.collect(); torch.cuda.empty_cache() log(f"evicted {names} -> {vram()}") return {"evicted": names, "vram": vram()}
def job_shutdown(j): Path(LOGS/"daemon.stop").write_text("1"); return {"bye": True}
HANDLERS = {"image": job_image, "critique": job_critique, "direct": job_direct, "iterate": job_iterate, "evict": job_evict, "ping": lambda j: {"pong": True}, "shutdown": job_shutdown}
def main(): (LOGS/"daemon.stop").unlink(missing_ok=True) log(f"daemon up pid={os.getpid()} cuda={torch.cuda.get_device_name(0)} {vram()}") while not (LOGS/"daemon.stop").exists(): found = False for f in sorted(JOBS.glob("*.json")): found = True; jid = f.stem try: j = json.loads(f.read_text()); jid = j.get("id", jid) h = HANDLERS.get(j.get("type")) if h is None: # not ours (e.g. a tts job) -> leave it for another daemon time.sleep(0.5); continue res = h(j) res = {"id": jid, "status": "ok", **(res or {})} except Exception as e: res = {"id": jid, "status": "error", "error": f"{type(e).__name__}: {e}", "trace": traceback.format_exc()[-1500:]} log("FAILED " + res["error"]) tmp = RESULTS/f".{res['id']}.tmp"; tmp.write_text(json.dumps(res, ensure_ascii=False, indent=2)) tmp.rename(RESULTS/f"{res['id']}.json"); f.rename(JOBS_DONE/f.name) log(f"done {res['id']} status={res['status']}") if not found: time.sleep(1)
if __name__ == "__main__": main()12345678910111213141516171819202122232425import sys, json, tracebackfrom pathlib import Pathimport numpy as np, soundfile as sf, torchfrom qwen_tts import Qwen3TTSModelB = Path("/marimo/ai_studio")model = Qwen3TTSModel.from_pretrained(str(B/"models"/"lyra-voice-cantonese"), device_map="cuda", dtype=torch.bfloat16)langs = model.get_supported_languages(); spks = model.get_supported_speakers()print("LANGS:", langs, flush=True)print("SPEAKERS:", spks, flush=True)default_spk = (spks[0] if isinstance(spks, (list, tuple)) and spks else spks)spec = json.loads(Path(sys.argv[1]).read_text())for it in spec: try: spk = it.get("speaker") or default_spk kw = dict(text=it["text"], speaker=spk) if it.get("language"): kw["language"] = it["language"] wavs, sr = model.generate_custom_voice(**kw) out = B/"assets/audio"/it["name"] sf.write(str(out), np.asarray(wavs[0]), sr) print("WROTE", out.name, f"{len(np.asarray(wavs[0]))/sr:.2f}s", flush=True) except Exception as e: print("FAIL", it.get("name"), type(e).__name__, e, flush=True) traceback.print_exc()print("TTS_DONE")1[{"name": "lyra_line1.wav", "language": "chinese", "text": "我唔係真人,但我一樣會唱到你心入面。"}, {"name": "lyra_line2.wav", "language": "chinese", "text": "大家好,我係 LYRA,一個嗎機器入面出世嘅歌手。"}, {"name": "lyra_line3.wav", "language": "chinese", "text": "香港嘅夜晩,霓虹燈照住我哋嘅回憶。"}]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""voice_daemon.py - resident Cantonese TTS server for LYRA.Runs in the isolated `envs/voice` environment (qwen-tts, transformers 4.57.3)."""import json, os, sys, time, tracebackfrom pathlib import Pathimport numpy as np, soundfile as sf, torchsys.path.insert(0, "/marimo/ai_studio")from studio_core import BASE, JOBS, JOBS_DONE, RESULTS, LOGS, VOICE_MODEL
MODEL = Nonedef log(m): line = f"[{time.strftime('%H:%M:%S')}] {m}" print(line, flush=True) with open(LOGS/"voice_daemon.log", "a") as f: f.write(line + "\n")
def get_model(): global MODEL if MODEL is None: from qwen_tts import Qwen3TTSModel log("load Qwen3-TTS + Cantonese LoRA ...") MODEL = Qwen3TTSModel.from_pretrained(str(VOICE_MODEL), device_map="cuda", dtype=torch.bfloat16) log(f"voice ready | speakers={MODEL.get_supported_speakers()} | langs={MODEL.get_supported_languages()}") return MODEL
def job_tts(j): m = get_model() spk = j.get("speaker") or (m.get_supported_speakers() or [None])[0] kw = dict(text=j["text"], speaker=spk, language=j.get("language") or "chinese") if j.get("instruct"): kw["instruct"] = j["instruct"] log(f"tts '{j['name']}' spk={spk} :: {j['text'][:30]}") t0 = time.time() wavs, sr = m.generate_custom_voice(**kw) out = BASE/"assets"/"audio"/j["name"] sf.write(str(out), np.asarray(wavs[0]), sr) dur = len(np.asarray(wavs[0]))/sr log(f"wrote {out.name} {dur:.2f}s in {time.time()-t0:.1f}s") return {"files": [str(out)], "seconds": round(dur,2), "speaker": spk}
HANDLERS = {"tts": job_tts, "ping": lambda j: {"pong": True}}
def main(): log(f"voice daemon up pid={os.getpid()}") while True: found = False for f in sorted(JOBS.glob("*.json")): try: j = json.loads(f.read_text()) except Exception: continue if j.get("type") not in HANDLERS: # not ours -> leave it continue found = True; jid = j.get("id", f.stem) try: res = {"id": jid, "status": "ok", **(HANDLERS[j["type"]](j) or {})} except Exception as e: res = {"id": jid, "status": "error", "error": f"{type(e).__name__}: {e}", "trace": traceback.format_exc()[-1200:]} log("FAILED " + res["error"]) tmp = RESULTS/f".{res['id']}.tmp"; tmp.write_text(json.dumps(res, ensure_ascii=False, indent=2)) tmp.rename(RESULTS/f"{res['id']}.json"); f.rename(JOBS_DONE/f.name) log(f"done {res['id']} status={res['status']}") if not found: time.sleep(1)
if __name__ == "__main__": main()123456789101112#!/bin/bash# usage: yue_sing.sh <lyrics_txt> <genre_txt> <out_dir> <segments> <seed>cd /marimo/ai_studio/vendor/YuE/inference || exit 1export PYTHONPATH=/marimo/ai_studio/vendor/YuE/inferenceexport PYTHONSAFEPATH=export YUES_NO_COMPILE=1exec /marimo/ai_studio/envs/music/bin/python infer.py \ --stage1_model m-a-p/YuE-s1-7B-anneal-en-cot \ --stage2_model m-a-p/YuE-s2-1B-general \ --genre_txt "$2" --lyrics_txt "$1" \ --run_n_segments "$4" --stage2_batch_size 4 \ --output_dir "$3" --cuda_idx 0 --seed "$5".gitattributes+19
README.mdAdded+105
assets/audio/lyra_line1.wavAdded+3
assets/audio/lyra_line2.wavAdded+3
assets/audio/lyra_line3.wavAdded+3
assets/audio/lyra_sig.wavAdded+3
assets/img/lyra_closeup.pngAdded

Large File Pointer Details
- SHA256: 7e7765dd9514f8dc9dabb6afc47b913ed2b6b557e076022546b8991dbf7cb072
- Pointer size: 132 Bytes
- Size of remote file: 1.68 MB
assets/img/lyra_hero.pngAdded

Large File Pointer Details
- SHA256: 99e92e53761ac89848ed6b9942abc892c971325179b699c86d7910c50f4f0da4
- Pointer size: 132 Bytes
- Size of remote file: 1.56 MB
assets/img/lyra_hero_r1.pngAdded

Large File Pointer Details
- SHA256: 5b0c5577b1d1fd5b1180d861ad1d273bc5b6048909fbb4a63cab6ce7ea633e4b
- Pointer size: 132 Bytes
- Size of remote file: 1.59 MB
assets/img/lyra_main.pngAdded

Large File Pointer Details
- SHA256: acb74feabc25824ba03a730a50008444a94b69e46b5585f6f92ecb4650d74b96
- Pointer size: 132 Bytes
- Size of remote file: 1.54 MB
assets/img/lyra_poster.pngAdded

Large File Pointer Details
- SHA256: 7a3da8481c2bc707679c4f416965c55c11c5788c7a7745806b63aa13961e20ca
- Pointer size: 132 Bytes
- Size of remote file: 1.63 MB
assets/img/lyra_poster_r1.pngAdded

Large File Pointer Details
- SHA256: 2b0f0911cf6508da2bd2590fa20d6cb45c60959ac0e8c3202b00638a67e2a94e
- Pointer size: 132 Bytes
- Size of remote file: 1.63 MB
assets/img/lyra_quarter.pngAdded

Large File Pointer Details
- SHA256: 920398274ee07629695af3cde514813d049517348c40f96ecd3e2b315fdaa003
- Pointer size: 132 Bytes
- Size of remote file: 1.6 MB
assets/img/lyra_stage.pngAdded

Large File Pointer Details
- SHA256: c085b3b02770f15b127a342e1bcb14749368a36f83fc5f884a8fcb3f1e540cc5
- Pointer size: 132 Bytes
- Size of remote file: 1.73 MB
assets/img/lyra_titlecard.pngAdded

Large File Pointer Details
- SHA256: 9a4a62192fdd3b06ca3af2b640f7b2d8851683c53bf9b262709e5fa7444a2670
- Pointer size: 132 Bytes
- Size of remote file: 1.82 MB
assets/music/song1_instrumental.wavAdded+3
assets/music/song1_mix.mp3Added+3
assets/music/song1_vocal.wavAdded+3
assets/video/lyra_perf_song1.mp4Added+3
assets/video/lyra_talk_sig.mp4Added+3
assets/video/neon_me_mv.mp4Added+3
character/genre_canto.txtAdded+1
character/genre_star.txtAdded+1
character/lyrics_canto.txtAdded+21
character/lyrics_star.txtAdded+27
character/refinements.jsonAdded+8
character/studio_core.pyAdded+183
scripts/asr_check.pyAdded+21
scripts/edit_mv.shAdded+18
scripts/merge_voice.shAdded+22
scripts/run_yue.shAdded+16
scripts/setup_cosy.shAdded+13
scripts/setup_lipsync.shAdded+8
scripts/setup_music.shAdded+9
scripts/setup_voice.shAdded+9
scripts/studio_daemon.pyAdded+170
scripts/tts_say.pyAdded+25
scripts/tts_spec.jsonAdded+1
scripts/voice_daemon.pyAdded+62
scripts/yue_sing.shAdded+12