CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
"""Mede tempo de CPU por segundo de áudio do motor da V1 (Piper) dentro do container.
|
||||
|
||||
Uso: docker compose run --rm voice python scripts/bench.py
|
||||
Mede síntese + codificação Opus, que é o custo real de um cache miss.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from app.audio import encode_ogg_opus # noqa: E402
|
||||
from app.catalog import load_catalog # noqa: E402
|
||||
from app.engine import PiperEngine # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
TEXTS = [
|
||||
"Olá! Valeu pela doação, o streamer agradece demais.",
|
||||
"Atenção, sobrevivente: uma horda de infectados está chegando pelo norte, prepare a munição e corra para o galpão.",
|
||||
"Isso é um teste de voz do DROPSZ, com frases um pouco mais longas, números como dois mil e vinte e seis, "
|
||||
"e pontuação variada; será que fica natural?",
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
models = Path(os.environ.get("VOICE_MODELS_DIR", "/models"))
|
||||
voices = load_catalog(ROOT / "voices" / "catalog.json", ROOT / "models.lock.json", models)
|
||||
voice = next(v for v in voices.values() if v.default)
|
||||
threads = int(os.environ.get("VOICE_ONNX_THREADS", "2"))
|
||||
engine = PiperEngine(threads)
|
||||
engine.synthesize(voice, "aquecimento", 1.0, 30)
|
||||
rounds = int(os.environ.get("BENCH_ROUNDS", "3"))
|
||||
cpu = wall = audio = 0.0
|
||||
for _ in range(rounds):
|
||||
for text in TEXTS:
|
||||
c0, w0 = time.process_time(), time.perf_counter()
|
||||
pcm = engine.synthesize(voice, text, 1.0, 60)
|
||||
encode_ogg_opus(pcm)
|
||||
cpu += time.process_time() - c0
|
||||
wall += time.perf_counter() - w0
|
||||
audio += pcm.duration_s
|
||||
print(
|
||||
f"voz={voice.id} threads={threads} audio={audio:.1f}s cpu={cpu:.2f}s wall={wall:.2f}s "
|
||||
f"cpu_por_s_audio={cpu / audio:.3f} rtf_wall={wall / audio:.3f}"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Mede tempo de CPU por segundo de áudio da transcrição (faster-whisper) dentro do container.
|
||||
|
||||
Uso: docker compose run --rm voice python scripts/bench_stt.py
|
||||
BENCH_MODELS=base,small (precisa dos dois baixados: fetch_models.py --group stt-base --group stt-small)
|
||||
BENCH_OUT=/tmp/x.ogg (opcional: grava o clipe de ~10 s para o teste com curl)
|
||||
|
||||
O áudio de teste é gerado pelo próprio Piper do serviço (texto sintético, nunca de espectador) e
|
||||
codificado em OGG/Opus como o backend manda. Mede decodificação + transcrição: o custo real de um job.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from app.audio import encode_ogg_opus # noqa: E402
|
||||
from app.catalog import load_catalog # noqa: E402
|
||||
from app.engine import Pcm, PiperEngine # noqa: E402
|
||||
from app.stt import SAMPLE_RATE, FasterWhisperEngine # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SENTENCES = [
|
||||
"Olá! Valeu pela doação, o streamer agradece demais.",
|
||||
"Atenção, sobrevivente: uma horda de infectados está chegando pelo norte, prepare a munição e corra para o galpão.",
|
||||
"Isso é um teste de voz do DROPSZ, com frases um pouco mais longas e pontuação variada.",
|
||||
"Manda um abraço para o pessoal do chat e boa sorte na próxima partida.",
|
||||
]
|
||||
|
||||
|
||||
def build_clip(engine: PiperEngine, voice, seconds: float) -> bytes:
|
||||
parts: list[np.ndarray] = []
|
||||
total = 0.0
|
||||
rate = 0
|
||||
index = 0
|
||||
while total < seconds:
|
||||
pcm = engine.synthesize(voice, SENTENCES[index % len(SENTENCES)], 1.0, 30)
|
||||
rate = pcm.sample_rate
|
||||
parts.append(pcm.samples)
|
||||
parts.append(np.zeros(rate // 3, dtype=np.int16)) # pausa entre frases
|
||||
total = sum(len(p) for p in parts) / rate
|
||||
index += 1
|
||||
samples = np.concatenate(parts)[: int(seconds * rate)]
|
||||
return encode_ogg_opus(Pcm(samples, rate))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
models_dir = Path(os.environ.get("VOICE_MODELS_DIR", "/models"))
|
||||
voices = load_catalog(ROOT / "voices" / "catalog.json", ROOT / "models.lock.json", models_dir)
|
||||
voice = next(v for v in voices.values() if v.default)
|
||||
piper = PiperEngine(int(os.environ.get("VOICE_ONNX_THREADS", "2")))
|
||||
clips = {f"{s}s": build_clip(piper, voice, s) for s in (5, 10, 30, 58)}
|
||||
out = os.environ.get("BENCH_OUT")
|
||||
if out:
|
||||
Path(out).write_bytes(clips["10s"])
|
||||
print(f"clipe de 10 s gravado em {out} ({len(clips['10s'])} bytes)")
|
||||
|
||||
threads = int(os.environ.get("VOICE_STT_THREADS", "2"))
|
||||
beam = int(os.environ.get("VOICE_STT_BEAM_SIZE", "1"))
|
||||
names = os.environ.get("BENCH_MODELS", os.environ.get("VOICE_STT_MODEL", "base")).split(",")
|
||||
for name in names:
|
||||
c0 = time.process_time()
|
||||
w0 = time.perf_counter()
|
||||
engine = FasterWhisperEngine(models_dir / "whisper" / name, name, "int8", threads, beam, True, 4000)
|
||||
engine.transcribe(engine.decode(clips["5s"], 61), "pt") # aquecimento
|
||||
print(f"[{name}] carga+aquecimento cpu={time.process_time() - c0:.2f}s wall={time.perf_counter() - w0:.2f}s")
|
||||
cpu_total = audio_total = 0.0
|
||||
for label, data in clips.items():
|
||||
c0, w0 = time.process_time(), time.perf_counter()
|
||||
samples = engine.decode(data, 61)
|
||||
result = engine.transcribe(samples, "pt")
|
||||
cpu, wall = time.process_time() - c0, time.perf_counter() - w0
|
||||
audio = samples.size / SAMPLE_RATE
|
||||
cpu_total += cpu
|
||||
audio_total += audio
|
||||
print(
|
||||
f"[{name}] {label}: audio={audio:.1f}s cpu={cpu:.2f}s wall={wall:.2f}s cpu_por_s={cpu / audio:.3f} "
|
||||
f"rtf_wall={wall / audio:.3f} no_speech={result.no_speech_prob:.3f} texto='{result.text[:70]}'"
|
||||
)
|
||||
print(f"[{name}] TOTAL threads={threads} beam={beam} cpu_por_s_audio={cpu_total / audio_total:.3f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Baixa os pesos listados no models.lock.json para VOICE_MODELS_DIR e confere o sha256.
|
||||
|
||||
Uso: python scripts/fetch_models.py [--group v1 --group stt-base] [--dest /models]
|
||||
Reprodutível: arquivo já presente com o hash certo não é baixado de novo; hash errado = falha.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for block in iter(lambda: handle.read(1 << 20), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def fetch(entry: dict, dest: Path) -> None:
|
||||
target = dest / entry["path"]
|
||||
if target.is_file() and sha256_file(target) == entry["sha256"]:
|
||||
print(f"ok (já presente) {entry['path']}")
|
||||
return
|
||||
if not entry["url"].startswith("https://"):
|
||||
raise SystemExit(f"URL não-HTTPS recusada: {entry['path']}")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = target.with_suffix(target.suffix + ".part")
|
||||
print(f"baixando {entry['path']} ...")
|
||||
with urllib.request.urlopen(entry["url"], timeout=120) as response, tmp.open("wb") as out: # noqa: S310 - https checado acima
|
||||
while block := response.read(1 << 20):
|
||||
out.write(block)
|
||||
actual = sha256_file(tmp)
|
||||
if actual != entry["sha256"]:
|
||||
tmp.unlink(missing_ok=True)
|
||||
raise SystemExit(f"checksum divergente em {entry['path']}: {actual}")
|
||||
os.replace(tmp, target)
|
||||
print(f"ok {entry['path']}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--group", action="append", help="repita para baixar vários grupos (padrão: v1)")
|
||||
parser.add_argument("--dest", default=os.environ.get("VOICE_MODELS_DIR", str(ROOT.parent / "data" / "voice" / "models")))
|
||||
parser.add_argument("--lock", default=str(ROOT / "models.lock.json"))
|
||||
args = parser.parse_args()
|
||||
lock = json.loads(Path(args.lock).read_text(encoding="utf-8"))
|
||||
groups = set(args.group or ["v1"])
|
||||
entries = [e for e in lock["files"] if e.get("group", "v1") in groups]
|
||||
if not entries:
|
||||
print(f"nenhum arquivo nos grupos {sorted(groups)}", file=sys.stderr)
|
||||
return 1
|
||||
for entry in entries:
|
||||
fetch(entry, Path(args.dest))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,12 @@
|
||||
"""HEALTHCHECK do container: chama /health (liveness sem chave e sem dado; o estado fica no /v1/status)."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
url = f"http://127.0.0.1:{os.environ.get('PORT', '8000')}/health"
|
||||
with urllib.request.urlopen(url, timeout=5) as response: # noqa: S310 - localhost fixo
|
||||
sys.exit(0 if response.status == 200 else 1)
|
||||
except Exception:
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Teste de fumaça do serviço de voz rodando (porta 4510): status, síntese de cada voz e transcrição com tempos.
|
||||
|
||||
Uso: voice/.venv/Scripts/python voice/scripts/smoke.py [--out output/voice-smoke]
|
||||
Lê a chave do voice/.env. Grava os WAV gerados e o JSON da transcrição na pasta de saída.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
VOICE_ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(VOICE_ROOT))
|
||||
from app.config import PROJECT_ROOT, load_dotenv # noqa: E402
|
||||
|
||||
TEXT = "Olá! Este é o serviço de voz do CenaForge, gerando a narração do episódio."
|
||||
|
||||
|
||||
def call(method: str, path: str, key: str, port: int, body: bytes | None = None, headers: dict | None = None):
|
||||
request = urllib.request.Request(
|
||||
f"http://127.0.0.1:{port}{path}", data=body, method=method,
|
||||
headers={"X-Service-Key": key, **(headers or {})},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=300) as response: # noqa: S310 - localhost fixo
|
||||
return response.status, {k.lower(): v for k, v in response.headers.items()}, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, {k.lower(): v for k, v in error.headers.items()}, error.read()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--out", default=str(PROJECT_ROOT / "output" / "voice-smoke"))
|
||||
parser.add_argument("--detail", default="words", choices=("text", "segments", "words"))
|
||||
args = parser.parse_args()
|
||||
load_dotenv(VOICE_ROOT / ".env")
|
||||
key = os.environ["VOICE_SERVICE_KEY"]
|
||||
port = int(os.environ.get("VOICE_PORT", "4510"))
|
||||
out = Path(args.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
status, _, raw = call("GET", "/v1/status", key, port)
|
||||
data = json.loads(raw)
|
||||
print(f"status {status}: dispositivo={data['device']} rvc={data['rvc']} motores={data['engines']}")
|
||||
|
||||
voices = json.loads(call("GET", "/v1/voices", key, port)[2])["items"]
|
||||
first_wav: Path | None = None
|
||||
for voice in voices:
|
||||
request_id = f"smoke-{voice['id']}-{int(time.time())}"
|
||||
payload = {"requestId": request_id[:64], "text": TEXT, "voiceId": voice["id"], "params": {"format": "wav"}}
|
||||
started = time.perf_counter()
|
||||
code, headers, audio = call(
|
||||
"POST", "/v1/synthesize", key, port, json.dumps(payload).encode(), {"Content-Type": "application/json"}
|
||||
)
|
||||
wall = time.perf_counter() - started
|
||||
if code != 200:
|
||||
print(f" {voice['id']}: ERRO {code} {audio[:200]!r}")
|
||||
continue
|
||||
target = out / f"{voice['id']}.wav"
|
||||
target.write_bytes(audio)
|
||||
first_wav = first_wav or target
|
||||
print(f" {voice['id']} ({voice.get('provider')}): {headers.get('x-audio-duration-ms')} ms de áudio "
|
||||
f"em {wall:.2f} s -> {target}")
|
||||
|
||||
if first_wav is None:
|
||||
print("nenhuma voz gerou áudio")
|
||||
return 1
|
||||
audio = first_wav.read_bytes()
|
||||
duration_ms = max(1, int((len(audio) - 44) / 2 / 24000 * 1000)) # WAV PCM16 mono; só uma estimativa
|
||||
started = time.perf_counter()
|
||||
code, _, raw = call("POST", "/v1/transcribe", key, port, audio, {
|
||||
"Content-Type": "audio/wav", "X-Idempotency-Key": f"smoke-{int(time.time())}",
|
||||
"X-Audio-Duration-Ms": str(duration_ms), "X-Language": "pt-BR", "X-Detail": args.detail,
|
||||
})
|
||||
result = json.loads(raw)
|
||||
while code == 202:
|
||||
time.sleep(result["retryAfterMs"] / 1000)
|
||||
code, _, raw = call("GET", f"/v1/transcribe/jobs/{result['jobRef']}", key, port)
|
||||
result = json.loads(raw)
|
||||
wall = time.perf_counter() - started
|
||||
(out / "transcribe.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(f"transcrição {code} em {wall:.2f} s: {result.get('text')!r}")
|
||||
if result.get("segments"):
|
||||
words = [w for s in result["segments"] for w in s.get("words", [])]
|
||||
print(f" {len(result['segments'])} segmento(s), {len(words)} palavra(s) com tempo")
|
||||
return 0 if code == 200 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user