Files
MateuusandClaude Opus 5.5 84f30bbc2d CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz,
Clipador de lives e Publicador para YouTube, TikTok e Instagram.

Inclui a leitura das visualizações dos posts para o Dashboard e o botão
"Publicar no <rede>" nos cartões das publicações.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:35:09 -03:00

159 lines
6.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Emotes do chat: reconhecer, contar por canal e APRENDER quais indicam um bom momento.
Por quê: chat pequeno (3–5 pessoas) e público que reage com emote em vez de texto ("kkkk") faziam a heurística
não ver nada. Agora cada mensagem leva a lista de emotes, e cada canal tem um peso aprendido por emote.
De onde vêm:
- Twitch nativos: tag `emotes` do IRC (CAP twitch.tv/tags) com as posições na mensagem;
- 7TV, BTTV e FFZ do canal + globais: APIs públicas por `room-id` (o id do canal vem nas tags do IRC);
- emojis Unicode.
Cada fonte externa é opcional: a que falhar (404, lenta) é ignorada e tentada de novo na próxima hora.
Aprendizado (por canal, tabela `emotes`):
- `uses`: quantas vezes apareceu (contagem simples, para o painel);
- `weight`: sobe quando o emote aparece na reação de um corte aprovado/bem avaliado, desce quando o corte é
rejeitado/descartado. Entra no peso da mensagem na pontuação do chat.
"""
from __future__ import annotations
import logging
import re
import threading
import time
import httpx
log = logging.getLogger("cenaforge_clipper.emotes")
CATALOG_TTL_S = 3600
LEARN_UP, LEARN_DOWN = 0.3, 0.15
WEIGHT_MIN, WEIGHT_MAX = -1.0, 3.0
BASE_EMOTE_BONUS = 0.4 # mensagem com emote já é reação
BONUS_MIN, BONUS_MAX = -0.5, 3.0
# Faixas comuns de emoji (pictogramas, símbolos, bandeiras, rostos). Não é exaustivo, só precisa pegar os de reação.
EMOJI_RE = re.compile("[\U0001F300-\U0001FAFF\U00002600-\U000027BF\U0001F1E6-\U0001F1FF]")
GLOBAL_URLS = {
"7tv": "https://7tv.io/v3/emote-sets/global",
"bttv": "https://api.betterttv.net/3/cached/emotes/global",
"ffz": "https://api.frankerfacez.com/v1/set/global",
}
CHANNEL_URLS = {
"7tv": "https://7tv.io/v3/users/twitch/{room}",
"bttv": "https://api.betterttv.net/3/cached/users/twitch/{room}",
"ffz": "https://api.frankerfacez.com/v1/room/id/{room}",
}
def parse_twitch_tag(tag_value: str, text: str) -> list[str]:
"""`emotes=25:0-4,12-16/1902:6-10` → nomes recortados do texto (posições em code points, como o str do Python)."""
names: list[str] = []
if not tag_value:
return names
for part in tag_value.split("/"):
if ":" not in part:
continue
_id, spans = part.split(":", 1)
for span in spans.split(","):
try:
a, b = (int(x) for x in span.split("-"))
except ValueError:
continue
if 0 <= a <= b < len(text):
names.append(text[a: b + 1])
return names
def _names_from(source: str, data) -> list[str]:
if source == "7tv":
emotes = data.get("emotes") or (data.get("emote_set") or {}).get("emotes") or []
return [e["name"] for e in emotes if isinstance(e, dict) and e.get("name")]
if source == "bttv":
items = data if isinstance(data, list) else (data.get("channelEmotes", []) + data.get("sharedEmotes", []))
return [e["code"] for e in items if isinstance(e, dict) and e.get("code")]
if source == "ffz":
return [e["name"] for s in (data.get("sets") or {}).values() for e in s.get("emoticons", []) if e.get("name")]
return []
class EmoteCatalog:
"""Nomes de emotes de terceiros (globais + do canal), com cache de 1 h por canal."""
def __init__(self, fetch=None):
self._fetch = fetch or self._http_json
self._lock = threading.Lock()
self._global: dict[str, str] = {}
self._global_at = 0.0
self._channels: dict[str, tuple[float, dict[str, str]]] = {}
@staticmethod
def _http_json(url: str):
response = httpx.get(url, timeout=20, headers={"User-Agent": "CenaForge-Clipador"})
if response.status_code != 200:
return None
return response.json()
def _load(self, urls: dict[str, str]) -> dict[str, str]:
found: dict[str, str] = {}
for source, url in urls.items():
try:
data = self._fetch(url)
except Exception as exc: # noqa: BLE001 - fonte externa opcional
log.info("emotes %s indisponível (%s)", source, type(exc).__name__)
continue
if data:
for name in _names_from(source, data):
found.setdefault(name, source)
return found
def cached(self, room_id: str | None) -> dict[str, str]:
"""O que já foi baixado, sem tocar na rede (usado na linha do chat, que não pode esperar API externa)."""
with self._lock:
merged = dict(self._global)
if room_id and room_id in self._channels:
merged.update(self._channels[room_id][1])
return merged
def names(self, room_id: str | None) -> dict[str, str]:
now = time.time()
with self._lock:
if now - self._global_at > CATALOG_TTL_S:
self._global, self._global_at = self._load(GLOBAL_URLS), now
merged = dict(self._global)
if room_id:
cached = self._channels.get(room_id)
if not cached or now - cached[0] > CATALOG_TTL_S:
cached = (now, self._load({k: v.format(room=room_id) for k, v in CHANNEL_URLS.items()}))
self._channels[room_id] = cached
merged.update(cached[1])
return merged
def extract(text: str, twitch_emotes: list[str], catalog: dict[str, str]) -> list[tuple[str, str]]:
"""(nome, fonte) de cada emote da mensagem: nativos da Twitch, de terceiros (palavra exata) e emojis."""
out: list[tuple[str, str]] = [(name, "twitch") for name in twitch_emotes]
seen = {name for name, _ in out}
for token in text.split():
if token in catalog and token not in seen:
out.append((token, catalog[token]))
seen.add(token)
for emoji in EMOJI_RE.findall(text):
if emoji not in seen:
out.append((emoji, "emoji"))
seen.add(emoji)
return out
def message_bonus(emotes: list[str], weights: dict[str, float]) -> float:
"""Bônus de peso da mensagem pelos emotes: base por ter emote + pesos aprendidos do canal."""
if not emotes:
return 0.0
learned = sum(max(WEIGHT_MIN, min(WEIGHT_MAX, weights.get(name, 0.0))) for name in set(emotes))
return max(BONUS_MIN, min(BONUS_MAX, BASE_EMOTE_BONUS + learned))
def learn_delta(positive: bool) -> float:
return LEARN_UP if positive else -LEARN_DOWN