import re import shutil import subprocess import tempfile import time from typing import Optional import gradio as gr from gradio_client import Client, handle_file # ── Voice presets ────────────────────────────────────────────────────────── VOICE_PRESETS = { "ស្ងប់ស្ងាត់": "calm female Khmer narrator, warm and natural, gentle conversational pace, human breathing, no AI tone", "សារព័ត៌មាន": "mature female broadcaster, professional and grounded, clear Khmer articulation, natural emphasis, human delivery", "បុរសសប្បុរស": "calm male narrator, deep resonant voice, measured natural Khmer speech, human warmth, relaxed", "អ្នកអាន": "professional male news anchor, authoritative clear Khmer, natural pauses and intonation, real human voice", "រីករាយ": "young energetic female voice, friendly natural Khmer, upbeat human tone, conversational and lively", } CUSTOM_KEY = "Custom" ALL_KEYS = list(VOICE_PRESETS.keys()) + [CUSTOM_KEY] OFFICIAL_SPACE = "openbmb/VoxCPM-Demo" _api_client: Optional[Client] = None def _get_client() -> Client: global _api_client if _api_client is None: _api_client = Client(OFFICIAL_SPACE) return _api_client # ── Text splitter (Khmer-aware, 200 char chunks) ─────────────────────────── # Split on: Khmer sentence-end markers, ellipsis (... …), English period # followed by whitespace/end (not decimals or abbreviations mid-run), and # newlines. The lookahead-guarded `\.` is what keeps English prose from # collapsing into runs that get hard-sliced mid-word. _SENT_END = re.compile(r"([។!?]+|\.{2,}|\.(?=\s|$)|…|\n+)") MAX_CHUNK = 200 def _strip_md(text: str) -> str: """Remove markdown formatting markers before TTS (** * ~~ # > etc.).""" text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text) # links → display text text = re.sub(r'\*{1,3}|_{1,2}|~~|`+', '', text) text = re.sub(r'^#{1,6}\s*|^>\s*', '', text, flags=re.MULTILINE) return text def _split(text: str) -> list[str]: text = text.strip() if not text: return [] parts = _SENT_END.split(text) sentences: list[str] = [] i = 0 while i < len(parts): s = parts[i].strip() if i + 1 < len(parts) and _SENT_END.fullmatch(parts[i + 1].strip()): # Keep the sentence-ending marker attached to its sentence s = (s + parts[i + 1]).strip() i += 2 else: i += 1 if s: sentences.append(s) result: list[str] = [] current = "" for s in sentences: if len(current) + len(s) + 1 <= MAX_CHUNK: current = f"{current} {s}".strip() if current else s else: if current: result.append(current) # Hard-split sentences that are still over MAX_CHUNK while len(s) > MAX_CHUNK: result.append(s[:MAX_CHUNK]) s = s[MAX_CHUNK:] current = s if current: result.append(current) return [s for s in result if s.strip()] # ── Audio concat via ffmpeg ──────────────────────────────────────────────── SR = 48_000 def _norm(src: str, dst: str) -> None: subprocess.run( ["ffmpeg", "-y", "-i", src, "-ar", str(SR), "-ac", "1", "-acodec", "pcm_s16le", dst], capture_output=True, check=True, ) def _silence(ms: int, dst: str) -> None: subprocess.run( ["ffmpeg", "-y", "-f", "lavfi", "-i", f"anullsrc=r={SR}:cl=mono", "-t", f"{ms/1000:.3f}", dst], capture_output=True, check=True, ) def _concat(segs: list[str], pause_ms: int, out: str) -> None: with tempfile.TemporaryDirectory() as tmp: files: list[str] = [] for i, seg in enumerate(segs): n = f"{tmp}/n{i:04d}.wav" _norm(seg, n) files.append(n) if i < len(segs) - 1: s = f"{tmp}/s{i:04d}.wav" _silence(pause_ms, s) files.append(s) lst = f"{tmp}/list.txt" with open(lst, "w") as f: for p in files: f.write(f"file '{p}'\n") subprocess.run( ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", lst, "-c", "copy", out], capture_output=True, check=True, ) # ── Core generate function ───────────────────────────────────────────────── def generate( text: str, voice_key: str, custom_voice: str, cfg: float, progress=gr.Progress(), ) -> str: voice = custom_voice.strip() if voice_key == CUSTOM_KEY else VOICE_PRESETS.get(voice_key, "") if not voice: voice = list(VOICE_PRESETS.values())[0] chunks = _split(text) if not chunks: raise gr.Error("សូមបញ្ចូលអត្ថបទ — please enter some text.") client = _get_client() tmpdir = tempfile.mkdtemp(prefix="kv_") ref_path: Optional[str] = None segs: list[str] = [] try: for i, chunk in enumerate(chunks): progress(i / len(chunks), desc=f"កំពុងបង្កើត {i+1} / {len(chunks)} chunks…") out = f"{tmpdir}/seg_{i:04d}.wav" result = client.predict( text_input=chunk, control_instruction=voice if ref_path is None else "", reference_wav_path_input=handle_file(ref_path) if ref_path else None, use_prompt_text=False, prompt_text_input="", cfg_value_input=cfg, do_normalize=True, denoise=False, api_name="/generate", ) shutil.copy(result, out) if ref_path is None: ref_path = out segs.append(out) progress(1.0, desc="កំពុងភ្ជាប់សំឡេង…") final = f"{tmpdir}/output.wav" if len(segs) == 1: shutil.copy(segs[0], final) else: _concat(segs, 80, final) dst = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name shutil.copy(final, dst) return dst finally: shutil.rmtree(tmpdir, ignore_errors=True) def on_voice_change(key: str): if key == CUSTOM_KEY: return gr.update(visible=True, value="") return gr.update(visible=False, value=VOICE_PRESETS.get(key, "")) # ── New helpers: voice resolution, interview parsing, generators ─────────── # Matches: **Name (Role)៖** or **Name:** (markdown bold, role optional; Khmer ៖, fullwidth :, or ASCII colon) _SPEAKER_MD = re.compile( r"^\*\*\s*([^*(៖::\[\n]+?)(?:\s*\([^)]*\))?\s*[៖::]\*?\*?\s*(.*)" ) # Matches: [Name]: text _SPEAKER_BRACKET = re.compile(r"^\[([^\]]+)\]\s*[៖::]\s*(.*)") # Strips inline stage directions like *(text)* _INLINE_STAGE = re.compile(r"\*\([^)]*\)\*") # Lines to skip entirely _SKIP_LINE = re.compile(r"^\s*(?:#{1,6}\s|---+|\*{1,2}[^*]|\s*[–—]\s|>\s|\*\s+)") def _find_cloned(name: str, cloned_voices: list[dict]) -> Optional[dict]: for v in cloned_voices or []: if v.get("name") == name: return v return None def _resolve_voice( voice_key: str, custom_voice: str, cloned_voices: list[dict], ) -> tuple[str, Optional[str]]: """Return (description, reference_path). One of them is populated.""" if voice_key == CUSTOM_KEY: desc = (custom_voice or "").strip() or list(VOICE_PRESETS.values())[0] return desc, None if voice_key in VOICE_PRESETS: return VOICE_PRESETS[voice_key], None cv = _find_cloned(voice_key, cloned_voices) if cv: return cv.get("description", ""), cv.get("path") return list(VOICE_PRESETS.values())[0], None def parse_interview(text: str) -> list[tuple[str, str]]: """Parse podcast/interview scripts into (speaker_name, dialogue_text) pairs. Handles **Name (Role):** and [Name]: formats. Strips inline *(stage)* directions. Speaker names are extracted without their role suffix. """ out: list[tuple[str, str]] = [] cur_speaker: Optional[str] = None cur_buf: list[str] = [] def flush(): if cur_speaker and cur_buf: out.append((cur_speaker, " ".join(cur_buf).strip())) for raw in (text or "").splitlines(): # Try bold markdown format first, then bracket format m = _SPEAKER_MD.match(raw) or _SPEAKER_BRACKET.match(raw) if m: flush() cur_speaker = m.group(1).strip() tail = _INLINE_STAGE.sub("", m.group(2)).strip() cur_buf = [tail] if tail else [] continue line = raw.strip() if not line: continue # Skip structural/stage-direction lines when no speaker is active if _SKIP_LINE.match(raw): continue # Continuation of current speaker's dialogue if cur_speaker is not None: cleaned = _INLINE_STAGE.sub("", line).strip() if cleaned: cur_buf.append(cleaned) flush() return [(sp, tx) for sp, tx in out if tx] def _all_voice_keys(cloned_voices: list[dict]) -> list[str]: extras = [v["name"] for v in (cloned_voices or []) if v.get("name")] return list(VOICE_PRESETS.keys()) + extras + [CUSTOM_KEY] def on_voice_select(key: str, cloned_voices: list[dict]): if key == CUSTOM_KEY: return ( gr.update(visible=True, value=""), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False, value=""), ) if key in VOICE_PRESETS: desc = VOICE_PRESETS[key] else: cv = _find_cloned(key, cloned_voices) desc = (cv or {}).get("description", "") if cv else "" return ( gr.update(visible=False, value=""), gr.update(visible=True, value=f'
{desc}
'), gr.update(visible=False), gr.update(visible=False, value=""), ) def save_cloned_voice( name: str, audio_path: Optional[str], cloned_voices: list[dict], ): name = (name or "").strip() if not name: raise gr.Error("Give the voice a name first.") if not audio_path: raise gr.Error("Upload a reference audio clip first.") # Persist the upload to a stable temp path dst = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name shutil.copy(audio_path, dst) new_voices = list(cloned_voices or []) # Replace by name if it already exists new_voices = [v for v in new_voices if v.get("name") != name] new_voices.append({ "name": name, "path": dst, "description": f"Cloned voice: {name}", }) keys = _all_voice_keys(new_voices) return ( new_voices, gr.update(choices=keys, value=name), gr.update(value=""), gr.update(value=None), gr.update(choices=keys), gr.update(choices=keys), gr.update(choices=keys), gr.update(choices=keys), gr.update(choices=keys), gr.update(choices=keys), ) def _tts_segment( client: Client, text: str, description: str, ref_path: Optional[str], cfg: float, out_path: str, ) -> str: result = client.predict( text_input=text, control_instruction=description if ref_path is None else "", reference_wav_path_input=handle_file(ref_path) if ref_path else None, use_prompt_text=False, prompt_text_input="", cfg_value_input=cfg, do_normalize=True, denoise=False, api_name="/generate", ) shutil.copy(result, out_path) return out_path def do_narrate( text: str, voice_key: str, custom_voice: str, cloned_voices: list[dict], cfg: float, progress=gr.Progress(), ) -> str: description, ref_path = _resolve_voice(voice_key, custom_voice, cloned_voices) chunks = _split(_strip_md(text)) if not chunks: raise gr.Error("សូមបញ្ចូលអត្ថបទ — please enter some text.") client = _get_client() tmpdir = tempfile.mkdtemp(prefix="kv_") cur_ref = ref_path segs: list[str] = [] try: for i, chunk in enumerate(chunks): progress(i / len(chunks), desc=f"កំពុងបង្កើត {i+1} / {len(chunks)} chunks…") out = f"{tmpdir}/seg_{i:04d}.wav" _tts_segment(client, chunk, description, cur_ref, cfg, out) if cur_ref is None: cur_ref = out segs.append(out) progress(1.0, desc="កំពុងភ្ជាប់សំឡេង…") final = f"{tmpdir}/output.wav" if len(segs) == 1: shutil.copy(segs[0], final) else: _concat(segs, 80, final) dst = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name shutil.copy(final, dst) return dst finally: shutil.rmtree(tmpdir, ignore_errors=True) def _spk_updates(n: int): return ( [gr.update(visible=(i < n)) for i in range(6)] + [gr.update(interactive=(n < 6)), gr.update(interactive=(n > 1))] ) def add_spk(n: int): n = min(n + 1, 6) return [n] + _spk_updates(n) def rm_spk(n: int): n = max(n - 1, 1) return [n] + _spk_updates(n) def do_interview( script: str, sp1_name: str, sp1_voice: str, sp2_name: str, sp2_voice: str, sp3_name: str, sp3_voice: str, sp4_name: str, sp4_voice: str, sp5_name: str, sp5_voice: str, sp6_name: str, sp6_voice: str, cloned_voices: list[dict], cfg: float, progress=gr.Progress(), ) -> str: speakers = [] for name, voice in [ (sp1_name, sp1_voice), (sp2_name, sp2_voice), (sp3_name, sp3_voice), (sp4_name, sp4_voice), (sp5_name, sp5_voice), (sp6_name, sp6_voice), ]: nm = (name or "").strip() if not nm: continue desc, ref = _resolve_voice(voice, "", cloned_voices) speakers.append({"name": nm, "desc": desc, "ref": ref}) if not speakers: raise gr.Error("Add at least one speaker name.") turns = parse_interview(script) if not turns: raise gr.Error("Write the script as [Speaker]: text lines.") # Map turn speaker names to configured speakers (case-insensitive fallback) by_name = {s["name"]: s for s in speakers} lc = {s["name"].lower(): s for s in speakers} client = _get_client() tmpdir = tempfile.mkdtemp(prefix="kvi_") # Track first-output ref per speaker so subsequent turns clone from it speaker_state: dict[str, dict] = {s["name"]: {"ref": s["ref"]} for s in speakers} segs: list[str] = [] try: total = len(turns) for i, (sp_name, line) in enumerate(turns): progress(i / total, desc=f"កំពុងបង្កើត {i+1} / {total}…") speaker = by_name.get(sp_name) or lc.get(sp_name.lower()) if speaker is None: # Unknown speaker label, fall back to first speaker speaker = speakers[0] state = speaker_state[speaker["name"]] out = f"{tmpdir}/turn_{i:04d}.wav" _tts_segment(client, _strip_md(line), speaker["desc"], state["ref"], cfg, out) if state["ref"] is None: state["ref"] = out segs.append(out) progress(1.0, desc="កំពុងភ្ជាប់សំឡេង…") final = f"{tmpdir}/output.wav" if len(segs) == 1: shutil.copy(segs[0], final) else: _concat(segs, 600, final) dst = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name shutil.copy(final, dst) return dst finally: shutil.rmtree(tmpdir, ignore_errors=True) # ── CSS ──────────────────────────────────────────────────────────────────── CSS = """ :root { --bg: oklch(98.5% 0.005 150); --surface: oklch(100% 0 0); --surface-2: oklch(97% 0.008 150); --border: oklch(92% 0.008 150); --border-soft: oklch(94.5% 0.006 150); --text: oklch(22% 0.02 150); --text-soft: oklch(48% 0.015 150); --text-muted: oklch(60% 0.012 150); --matcha: oklch(50% 0.19 152); --matcha-d: oklch(42% 0.19 152); --matcha-tint: oklch(94% 0.04 152); --matcha-tint-2: oklch(90% 0.06 152); } html, body, .gradio-container { background: var(--bg) !important; color: var(--text) !important; font-family: system-ui, -apple-system, "Segoe UI", "Noto Sans Khmer", sans-serif !important; } /* HuggingFace embeds the app in an auto-height iframe that watches document.body.scrollHeight to resize itself. overflow:hidden does NOT prevent scrollHeight from growing — it only clips visually. position:fixed removes elements from document flow entirely, so they contribute zero to scrollHeight and the iframe never grows. */ html, body { overflow: hidden !important; max-width: 100% !important; } .gradio-container { max-width: 100% !important; width: 100% !important; padding: 0 !important; margin: 0 !important; overflow: hidden !important; box-sizing: border-box !important; } .gradio-container > .main, .gradio-container .contain { max-width: 100% !important; padding: 0 !important; } footer, .footer { display: none !important; } /* Footer — fixed full-width bar at viewport bottom. left:0 + right:0 spans the viewport correctly. Avoid width:100vw which includes scrollbar width and creates a horizontal overflow cascade. */ .kv-footer { position: fixed; bottom: 0; left: 0; right: 0; box-sizing: border-box; z-index: 100; display: flex; align-items: center; justify-content: center; gap: 0.75rem; height: 36px; padding: 0 1rem; border-top: 1px solid var(--border); background: var(--surface); } .kv-footer .brand { font-weight: 600; font-size: 0.8rem; color: var(--text-muted); } .kv-footer .meta { font-size: 0.75rem; color: var(--text-muted); opacity: 0.6; } /* Main row: position:fixed removes it from document flow so scrollHeight stays at zero — HuggingFace's iframe resizer never sees content growth. top/right/bottom/left pin it to exactly the viewport minus the footer. */ #app-row { position: fixed !important; top: 0 !important; left: 0 !important; right: 0 !important; bottom: 36px !important; display: flex !important; flex-wrap: nowrap !important; gap: 0 !important; align-items: stretch !important; min-width: 0 !important; box-sizing: border-box !important; overflow: hidden !important; z-index: 1 !important; } /* Every direct flex child of #app-row must allow itself to shrink below its intrinsic content width — otherwise editors/canvases inside push the row past viewport and trigger a horizontal scrollbar cascade. */ #app-row > * { min-width: 0 !important; box-sizing: border-box !important; } /* Voice panel uses CSS Grid (not flex) for the column layout. Grid's overflow behaviour is simpler: items take their natural heights; if the total exceeds the container, overflow-y: auto scrolls cleanly. Flex-direction:column + overflow:auto has a long-standing browser bug where flex-shrink or flex-grow items cause scrollHeight to equal clientHeight even when content overflows, making the panel non-scrollable. */ #voice-panel { background: var(--surface); border-right: 1px solid var(--border); padding: 0 !important; /* Grid: title → voice-list → voice-desc → [save btn] → spacer → accordion */ display: grid !important; grid-template-rows: auto auto auto auto 1fr auto !important; overflow-x: hidden; overflow-y: auto; /* Lock width (as a flex item in #app-row) */ flex: 0 0 300px !important; min-width: 300px !important; max-width: 300px !important; width: 300px !important; } /* Any descendant of the locked 300px panel must respect it. */ #voice-panel * { max-width: 100% !important; box-sizing: border-box !important; } #main-panel { background: var(--bg); padding: 1rem 1.25rem 1.5rem !important; display: flex; flex-direction: column; gap: 0.75rem; min-width: 0 !important; max-width: 100% !important; box-sizing: border-box !important; overflow-y: auto; flex: 1 1 auto; } /* All direct children of the main panel must also tolerate shrinking. */ #main-panel > * { min-width: 0 !important; max-width: 100% !important; box-sizing: border-box !important; } .panel-title { font-size: 0.78rem; font-weight: 600; letter-spacing: 0.02em; color: var(--text-soft); padding: 0.875rem 1rem 0.5rem; } /* Voice list as inbox rows */ .voice-list { border: none !important; background: transparent !important; padding: 0 !important; margin: 0 !important; } .voice-list .wrap, .voice-list > div { display: flex !important; flex-direction: column !important; flex-wrap: nowrap !important; gap: 0 !important; max-height: 280px; overflow-y: auto; padding: 0 !important; } /* Prevent Gradio from switching the radio list to a multi-column grid when cloned voices are added (grid-template-columns override covers both CSS grid and column-count layouts). */ .voice-list, .voice-list .wrap, .voice-list .wrap > * { grid-template-columns: 1fr !important; columns: 1 !important; } .voice-list label { width: 100% !important; margin: 0 !important; padding: 0 1rem !important; height: 42px; display: flex !important; align-items: center; gap: 0.625rem; font-size: 0.875rem !important; color: var(--text); border: none !important; border-bottom: 1px solid var(--border-soft) !important; border-radius: 0 !important; background: transparent !important; cursor: pointer; transition: background 0.12s ease; } .voice-list label:hover { background: var(--surface-2) !important; } .voice-list label input[type="radio"] { appearance: none; width: 6px; height: 6px; border-radius: 999px; background: var(--border); border: none; margin: 0; } .voice-list label:has(input:checked) { background: var(--matcha-tint) !important; color: var(--matcha-d) !important; font-weight: 600; } .voice-list label:has(input:checked) input[type="radio"] { background: var(--matcha) !important; } #voice-panel .html-container { padding: 0 !important; } .voice-desc-area { /* grid-row 3: 1fr — fills available space, pushing accordion to the bottom */ min-height: 2.5rem; padding: 0.625rem 0.875rem !important; font-size: 0.78rem; color: var(--text-soft); border-bottom: 1px solid var(--border-soft); } .voice-desc { line-height: 1.45; } /* Clone accordion toggle button */ #voice-panel .label-wrap, #voice-panel button.label-wrap { font-size: 0.82rem !important; font-weight: 500 !important; color: var(--text-soft) !important; padding: 0.625rem 1rem !important; } /* Clone accordion block — flat styling, pinned at bottom of sidebar. Grid row 4 (auto) takes its natural height. margin: 0 overrides Gradio's auto-margin class. */ #voice-panel .block:last-of-type { margin-top: auto !important; margin-bottom: 0 !important; margin-left: 0 !important; margin-right: 0 !important; border: none !important; border-top: 1px solid var(--border-soft) !important; background: transparent !important; border-radius: 0 !important; } /* Custom voice input — blends with sidebar, replaces voice description area. Sits in grid row 3 (1fr) so it fills available space just like voice-desc-area. */ .custom-voice-input { border: none !important; background: transparent !important; padding: 0 !important; margin: 0 !important; align-self: start !important; } .custom-voice-input textarea { border: none !important; border-bottom: 1px solid var(--border-soft) !important; border-radius: 0 !important; background: transparent !important; padding: 0.625rem 0.875rem !important; font-size: 0.78rem !important; color: var(--text) !important; line-height: 1.55 !important; resize: none !important; min-height: 48px !important; max-height: 80px !important; font-family: inherit !important; width: 100% !important; box-sizing: border-box !important; } .custom-voice-input textarea:focus { outline: none !important; box-shadow: none !important; } .custom-voice-input textarea::placeholder { color: var(--text-muted) !important; font-style: italic; } .custom-save-btn { padding: 0.4rem 0.875rem !important; margin: 0 !important; background: transparent !important; border: none !important; } #voice-panel .custom-save-btn button, .custom-save-btn button { display: block !important; width: 100% !important; margin: 0 !important; height: 28px !important; border-radius: 4px !important; font-size: 0.78rem !important; background: var(--matcha) !important; color: oklch(99% 0.005 152) !important; border: none !important; box-shadow: none !important; font-family: inherit !important; cursor: pointer !important; transition: background 0.1s !important; } .custom-save-btn button:hover { background: var(--matcha-d) !important; } .custom-save-status { padding: 0 0.875rem 0.25rem !important; margin: 0 !important; font-size: 0.75rem !important; min-height: 0 !important; background: transparent !important; border: none !important; } .saved-tick { color: var(--matcha) !important; font-weight: 600 !important; } /* Main area: tabs */ #mode-tabs { min-width: 0 !important; max-width: 100% !important; box-sizing: border-box !important; } #mode-tabs > *, #mode-tabs .tabitem, #mode-tabs [role="tabpanel"] { min-width: 0 !important; max-width: 100% !important; box-sizing: border-box !important; } #mode-tabs .tab-nav, #mode-tabs > div > .tab-nav { border-bottom: 1px solid var(--border) !important; background: transparent !important; padding-left: 0 !important; } #mode-tabs .tab-nav button.selected { color: var(--matcha-d) !important; border-bottom: 2px solid var(--matcha) !important; font-weight: 600 !important; background: transparent !important; } #mode-tabs .tab-nav button { color: var(--text-muted) !important; background: transparent !important; font-size: 0.9rem !important; padding: 0.625rem 1rem !important; } /* Audio player */ .kv-audio { background: var(--surface) !important; border: 1px solid var(--border) !important; border-radius: 12px !important; padding: 0.75rem !important; box-sizing: border-box !important; max-width: 100% !important; min-width: 0 !important; overflow: hidden !important; } /* Lock the waveform canvas: it renders 0-wide at first, then resizes when audio loads — that resize was causing visible layout shift. */ .kv-audio canvas { min-height: 80px !important; width: 100% !important; max-width: 100% !important; display: block !important; } .kv-audio audio { width: 100% !important; max-width: 100% !important; } /* Audio player control bar: align everything on one row */ .kv-audio .controls, .kv-audio [class*="controls"] { display: flex !important; align-items: center !important; justify-content: center !important; gap: 0.75rem !important; flex-wrap: nowrap !important; } /* 1x speed — realign it with the other buttons */ .kv-audio .speed, .kv-audio button.speed, .kv-audio [class*="speed"] { display: inline-flex !important; align-items: center !important; justify-content: center !important; align-self: center !important; height: 2rem !important; padding: 0 0.5rem !important; border: 1px solid var(--border) !important; border-radius: 6px !important; font-size: 0.78rem !important; color: var(--text-soft) !important; background: var(--surface) !important; } /* Play / pause button — matcha green */ .kv-audio button.play-pause, .kv-audio [aria-label="Play"], .kv-audio [aria-label="Pause"], .kv-audio .play-pause-button, .kv-audio button[class*="play-pause"] { display: inline-flex !important; align-items: center !important; justify-content: center !important; width: 2.5rem !important; height: 2.5rem !important; border-radius: 50% !important; background: var(--matcha) !important; border: none !important; color: oklch(99% 0.004 150) !important; box-shadow: 0 2px 6px oklch(50% 0.19 152 / 0.35) !important; } .kv-audio button.play-pause svg, .kv-audio [aria-label="Play"] svg, .kv-audio [aria-label="Pause"] svg, .kv-audio .play-pause-button svg, .kv-audio button[class*="play-pause"] svg { fill: oklch(99% 0.004 150) !important; color: oklch(99% 0.004 150) !important; width: 16px !important; height: 16px !important; } /* Fallback: force any SVG path inside audio controls to show */ .kv-audio button.play-pause path, .kv-audio button[class*="play-pause"] path { fill: oklch(99% 0.004 150) !important; stroke: oklch(99% 0.004 150) !important; } /* Rewind / skip buttons — matcha tint */ .kv-audio [aria-label*="rewind"], .kv-audio [aria-label*="skip"], .kv-audio button[class*="skip"], .kv-audio button[class*="rewind"] { color: var(--matcha-d) !important; } .kv-audio [aria-label*="rewind"] svg, .kv-audio [aria-label*="skip"] svg { fill: var(--matcha-d) !important; } /* Duration: give it breathing room so it's not covered by download icons */ .kv-audio .timestamps, .kv-audio [class*="timestamps"], .kv-audio .time-container { padding-right: 4.5rem !important; } /* Download/share icons: keep them from floating over the time */ .kv-audio .icon-button-wrapper, .kv-audio [class*="icon-button-wrapper"], .kv-audio .action-buttons { top: 0.5rem !important; right: 0.5rem !important; } /* Textareas / inputs */ #main-panel textarea, #main-panel input[type="text"] { background: var(--surface) !important; border: 1px solid var(--border) !important; border-radius: 10px !important; color: var(--text) !important; font-family: inherit !important; font-size: 0.92rem !important; padding: 0.75rem 0.875rem !important; line-height: 1.55 !important; } #main-panel textarea:focus, #main-panel input[type="text"]:focus { outline: none !important; border-color: var(--matcha) !important; box-shadow: 0 0 0 3px var(--matcha-tint) !important; } /* Bottom bar */ #narrate-bar, #interview-bar { display: flex !important; align-items: center; gap: 0.75rem; padding-top: 0.5rem; } .cfg-accordion { flex: 1; background: transparent !important; border: none !important; } .cfg-accordion .label-wrap, .cfg-accordion button.label-wrap { font-size: 0.8rem !important; color: var(--text-muted) !important; padding: 0.5rem 0.75rem !important; background: transparent !important; border: 1px solid var(--border) !important; border-radius: 8px !important; } /* Primary button */ button.kv-btn, .kv-btn button { height: 44px !important; background: var(--matcha) !important; color: oklch(99% 0.004 150) !important; border: none !important; border-radius: 10px !important; font-weight: 650 !important; font-size: 0.95rem !important; letter-spacing: -0.01em !important; padding: 0 1.5rem !important; cursor: pointer; box-shadow: 0 2px 8px oklch(50% 0.19 152 / 0.38), 0 1px 2px oklch(50% 0.19 152 / 0.2) !important; transition: background 0.12s ease, box-shadow 0.12s ease, transform 0.07s ease !important; } button.kv-btn:hover, .kv-btn button:hover { background: var(--matcha-d) !important; box-shadow: 0 4px 16px oklch(50% 0.19 152 / 0.45), 0 2px 4px oklch(50% 0.19 152 / 0.25) !important; } button.kv-btn:active, .kv-btn button:active { transform: translateY(1px) !important; } button.kv-btn:disabled, .kv-btn button:disabled { background: oklch(88% 0.006 150) !important; color: var(--text-muted) !important; opacity: 1; cursor: not-allowed; box-shadow: none !important; } .kv-btn button:active { transform: translateY(1px) !important; box-shadow: 0 1px 4px oklch(50% 0.19 152 / 0.3) !important; } .kv-btn button:disabled { background: oklch(88% 0.006 150) !important; color: var(--text-muted) !important; opacity: 1; cursor: not-allowed; box-shadow: none !important; } /* Contain the audio waveform canvas inside the clone accordion so it never pushes the sidebar wider. overflow:hidden on the whole .block was clipping accordion content vertically in Firefox/Safari — target only the canvas. */ #voice-panel canvas, #voice-panel audio, #voice-panel .waveform-container, #voice-panel [data-testid="waveform"] { width: 100% !important; max-width: 100% !important; min-width: 0 !important; overflow: hidden !important; box-sizing: border-box !important; } /* ── Speakers table — Excel-style spreadsheet ────────────────────────────── */ #speakers-form { border: 1px solid oklch(87% 0.009 150) !important; border-radius: 6px !important; overflow: hidden !important; background: var(--surface) !important; box-shadow: 0 1px 4px oklch(0% 0 0 / 0.06) !important; padding: 0 !important; gap: 0 !important; margin-bottom: 0 !important; } /* Strip Gradio's block chrome — the grid lines own all borders */ #speakers-form .block, #speakers-form .prose, #speakers-form > div, #speakers-form > div > div, #speakers-form > .gap { border: none !important; background: transparent !important; box-shadow: none !important; padding: 0 !important; margin: 0 !important; gap: 0 !important; } /* Frozen column-header row */ .speakers-col-header { display: grid !important; grid-template-columns: 1fr 2fr !important; gap: 0 !important; padding: 0 !important; border-bottom: 2px solid oklch(83% 0.01 150) !important; background: oklch(96% 0.007 150) !important; } .speakers-col-header .speakers-label { padding: 0.35rem 0.75rem; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; color: var(--text-muted); } .speakers-col-header .speakers-label.name { border-right: 1px solid oklch(87% 0.009 150) !important; } /* Data rows — two-column grid matching the header */ .speaker-row { display: grid !important; grid-template-columns: 1fr 2fr !important; align-items: stretch !important; gap: 0 !important; padding: 0 !important; margin: 0 !important; border-bottom: 1px solid oklch(93% 0.007 150) !important; background: var(--surface) !important; min-height: 34px !important; } /* Remove Gradio block borders inside rows (column separator handles dividers) */ .speaker-row .block { border: none !important; border-radius: 0 !important; } /* Vertical column separator */ .speaker-row > *:first-child { border-right: 1px solid oklch(93% 0.007 150) !important; } /* Remove dropdown wrapper borders */ .speaker-row .wrap, .speaker-row .wrap-inner, .speaker-row .secondary-wrap { border: none !important; box-shadow: none !important; background: transparent !important; } /* Subtle alternating row tint */ .speaker-row:nth-of-type(even) { background: oklch(98.8% 0.004 150) !important; } /* Toolbar row: add / remove buttons */ .speaker-actions { display: flex !important; align-items: center !important; justify-content: space-between !important; padding: 0.3rem 0.625rem !important; background: oklch(96.5% 0.006 150) !important; border-top: 1px solid oklch(90% 0.008 150) !important; gap: 0.5rem !important; margin: 0 !important; } .speaker-actions button { height: 24px !important; min-width: 0 !important; padding: 0 0.6rem !important; font-size: 0.72rem !important; font-family: inherit !important; border-radius: 3px !important; border: 1px solid oklch(87% 0.009 150) !important; background: var(--surface) !important; color: var(--text-soft) !important; cursor: pointer !important; box-shadow: none !important; transition: color 0.1s, border-color 0.1s, background 0.1s !important; } .speaker-actions .kv-add-spk:hover { color: var(--matcha-d) !important; border-color: var(--matcha) !important; background: var(--matcha-tint) !important; } .speaker-actions .kv-rm-spk:hover { color: oklch(48% 0.18 25) !important; border-color: oklch(75% 0.1 25) !important; background: oklch(97% 0.02 25) !important; } .speaker-actions button:disabled { opacity: 0.35 !important; cursor: not-allowed !important; } /* Cell textarea — flush, no border (grid lines handle it) */ #speakers-form textarea { resize: none !important; overflow: hidden !important; height: 34px !important; min-height: 34px !important; max-height: 34px !important; padding: 0 0.75rem !important; line-height: 34px !important; border: none !important; border-radius: 0 !important; background: transparent !important; font-size: 0.85rem !important; font-family: inherit !important; color: var(--text) !important; width: 100% !important; box-sizing: border-box !important; } #speakers-form textarea:focus { outline: none !important; background: var(--matcha-tint) !important; box-shadow: inset 0 0 0 2px var(--matcha) !important; } #speakers-form textarea::placeholder { color: var(--text-muted) !important; } /* Cell dropdown — flush, no border */ #speakers-form .wrap-inner, #main-panel .wrap-inner { border: none !important; background: transparent !important; padding: 0 !important; box-shadow: none !important; height: auto !important; } #speakers-form .secondary-wrap, #speakers-form select { height: 34px !important; border: none !important; border-radius: 0 !important; background: transparent !important; font-size: 0.85rem !important; font-family: inherit !important; color: var(--text) !important; padding: 0 0.625rem !important; width: 100% !important; box-sizing: border-box !important; } #speakers-form .secondary-wrap:focus-within { background: var(--matcha-tint) !important; box-shadow: inset 0 0 0 2px var(--matcha) !important; } #main-panel .secondary-wrap, #main-panel select { background: transparent !important; border: none !important; border-radius: 0 !important; } /* Form labels (kept minimal) */ #main-panel label > span, #main-panel .label > span { font-size: 0.78rem !important; color: var(--text-soft) !important; font-weight: 500 !important; } /* Hide empty filler labels on textareas with label="" */ #main-panel label[for] > span:empty { display: none !important; } /* CodeMirror editors (narrate + interview script). CodeMirror writes inline min-height on .cm-scroller and measures content width during init — both can cause layout shift unless every layer is pinned to 100% width with min-width: 0 to allow shrinking. */ #narrate-editor, #script-editor { border: 1px solid var(--border) !important; border-radius: 10px !important; overflow: hidden !important; box-shadow: none !important; width: 100% !important; max-width: 100% !important; min-width: 0 !important; box-sizing: border-box !important; } #narrate-editor .block, #script-editor .block { border: none !important; box-shadow: none !important; padding: 0 !important; border-radius: 10px !important; overflow: hidden !important; width: 100% !important; max-width: 100% !important; min-width: 0 !important; box-sizing: border-box !important; } #narrate-editor .cm-editor, #script-editor .cm-editor { border-radius: 10px !important; font-size: 0.875rem !important; background: var(--surface) !important; width: 100% !important; max-width: 100% !important; min-width: 0 !important; box-sizing: border-box !important; overflow: hidden !important; /* Cap at 20 lines: 20 × line-height × font-size + top/bottom content padding */ max-height: calc(20 * 1.65 * 0.875rem + 1.5rem) !important; } #narrate-editor .cm-scroller, #script-editor .cm-scroller { max-width: 100% !important; min-width: 0 !important; overflow-x: auto !important; overflow-y: auto !important; box-sizing: border-box !important; } #narrate-editor .cm-editor.cm-focused, #script-editor .cm-editor.cm-focused { outline: none !important; box-shadow: 0 0 0 3px var(--matcha-tint) !important; } #narrate-editor .cm-content, #script-editor .cm-content { font-family: system-ui, -apple-system, "Noto Sans Khmer", sans-serif !important; line-height: 1.65 !important; padding: 0.75rem 1rem !important; caret-color: var(--matcha) !important; /* Wrap long unbreakable runs so CodeMirror doesn't measure a wide line and push its parent column past its flex share. */ word-break: break-word !important; overflow-wrap: anywhere !important; max-width: 100% !important; min-width: 0 !important; box-sizing: border-box !important; } #narrate-editor .cm-line, #script-editor .cm-line { max-width: 100% !important; word-break: break-word !important; overflow-wrap: anywhere !important; } #narrate-editor .cm-gutters, #script-editor .cm-gutters { background: var(--surface-2) !important; border-right: 1px solid var(--border-soft) !important; color: var(--text-muted) !important; font-size: 0.75rem !important; min-width: 0 !important; } #narrate-editor .cm-foldGutter, #script-editor .cm-foldGutter { display: none !important; } #narrate-editor .cm-lineNumbers, #script-editor .cm-lineNumbers { min-width: 2rem !important; } #narrate-editor .cm-lineNumbers .cm-gutterElement, #script-editor .cm-lineNumbers .cm-gutterElement { padding: 0 0.3rem 0 0.2rem !important; min-width: 0 !important; } #narrate-editor .cm-activeLineGutter, #narrate-editor .cm-activeLine, #script-editor .cm-activeLineGutter, #script-editor .cm-activeLine { background: var(--matcha-tint) !important; } /* Markdown bold gets a subtle highlight */ #narrate-editor .ͼb, #script-editor .ͼb { color: var(--matcha-d) !important; font-weight: 600 !important; } #narrate-editor .ͼe, #script-editor .ͼe { color: var(--text-soft) !important; font-style: italic !important; } """ FOOTER = """ """ INITIAL_DESC = f'
{VOICE_PRESETS[ALL_KEYS[0]]}
' with gr.Blocks(css=CSS, title="KOOMPI TTS · powered by VoxCPM2", theme=gr.themes.Base()) as demo: cloned_voices = gr.State(value=[]) sp_visible = gr.State(value=2) with gr.Row(elem_id="app-row"): with gr.Column(scale=3, min_width=260, elem_id="voice-panel"): gr.HTML('
Voices
') voice_radio = gr.Radio( choices=ALL_KEYS, value=ALL_KEYS[0], show_label=False, container=False, elem_classes="voice-list", ) voice_desc = gr.HTML(value=INITIAL_DESC, elem_classes="voice-desc-area") custom_voice = gr.Textbox( label="", lines=3, visible=False, show_label=False, placeholder="Describe a voice in plain English…\n\ne.g. calm male Khmer narrator, warm and natural", elem_classes="custom-voice-input", ) custom_save_btn = gr.Button( "Save", size="sm", visible=False, elem_classes="custom-save-btn kv-btn", ) custom_save_status = gr.HTML("", visible=False, elem_classes="custom-save-status") with gr.Accordion("+ Clone a voice", open=False): clone_audio = gr.Audio( type="filepath", label="Reference audio (5 to 30 seconds)", sources=["upload", "microphone"], ) clone_name = gr.Textbox( label="Voice name", placeholder="e.g. My Voice", lines=1, ) clone_btn = gr.Button("Save voice", size="sm", elem_classes="kv-btn", interactive=False) with gr.Column(scale=7, elem_id="main-panel"): with gr.Tabs(elem_id="mode-tabs"): with gr.Tab("ថតសំឡេង"): audio_out = gr.Audio( type="filepath", show_label=False, interactive=False, elem_classes="kv-audio", ) text_in = gr.Code( label="", language="markdown", lines=8, value="", elem_id="narrate-editor", ) with gr.Row(elem_id="narrate-bar"): with gr.Accordion("Advanced", open=False, elem_classes="cfg-accordion"): cfg_in = gr.Slider( 1.0, 3.0, value=1.5, step=0.1, label="Voice adherence", ) narrate_btn = gr.Button( "បង្កើតសំឡេង", variant="primary", elem_classes="kv-btn", scale=2, ) with gr.Tab("ការសម្ភាស"): audio_out_iv = gr.Audio( type="filepath", show_label=False, interactive=False, elem_classes="kv-audio", ) _sp_placeholders = ["ចំណិត", "ភ្ញៀវ", "ម្នាក់ទៀត", "ម្នាក់ទៀត", "ម្នាក់ទៀត", "ម្នាក់ទៀត"] _sp_defaults = [ALL_KEYS[2], ALL_KEYS[0], ALL_KEYS[1], ALL_KEYS[0], ALL_KEYS[2], ALL_KEYS[1]] sp_names = [] sp_voices = [] sp_rows = [] with gr.Column(elem_id="speakers-form"): gr.HTML("""
Speakers' name Voice
""") for _i in range(6): with gr.Row(elem_classes="speaker-row", visible=(_i < 2)) as _row: _name = gr.Textbox( show_label=False, placeholder=_sp_placeholders[_i], lines=1, scale=1, container=False, ) _voice = gr.Dropdown( choices=ALL_KEYS, value=_sp_defaults[_i], show_label=False, scale=2, container=False, ) sp_rows.append(_row) sp_names.append(_name) sp_voices.append(_voice) sp1_name, sp2_name, sp3_name, sp4_name, sp5_name, sp6_name = sp_names sp1_voice, sp2_voice, sp3_voice, sp4_voice, sp5_voice, sp6_voice = sp_voices with gr.Row(elem_classes="speaker-actions"): add_spk_btn = gr.Button( "+ Add Speaker", size="sm", elem_classes="kv-add-spk", interactive=True, ) rm_spk_btn = gr.Button( "− Remove last", size="sm", elem_classes="kv-rm-spk", interactive=False, ) script_in = gr.Code( label="Script", language="markdown", lines=12, value="", elem_id="script-editor", ) with gr.Row(elem_id="interview-bar"): with gr.Accordion("Advanced", open=False, elem_classes="cfg-accordion"): cfg_in_iv = gr.Slider( 1.0, 3.0, value=1.5, step=0.1, label="Voice adherence", ) interview_btn = gr.Button( "បង្កើតសំឡេង", variant="primary", elem_classes="kv-btn", scale=2, ) # ── Event wiring ─────────────────────────────────────────────────────── voice_radio.change( fn=on_voice_select, inputs=[voice_radio, cloned_voices], outputs=[custom_voice, voice_desc, custom_save_btn, custom_save_status], ) custom_save_btn.click( fn=lambda: gr.update(visible=True, value='✓ Saved'), outputs=[custom_save_status], ) custom_voice.change( fn=lambda _: gr.update(visible=False, value=""), inputs=[custom_voice], outputs=[custom_save_status], ) clone_name.change( fn=lambda name: gr.update(interactive=bool((name or "").strip())), inputs=[clone_name], outputs=[clone_btn], ) clone_btn.click( fn=save_cloned_voice, inputs=[clone_name, clone_audio, cloned_voices], outputs=[ cloned_voices, voice_radio, clone_name, clone_audio, sp1_voice, sp2_voice, sp3_voice, sp4_voice, sp5_voice, sp6_voice, ], ) add_spk_btn.click( fn=add_spk, inputs=[sp_visible], outputs=[sp_visible] + sp_rows + [add_spk_btn, rm_spk_btn], ) rm_spk_btn.click( fn=rm_spk, inputs=[sp_visible], outputs=[sp_visible] + sp_rows + [add_spk_btn, rm_spk_btn], ) narrate_btn.click( fn=lambda: gr.update(value=None), outputs=[audio_out], ).then( fn=do_narrate, inputs=[text_in, voice_radio, custom_voice, cloned_voices, cfg_in], outputs=[audio_out], api_name="generate", ) interview_btn.click( fn=lambda: gr.update(value=None), outputs=[audio_out_iv], ).then( fn=do_interview, inputs=[ script_in, sp1_name, sp1_voice, sp2_name, sp2_voice, sp3_name, sp3_voice, sp4_name, sp4_voice, sp5_name, sp5_voice, sp6_name, sp6_voice, cloned_voices, cfg_in_iv, ], outputs=[audio_out_iv], ) gr.HTML(FOOTER) if __name__ == "__main__": demo.queue(max_size=5).launch()