#!/usr/bin/env python3 """Generate TTS from a text file. Handles URL encoding properly.""" import sys, urllib.parse, subprocess, os, hashlib, time TTS_URL = "https://hf4uwho-pocket-tts.hf.space/tts" OUTDIR = "/tmp/tts" os.makedirs(OUTDIR, exist_ok=True) textfile = sys.argv[1] if len(sys.argv) > 1 else None voice = sys.argv[2] if len(sys.argv) > 2 else "af_alloy" fmt = sys.argv[3] if len(sys.argv) > 3 else "ogg" if not textfile: print("Usage: voice-from-file.py [voice] [format]", file=sys.stderr) sys.exit(1) with open(textfile, "r") as f: text = f.read().strip() encoded = urllib.parse.quote(text) url = f"{TTS_URL}?text={encoded}&voice={voice}&format={fmt}" h = hashlib.md5(f"{textfile}{voice}{time.time()}".encode()).hexdigest()[:12] outfile = f"{OUTDIR}/magi_{h}.{fmt}" print(f"Generating {len(text)} chars...", file=sys.stderr) start = time.time() r = subprocess.run( ["curl", "-s", "-o", outfile, "-w", "%{http_code}\n%{time_total}", "--max-time", "300", url], capture_output=True, text=True, timeout=310 ) elapsed = time.time() - start parts = r.stdout.strip().split("\n") code = parts[0] if parts else "?" curl_time = parts[1] if len(parts) > 1 else "?" print(f"HTTP {code} | curl: {curl_time}s | total: {elapsed:.1f}s", file=sys.stderr) if code != "200": print(f"ERROR: HTTP {code}", file=sys.stderr) if os.path.exists(outfile): os.remove(outfile) sys.exit(1) sz = os.path.getsize(outfile) print(f"Output: {outfile} ({sz} bytes)", file=sys.stderr) print(outfile)