"""Inteligência do Clipador além da heurística: contexto do jogo, varredura da IA, webcam e emotes que aprendem. Pedido do usuário (17/11/2026), depois de uma live com chat pequeno (skipnho, 0,15 msg/s) passar 15 min sem corte: - a IA precisa saber QUE JOGO é (categoria da plataforma, título, chat e a própria tela) e conhecer o jogo (pesquisa na web, guardada por jogo); - a IA precisa VER a tela (frames) e procurar momentos sozinha, mesmo sem pico de chat (varredura); - achar a webcam do streamer para o layout câmera-em-cima; - emotes da Twitch/7TV/BTTV/FFZ contam como reação e ganham peso por canal conforme os cortes aprovados. """ from __future__ import annotations import json import logging import re import threading import time from pathlib import Path from typing import TYPE_CHECKING from . import clip_delete, layout from .db import loads, now from .emotes import EmoteCatalog, extract, learn_delta, message_bonus from .face import FaceError, FaceUnavailable from .game_detect import ( CHAT_FULL_AT, CHAT_MIN_MESSAGES, SPEECH_FULL_AT, Evidence, count_mentions, fuse, is_generic, screen_strength, slug_all, ) from .hashtags import fold, to_tag from .judge import JudgeError, build_scan_prompt, game_context, lang_key, output_language_note from .scoring import fit_window from .sources import parse_source if TYPE_CHECKING: # pragma: no cover from .worker import Engine log = logging.getLogger("cenaforge_clipper.intel") # faceTrack: rastreio do rosto do streamer (face.py) — reforça/cria cortes e vai em texto para o analista. OPTION_DEFAULTS = {"scanEnabled": True, "scanIntervalS": 180, "vision": True, "camDetect": True, "faceTrack": True} CAM_RETRY_S = 300 # câmera não achada enquanto grava: nova tentativa depois de mais 5 min de gravação CAM_MAX_ATTEMPTS = 6 # falha sem rosto decidido (poucos quadros legíveis): no máximo isto de tentativas GAME_CHECK_S = 180 # rechecar a categoria da live (e cruzar com tela, chat e fala) a cada 3 min: o streamer troca de jogo UNKNOWN_GAMES = {"", "desconhecido", "não identificável", "nao identificavel", "unknown", "none", "n/a", "não sei", "nenhum"} SCREEN_FRESH_S = 900 # o que a IA viu na tela vale como pista por 15 min CHAT_WINDOW_S = 360 # chat e fala dos últimos 6 min entram na detecção do jogo SPEECH_SEGMENTS = 12 # = 6 min de blocos de 30 s SCAN_FRAME_EVERY_S = 30 SCAN_MAX_FRAMES = 7 MEMORY_KEEP = 6 SCAN_MAX_MOMENTS = 2 SCAN_MIN_PROPOSAL = 4 # proposta da varredura abaixo disso nem vai aos juízes (economia) class CamRetryLater(JudgeError): """Câmera local indisponível por um motivo passageiro (modelo/download): não é "sem câmera".""" def game_id(name: str) -> str: return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:60] or "desconhecido" PROFILE_LISTS = ("mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags", "sources", "aliases", "end_triggers") # Teto de cada lista (o resto: 20). Missões ficam à parte (objetos, até 120). LIST_LIMITS = {"aliases": 10, "end_triggers": 12} MAX_MISSIONS = 120 MAX_MISSION_TRIGGERS = 8 # Sementes: perfis prontos que vêm com o repositório (ex.: GTA VI). Importados na subida só se o jogo não existe. SEEDS_DIR = Path(__file__).resolve().parent / "seeds" / "games" def _clean_text_list(values, limit: int, item_chars: int = 300) -> list[str]: items, seen = [], set() for item in values or []: text = str(item or "").strip()[:item_chars] if text and text.lower() not in seen: seen.add(text.lower()) items.append(text) return items[:limit] def clean_missions(values) -> list[dict]: """Missões: nome obrigatório (sem repetir), capítulo, resumo e até 8 gatilhos de fim (até 200 caracteres cada).""" out, seen = [], set() for raw in values or []: if not isinstance(raw, dict): continue name = str(raw.get("name") or "").strip()[:160] if not name or name.lower() in seen: continue seen.add(name.lower()) out.append({ "name": name, "chapter": str(raw.get("chapter") or "").strip()[:120], "summary": str(raw.get("summary") or "").strip()[:500], "completion_triggers": _clean_text_list(raw.get("completion_triggers"), MAX_MISSION_TRIGGERS, 200), }) if len(out) >= MAX_MISSIONS: break return out def clean_profile(raw: dict) -> dict: """Normaliza um perfil de jogo (vindo da IA, da tradução ou da edição à mão): textos aparados, listas sem vazios/duplicados, missões validadas. Hashtags viram tag de verdade ("rob run" → "#RobRun"; sem letra some), comparadas sem acento/maiúscula.""" raw = raw if isinstance(raw, dict) else {} out: dict = {k: str(raw.get(k) or "").strip()[:limit] for k, limit in (("name", 120), ("summary", 1500), ("genre", 120))} for key in PROFILE_LISTS: if key == "hashtags": items, seen = [], set() for item in raw.get(key) or []: text = to_tag(str(item or "").strip()[:300]) or "" if text and fold(text) not in seen: seen.add(fold(text)) items.append(text) out[key] = items[:20] else: out[key] = _clean_text_list(raw.get(key), LIST_LIMITS.get(key, 20)) out["missions"] = clean_missions(raw.get("missions")) return out def alias_ids(*profiles: dict | None) -> list[str]: """Ids normalizados dos outros nomes do jogo (das duas versões do perfil), sem repetir.""" ids: list[str] = [] for profile in profiles: for alias in (profile or {}).get("aliases") or []: gid = game_id(str(alias)) if gid != "desconhecido" and gid not in ids: ids.append(gid) return ids class Intel: def __init__(self, engine: "Engine"): self.e = engine self.catalog = EmoteCatalog() self._weights: dict[str, tuple[float, dict[str, float]]] = {} self._rooms_ready: set[str] = set() self._game_checked: dict[int, float] = {} self._detect_lock = threading.RLock() # `game_detect_json` é lido-e-gravado pelo laço de contexto e pela varredura self._cam_retry_at: dict[int, float] = {} # falha transitória da câmera local (modelo/download): só em memória self.last_scan_error: str | None = None saved = {r["key"]: r["value"] for r in engine.db.all("SELECT key, value FROM settings")} self.opts = dict(OPTION_DEFAULTS) for key in OPTION_DEFAULTS: if f"opt_{key}" in saved: self.opts[key] = json.loads(saved[f"opt_{key}"]) self.import_seeds() # ---------------------------------------------------------------- sementes de jogos def import_seeds(self, folder: Path | None = None) -> list[str]: """Importa os perfis de `seeds/games/*.json` ({name, aliases, researchedAt, sources, profileAi, profile}) que ainda não existem no banco (por id ou alias). Nunca sobrescreve: o que você editou fica. Devolve os ids novos.""" added: list[str] = [] for path in sorted((folder or SEEDS_DIR).glob("*.json")): try: seed = json.loads(path.read_text(encoding="utf-8")) name = str(seed.get("name") or "").strip() if not name: continue ai = clean_profile({**(seed.get("profileAi") or {}), "name": name}) pt = clean_profile({**(seed.get("profile") or seed.get("profileAi") or {}), "name": name}) for profile in (ai, pt): profile["aliases"] = profile["aliases"] or list(seed.get("aliases") or []) profile["sources"] = profile["sources"] or list(seed.get("sources") or []) gid = game_id(name) if self.find_game(name) or any(self.find_game(a) for a in ai["aliases"]): continue self.e.db.run( "INSERT INTO games (id, name, status, profile_json, profile_ai_json, aliases_json, model, researched_at," " translated_at) VALUES (?, ?, 'ready', ?, ?, ?, 'seed', ?, ?)", gid, name[:120], json.dumps(pt, ensure_ascii=False), json.dumps(ai, ensure_ascii=False), json.dumps(alias_ids(ai, pt)), seed.get("researchedAt") or now(), seed.get("researchedAt") or now()) added.append(gid) log.info("jogo importado da semente %s: %s", path.name, name) except (OSError, ValueError) as exc: log.warning("semente de jogo %s inválida: %s", path.name, exc) return added # ---------------------------------------------------------------- opções (painel) def set_options(self, values: dict) -> dict: clean = {} for key, value in values.items(): if key not in OPTION_DEFAULTS or value is None: continue if key == "scanIntervalS": value = int(value) if not 60 <= value <= 900: raise JudgeError("intervalo da varredura vai de 60 a 900 s") else: value = bool(value) clean[key] = value self.opts.update(clean) self.e.db.many("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", [(f"opt_{k}", json.dumps(v)) for k, v in clean.items()]) return dict(self.opts) # ---------------------------------------------------------------- canal / configuração do corte @staticmethod def channel_key(session: dict) -> str: source = parse_source(session["url"]) return source.channel_id if source.channel else "" def settings_for(self, session: dict) -> dict: channel = None if session.get("channel_id"): channel = self.e.db.get("SELECT settings_json FROM channels WHERE id = ?", session["channel_id"]) return layout.merge(loads(channel["settings_json"], {}) if channel else {}, loads(session.get("settings_json"), {})) # ---------------------------------------------------------------- emotes def ingest_chat(self, session_id: int, channel_key: str, room_id: str | None, batch: list[tuple[float, str, str, list[str]]]) -> None: if room_id: if room_id not in self._rooms_ready: self.e.db.run("UPDATE sessions SET room_id = ? WHERE id = ? AND room_id IS NULL", room_id, session_id) # Baixa o catálogo do canal fora da linha do chat (APIs externas podem demorar). self._rooms_ready.add(room_id) threading.Thread(target=self.catalog.names, args=(room_id,), daemon=True).start() catalog = self.catalog.cached(room_id) rows, seen = [], [] for wall, user, text, twitch_emotes in batch: found = extract(text, twitch_emotes, catalog) rows.append((session_id, wall, user, text, json.dumps([n for n, _ in found], ensure_ascii=False) if found else None)) seen.extend(found) self.e.db.many("INSERT INTO chat (session_id, wall, user, text, emotes) VALUES (?, ?, ?, ?, ?)", rows) if channel_key and seen: ts = now() self.e.db.many( "INSERT INTO emotes (channel_key, name, source, uses, weight, first_seen, last_seen) VALUES (?, ?, ?, 1, 0, ?, ?)" " ON CONFLICT (channel_key, name) DO UPDATE SET uses = uses + 1, last_seen = excluded.last_seen", [(channel_key, name, source, ts, ts) for name, source in seen]) def weights(self, channel_key: str) -> dict[str, float]: cached = self._weights.get(channel_key) if cached and time.time() - cached[0] < 30: return cached[1] rows = self.e.db.all("SELECT name, weight FROM emotes WHERE channel_key = ? AND weight != 0", channel_key) weights = {r["name"]: r["weight"] for r in rows} self._weights[channel_key] = (time.time(), weights) return weights def bonus(self, emotes: list[str], channel_key: str) -> float: return message_bonus(emotes, self.weights(channel_key)) if emotes else 0.0 def learn_from_clip(self, clip: dict, positive: bool, factor: float = 1.0, mark: bool = False) -> int: """Emotes da reação do corte (−10 s a +6 s do pico) ganham (aprovado) ou perdem (rejeitado) peso no canal.""" session = self.e.db.get("SELECT * FROM sessions WHERE id = ?", clip["session_id"]) if not session or (mark and clip.get("learned")): return 0 key = self.channel_key(session) if not key: return 0 tl = self.e.load_timeline(session["id"], max(0.0, clip["peak_s"] - 120)) names = {e for m in tl["chat"] if clip["peak_s"] - 10 <= m.t <= clip["peak_s"] + 6 for e in m.emotes} delta = learn_delta(positive) * factor self.e.db.many("UPDATE emotes SET weight = MAX(-1.0, MIN(3.0, weight + ?)) WHERE channel_key = ? AND name = ?", [(delta, key, n) for n in names]) if mark: self.e.db.run("UPDATE clips SET learned = 1 WHERE id = ?", clip["id"]) self._weights.pop(key, None) return len(names) # ---------------------------------------------------------------- jogo def check_game(self, session: dict, force: bool = False, detect: bool = True) -> None: """Categoria atual da live (Streamlink) e título → pistas da sessão; depois cruza tudo (`detect_game`).""" if session["kind"] != "live": return last = self._game_checked.get(session["id"], 0) if not force and time.time() - last < GAME_CHECK_S: return self._game_checked[session["id"]] = time.time() meta = self.e.check_meta(session["url"]) if not meta: return if meta.get("title") and not session.get("title"): self.e.db.run("UPDATE sessions SET title = ? WHERE id = ?", meta["title"][:200], session["id"]) with self._detect_lock: state = self._detect_state(session["id"]) state["platform"] = {"game": (meta.get("category") or "").strip()[:120], "title": (meta.get("title") or "")[:200], "at": now()} self._save_detect_state(session["id"], state) if detect: self.detect_game(session["id"]) # ---- detecção do jogo (game_detect.py: a regra; aqui: juntar as pistas e aplicar) def _detect_state(self, session_id: int) -> dict: row = self.e.db.get("SELECT game_detect_json FROM sessions WHERE id = ?", session_id) or {} state = loads(row.get("game_detect_json"), {}) return state if isinstance(state, dict) else {} def _save_detect_state(self, session_id: int, state: dict) -> None: self.e.db.run("UPDATE sessions SET game_detect_json = ? WHERE id = ?", json.dumps(state, ensure_ascii=False), session_id) def canon(self, name: str) -> tuple[str, str]: """(id canônico, nome para mostrar): "GTA 6" e "Grand Theft Auto VI" dão o mesmo id quando o jogo está cadastrado.""" row = self.find_game(name) return (row["id"], row["name"]) if row else (game_id(name), name.strip()) def note_screen(self, session_id: int, game: str, confidence: str = "", evidence: str = "") -> None: """O que a IA viu na tela (varredura ou "Detectar agora") vira pista; vale por SCREEN_FRESH_S.""" game = (game or "").strip() if not game or game.lower() in UNKNOWN_GAMES: return with self._detect_lock: state = self._detect_state(session_id) state["screen"] = {"game": game[:120], "confidence": (confidence or "medium").lower()[:10], "evidence": (evidence or "")[:240], "at": now(), "ts": time.time()} self._save_detect_state(session_id, state) def _mention_forms(self) -> tuple[dict[str, set[str]], dict[str, str]]: """Jogos conhecidos → formas de nome para procurar no texto (id, nome e outros nomes) e o nome de cada um.""" forms: dict[str, set[str]] = {} names: dict[str, str] = {} for row in self.e.db.all("SELECT id, name, aliases_json FROM games"): if is_generic(row["id"]): continue forms[row["id"]] = {row["id"], slug_all(row["name"]), *loads(row["aliases_json"], [])} names[row["id"]] = row["name"] return forms, names def _recent_texts(self, session_id: int) -> tuple[list[str], list[str]]: """(mensagens do chat, trechos de fala) dos últimos minutos — só texto cru, sem montar a linha do tempo.""" from .speakers import parse_words # import local: speakers importa módulos que importam este chat = [r["text"] for r in self.e.db.all( "SELECT text FROM chat WHERE session_id = ? AND wall >= (SELECT COALESCE(MAX(wall), 0) - ? FROM chat WHERE session_id = ?)", session_id, CHAT_WINDOW_S, session_id)] speech = [" ".join(w.word for w in parse_words(r["words_json"])) for r in self.e.db.all( "SELECT words_json FROM segments WHERE session_id = ? AND analyzed = 1 ORDER BY idx DESC LIMIT ?", session_id, SPEECH_SEGMENTS)] return chat, speech def gather_evidence(self, session: dict, state: dict) -> list[Evidence]: out: list[Evidence] = [] forms, names = self._mention_forms() plat = state.get("platform") or {} if plat.get("game") and not is_generic(plat["game"]): gid, _ = self.canon(plat["game"]) out.append(Evidence("platform", plat["game"], gid, 1.0, "categoria da live na plataforma")) title = plat.get("title") or session.get("title") or "" for gid, n in count_mentions([title], forms).items(): out.append(Evidence("title", names.get(gid, gid), gid, 1.0, "o título da live cita o jogo")) screen = state.get("screen") or {} if screen.get("game") and time.time() - float(screen.get("ts") or 0) < SCREEN_FRESH_S and not is_generic(screen["game"]): gid, _ = self.canon(screen["game"]) out.append(Evidence("screen", screen["game"], gid, screen_strength(screen.get("confidence", "")), screen.get("evidence") or "a IA viu o jogo nos frames")) chat, speech = self._recent_texts(session["id"]) for gid, n in count_mentions(chat, forms).items(): if n >= CHAT_MIN_MESSAGES: out.append(Evidence("chat", names.get(gid, gid), gid, min(1.0, n / CHAT_FULL_AT), f"{n} mensagem(ns) do chat citam o jogo")) for gid, n in count_mentions(speech, forms).items(): out.append(Evidence("speech", names.get(gid, gid), gid, min(1.0, n / SPEECH_FULL_AT), f"citado em {n} trecho(s) da fala")) return out def detect_game(self, session_id: int, immediate: bool = False) -> dict | None: """Cruza as pistas (categoria, título, tela, chat e fala) e atualiza o jogo da sessão. Regras: jogo que VOCÊ confirmou nunca muda sozinho (se as pistas apontarem outro jogo duas vezes seguidas, vira `suggestion` para o painel perguntar); sem confirmação, só troca de jogo se a categoria da plataforma apoiar ou se a mesma resposta vier duas checagens seguidas (`immediate` pula isso: pedido do usuário); categoria e tela discordando = `conflict` (mantém o jogo e pergunta).""" with self._detect_lock: session = self.e.db.get("SELECT * FROM sessions WHERE id = ?", session_id) if not session: return None state = self._detect_state(session_id) decision = fuse(self.gather_evidence(session, state)) current = session.get("game") or "" cur_gid = self.canon(current)[0] if current else "" locked = session.get("game_source") == "user" and bool(current) top = decision.top state["candidates"] = [c.view() for c in decision.candidates[:4]] state["checkedAt"] = now() state["suggestion"] = None status = decision.status if locked: status = "user" if top and top.gid != cur_gid and decision.status == "agreed": state["pending"] = self._streak(state, top.gid) if state["pending"]["n"] >= 2: state["suggestion"] = {"game": self.canon(top.game)[1], "score": round(top.score, 2), "sources": top.sources} else: state["pending"] = None elif top and top.gid != cur_gid and (decision.status in ("agreed", "probable") or (decision.status == "conflict" and not current)): platform_backs = any(e.source == "platform" for e in top.evidence) state["pending"] = self._streak(state, top.gid) if immediate or not current or is_generic(current) or platform_backs or state["pending"]["n"] >= 2: source = "platform" if platform_backs else "screen" if "screen" in top.sources else "chat" self.set_game(session_id, self.canon(top.game)[1], source) state["pending"] = None else: state["pending"] = None self.e.db.run("UPDATE sessions SET game_status = ? WHERE id = ?", status, session_id) self._save_detect_state(session_id, state) return {"status": status, **{k: state[k] for k in ("candidates", "suggestion")}} @staticmethod def _streak(state: dict, gid: str) -> dict: pending = state.get("pending") or {} return {"gid": gid, "n": pending.get("n", 0) + 1 if pending.get("gid") == gid else 1} def detect_game_now(self, session_id: int) -> dict: """"Detectar agora" (painel): a IA olha 3 frames recentes e diz que jogo é; depois cruza com o resto.""" session = self.e.db.get("SELECT * FROM sessions WHERE id = ?", session_id) if not session: raise JudgeError("sessão não encontrada") if not (self.opts["vision"] and self.e.judge.enabled): raise JudgeError("a detecção pela tela precisa da IA ligada e da visão ligada (Configurações → IA)") d = session["duration_s"] if d < 5: raise JudgeError("gravação curta demais para olhar a tela") times = sorted({max(1.0, d - 120), max(1.0, d - 60), max(1.0, d - 6)}) frames = self.frames(session, times, "game") if not frames: raise JudgeError("sem frames da tela (blocos apagados ou visão sem vídeo)") data = self.e.judge.detect_game([p for _, p in frames], (self._detect_state(session_id).get("platform") or {}).get("title", "")) game = str(data.get("game") or "").strip() if game and game.lower() not in UNKNOWN_GAMES: self.note_screen(session_id, game, str(data.get("confidence") or ""), str(data.get("evidence") or "")) self.e.db.run("UPDATE sessions SET screen_game = ? WHERE id = ?", game[:120], session_id) self.check_game(session, force=True, detect=False) result = self.detect_game(session_id, immediate=True) or {} return result | {"screen": {"game": game, "confidence": data.get("confidence", ""), "evidence": data.get("evidence", "")}} def set_game(self, session_id: int, name: str, source: str) -> None: session = self.e.db.get("SELECT * FROM sessions WHERE id = ?", session_id) if not session: return history = loads(session["games_json"], []) history.append({"game": name, "source": source, "atS": session["duration_s"], "at": now()}) self.e.db.run("UPDATE sessions SET game = ?, game_source = ?, games_json = ? WHERE id = ?", name[:120], source, json.dumps(history[-20:], ensure_ascii=False), session_id) gid = game_id(name) if not self.find_game(name): self.e.db.run("INSERT INTO games (id, name, status) VALUES (?, ?, 'pending')", gid, name[:120]) def research_pending(self) -> None: if not self.e.judge.enabled: return # IA desligada: o jogo fica 'pending' até ligar (antes: um WARNING no log a cada 30 s) for game in self.e.db.all("SELECT * FROM games WHERE status = 'pending' LIMIT 1"): self.research(game["id"]) def research(self, gid: str) -> dict: """Pesquisa na web EM INGLÊS (missões e gatilhos inclusos) → versão da IA; depois traduz para português (a que o painel mostra). Tradução falhou: as duas ficam em inglês e `error` explica (o jogo continua utilizável).""" game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid) if not game: raise JudgeError("jogo não encontrado") if not self.e.judge.enabled: raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para pesquisar o jogo") title = (self.e.db.get("SELECT title FROM sessions WHERE game = ? ORDER BY id DESC LIMIT 1", game["name"]) or {}).get("title", "") notes = [n.get("text", "") for n in loads(game.get("notes_json"), []) if n.get("text")] try: ai = clean_profile(self.e.judge.research_game(game["name"], title, notes)) model = self.e.judge.responder() # quem DE FATO respondeu (pode ter sido a IA reserva) except (JudgeError, json.JSONDecodeError) as exc: self.e.db.run("UPDATE games SET status = 'error', error = ? WHERE id = ?", str(exc)[:300], gid) raise JudgeError(str(exc)) from exc self.e.db.run("UPDATE games SET profile_ai_json = ?, model = ?, researched_at = ? WHERE id = ?", json.dumps(ai, ensure_ascii=False), model, now(), gid) pt, error = self._translated(ai, "pt-BR") self._store(gid, pt=pt, ai=ai, translated=error is None, error=error) return ai def _translated(self, profile: dict, target: str) -> tuple[dict, str | None]: """(perfil traduzido, None) ou (o próprio perfil, motivo) se a IA está desligada ou a tradução falhou.""" if not self.e.judge.enabled: return profile, "IA desligada: a outra versão do perfil não foi atualizada" try: out = clean_profile(self.e.judge.translate_game(profile, target)) except (JudgeError, json.JSONDecodeError) as exc: return profile, f"tradução falhou: {exc}"[:300] # A tradução nunca mexe em nome, hashtags, fontes e outros nomes (a IA às vezes "traduz" o que não devia). for key in ("name", "hashtags", "sources", "aliases"): out[key] = profile.get(key) or out.get(key) if len(out.get("missions") or []) != len(profile.get("missions") or []): return profile, "tradução perdeu missões: a outra versão ficou igual à original" return out, None def _store(self, gid: str, *, pt: dict | None = None, ai: dict | None = None, translated: bool = False, error: str | None = None, edited: bool = False, extra_sql: str = "", extra: tuple = ()) -> None: """Grava as versões que vieram (None = não mexe), os outros nomes (união das duas) e o estado.""" game = self.e.db.get("SELECT profile_json, profile_ai_json FROM games WHERE id = ?", gid) or {} pt_now = pt if pt is not None else loads(game.get("profile_json"), None) ai_now = ai if ai is not None else loads(game.get("profile_ai_json"), None) self.e.db.run( "UPDATE games SET status = 'ready', profile_json = ?, profile_ai_json = ?, aliases_json = ?, error = ?," " translated_at = CASE WHEN ? THEN ? ELSE translated_at END," " edited_at = CASE WHEN ? THEN ? ELSE edited_at END" + extra_sql + " WHERE id = ?", json.dumps(pt_now, ensure_ascii=False) if pt_now is not None else None, json.dumps(ai_now, ensure_ascii=False) if ai_now is not None else None, json.dumps(alias_ids(ai_now, pt_now)), error, int(translated), now(), int(edited), now(), *extra, gid) def save_profile(self, gid: str, profile: dict, lang: str = "pt") -> dict: """Grava a edição à mão na versão `lang` ("pt" = a que você lê; "en" = a da IA) e traduz para a outra. Com a IA desligada, grava só essa e a outra fica como estava (`translatedAt` não muda: o painel avisa que está velha).""" if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid): raise JudgeError("jogo não encontrado") clean = clean_profile(profile) target = "en-US" if lang == "pt" else "pt-BR" other, error = self._translated(clean, target) translated = error is None if lang == "pt": self._store(gid, pt=clean, ai=other if translated else None, translated=translated, error=error, edited=True) else: self._store(gid, ai=clean, pt=other if translated else None, translated=translated, error=error, edited=True) return clean def translate(self, gid: str) -> dict: """Gera a versão da IA (inglês) a partir da portuguesa — para jogos de antes da v12.""" game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid) if not game: raise JudgeError("jogo não encontrado") if not self.e.judge.enabled: raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para traduzir o perfil") pt = loads(game["profile_json"], None) if not pt: raise JudgeError("o jogo ainda não tem perfil para traduzir") ai, error = self._translated(clean_profile(pt), "en-US") if error: raise JudgeError(error) self._store(gid, ai=ai, translated=True) return ai def refine(self, gid: str, instruction: str, search: bool = True, section: str = "", history: list[dict] | None = None) -> tuple[dict, str]: """Pede à IA para acrescentar/corrigir algo no perfil (opcionalmente numa seção). Aplica na versão em inglês (a da IA; jogo antigo sem ela: na portuguesa) e traduz para português. O pedido fica guardado e volta em toda pesquisa. Devolve (perfil em português, resposta curta da IA em português).""" game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid) if not game: raise JudgeError("jogo não encontrado") if not self.e.judge.enabled: raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para editar o perfil pela IA") current = (loads(game.get("profile_ai_json"), None) or loads(game["profile_json"], None) or clean_profile({"name": game["name"]})) try: data = self.e.judge.refine_game(game["name"], current, instruction, search, section, history) model = self.e.judge.responder() # antes da tradução, que também passa pelo juiz except json.JSONDecodeError as exc: raise JudgeError(f"a IA devolveu um perfil inválido: {exc}") from exc reply = str(data.get("reply") or "").strip()[:600] ai = clean_profile(data) pt, error = self._translated(ai, "pt-BR") notes = loads(game.get("notes_json"), []) notes.append({"text": instruction, "at": now(), **({"section": section} if section else {})}) self._store(gid, ai=ai, pt=pt, translated=error is None, error=error, edited=True, extra_sql=", notes_json = ?, model = ?", extra=(json.dumps(notes[-30:], ensure_ascii=False), model)) return pt, reply def add_game(self, name: str, notes: str = "") -> str: """Cadastra um jogo pelo painel (antes só nascia da categoria da live) e pesquisa em segundo plano. Já existe (pelo id ou por outro nome dele) → UserError 409.""" name = name.strip()[:120] if not name: raise ValueError("Diga o nome do jogo.") existing = self.find_game(name) if existing: raise LookupError(f"“{existing['name']}” já está na lista.") gid = game_id(name) note_list = [{"text": notes.strip()[:1500], "at": now()}] if notes.strip() else [] self.e.db.run("INSERT INTO games (id, name, status, notes_json) VALUES (?, ?, 'pending', ?)", gid, name, json.dumps(note_list, ensure_ascii=False)) if self.e.judge.enabled: threading.Thread(target=self._research_quietly, args=(gid,), name=f"game-{gid}", daemon=True).start() return gid def _research_quietly(self, gid: str) -> None: try: self.research(gid) except JudgeError as exc: log.warning("pesquisa do jogo %s falhou: %s", gid, exc) def delete_game(self, gid: str) -> None: """Apaga o jogo. Sessões não mudam; se o jogo voltar numa live, nasce de novo e é pesquisado.""" if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid): raise JudgeError("jogo não encontrado") self.e.db.run("DELETE FROM games WHERE id = ?", gid) def delete_note(self, gid: str, index: int) -> None: """Esquece um pedido (ele deixa de voltar nas próximas pesquisas; o perfil atual não muda).""" game = self.e.db.get("SELECT notes_json FROM games WHERE id = ?", gid) if not game: raise JudgeError("jogo não encontrado") notes = loads(game["notes_json"], []) if 0 <= index < len(notes): notes.pop(index) self.e.db.run("UPDATE games SET notes_json = ? WHERE id = ?", json.dumps(notes, ensure_ascii=False), gid) def find_game(self, name: str) -> dict | None: """Linha do jogo pelo nome: id normalizado ou, se não achar, um jogo que tem esse nome entre os outros nomes.""" gid = game_id(name or "") if not name or gid == "desconhecido": return None row = self.e.db.get("SELECT * FROM games WHERE id = ?", gid) if row: return row # aliases_json é uma lista JSON de ids: procura o id entre aspas (LIKE barato, confere no Python). for row in self.e.db.all("SELECT * FROM games WHERE aliases_json LIKE ?", f'%"{gid}"%'): if gid in loads(row.get("aliases_json"), []): return row return None def profile(self, name: str) -> dict | None: """Perfil que vai para a IA: a versão em inglês; jogo antigo, sem ela, usa a portuguesa.""" row = self.find_game(name) if not row or row["status"] != "ready": return None return loads(row.get("profile_ai_json"), None) or loads(row["profile_json"], None) def session_game(self, session: dict) -> tuple[str, dict | None]: """(nome do jogo, perfil) da sessão — o mesmo critério do contexto: jogo confirmado por você vale sozinho; senão a categoria e, sem perfil dela, o jogo que a IA viu na tela.""" confirmed = session.get("game_source") == "user" and bool(session.get("game")) game, screen = session.get("game") or "", session.get("screen_game") or "" profile = self.profile(game) if profile or confirmed: return game, profile screen_profile = self.profile(screen) if screen.lower() not in ("", "desconhecido") else None return (screen, screen_profile) if screen_profile else (game or ("" if screen.lower() == "desconhecido" else screen), None) def lang(self, session: dict) -> str: """'en' = fonte em inglês (juízes em inglês, tradução para o painel); 'pt' = o resto.""" return lang_key(session.get("language") or self.e.settings.language) def context(self, session: dict) -> str: memory = loads(session.get("memory_json"), []) confirmed = session.get("game_source") == "user" and bool(session.get("game")) profile = self.profile(session.get("game", "")) or (None if confirmed else self.profile(session.get("screen_game", ""))) text = game_context(session.get("game", ""), session.get("screen_game", ""), profile, session.get("title", ""), " | ".join(m["summary"] for m in memory[-3:] if m.get("summary")), confirmed=confirmed, lang=self.lang(session)) # Sessão em outro idioma (fonte gringa): o editor e a varredura escrevem título/legenda nesse idioma. note = output_language_note(session.get("language") or self.e.settings.language) return f"{text}\n{note}" if note else text # ---------------------------------------------------------------- frames def frames(self, session: dict, times: list[float], tag: str) -> list[tuple[float, Path]]: if not self.opts["vision"]: return [] segments = [(self.e.repo_path(s["file"]), s["start_s"], s["end_s"]) for s in self.e.db.all("SELECT * FROM segments WHERE session_id = ? AND deleted = 0 ORDER BY idx", session["id"])] out_dir = self.e.repo_path(session["dir"]) / "frames" frames = [] for t in times: try: frames.append((t, self.e.grab_frame(segments, t, out_dir / f"{tag}-{int(t)}.jpg"))) except Exception as exc: # noqa: BLE001 - sem frame a IA decide só pelo texto log.info("frame %.0fs indisponível: %s", t, exc) return frames # ---------------------------------------------------------------- webcam def maybe_detect_cam(self, session: dict) -> None: """Acha a câmera no início da sessão. A detecção local (YuNet) não precisa de IA, visão nem juiz ligados.""" if not self.opts["camDetect"] or time.time() < self._cam_retry_at.get(session["id"], 0.0): return saved = loads(session.get("cam_json"), None) # Sem rosto na 1ª olhada (tela de "já volto" no começo da live): tenta de novo mais tarde enquanto grava. # Falha sem rosto decidido (poucos quadros legíveis): tenta de novo pelo relógio, também em VOD/sessão parada. due = saved and ((saved.get("retryAfterS") and session["duration_s"] >= saved["retryAfterS"]) or (saved.get("retryAt") is not None and time.time() >= saved["retryAt"] and saved.get("attempts", 1) < CAM_MAX_ATTEMPTS)) if saved and not due: return analyzed = self.e.db.get("SELECT COUNT(*) AS n FROM segments WHERE session_id = ? AND analyzed = 1", session["id"])["n"] if analyzed < 2: return if self.settings_for(session)["layout"]["cam"]: self.e.db.run("UPDATE sessions SET cam_json = ? WHERE id = ?", json.dumps({"skipped": "já definida", "source": "manual"}), session["id"]) return try: self.detect_cam(session["id"], apply=True) except CamRetryLater as exc: # Modelo indisponível/download falhou: nada a ver com a live. Não grava "sem câmera" (seria permanente e # o rastreio marcaria tudo no_cam); tenta de novo em 5 min. self._cam_retry_at[session["id"]] = time.time() + CAM_RETRY_S log.warning("câmera da sessão %s: %s (nova tentativa em %d s)", session["id"], exc, CAM_RETRY_S) except JudgeError as exc: # Sem frame legível e sem IA: registra para não repetir a cada 30 s, com nova tentativa marcada # (por tempo de gravação enquanto grava; pelo relógio em qualquer estado, até CAM_MAX_ATTEMPTS vezes). attempts = (saved or {}).get("attempts", 0) + 1 self.e.db.run("UPDATE sessions SET cam_json = ? WHERE id = ?", json.dumps( {"hasWebcam": False, "cam": None, "source": "yunet", "error": str(exc)[:200], "at": now(), "retryAt": time.time() + CAM_RETRY_S, "attempts": attempts, **({"retryAfterS": session["duration_s"] + CAM_RETRY_S} if session["status"] == "recording" else {})}, ensure_ascii=False), session["id"]) def detect_cam(self, session_id: int, apply: bool = False, use_ai: bool = False) -> dict: """Onde está a webcam. Primeiro local (YuNet + reaction.locate_cam, sem custo de IA); a IA só entra se o local não achar rosto (e a IA estiver ligada com visão) ou se pedirem (`use_ai`). `cam_json.source` diz quem achou: yunet | ai | manual.""" session = self.e.db.get("SELECT * FROM sessions WHERE id = ?", session_id) if not session or session["duration_s"] < 5: raise JudgeError("gravação curta demais para achar a câmera") ai_ready = self.opts["vision"] and self.e.judge.enabled local, local_error, transient = None, "", False if not use_ai: try: local = self.e.face.locate(session) except FaceUnavailable as exc: # modelo/biblioteca/download: passageiro, não é "sem câmera" local_error, transient = str(exc), True log.info("câmera local da sessão %s indisponível: %s", session_id, exc) except FaceError as exc: local_error = str(exc) log.info("câmera local da sessão %s falhou: %s", session_id, exc) if local is not None and (local["hasWebcam"] or not ai_ready): result = local if not local["hasWebcam"] and session["status"] == "recording": result["retryAfterS"] = session["duration_s"] + CAM_RETRY_S self.e.db.run("UPDATE sessions SET cam_json = ? WHERE id = ?", json.dumps(result, ensure_ascii=False), session_id) # Câmera em tela cheia (só o streamer) não vira layout câmera-em-cima; o rastreio usa o quadro inteiro. if local["hasWebcam"] and not local["fullFrame"] and apply: try: rect = layout.validate({"layout": {"cam": local["cam"]}})["layout"]["cam"] except layout.LayoutError: rect = None if rect: self._apply_cam(session, rect) return result if not ai_ready: if transient: raise CamRetryLater(f"detector de rosto indisponível agora ({local_error}); tente de novo em instantes") raise JudgeError(f"não deu para achar a câmera sem a IA ({local_error or 'sem rosto'}); ligue a visão ou marque à mão") d = session["duration_s"] frames = self.frames(session, [d * 0.25, d * 0.55, max(1.0, d - 8)], "cam") if not frames: raise JudgeError("sem frames (visão desligada ou blocos apagados)") data = self.e.judge.detect_cam([p for _, p in frames]) rect = None if data.get("has_webcam"): try: rect = layout.validate({"layout": {"cam": {k: data[k] for k in ("x", "y", "w", "h")}}})["layout"]["cam"] except layout.LayoutError: rect = None result = {"hasWebcam": bool(data.get("has_webcam")), "cam": rect, "gameOnScreen": data.get("game_on_screen", ""), "frame": self.e.rel(frames[-1][1]), "at": now(), "source": "ai"} self.e.db.run("UPDATE sessions SET cam_json = ? WHERE id = ?", json.dumps(result, ensure_ascii=False), session_id) if rect and apply: self._apply_cam(session, rect) if result["gameOnScreen"] and result["gameOnScreen"].lower() not in ("desconhecido", "não identificável"): self.e.db.run("UPDATE sessions SET screen_game = ? WHERE id = ?", result["gameOnScreen"][:120], session_id) return result def _apply_cam(self, session: dict, rect: dict) -> None: """Câmera achada vira padrão do canal (se o canal não tiver uma); sem canal, vale para a sessão.""" if session.get("channel_id"): row = self.e.db.get("SELECT settings_json FROM channels WHERE id = ?", session["channel_id"]) current = loads(row["settings_json"], {}) if row else {} if row and not (current.get("layout") or {}).get("cam"): current.setdefault("layout", {})["cam"] = rect self.e.db.run("UPDATE channels SET settings_json = ? WHERE id = ?", json.dumps(current), session["channel_id"]) return current = loads(session.get("settings_json"), {}) if not (current.get("layout") or {}).get("cam"): current.setdefault("layout", {})["cam"] = rect self.e.db.run("UPDATE sessions SET settings_json = ? WHERE id = ?", json.dumps(current), session["id"]) # ---------------------------------------------------------------- varredura def scan_due(self, session: dict, analyzed_until: float) -> tuple[float, float] | None: if not (self.opts["scanEnabled"] and self.e.judge.enabled): return None if session["status"] == "recording" and session["kind"] == "vod": return None # VOD baixa mais rápido que o tempo real: varre quando terminar lo = session["scanned_until"] hi = lo + self.opts["scanIntervalS"] if hi <= analyzed_until: return lo, hi if session["status"] in ("processing", "stopped") and analyzed_until - lo >= 20: return lo, analyzed_until # fim da gravação: varre o resto return None def scan_session(self, session: dict) -> int | None: """Varre a próxima janela pronta. None = nada a varrer agora; senão, quantos cortes criou.""" if not (self.opts["scanEnabled"] and self.e.judge.enabled): return None tl = self.e.load_timeline(session["id"], max(0.0, session["scanned_until"] - 200)) window = self.scan_due(session, tl["analyzedUntil"]) if not window: return None lo, hi = window cfg = self.settings_for(session) dur = cfg["duration"] back_lo = max(0.0, lo - dur["backtrackS"]) step = max(SCAN_FRAME_EVERY_S, (hi - lo) / SCAN_MAX_FRAMES) times = [lo + step / 2 + i * step for i in range(int((hi - lo) // step) or 1)][:SCAN_MAX_FRAMES] frames = self.frames(session, times, "scan") existing = [(c["start_s"], c["end_s"], c["title"]) for c in self.e.db.all( "SELECT start_s, end_s, title FROM clips WHERE session_id = ? AND end_s > ? AND start_s < ?", session["id"], back_lo, hi)] existing += clip_delete.mark_spans(self.e.db, session["id"], back_lo, hi) # apagados não voltam pela varredura prompt = build_scan_prompt(self.e.streamer_name(session), session["platform"], lo, hi, back_lo, tl["words"], tl["chat"], self.context(session), frames, existing, dur["minS"], dur["maxS"], lang=self.lang(session)) created = 0 try: data = self.e.judge.scan(prompt, [p for _, p in frames], lang=self.lang(session)) self.last_scan_error = None except (JudgeError, json.JSONDecodeError) as exc: # Avança mesmo assim: repetir a mesma janela com a CLI quebrada só gastaria cota. self.last_scan_error = str(exc)[:300] log.warning("varredura %s %.0f–%.0fs falhou: %s", session["id"], lo, hi, exc) data = {"moments": [], "summary": "", "screen_game": ""} proposals = data.get("moments", [])[:SCAN_MAX_MOMENTS] for moment in proposals: if self._insert_scan_moment(session, moment, back_lo, hi, dur, existing): created += 1 # Quantas propostas a IA fez e quantas viraram candidato (as outras: nota < SCAN_MIN_PROPOSAL, curtas ou em # cima de um corte). Antes não ficava registrado (diagnóstico de 17/11/2026: impossível saber se a varredura # não propôs nada ou se foi barrada). log.info("varredura %s %.0f–%.0fs: %d proposta(s), %d candidato(s)", session["id"], lo, hi, len(proposals), created) memory = loads(session.get("memory_json"), []) if data.get("summary") or proposals: item = {"fromS": lo, "toS": hi, "summary": str(data.get("summary") or "")[:240], "proposals": len(proposals), "created": created} if data.get("summary_pt"): # fonte em inglês: o resumo vai em inglês à IA e em português ao painel item["summaryPt"] = str(data["summary_pt"])[:240] memory.append(item) screen = str(data.get("screen_game") or "") if screen.strip().lower() in UNKNOWN_GAMES: screen = "" self.e.db.run("UPDATE sessions SET scanned_until = ?, memory_json = ?, screen_game = CASE WHEN ? != '' THEN ? ELSE screen_game END WHERE id = ?", hi, json.dumps(memory[-MEMORY_KEEP:], ensure_ascii=False), screen, screen[:120], session["id"]) if screen: # A tela é uma pista (com a confiança e o que a IA leu), não a palavra final: cruza com categoria, título, # chat e fala. Sem categoria (YouTube/VOD), a tela sozinha ainda define o jogo (estado "provável"). self.note_screen(session["id"], screen, str(data.get("screen_game_confidence") or ""), str(data.get("screen_evidence") or "")) self.detect_game(session["id"]) return created def _insert_scan_moment(self, session: dict, m: dict, lo: float, hi: float, dur: dict, existing: list) -> bool: """Momento proposto pela varredura vira CANDIDATO: passa pelos dois juízes (analista + editor) como os do chat.""" try: # Mínimo + 1 s de verdade: se o fim bate no fim da janela, o início recua (fit_window). start, end = fit_window(float(m["start_s"]), float(m["end_s"]), lo, hi, layout.min_target({"duration": dur}), float(dur["maxS"]), keep="start") score = max(0.0, min(10.0, float(m["score"]))) except (KeyError, TypeError, ValueError): return False if end - start < min(10.0, dur["minS"]) or score < SCAN_MIN_PROPOSAL: return False from .scoring import overlaps # import local: evita ciclo na carga do módulo if any(overlaps(start, end, a, b) for a, b, _ in existing): return False ts = now() reasons = {"via": "varredura", "scanFromS": lo, "scanToS": hi, "proposalScore": score, "proposalTitle": str(m.get("title", ""))[:100], "proposalReason": str(m.get("reason", ""))[:300]} pt = m.get("pt") if isinstance(m.get("pt"), dict) else {} if pt.get("title") or pt.get("reason"): # fonte em inglês: a mesma proposta em português para o painel reasons |= {"proposalTitlePt": str(pt.get("title", ""))[:100], "proposalReasonPt": str(pt.get("reason", ""))[:300]} self.e.db.run( "INSERT INTO clips (session_id, peak_s, start_s, end_s, score, source, reasons_json, status, created_at, updated_at)" " VALUES (?, ?, ?, ?, ?, 'ai', ?, 'candidate', ?, ?)", session["id"], round((start + end) / 2, 2), round(start, 2), round(end, 2), score, json.dumps(reasons, ensure_ascii=False), ts, ts) existing.append((start, end, "")) return True