"""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 .hashtags import fold, to_tag from .judge import JudgeError, build_scan_prompt, game_context 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 = 600 # rechecar a categoria da live a cada 10 min (o streamer troca de jogo) 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") def clean_profile(raw: dict) -> dict: """Normaliza um perfil de jogo (vindo da IA ou da edição à mão): textos aparados, listas sem vazios/duplicados. 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: items, seen = [], set() for item in raw.get(key) or []: text = str(item or "").strip()[:300] if key == "hashtags": text = to_tag(text) or "" if text and fold(text) not in seen: seen.add(fold(text)) items.append(text) continue if text and text.lower() not in seen: seen.add(text.lower()) items.append(text) out[key] = items[:20] return out 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._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}"]) # ---------------------------------------------------------------- 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) -> None: """Categoria atual da live (Streamlink) → jogo da sessão; troca registrada; perfil pesquisado se novo.""" 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"]) category = (meta.get("category") or "").strip() if category and category != session.get("game") and session.get("game_source") != "user": self.set_game(session["id"], category, "platform") 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.e.db.get("SELECT 1 FROM games WHERE id = ?", gid): 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: 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: ligue o Codex ou o Claude 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: profile = self.e.judge.research_game(game["name"], title, notes) 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 status = 'ready', profile_json = ?, error = NULL, model = ?, researched_at = ? WHERE id = ?", json.dumps(profile, ensure_ascii=False), f"{self.e.judge.provider}:{self.e.judge.model}", now(), gid) return profile def save_profile(self, gid: str, profile: dict) -> dict: """Grava o perfil editado à mão no painel. Vale na hora para a IA (status 'ready').""" if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid): raise JudgeError("jogo não encontrado") clean = clean_profile(profile) self.e.db.run("UPDATE games SET status = 'ready', profile_json = ?, error = NULL, edited_at = ? WHERE id = ?", json.dumps(clean, ensure_ascii=False), now(), gid) return clean 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). O pedido fica guardado e volta em toda pesquisa. Devolve (perfil, resposta curta da IA).""" 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: ligue o Codex ou o Claude para editar o perfil pela IA") current = 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) 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] profile = clean_profile(data) notes = loads(game.get("notes_json"), []) notes.append({"text": instruction, "at": now(), **({"section": section} if section else {})}) self.e.db.run("UPDATE games SET status = 'ready', profile_json = ?, error = NULL, notes_json = ?, edited_at = ?," " model = ? WHERE id = ?", json.dumps(profile, ensure_ascii=False), json.dumps(notes[-30:], ensure_ascii=False), now(), f"{self.e.judge.provider}:{self.e.judge.model}", gid) return profile, reply 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 profile(self, name: str) -> dict | None: if not name: return None row = self.e.db.get("SELECT profile_json FROM games WHERE id = ? AND status = 'ready'", game_id(name)) return loads(row["profile_json"], None) if row else 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 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", ""))) return 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) # ---------------------------------------------------------------- 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"]) created = 0 try: data = self.e.judge.scan(prompt, [p for _, p in frames]) 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: memory.append({"fromS": lo, "toS": hi, "summary": str(data.get("summary") or "")[:240], "proposals": len(proposals), "created": created}) screen = str(data.get("screen_game") or "") if screen.lower() in ("desconhecido", "não identificável", "nao identificavel"): 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 and not session.get("game"): self.set_game(session["id"], screen, "screen") # sem categoria (YouTube/VOD): o jogo vem da tela 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]} 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