Integração: falantes + dublagem + vídeo final
- editor_api: importa dub e speakers juntos. - voice_chunks (falantes) vira a migração v15, depois da v14 do vídeo final (antes era criada fora das migrações). - dub.voice_for: qualquer voz que não é o streamer (other1, other2…) usa a segunda voz da dublagem. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+28
-9
@@ -40,6 +40,7 @@ from .intel import Intel
|
||||
from .judge import Judge, JudgeError, analysis_block, build_prompt
|
||||
from .scoring import ChatMessage, Params, Word, find_moments, overlaps
|
||||
from .sources import Source, parse_source
|
||||
from .speakers import SpeakerService, dump_words, parse_words
|
||||
from .subtitles import build_ass, phrases
|
||||
|
||||
log = logging.getLogger("cenaforge_clipper")
|
||||
@@ -353,6 +354,7 @@ class Engine:
|
||||
self._threads: list[threading.Thread] = []
|
||||
self.intel = Intel(self)
|
||||
self.face = FaceService(self) # rastreio do rosto do streamer (face.py); não carrega modelo aqui
|
||||
self.speakers = SpeakerService(self) # quem fala cada palavra (speakers.py); modelo de voz só no 1º bloco
|
||||
self.resume_delays: tuple[float, ...] = RESUME_DELAYS_S # os testes encurtam
|
||||
self._recovering: set[int] = set() # sessões com uma thread de retomada em andamento
|
||||
self._rendering: set[int] = set() # cortes que ESTE processo está renderizando agora
|
||||
@@ -754,12 +756,18 @@ class Engine:
|
||||
for w in rel_words]
|
||||
except Exception as exc: # noqa: BLE001 - sem voz o corte segue pelo chat
|
||||
error = str(exc)[:300]
|
||||
if words:
|
||||
try:
|
||||
# Impressão de voz de cada trecho de fala (doc/clipador/FALANTES.md): ~0,2 s de CPU por bloco.
|
||||
self.speakers.index_block(segment, pcm, words)
|
||||
except Exception as exc: # noqa: BLE001 - sem falantes a legenda segue toda como do streamer
|
||||
self.speakers.last_error = str(exc)[:300]
|
||||
log.warning("falantes do bloco %s/%s: %s", segment["session_id"], segment["idx"], exc)
|
||||
except media.MediaError as exc:
|
||||
error = f"áudio: {exc}"[:300]
|
||||
self.db.run(
|
||||
"UPDATE segments SET analyzed = 1, loudness_json = ?, words_json = ?, transcript_error = ? WHERE session_id = ? AND idx = ?",
|
||||
json.dumps(loudness), json.dumps([[w.start, w.end, w.word] for w in words], ensure_ascii=False), error,
|
||||
segment["session_id"], segment["idx"])
|
||||
json.dumps(loudness), dump_words(words), error, segment["session_id"], segment["idx"])
|
||||
|
||||
# ---------- linha do tempo de uma sessão
|
||||
def load_timeline(self, session_id: int, since_s: float = 0.0) -> dict:
|
||||
@@ -775,7 +783,7 @@ class Engine:
|
||||
if seg["analyzed"]:
|
||||
if analyzed_until >= seg["start_s"] - 0.01: # só o trecho contínuo desde o início conta
|
||||
analyzed_until = seg["end_s"]
|
||||
words.extend(Word(a, b, c) for a, b, c in loads(seg["words_json"], []))
|
||||
words.extend(parse_words(seg["words_json"]))
|
||||
chat = []
|
||||
if segments:
|
||||
first_wall = segments[0]["wall_end"] - (segments[0]["end_s"] - segments[0]["start_s"])
|
||||
@@ -789,9 +797,17 @@ class Engine:
|
||||
continue
|
||||
emotes = tuple(loads(r["emotes"], []))
|
||||
chat.append(ChatMessage(t, r["text"], r["user"], emotes, self.intel.bonus(list(emotes), key)))
|
||||
# Quem fala cada palavra (streamer × outra pessoa): juízes, tradução e legenda leem daqui.
|
||||
words = self.speakers.label(session_id, words)
|
||||
return {"segments": segments, "duration": duration, "loudness": loudness, "words": words, "chat": chat,
|
||||
"analyzedUntil": analyzed_until}
|
||||
|
||||
def words_between(self, session_id: int, lo: float, hi: float) -> list[Word]:
|
||||
"""Palavras dos blocos que tocam [lo, hi] (sem filtrar o tempo de cada palavra), já com o falante."""
|
||||
rows = self.db.all("SELECT words_json FROM segments WHERE session_id = ? AND end_s > ? AND start_s < ? ORDER BY idx",
|
||||
session_id, lo, hi)
|
||||
return self.speakers.label(session_id, [w for r in rows for w in parse_words(r["words_json"])])
|
||||
|
||||
# ---------- cortes
|
||||
def _clip_loop(self) -> None:
|
||||
while not self.stop_event.is_set():
|
||||
@@ -816,7 +832,7 @@ class Engine:
|
||||
return 0
|
||||
offset = int(since)
|
||||
chat = [replace(m, t=m.t - offset) for m in tl["chat"] if m.t >= offset]
|
||||
words = [Word(w.start - offset, w.end - offset, w.word) for w in tl["words"] if w.start >= offset]
|
||||
words = [replace(w, start=w.start - offset, end=w.end - offset) for w in tl["words"] if w.start >= offset]
|
||||
face, face_until = self.face.for_scoring(session, offset, tl["duration"]) # None = sem câmera/rastreio
|
||||
# O candidato já nasce na duração da configuração do corte desta sessão (padrão 60–90 s).
|
||||
dur = self.intel.settings_for(session)["duration"]
|
||||
@@ -980,20 +996,23 @@ class Engine:
|
||||
hi = clip["end_s"] if hi is None else hi
|
||||
current = loads(clip.get("translation_json"), None)
|
||||
if (isinstance(current, dict) and not force and current.get("startS", 1e12) <= lo + 0.5
|
||||
and current.get("endS", -1) >= hi - 0.5):
|
||||
and current.get("endS", -1) >= hi - 0.5
|
||||
and all("speaker" in line for line in current.get("lines") or [])): # antiga, sem falante: refaz
|
||||
return current
|
||||
tl = self.load_timeline(session["id"], max(0.0, lo - 30))
|
||||
items = phrases([w for w in tl["words"] if lo - 0.3 <= w.start <= hi])
|
||||
# Frases que nunca misturam falantes (doc/clipador/FALANTES.md); cada linha diz quem fala (`speaker`:
|
||||
# "streamer" ou "otherN") — a legenda de desenvolvimento e a dublagem escolhem posição e voz por ela.
|
||||
items = phrases([w for w in tl["words"] if lo - 0.3 <= w.start <= hi], with_speaker=True)
|
||||
if not items:
|
||||
return None
|
||||
try:
|
||||
pt = self.judge.translate_lines([text for _, _, text in items])
|
||||
pt = self.judge.translate_lines([text for _, _, text, _ in items])
|
||||
except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc:
|
||||
log.warning("tradução da fala do corte %s falhou: %s", clip_id, exc)
|
||||
return None
|
||||
data = {"language": "pt-BR", "startS": round(lo, 2), "endS": round(hi, 2), "model": self.judge.responder(),
|
||||
"lines": [{"s": round(s, 3), "e": round(e, 3), "text": text, "pt": tr}
|
||||
for (s, e, text), tr in zip(items, pt)]}
|
||||
"lines": [{"s": round(s, 3), "e": round(e, 3), "text": text, "pt": tr, "speaker": speaker}
|
||||
for (s, e, text, speaker), tr in zip(items, pt)]}
|
||||
self.db.run("UPDATE clips SET translation_json = ? WHERE id = ?", json.dumps(data, ensure_ascii=False), clip_id)
|
||||
return data
|
||||
|
||||
|
||||
Reference in New Issue
Block a user