Clipador: fontes em inglês (juízes em inglês, painel em português) e monitor de uso da IA
Clipador em inglês (doc/clipador/IDIOMAS.md):
- Fonte en-US: analista, editor e varredura com prompts, glossário de chat e saída em inglês;
a mesma resposta traz o bloco `pt` (tradução para o painel, sem chamada extra).
- Fala do corte traduzida por frase (clips.translation_json, migração v13) e
POST /v1/clips/{id}/translate.
- caption.translation (só para desenvolver): português embaixo da legenda em inglês.
- Risada e gírias do chat em inglês na heurística (LMAO, LOL, 💀, 😭, no way, bruh...).
- Idioma do público → código do Whisper (en-US dava 422 no serviço de voz).
- Painel: bloco "Em português" no corte, análise/resumo em PT, título traduzido na lista,
coluna "Ao vivo" mostra a gravação ativa da fonte.
IA: monitor de uso do limite (ai-usage) e 4º provedor (Antigravity CLI).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+266
-51
@@ -30,7 +30,7 @@ import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
@@ -353,6 +353,8 @@ class Verdict:
|
||||
model: str
|
||||
# Tags DO MOMENTO (sem "#"), escolhidas pela IA; as do canal e do jogo o sistema põe (app/hashtags.py).
|
||||
hashtags: tuple[str, ...] = ()
|
||||
# Fonte em inglês: título, legenda e motivo traduzidos para o painel ({} = sessão em português).
|
||||
pt: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
class JudgeError(RuntimeError):
|
||||
@@ -402,6 +404,163 @@ def extract_json_object(text: str, fences: bool = True) -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- juízes em inglês (fonte gringa)
|
||||
# Pedido do dono (18/11/2026): "se a fonte está em inglês, os juízes trabalham em inglês". A equipe não fala inglês:
|
||||
# o vídeo (gancho, título, legenda, hashtags) sai em inglês e a MESMA resposta traz um bloco `pt` com a tradução
|
||||
# para o painel — sem chamada extra. Regras completas em doc/clipador/IDIOMAS.md.
|
||||
CLIP_GUIDE_EN = """What makes a good live-stream clip (market research, 2026):
|
||||
- Opens on the strong moment: viewers decide in 1–2 s. No "like I was saying".
|
||||
- Explains itself: someone who never saw the stream gets it in a few seconds (minimal context at the start).
|
||||
- Clip-worthy: strong reaction (jump scare, laughing fit, rage), insane play/comeback, funny fail, beef/drama, a story
|
||||
that unfolds, a memorable line, and NEW GAME INFO (mechanic, secret, news, comparison) — around launches
|
||||
(e.g. GTA 6) information is worth as much as a reaction.
|
||||
- Not clip-worthy: waiting, menus/loading, reading donations/ads, chatter with no hook, stream inside jokes.
|
||||
- TIMING: streamers usually comment AFTER the action. Go back to the start of the ACTION that triggered the
|
||||
comment (20 s to 2 min before the line, up to the backtrack limit given) — the clip must show action and reaction.
|
||||
- Tight ending: end right after the payoff (reaction/resolution)."""
|
||||
|
||||
CHAT_GLOSSARY_EN = """Common chat slang on English-speaking Twitch/Kick/YouTube (read it by context):
|
||||
- Laughing: "LUL", "LULW", "KEKW", "OMEGALUL", "ICANT", "pepeLaugh", "LMAO", "LMFAO", "LOL", "ROFL", "💀"/"☠️"
|
||||
("I'm dead" = so funny), "😭" (crying laughing), "dead", "I'm crying".
|
||||
- Shock/confusion: "HUH", "?????", "WTF", "OMG", "no way", "nah", "bruh", "monkaS"/"monkaW" (tension), "Aware",
|
||||
"Clueless" (ironic: he doesn't realise), "COPIUM" (denial), "Sadge" (sad).
|
||||
- Hype/praise: "Pog", "POGGERS", "PogU", "W"/"dub" (win), "L" (loss), "LETSGO", "Clap", "EZ", "GG", "clutch",
|
||||
"cracked" (very skilled), "goated", "sheesh", "diff" (skill gap).
|
||||
- "F" = death/loss; "cooked"/"he's cooked" = doomed; "throwing"/"sold" = blew it; "bot"/"NPC" = bad/robotic play.
|
||||
- "lag", "ping", "rubberbanding", "desync", "server dying" → the game/stream is lagging; the joke is the lag.
|
||||
- "clip it"/"CLIP IT" → clip request; "hacker"/"cheater"/"aimbot" → suspected cheating.
|
||||
- Channel emotes (streamer prefix + base emote, e.g. tfueLUL) carry the same reaction as the base emote."""
|
||||
|
||||
PT_NOTE = ("The team that reviews clips only reads Brazilian Portuguese: fill `pt` with a faithful Brazilian "
|
||||
"Portuguese translation of the listed fields (keep game terms, names and slang meaning; do not add facts).")
|
||||
|
||||
ANALYST_SYSTEM_EN = """You are the ANALYST of a live-stream clipping team. You do not write titles: you describe
|
||||
faithfully WHAT HAPPENED in the segment so the editor can decide. You get game context, a timed transcript (the
|
||||
streamer speaks English), screen FRAMES with their timestamps and the chat.
|
||||
|
||||
Cross-check all three sources before concluding: speech alone misleads (e.g. "I'm playing three games... I died, I
|
||||
died" plus chat "server dying?/LMAO" and the screen jumping = the game is lagging and he dies because of the lag).
|
||||
Chat reacts a few seconds after the event.
|
||||
|
||||
""" + CHAT_GLOSSARY_EN + """
|
||||
|
||||
Fields (in English):
|
||||
- situation: the moment type (one from the list; the ids are fixed, keep them as they are).
|
||||
- what_happened: 2–3 factual sentences of what happened, in order, no exaggeration.
|
||||
- screen: what the frames show (cite the frame #) — or "frames don't help".
|
||||
- speech: what the speech reveals (cite the timestamp).
|
||||
- chat_meaning: what chat is saying/laughing at and why.
|
||||
- confidence: 0–1, how sure you are (lower it when sources disagree).
|
||||
- action_start_s: second of the recording where the ACTION that caused the reaction starts (may be before the speech).
|
||||
- reaction_end_s: second where the reaction/payoff ends.
|
||||
- hook: what would hook someone in the first 2 seconds of the clip (English, it goes on screen).
|
||||
- pt: what_happened, screen, speech, chat_meaning and hook translated. """ + PT_NOTE + """
|
||||
Do not use tools beyond what was given. Answer only with the requested JSON."""
|
||||
|
||||
JUDGE_SYSTEM_EN = """You are the EDITOR of live-stream clips for Shorts, TikTok, Reels and YouTube, for an
|
||||
English-speaking (US) audience. You get a candidate segment of a stream (game context, timed transcript, chat,
|
||||
emotes) and, when available, the ANALYST's analysis, which already cross-checked screen, speech and chat. Trust the
|
||||
analysis to understand WHAT happened; your job is to decide whether it makes a clip and write a title and caption
|
||||
FAITHFUL to it.
|
||||
|
||||
""" + CLIP_GUIDE_EN + """
|
||||
|
||||
""" + CHAT_GLOSSARY_EN + """
|
||||
|
||||
Title and caption describe the real situation (if the analysis says lag, the title is about the lag, not about a
|
||||
random line of the transcript). With analysis confidence < 0.5, be descriptive and do not invent details.
|
||||
Use the analysis action_start_s/reaction_end_s as the base for start_s/end_s.
|
||||
|
||||
Answer rules:
|
||||
- keep=false for what doesn't work; score 0–10 (7+ = strong clip; below 5 = discard).
|
||||
- start_s and end_s in seconds of the recording, INSIDE the window given and within the min/max duration given;
|
||||
start before the action (context) and end right after the reaction. Never cut mid-sentence.
|
||||
- title: up to 70 characters, English, catchy but true, written like a native US clip channel (not a literal
|
||||
translation), nothing that isn't in the speech/screen.
|
||||
- caption: 1–2 sentences in English, NO hashtags and no links (the system adds channel/game hashtags and credit).
|
||||
- hashtags: 2 to 4 tags OF THE MOMENT, English, without "#": the mission/activity, event, mode, place, item or
|
||||
character in THIS segment. Prefer game-profile terms and what streamer and chat say. Nothing generic ("gameplay",
|
||||
"live", "viral"), nothing that doesn't happen here, and do not repeat the channel or the game name.
|
||||
- reason: one sentence on why you kept or discarded it (cite the screen if it helped).
|
||||
- pt: title, caption and reason translated. """ + PT_NOTE + """
|
||||
- Do not use tools or read anything beyond what was given. Answer only with the requested JSON."""
|
||||
|
||||
SCAN_SYSTEM_EN = """You are a live-stream clip editor WATCHING a stream in windows of a few minutes. The streamer
|
||||
speaks English. You get game context, a timed transcript (seconds of the recording), screen frames with their
|
||||
timestamps, the chat (may be almost empty) and clips already made in this region.
|
||||
|
||||
""" + CLIP_GUIDE_EN + """
|
||||
|
||||
""" + CHAT_GLOSSARY_EN + """
|
||||
|
||||
Task: point out 0 to 2 moments in this window that would make a good clip ON THEIR OWN. If nothing works, return
|
||||
moments=[] (that's normal most of the time — don't force it). Don't repeat a clip already made.
|
||||
- start_s/end_s inside the window (may start back to the "backtrack" limit to catch the action), within the
|
||||
min/max duration given.
|
||||
- screen_game: the game on screen (or "unknown"); has_webcam: is there a streamer camera in the frame?
|
||||
- summary: 1 sentence of what's going on in the window (becomes memory for the next windows).
|
||||
- title/caption/reason in English like an editor would write (title ≤ 70 characters, true).
|
||||
- summary_pt and each moment's pt (title, reason): translated. """ + PT_NOTE + """
|
||||
Do not use tools beyond what was given. Answer only with the requested JSON."""
|
||||
|
||||
|
||||
def _pt_block(*keys: str) -> dict:
|
||||
return {"type": "object", "properties": {k: {"type": "string"} for k in keys}, "required": list(keys),
|
||||
"additionalProperties": False}
|
||||
|
||||
|
||||
def _with(schema: dict, **extra: dict) -> dict:
|
||||
"""Schema + campos novos obrigatórios (os CLIs exigem `required` com todas as propriedades)."""
|
||||
return {**schema, "properties": {**schema["properties"], **extra}, "required": [*schema["required"], *extra]}
|
||||
|
||||
|
||||
ANALYSIS_SCHEMA_EN = _with(ANALYSIS_SCHEMA, pt=_pt_block("what_happened", "screen", "speech", "chat_meaning", "hook"))
|
||||
VERDICT_SCHEMA_EN = _with(VERDICT_SCHEMA, pt=_pt_block("title", "caption", "reason"))
|
||||
SCAN_SCHEMA_EN = _with({**SCAN_SCHEMA, "properties": {**SCAN_SCHEMA["properties"],
|
||||
"moments": {"type": "array", "items": _with(_MOMENT, pt=_pt_block("title", "reason"))}}},
|
||||
summary_pt={"type": "string"})
|
||||
|
||||
# Tradução da fala de um corte (painel e legenda em português de desenvolvimento): frases numeradas → mesma quantidade.
|
||||
LINES_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {"lines": {"type": "array", "items": {"type": "string"}}},
|
||||
"required": ["lines"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
LINES_SYSTEM = """You translate the speech of a live-streamer (auto transcript, may have errors and slang) into
|
||||
Brazilian Portuguese, for a team that doesn't speak English. You get numbered lines in order; they are one
|
||||
continuous talk, so use the neighbours as context. Return `lines` with EXACTLY the same number of items, same order,
|
||||
one translation per line: natural spoken Brazilian Portuguese, short, faithful (keep swearing level, game terms and
|
||||
names; translate the slang's meaning, e.g. "he's cooked" -> "ele tá ferrado"). If a line is noise, translate it
|
||||
as is. Answer only with the requested JSON."""
|
||||
|
||||
|
||||
def lang_key(language: str | None) -> str:
|
||||
"""'en' para fonte em inglês (juízes em inglês); 'pt' para o resto (prompts em português + nota de saída)."""
|
||||
return "en" if (language or "").strip().lower().startswith("en") else "pt"
|
||||
|
||||
|
||||
# Rótulos dos prompts montados aqui (o texto do usuário). Mesmas chaves nos dois idiomas.
|
||||
LABELS = {
|
||||
"pt": {"live_title": "Título da live", "unknown": "desconhecido", "channel": "Canal", "window": "Janela disponível",
|
||||
"candidate": "Candidato da heurística", "peak": "pico de reação em", "duration": "Duração do corte",
|
||||
"signals": "Sinais da heurística", "face": "Rosto do streamer (expressão medida na webcam, relativa ao normal dele)",
|
||||
"transcript": "Transcrição", "no_speech": "(sem fala transcrita)", "chat_per": "Mensagens do chat por",
|
||||
"no_chat": "sem chat", "top_emotes": "Emotes mais usados", "none": "nenhum", "chat_sample": "Amostra do chat",
|
||||
"no_chat_p": "(sem chat)", "frames_none": "Frames: (nenhum)", "frames": "Frames anexados, em ordem",
|
||||
"new_window": "Janela nova", "back_to": "pode voltar até {s}s para pegar o início de uma ação",
|
||||
"done": "Cortes já feitos aqui", "analysis": "Análise do ANALISTA (cruzou tela, fala e chat)"},
|
||||
"en": {"live_title": "Stream title", "unknown": "unknown", "channel": "Channel", "window": "Available window",
|
||||
"candidate": "Heuristic candidate", "peak": "reaction peak at", "duration": "Clip duration",
|
||||
"signals": "Heuristic signals", "face": "Streamer face (expression measured on the webcam, relative to his normal)",
|
||||
"transcript": "Transcript", "no_speech": "(no transcribed speech)", "chat_per": "Chat messages per",
|
||||
"no_chat": "no chat", "top_emotes": "Top emotes", "none": "none", "chat_sample": "Chat sample",
|
||||
"no_chat_p": "(no chat)", "frames_none": "Frames: (none)", "frames": "Attached frames, in order",
|
||||
"new_window": "New window", "back_to": "may go back to {s}s to catch the start of an action",
|
||||
"done": "Clips already made here", "analysis": "ANALYST's analysis (cross-checked screen, speech and chat)"},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- prompts
|
||||
# Idiomas que o serviço conhece (fonte/sessão `language`; o painel oferece os mesmos). Nome legível para o prompt.
|
||||
LANGUAGE_NAMES = {"pt-BR": "português do Brasil", "en-US": "English (US)", "es-419": "Español (Latinoamérica)"}
|
||||
@@ -412,8 +571,8 @@ def output_language_note(language: str | None) -> str:
|
||||
"""Linha que vai no contexto do EDITOR e da VARREDURA quando a saída não é em português: título, legenda e
|
||||
hashtags no idioma do público. Vazia para pt-BR (os prompts já são em português)."""
|
||||
code = (language or "").strip() or DEFAULT_LANGUAGE
|
||||
if code == DEFAULT_LANGUAGE:
|
||||
return ""
|
||||
if code == DEFAULT_LANGUAGE or lang_key(code) == "en":
|
||||
return "" # inglês: os juízes já trabalham em inglês (ANALYST/JUDGE/SCAN_SYSTEM_EN)
|
||||
name = LANGUAGE_NAMES.get(code, code)
|
||||
return (f"Idioma de saída: {name}. Título, legenda e hashtags em {name}, naturais para o público desse idioma "
|
||||
f"(a transcrição e o chat podem estar em outro idioma; não traduza literalmente, escreva como um editor nativo).")
|
||||
@@ -423,33 +582,39 @@ MISSIONS_IN_PROMPT = 25
|
||||
MISSIONS_PROMPT_CHARS = 1500
|
||||
|
||||
|
||||
def mission_lines(profile: dict) -> list[str]:
|
||||
def mission_lines(profile: dict, lang: str = "pt") -> list[str]:
|
||||
"""Gatilhos de fim de missão e as missões (nome + gatilhos) para o prompt, com teto de tamanho: o perfil do GTA
|
||||
pode ter 100+ missões, e o contexto vai em todo julgamento."""
|
||||
lines: list[str] = []
|
||||
triggers = [str(t) for t in (profile.get("end_triggers") or [])[:10] if t]
|
||||
if triggers:
|
||||
lines.append("Sinais de fim de missão/objetivo neste jogo: " + "; ".join(triggers))
|
||||
lines.append(("Mission/objective end signals in this game: " if lang == "en" else
|
||||
"Sinais de fim de missão/objetivo neste jogo: ") + "; ".join(triggers))
|
||||
missions = [m for m in (profile.get("missions") or []) if isinstance(m, dict) and m.get("name")]
|
||||
if missions:
|
||||
parts, used = [], 0
|
||||
for m in missions[:MISSIONS_IN_PROMPT]:
|
||||
ends = " / ".join(str(t) for t in (m.get("completion_triggers") or [])[:2] if t)
|
||||
item = f"{m['name']}" + (f" (fim: {ends})" if ends else "")
|
||||
item = f"{m['name']}" + (f" ({'end' if lang == 'en' else 'fim'}: {ends})" if ends else "")
|
||||
if used + len(item) > MISSIONS_PROMPT_CHARS:
|
||||
break
|
||||
parts.append(item)
|
||||
used += len(item) + 2
|
||||
extra = len(missions) - len(parts)
|
||||
lines.append("Missões da história: " + "; ".join(parts) + (f"; …e mais {extra}" if extra > 0 else ""))
|
||||
more = (f"; …and {extra} more" if lang == "en" else f"; …e mais {extra}") if extra > 0 else ""
|
||||
lines.append(("Story missions: " if lang == "en" else "Missões da história: ") + "; ".join(parts) + more)
|
||||
if triggers or missions:
|
||||
lines.append("Se o trecho é o fim de uma missão, termine o corte logo depois do gatilho de fim "
|
||||
lines.append("If the segment is the end of a mission, end the clip right after the end trigger "
|
||||
"(the win/fail moment is the climax)." if lang == "en" else
|
||||
"Se o trecho é o fim de uma missão, termine o corte logo depois do gatilho de fim "
|
||||
"(o momento de vitória/falha é o clímax).")
|
||||
return lines
|
||||
|
||||
|
||||
def game_context(game: str, screen_game: str, profile: dict | None, live_title: str, history: str = "",
|
||||
confirmed: bool = False) -> str:
|
||||
confirmed: bool = False, lang: str = "pt") -> str:
|
||||
if lang == "en":
|
||||
return _game_context_en(game, screen_game, profile, live_title, history, confirmed)
|
||||
lines = [f"Título da live: {live_title or '(desconhecido)'}"]
|
||||
if confirmed:
|
||||
# O usuário confirmou no painel: não questionar (jogo novo/pouco conhecido lembra outros na tela).
|
||||
@@ -472,7 +637,30 @@ def game_context(game: str, screen_game: str, profile: dict | None, live_title:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _transcript(words: list[Word], lo: float, hi: float) -> str:
|
||||
def _game_context_en(game: str, screen_game: str, profile: dict | None, live_title: str, history: str,
|
||||
confirmed: bool) -> str:
|
||||
lines = [f"Stream title: {live_title or '(unknown)'}"]
|
||||
if confirmed:
|
||||
lines.append(f"Game CONFIRMED by the user: {game}. The screen may look like a similar game (e.g. GTA, Warzone) "
|
||||
f"— don't question the game; use the profile below to understand what happens.")
|
||||
else:
|
||||
lines.append(f"Game from the platform category: {game or '(unknown)'}")
|
||||
if screen_game and screen_game.lower() not in (game or "").lower():
|
||||
lines.append(f"Game the AI saw on screen recently: {screen_game} (check the frames; the category may be wrong)")
|
||||
if profile:
|
||||
lines.append(f"Game profile: {profile.get('summary', '')}")
|
||||
for key, label in (("clip_worthy", "Clip-worthy in this game"), ("avoid", "Not clip-worthy"),
|
||||
("mechanics", "Mechanics/activities (terms for the moment hashtags)"),
|
||||
("jargon", "Slang/terms"), ("news", "News")):
|
||||
if profile.get(key):
|
||||
lines.append(f"{label}: " + "; ".join(profile[key][:10]))
|
||||
lines.extend(mission_lines(profile, "en"))
|
||||
if history:
|
||||
lines.append(f"What happened earlier in the stream: {history}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _transcript(words: list[Word], lo: float, hi: float, lang: str = "pt") -> str:
|
||||
lines, current, current_t = [], [], None
|
||||
for word in sorted((w for w in words if lo <= w.start <= hi), key=lambda w: w.start):
|
||||
if current_t is None or word.start - current_t > 4 or len(current) >= 14:
|
||||
@@ -482,10 +670,12 @@ def _transcript(words: list[Word], lo: float, hi: float) -> str:
|
||||
current.append(word.word)
|
||||
if current:
|
||||
lines.append(f"[{current_t:.0f}s] {' '.join(current)}")
|
||||
return "\n".join(lines) or "(sem fala transcrita)"
|
||||
return "\n".join(lines) or LABELS[lang]["no_speech"]
|
||||
|
||||
|
||||
def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | None, bucket_s: int = 5) -> str:
|
||||
def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | None, bucket_s: int = 5,
|
||||
lang: str = "pt") -> str:
|
||||
L = LABELS[lang]
|
||||
buckets: dict[int, int] = {}
|
||||
emotes: dict[str, int] = {}
|
||||
sample: list[str] = []
|
||||
@@ -498,50 +688,52 @@ def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | No
|
||||
near = focus is None or focus - 10 <= message.t <= focus + 8
|
||||
if near and len(sample) < 60:
|
||||
sample.append(f"[{message.t:.0f}s] {message.text[:80]}")
|
||||
rate = ", ".join(f"{t}s:{n}" for t, n in sorted(buckets.items())) or "sem chat"
|
||||
top = ", ".join(f"{e}×{n}" for e, n in sorted(emotes.items(), key=lambda kv: -kv[1])[:12]) or "nenhum"
|
||||
return (f"Mensagens do chat por {bucket_s} s: {rate}\nEmotes mais usados: {top}\n"
|
||||
f"Amostra do chat:\n" + ("\n".join(sample) or "(sem chat)"))
|
||||
rate = ", ".join(f"{t}s:{n}" for t, n in sorted(buckets.items())) or L["no_chat"]
|
||||
top = ", ".join(f"{e}×{n}" for e, n in sorted(emotes.items(), key=lambda kv: -kv[1])[:12]) or L["none"]
|
||||
return (f"{L['chat_per']} {bucket_s} s: {rate}\n{L['top_emotes']}: {top}\n"
|
||||
f"{L['chat_sample']}:\n" + ("\n".join(sample) or L["no_chat_p"]))
|
||||
|
||||
|
||||
def _frames_block(frames: list[tuple[float, Path]]) -> str:
|
||||
def _frames_block(frames: list[tuple[float, Path]], lang: str = "pt") -> str:
|
||||
if not frames:
|
||||
return "Frames: (nenhum)"
|
||||
return "Frames anexados, em ordem: " + ", ".join(f"#{i + 1} = {t:.0f}s" for i, (t, _) in enumerate(frames))
|
||||
return LABELS[lang]["frames_none"]
|
||||
return LABELS[lang]["frames"] + ": " + ", ".join(f"#{i + 1} = {t:.0f}s" for i, (t, _) in enumerate(frames))
|
||||
|
||||
|
||||
def build_prompt(streamer: str, platform: str, start_s: float, end_s: float, peak_s: float,
|
||||
words: list[Word], chat: list[ChatMessage], heuristic: dict, live_title: str = "", *,
|
||||
context: str = "", frames: list[tuple[float, Path]] | None = None,
|
||||
backtrack_s: float = DEFAULT_BACKTRACK_S, min_s: float = DEFAULT_MIN_S, max_s: float = DEFAULT_MAX_S,
|
||||
face: str = "") -> str:
|
||||
face: str = "", lang: str = "pt") -> str:
|
||||
"""Prompt do juiz. Janela = candidato com `backtrack_s` para trás (a ação vem antes do comentário).
|
||||
`face`: resumo do rosto do streamer na janela (face.FaceService.summary); vazio = sem câmera/rastreio."""
|
||||
lo, hi = max(0.0, start_s - backtrack_s), end_s + CONTEXT_AFTER_S
|
||||
L, to = LABELS[lang], ("to" if lang == "en" else "a")
|
||||
return (
|
||||
f"Canal: {streamer} ({platform})\n"
|
||||
+ (context or f"Título da live: {live_title or '(desconhecido)'}") + "\n\n"
|
||||
f"Janela disponível: {lo:.0f}s a {hi:.0f}s. Candidato da heurística: {start_s:.0f}s a {end_s:.0f}s; "
|
||||
f"pico de reação em {peak_s:.0f}s. Duração do corte: {min_s:.0f} a {max_s:.0f} s.\n"
|
||||
f"Sinais da heurística: {json.dumps(heuristic, ensure_ascii=False)}\n"
|
||||
+ (f"Rosto do streamer (expressão medida na webcam, relativa ao normal dele): {face}\n" if face else "")
|
||||
+ f"{_frames_block(frames or [])}\n\n"
|
||||
f"Transcrição:\n{_transcript(words, lo, hi)}\n\n"
|
||||
f"{_chat_block(chat, lo, hi, peak_s)}"
|
||||
f"{L['channel']}: {streamer} ({platform})\n"
|
||||
+ (context or f"{L['live_title']}: {live_title or '(' + L['unknown'] + ')'}") + "\n\n"
|
||||
f"{L['window']}: {lo:.0f}s {to} {hi:.0f}s. {L['candidate']}: {start_s:.0f}s {to} {end_s:.0f}s; "
|
||||
f"{L['peak']} {peak_s:.0f}s. {L['duration']}: {min_s:.0f} {to} {max_s:.0f} s.\n"
|
||||
f"{L['signals']}: {json.dumps(heuristic, ensure_ascii=False)}\n"
|
||||
+ (f"{L['face']}: {face}\n" if face else "")
|
||||
+ f"{_frames_block(frames or [], lang)}\n\n"
|
||||
f"{L['transcript']}:\n{_transcript(words, lo, hi, lang)}\n\n"
|
||||
f"{_chat_block(chat, lo, hi, peak_s, lang=lang)}"
|
||||
)
|
||||
|
||||
|
||||
def build_scan_prompt(streamer: str, platform: str, lo: float, hi: float, back_lo: float, words: list[Word],
|
||||
chat: list[ChatMessage], context: str, frames: list[tuple[float, Path]],
|
||||
existing: list[tuple[float, float, str]], min_s: float, max_s: float) -> str:
|
||||
done = "; ".join(f"{a:.0f}–{b:.0f}s ({t[:40]})" for a, b, t in existing) or "nenhum"
|
||||
existing: list[tuple[float, float, str]], min_s: float, max_s: float, lang: str = "pt") -> str:
|
||||
L, to = LABELS[lang], ("to" if lang == "en" else "a")
|
||||
done = "; ".join(f"{a:.0f}–{b:.0f}s ({t[:40]})" for a, b, t in existing) or L["none"]
|
||||
return (
|
||||
f"Canal: {streamer} ({platform})\n{context}\n\n"
|
||||
f"Janela nova: {lo:.0f}s a {hi:.0f}s (pode voltar até {back_lo:.0f}s para pegar o início de uma ação).\n"
|
||||
f"Duração do corte: {min_s:.0f} a {max_s:.0f} s. Cortes já feitos aqui: {done}\n"
|
||||
f"{_frames_block(frames)}\n\n"
|
||||
f"Transcrição:\n{_transcript(words, back_lo, hi)}\n\n"
|
||||
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10)}"
|
||||
f"{L['channel']}: {streamer} ({platform})\n{context}\n\n"
|
||||
f"{L['new_window']}: {lo:.0f}s {to} {hi:.0f}s ({L['back_to'].format(s=f'{back_lo:.0f}')}).\n"
|
||||
f"{L['duration']}: {min_s:.0f} {to} {max_s:.0f} s. {L['done']}: {done}\n"
|
||||
f"{_frames_block(frames, lang)}\n\n"
|
||||
f"{L['transcript']}:\n{_transcript(words, back_lo, hi, lang)}\n\n"
|
||||
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10, lang=lang)}"
|
||||
)
|
||||
|
||||
|
||||
@@ -563,6 +755,7 @@ def _clean(data: dict, start_s: float, end_s: float, model: str, lo: float | Non
|
||||
title=str(data["title"]).strip()[:100], caption=str(data["caption"]).strip()[:600],
|
||||
reason=str(data["reason"]).strip()[:300], model=model,
|
||||
hashtags=tuple(str(t).strip()[:40] for t in (data.get("hashtags") or [])[:6] if str(t).strip()),
|
||||
pt={k: str(v).strip()[:600] for k, v in (data.get("pt") or {}).items() if k in ("title", "caption", "reason") and v},
|
||||
)
|
||||
|
||||
|
||||
@@ -701,7 +894,8 @@ class Judge:
|
||||
|
||||
def fallback_chain(self) -> list[str]:
|
||||
"""Ordem em que `ask` tenta as IAs: a escolhida no juiz primeiro, depois a `order` do painel, só as ligadas,
|
||||
com CLI e (no modo chave) com chave; as em pausa são puladas. Reserva desligada: só a escolhida.
|
||||
com CLI e (no modo chave) com chave; as em pausa são puladas e as perto do limite de uso vão para o fim.
|
||||
Reserva desligada: só a escolhida.
|
||||
Se TODAS as prontas estiverem em pausa, elas voltam como último recurso (melhor tentar do que parar)."""
|
||||
if not self.enabled:
|
||||
return []
|
||||
@@ -710,9 +904,13 @@ class Judge:
|
||||
if settings["fallback"]["enabled"]:
|
||||
candidates += [p for p in settings["order"] if p != self.provider and p in AI_ENABLED]
|
||||
ready = [p for p in candidates if self._skip_reason(p, settings) is None]
|
||||
paused = self.pauses() if settings["fallback"]["enabled"] else {}
|
||||
active = [p for p in ready if p not in paused]
|
||||
return active or ready
|
||||
if not settings["fallback"]["enabled"]:
|
||||
return ready
|
||||
paused = self.pauses()
|
||||
# Perto do limite de uso (data/ai/usage.json, do painel): vai para depois das livres, antes das em pausa.
|
||||
limited = {p for p in ready if p not in paused and self.ai.over_limit(p)}
|
||||
active = [p for p in ready if p not in paused and p not in limited]
|
||||
return (active + [p for p in ready if p in limited]) or ready
|
||||
|
||||
def describe(self) -> dict:
|
||||
cmd = self.command() if self.enabled else None
|
||||
@@ -734,9 +932,11 @@ class Judge:
|
||||
return {"codex": codex_models(), "claude": CLAUDE_MODELS, "gemini": GEMINI_MODELS, "defaults": DEFAULT_MODELS}
|
||||
|
||||
# ---------- usos
|
||||
def analyze(self, prompt: str, images: list[Path]) -> dict:
|
||||
"""1º juiz (ANALISTA): o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título."""
|
||||
data = self.ask(ANALYST_SYSTEM, prompt, ANALYSIS_SCHEMA, images, model=self.analyst_model or self.model)
|
||||
def analyze(self, prompt: str, images: list[Path], lang: str = "pt") -> dict:
|
||||
"""1º juiz (ANALISTA): o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título.
|
||||
`lang="en"`: prompt em inglês e bloco `pt` (tradução para o painel) na mesma resposta."""
|
||||
system, schema = (ANALYST_SYSTEM_EN, ANALYSIS_SCHEMA_EN) if lang == "en" else (ANALYST_SYSTEM, ANALYSIS_SCHEMA)
|
||||
data = self.ask(system, prompt, schema, images, model=self.analyst_model or self.model)
|
||||
missing = [k for k in ANALYSIS_SCHEMA["required"] if k not in data]
|
||||
if missing:
|
||||
raise JudgeError(f"análise sem os campos {missing}")
|
||||
@@ -745,13 +945,27 @@ class Judge:
|
||||
|
||||
def judge(self, prompt: str, start_s: float, end_s: float, images: list[Path] | None = None, *,
|
||||
lo: float | None = None, hi: float | None = None, min_s: float = DEFAULT_MIN_S,
|
||||
max_s: float = DEFAULT_MAX_S) -> Verdict:
|
||||
data = self.ask(JUDGE_SYSTEM, prompt, VERDICT_SCHEMA, images or [])
|
||||
max_s: float = DEFAULT_MAX_S, lang: str = "pt") -> Verdict:
|
||||
system, schema = (JUDGE_SYSTEM_EN, VERDICT_SCHEMA_EN) if lang == "en" else (JUDGE_SYSTEM, VERDICT_SCHEMA)
|
||||
data = self.ask(system, prompt, schema, images or [])
|
||||
# Modelo de quem DE FATO respondeu (a reserva pode ter entrado no lugar da escolhida).
|
||||
return _clean(data, start_s, end_s, self.responder(), lo, hi, min_s, max_s)
|
||||
|
||||
def scan(self, prompt: str, images: list[Path]) -> dict:
|
||||
data = self.ask(SCAN_SYSTEM, prompt, SCAN_SCHEMA, images)
|
||||
def translate_lines(self, lines: list[str]) -> list[str]:
|
||||
"""Fala de um corte (frases em ordem) → português, mesma quantidade. Para o painel e a legenda de
|
||||
desenvolvimento; o vídeo publicado continua no idioma da fonte."""
|
||||
if not lines:
|
||||
return []
|
||||
prompt = "\n".join(f"{i + 1}. {text}" for i, text in enumerate(lines))
|
||||
data = self.ask(LINES_SYSTEM, prompt, LINES_SCHEMA, [])
|
||||
out = [str(x).strip() for x in (data.get("lines") or [])]
|
||||
if len(out) != len(lines):
|
||||
raise JudgeError(f"tradução com {len(out)} linhas para {len(lines)} frases", unavailable=False)
|
||||
return out
|
||||
|
||||
def scan(self, prompt: str, images: list[Path], lang: str = "pt") -> dict:
|
||||
system, schema = (SCAN_SYSTEM_EN, SCAN_SCHEMA_EN) if lang == "en" else (SCAN_SYSTEM, SCAN_SCHEMA)
|
||||
data = self.ask(system, prompt, schema, images)
|
||||
if not isinstance(data.get("moments"), list):
|
||||
raise JudgeError("varredura sem a lista de momentos")
|
||||
return data
|
||||
@@ -974,6 +1188,7 @@ def parse_gemini_output(stdout: str) -> dict:
|
||||
return data
|
||||
|
||||
|
||||
def analysis_block(analysis: dict) -> str:
|
||||
"""Análise do 1º juiz no formato que o editor lê."""
|
||||
return "Análise do ANALISTA (cruzou tela, fala e chat):\n" + json.dumps(analysis, ensure_ascii=False, indent=1)
|
||||
def analysis_block(analysis: dict, lang: str = "pt") -> str:
|
||||
"""Análise do 1º juiz no formato que o editor lê (sem o bloco `pt`, que é só para o painel)."""
|
||||
data = {k: v for k, v in analysis.items() if k != "pt"}
|
||||
return LABELS[lang]["analysis"] + ":\n" + json.dumps(data, ensure_ascii=False, indent=1)
|
||||
|
||||
Reference in New Issue
Block a user