import spaces import gradio as gr import torch import os, json, time, uuid, datetime, pathlib # torch >= 2.6 defaults torch.load(weights_only=True), which breaks TTS's # pickle-based config loading. Restore the older behavior before TTS imports. _orig_torch_load = torch.load def _patched_torch_load(*args, **kwargs): kwargs.setdefault("weights_only", False) return _orig_torch_load(*args, **kwargs) torch.load = _patched_torch_load os.environ["COQUI_TOS_AGREED"] = "1" from TTS.api import TTS device = "cuda" if torch.cuda.is_available() else "cpu" tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(device) # ── where the upgrade links go. Every link names its position so the site can tell which spot works. ── SITE = "https://voice-clone.co/" def link(position): return f"{SITE}?utm_source=hf_voice_clone&utm_medium={position}&utm_campaign=launch" # ── event log: one JSON line per event, batched into a PRIVATE dataset repo. No text, no audio. ── # Events: generate · done (with seconds) · quota_wall · error · cta_click (with position) LOG_REPO = os.environ.get("SURVEY_REPO", "tonyassi/voice-clone-survey") DATA_DIR = pathlib.Path("survey_data"); DATA_DIR.mkdir(exist_ok=True) DATA_FILE = DATA_DIR / f"events-{uuid.uuid4().hex[:8]}.jsonl" scheduler = None if os.environ.get("TOKEN"): # Logging must never take the Space down: a bad or expired token just means no log. try: from huggingface_hub import CommitScheduler scheduler = CommitScheduler(repo_id=LOG_REPO, repo_type="dataset", folder_path=DATA_DIR, path_in_repo="data", every=5, token=os.environ["TOKEN"], private=True) except Exception as e: print(f"[log] disabled: {type(e).__name__}: {str(e)[:200]}") scheduler = None _fallback_lock = __import__("threading").Lock() def log_event(event, **fields): try: row = {"ts": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), "event": event, **fields} with (scheduler.lock if scheduler else _fallback_lock): with DATA_FILE.open("a") as f: f.write(json.dumps(row) + "\n") except Exception as e: print(f"[log] write failed: {e}") # ── the model call itself, unchanged ── @spaces.GPU def _clone_gpu(text, audio): tts.tts_to_file(text=text, speaker_wav=audio, language="en", file_path="./output.wav") return "./output.wav" def cta_card(headline, body, position, button): return f"""
""" def clone(text, audio): # Submit with no clip or no text used to end in a raw model error (about half of all presses after launch). # Say what is missing, and offer the new Voice Clone at the same moment. no_clip, no_text = not audio, not (text or "").strip() if no_clip or no_text: what = "a voice clip and some text" if (no_clip and no_text) else ("a voice clip" if no_clip else "some text") how = {"a voice clip and some text": "Upload or record the voice you want, type what it should say, then press Submit.", "a voice clip": "Upload or record a few seconds of the voice you want, then press Submit.", "some text": "Type what you want the voice to say, then press Submit."}[what] position = "no_clip" if no_clip else "no_text" log_event(position) gr.Warning(f"Add {what} first.", duration=8) return None, gr.update(visible=True, value=cta_card( f"Add {what} first.", how + " Or try the new Voice Clone: much closer to the real voice, saves your voices, free to try, no card.", position, "Try the new Voice Clone →")) t0 = time.time() try: if os.environ.get("VC_FORCE_QUOTA") == "1": # rehearsal only: preview the quota card without burning real quota raise RuntimeError("You have exceeded your GPU quota (60s requested vs. 12s left). Create a free account to get more daily usage quota.") path = _clone_gpu(text, audio) except Exception as e: msg = str(e) if "quota" in msg.lower(): # The visitor has used today's free GPU time. Keep Hugging Face's own message, and offer a way to keep going. log_event("quota_wall") gr.Warning(msg, duration=10) return None, gr.update(visible=True, value=cta_card( "You've used today's free GPU time here.", "It resets in 24 hours. To keep going right now, Voice Clone has no queue and is free to try. No card needed.", "quota", "Keep going on Voice Clone →")) log_event("error") raise secs = round(time.time() - t0) log_event("done", seconds=secs) gr.Info(f'Done. Want it closer to the real voice? Try the new Voice Clone →', duration=8) # Only talk about speed when this run was actually slow; otherwise lead with what the new one does better. if secs >= 10: head = f"That took {secs} seconds on the free model." body = "The new Voice Clone takes about 2, with no queue, and sounds much closer to the real voice. It also saves your voices and takes longer text. Free to try, no card." else: head = "Want it closer to the real voice?" body = "The new Voice Clone sounds much closer, has no daily GPU limit, saves your voices and takes longer text. Free to try, no card." return path, gr.update(visible=True, value=cta_card(head, body, "result", "Hear the difference →")) def on_submit(): log_event("generate") return gr.Sidebar(open=True) def log_click(position): def _f(): log_event("cta_click", position=position) return _f CSS = """ .vc-banner { display:flex !important; flex-wrap:wrap; align-items:center; justify-content:center; gap:10px 14px; box-sizing:border-box; width:100%; padding:12px 16px !important; border:1px solid #e5e7eb; background:#f9fafb; color:#111827 !important; text-decoration:none !important; font-weight:600; font-size:15px; line-height:1.4; border-radius:12px; } .vc-banner:hover { background:#f3f4f6; } .vc-banner .vc-pill { display:inline-block; background:#ff4d2e; color:#fff; padding:2px 9px; border-radius:999px; margin-right:8px; font-size:12px; font-weight:700; line-height:1.4; vertical-align:middle; } .vc-banner .vc-btn { padding:8px 16px; white-space:nowrap; } .vc-banner:hover .vc-btn { background:#e63e20; } .vc-card { border:1px solid #e5e7eb; background:#f9fafb; border-radius:12px; padding:14px 16px; } .vc-card-h { font-weight:700; font-size:16px; color:#111827; margin-bottom:4px; } .vc-card-b { font-size:14px; color:#374151; margin-bottom:12px; line-height:1.45; } .vc-btn { display:inline-block; background:#ff4d2e; color:#fff !important; text-decoration:none !important; font-weight:700; padding:10px 18px; border-radius:10px; } .vc-btn:hover { background:#e63e20; } .vc-list { margin:8px 0 14px; padding-left:18px; line-height:1.7; } .vc-small { font-size:12px; opacity:.7; } #side-cta { width:100%; background:#ff4d2e !important; color:#fff !important; border-color:#ff4d2e !important; font-weight:700 !important; font-size:16px !important; padding:14px 12px !important; box-shadow:0 4px 14px rgba(255,77,46,.35); } #side-cta:hover { background:#e63e20 !important; border-color:#e63e20 !important; } """ # Links inside the Space must open in a new tab (the Space runs in a frame). NEW_TAB_JS = """ () => { const fix = () => document.querySelectorAll('a[href*="voice-clone.co"]').forEach(a => { a.target = '_blank'; a.rel = 'noopener'; }); fix(); new MutationObserver(fix).observe(document.body, { childList: true, subtree: true }); } """ with gr.Blocks(title="Voice Clone", css=CSS, js=NEW_TAB_JS, theme=gr.themes.Base(primary_hue="teal", secondary_hue="teal", neutral_hue="slate")) as demo: gr.HTML(f'' 'NEWA better Voice Clone is live: closer to the real voice, no GPU limit, saves your voices.' 'Try it free →') gr.Markdown(""" # Voice Clone by [Tony Assi](https://www.tonyassi.com/) ---