Download modules/debate_manager.py from akra35567/Akiragpu: direct link, hf CLI and curl.
- Browser
- Download file 24.1 kB
-
https://huggingface.co/spaces/akra35567/Akiragpu/resolve/main/modules/debate_manager.py
- Command line
-
hf download hf://spaces/akra35567/Akiragpu/modules/debate_manager.py
-
curl -L -o debate_manager.py https://huggingface.co/spaces/akra35567/Akiragpu/resolve/main/modules/debate_manager.py
24.1 kB
| """ | |
| DEBATE MANAGER - Módulo para detecção, rastreamento e gestão de debates | |
| Garante coerência de posições, detecção de falácias e consistência argumentativa | |
| """ | |
| import re | |
| import time | |
| from typing import Dict, List, Optional, Tuple, Any | |
| from dataclasses import dataclass, field | |
| from datetime import datetime | |
| from loguru import logger | |
| # Garantir que time está disponível | |
| _time = time | |
| class ArgumentPosition: | |
| """Representa uma posição argumentativa num debate""" | |
| speaker: str | |
| speaker_name: str # Nome legível (ex: "Isaac", "Akira") | |
| position: str # Resumo da posição | |
| full_text: str # Texto completo da mensagem (para referência futura) | |
| claims: List[str] = field(default_factory=list) # Afirmações específicas | |
| stance: str = "neutro" # pró, contra, neutro | |
| timestamp: float = field(default_factory=time.time) | |
| confidence: float = 0.0 # Quão firme é a posição | |
| class DebateState: | |
| """Estado atual de um debate ativo""" | |
| topic: str | |
| positions: Dict[str, ArgumentPosition] = field(default_factory=dict) | |
| is_active: bool = False | |
| started_at: float = field(default_factory=time.time) | |
| fallacies_detected: List[Dict[str, Any]] = field(default_factory=list) | |
| contradictions: List[Dict[str, Any]] = field(default_factory=list) | |
| class DebateManager: | |
| """ | |
| Gerencia debates detectados no grupo/PV | |
| - Rastreia posições de cada participante | |
| - Detecta falácias lógicas | |
| - Identifica contradições | |
| - Mantém coerência de argumentos | |
| """ | |
| # Sinais de debate ativo — expandido para debates filosóficos/abstratos + insultos pessoais | |
| DEBATE_SIGNALS = [ | |
| "discordo", "não concordo", "errado", "certo", "verdade", "mentira", | |
| "isso aí", "não é", "é sim", "vc tá", "você tá", | |
| "argumento", "razão", "lógica", "prova", "evidência", | |
| "falácia", "contradição", "hipocrisia", "falso", | |
| "como assim", "onde está", "qual ponto", "explica aí", | |
| "vc disse", "você disse", "afirmou que", "disse que", | |
| "mas eu", "mas você", "porém", "entretanto", "no entanto", | |
| # Debates filosóficos/abstratos | |
| "é placebo", "não é placebo", "é ilusão", "é farsa", "é verdade", | |
| "depende", "nem sempre", "nunca", "sempre", "tudo é", "nada é", | |
| "concordas", "discordas", "achas que", | |
| "então tu", "então você", "tu é que", "você é que", | |
| "isso é", "isso não é", "não faz sentido", "faz sentido", | |
| # Insultos pessoais / ad hominem — ativa debate quando há agressão | |
| "seu lixo", "seu burro", "seu idiota", "seu imbecil", "seu verme", | |
| "seu merda", "seu fracassado", "seu perdedor", | |
| "vagabundo", "otário", "cuzão", "arrombado", "filho da puta", | |
| "animal", "jumento", "palhaço", "palhaça", | |
| "nojento", "nojenta", "repugnante", "asqueroso", | |
| "vc é", "você é um", "tu és", "és um", | |
| "lição", "lixo humano", "escória", "desgraça", | |
| ] | |
| # Padrões de falácias comuns | |
| FALLACY_PATTERNS = { | |
| "ad_hominem": r"\b(burro|idiot|estúpido|tolo|imbecil|maluco|doido)\b", | |
| "espantalho": r"\b(ou seja|isto é|basicamente|resumindo) que você (acha|diz|quer dizer)", | |
| "falso_dilema": r"\b(ou|só) (isso|aquilo|um|outro)\b", | |
| "apelo_à_emocao": r"\b(sinto|pena|medo|raiva|justiça|direito)\b", | |
| "generalizacao": r"\b(todos|todos os|todas|ninguém|nunca|sempre)\b", | |
| "causa_falsa": r"\b(porque|já que|visto que|pois) (isso|aquilo|ele|ela)\b", | |
| "argumento_autoridade": r"\b(especialista|dizem|segundo|fonte|estudo mostra)\b", | |
| } | |
| def __init__(self): | |
| self.logger = logger | |
| self.active_debates: Dict[str, DebateState] = {} # conversation_id -> DebateState | |
| self.position_history: Dict[str, List[ArgumentPosition]] = {} # speaker -> history | |
| self.speaker_names: Dict[str, str] = {} # speaker_id -> nome legível (ex: "Akira", "Isaac") | |
| def set_speaker_name(self, speaker_id: str, name: str): | |
| """Registra o nome legível de um speaker (ex: '5511999999999_Isaac' -> 'Isaac')""" | |
| if speaker_id and name: | |
| self.speaker_names[speaker_id] = name | |
| def get_speaker_display(self, speaker_id: str) -> str: | |
| """Retorna nome legível do speaker, ou o ID original se não mapeado""" | |
| return self.speaker_names.get(speaker_id, speaker_id) | |
| def detect_debate(self, mensagem: str, contexto_recente: List[Dict] = None) -> bool: | |
| """Detecta se a mensagem indica início ou continuação de debate""" | |
| msg_lower = mensagem.lower() | |
| # Verifica sinais de debate na mensagem atual | |
| debate_score = sum(1 for signal in self.DEBATE_SIGNALS if signal in msg_lower) | |
| # Verifica contexto recente para debate em andamento | |
| if contexto_recente: | |
| context_texts = [m.get('content', '').lower() for m in contexto_recente[-5:]] | |
| context_debate_score = sum( | |
| sum(1 for signal in self.DEBATE_SIGNALS if signal in ctx) | |
| for ctx in context_texts | |
| ) | |
| debate_score += context_debate_score * 0.5 | |
| return debate_score >= 1 # Threshold baixo — debates filosóficos podem ter poucos sinais | |
| def extract_position(self, mensagem: str, speaker: str, speaker_name: str = None) -> Optional[ArgumentPosition]: | |
| """Extrai a posição argumentativa de uma mensagem""" | |
| msg_lower = mensagem.lower() | |
| # Detecta stance (pró/contra/neutro) — usa contagem para desempatar | |
| pro_signals = ["concordo", "certo", "verdade", "exato", "é isso"] | |
| contra_signals = ["discordo", "errado", "mentira", "falso", "injusto"] | |
| # "não" sozinho não é sinal de contra — precisa de contexto | |
| contra_contextual = ["não concordo", "não é", "não funciona", "não existe"] | |
| pro_count = sum(1 for p in pro_signals if p in msg_lower) | |
| contra_count = sum(1 for c in contra_signals if c in msg_lower) | |
| contra_count += sum(1 for c in contra_contextual if c in msg_lower) | |
| if pro_count > contra_count: | |
| stance = "pró" | |
| elif contra_count > pro_count: | |
| stance = "contra" | |
| else: | |
| stance = "neutro" | |
| # Extrai claims (afirmações principais) — padrões expandidos | |
| claims = [] | |
| claim_patterns = [ | |
| # Padrões originais (lei, documentos, juízes) | |
| r"\b(lei (?:é|deve ser|não é) .{0,50})\b", | |
| r"\b(documento (?:é|pode ser|não é) .{0,50})\b", | |
| r"\b(juí?ze[s]? (?:são|é|são) .{0,50})\b", | |
| r"\b(corrupto[s]? .{0,30})\b", | |
| r"\b(imparcial(idade)? .{0,50})\b", | |
| r"\b(processo[s]? .{0,50})\b", | |
| # Padrões filosóficos/abstratos | |
| r"\b(\w+ é (?:o |a |um |uma )?(?:placebo|ilusão|farsa|verdade|facto|factos|realidade|mito|fictício|invenção|constructo))\b", | |
| r"\b(\w+ (?:não é|nao é) (?:o |a |um |uma )?(?:placebo|ilusão|farsa|verdade|facto|factos|realidade|mito))\b", | |
| r"\b(\w+ (?:deve ser|tem de ser|precisa ser) .{0,40})\b", | |
| r"\b(a (?:verdade|realidade|natureza) (?:é|da|de) .{0,40})\b", | |
| # Padrões gerais: "X é Y" ou "X não é Y" | |
| r"\b(\w+ é \w[\w\s]{5,50})\b", | |
| r"\b(\w+ não é \w[\w\s]{5,50})\b", | |
| ] | |
| for pattern in claim_patterns: | |
| matches = re.findall(pattern, msg_lower) | |
| if matches: | |
| # matches pode ser lista de tuples ou strings | |
| for m in matches[:2]: | |
| claim = m if isinstance(m, str) else m[0] if m else "" | |
| if claim and claim not in claims: | |
| claims.append(claim) | |
| if not claims: | |
| # Fallback: pega frases curtas como claims | |
| sentences = re.split(r'[.!?]', mensagem)[:3] | |
| claims = [s.strip() for s in sentences if len(s.strip()) > 10 and len(s.strip()) < 100] | |
| if not claims: | |
| return None | |
| return ArgumentPosition( | |
| speaker=speaker, | |
| speaker_name=speaker_name or speaker, | |
| position=mensagem[:200], # Resumo curto | |
| full_text=mensagem[:500], # Texto completo para referência | |
| claims=claims, | |
| stance=stance, | |
| confidence=0.7 # Default | |
| ) | |
| def detect_fallacies(self, mensagem: str, speaker: str = "unknown") -> List[Dict[str, Any]]: | |
| """Detecta falácias lógicas numa mensagem""" | |
| msg_lower = mensagem.lower() | |
| detected = [] | |
| for fallacy_type, pattern in self.FALLACY_PATTERNS.items(): | |
| if re.search(pattern, msg_lower, re.IGNORECASE): | |
| detected.append({ | |
| "type": fallacy_type, | |
| "speaker": speaker, | |
| "message": mensagem[:100], | |
| "timestamp": time.time() | |
| }) | |
| return detected | |
| def detect_contradiction(self, new_position: ArgumentPosition, | |
| previous_positions: List[ArgumentPosition]) -> Optional[Dict[str, Any]]: | |
| """Detecta se uma nova posição contradiz posições anteriores do mesmo speaker""" | |
| if not previous_positions: | |
| return None | |
| # Compara claims atuais com anteriores | |
| for prev in previous_positions[-3:]: # Últimas 3 posições | |
| # Verifica contradição de stance (bidirecional: pró↔contra) | |
| if ((new_position.stance == "pró" and prev.stance == "contra") or | |
| (new_position.stance == "contra" and prev.stance == "pró")): | |
| # Verifica se é sobre o mesmo tópico | |
| if self._topics_overlap(new_position.position, prev.position): | |
| return { | |
| "type": "stance_reversal", | |
| "speaker": new_position.speaker, | |
| "new_position": new_position.position, | |
| "old_position": prev.position, | |
| "topic": self._extract_topic(new_position.position) | |
| } | |
| # Verifica contradição de claims | |
| for new_claim in new_position.claims: | |
| for prev_claim in prev.claims: | |
| if self._claims_contradict(new_claim, prev_claim): | |
| return { | |
| "type": "claim_contradiction", | |
| "speaker": new_position.speaker, | |
| "new_claim": new_claim, | |
| "old_claim": prev_claim, | |
| "topic": self._extract_topic(new_claim) | |
| } | |
| return None | |
| def _topics_overlap(self, topic1: str, topic2: str) -> bool: | |
| """Verifica se dois tópicos são relacionados (requer 2+ palavras partilhadas)""" | |
| words1 = set(re.findall(r'\b\w{5,}\b', topic1.lower())) | |
| words2 = set(re.findall(r'\b\w{5,}\b', topic2.lower())) | |
| # Stop words para remover | |
| stop_words = {"pode", "ser", "que", "para", "com", "não", "é", "são", "essa", "esse", "isto", "isso", "aquilo", "quando", "porque", "então", "também", "apenas", "ainda", "sobre", "entre", "depois", "antes", "desde"} | |
| words1 -= stop_words | |
| words2 -= stop_words | |
| # Requer pelo menos 2 palavras partilhadas para evitar falsos positivos | |
| return len(words1 & words2) >= 2 | |
| def _claims_contradict(self, claim1: str, claim2: str) -> bool: | |
| """Verifica se dois claims se contradizem de forma semântica.""" | |
| c1 = claim1.lower().strip() | |
| c2 = claim2.lower().strip() | |
| # Ignorar claims que são muito diferentes em comprimento (provavelmente tópicos distintos) | |
| if abs(len(c1) - len(c2)) > max(len(c1), len(c2)) * 0.6: | |
| return False | |
| # Ignorar claims idênticos ou que são substring um do outro | |
| if c1 == c2 or c1 in c2 or c2 in c1: | |
| return False | |
| negation_patterns = [ | |
| (r"\b(não é|não existe|não tem|não há)\b", r"\b(é|existe|tem|há)\b"), | |
| (r"\b(impossível|nunca)\b", r"\b(possível|sempre)\b"), | |
| (r"\b(falso|mentira)\b", r"\b(verdade|certo)\b"), | |
| ] | |
| has_neg_1 = any(re.search(np, c1) for np, _ in negation_patterns) | |
| has_aff_1 = any(re.search(ap, c1) for _, ap in negation_patterns) | |
| has_neg_2 = any(re.search(np, c2) for np, _ in negation_patterns) | |
| has_aff_2 = any(re.search(ap, c2) for _, ap in negation_patterns) | |
| # Se AMBOS os claims têm negação E afirmação ao mesmo tempo, não é contradição | |
| # (ex: "é impossível" tem "impossível" (neg) + "é" (aff) — é uma frase coerente) | |
| if (has_neg_1 and has_aff_1) or (has_neg_2 and has_aff_2): | |
| return False | |
| # Só contradiz se UM afirma e o Outro NEGA algo sobre o MESMO sujeito | |
| if not ((has_neg_1 and has_aff_2) or (has_aff_1 and has_neg_2)): | |
| return False | |
| # Extrair sujeito principal (primeira palavra significativa antes de "é"/"não é") | |
| subj_pattern = r"^([\w\s]{3,30}?)\s+(?:é|não é|nao é)" | |
| s1 = re.search(subj_pattern, c1) | |
| s2 = re.search(subj_pattern, c2) | |
| if s1 and s2: | |
| # Se os sujeitos são muito diferentes, NÃO é contradição | |
| # Ex: "parecida não é clonar" vs "clonar é crime" → sujeitos "parecida" vs "clonar" | |
| subj1 = s1.group(1).strip() | |
| subj2 = s2.group(1).strip() | |
| if subj1 != subj2 and not self._topics_overlap(subj1, subj2): | |
| return False | |
| if self._topics_overlap(c1, c2): | |
| return True | |
| return False | |
| def _extract_topic(self, text: str) -> str: | |
| """Extrai o tópico principal de um texto""" | |
| # Pega as primeiras palavras significativas | |
| words = re.findall(r'\b\w{5,}\b', text.lower()) | |
| stop_words = {"pode", "ser", "que", "para", "com", "não", "é", "são", "mais", "menos"} | |
| significant = [w for w in words if w not in stop_words] | |
| return " ".join(significant[:3]) if significant else "geral" | |
| def update_debate_state(self, conversation_id: str, mensagem: str, | |
| speaker: str, speaker_name: str = None, is_group: bool = True): | |
| """Atualiza o estado do debate com nova mensagem""" | |
| # Registra nome legível se fornecido | |
| if speaker_name: | |
| self.set_speaker_name(speaker, speaker_name) | |
| if not self.detect_debate(mensagem): | |
| return | |
| # Cria ou recupera debate state | |
| if conversation_id not in self.active_debates: | |
| self.active_debates[conversation_id] = DebateState( | |
| topic=self._extract_topic(mensagem), | |
| is_active=True | |
| ) | |
| debate = self.active_debates[conversation_id] | |
| # Extrai posição | |
| position = self.extract_position(mensagem, speaker, speaker_name=speaker_name) | |
| if position: | |
| # Detecta contradição | |
| prev_positions = self.position_history.get(speaker, []) | |
| contradiction = self.detect_contradiction(position, prev_positions) | |
| if contradiction: | |
| debate.contradictions.append(contradiction) | |
| # Atualiza posição atual | |
| debate.positions[speaker] = position | |
| # Atualiza history | |
| if speaker not in self.position_history: | |
| self.position_history[speaker] = [] | |
| self.position_history[speaker].append(position) | |
| # Detecta falácias | |
| fallacies = self.detect_fallacies(mensagem, speaker) | |
| debate.fallacies_detected.extend(fallacies) | |
| def track_bot_response(self, conversation_id: str, resposta: str, speaker: str = "Akira"): | |
| """Rastreia a resposta do bot (Akira) para detectar auto-contradições futuras""" | |
| if conversation_id not in self.active_debates: | |
| return | |
| debate = self.active_debates[conversation_id] | |
| # Registra nome "Akira" para exibição | |
| self.set_speaker_name(speaker, "Akira") | |
| # Extrai posição do bot | |
| position = self.extract_position(resposta, speaker, speaker_name="Akira") | |
| if position: | |
| # Detecta contradição com posições anteriores do bot | |
| prev_positions = self.position_history.get(speaker, []) | |
| contradiction = self.detect_contradiction(position, prev_positions) | |
| if contradiction: | |
| debate.contradictions.append(contradiction) | |
| speaker_display = self.get_speaker_display(speaker) | |
| self.logger.warning(f"🎭 [DEBATE] AUTO-CONTRADIÇÃO DETECTADA em {speaker_display}: {contradiction}") | |
| # Atualiza posição atual do bot | |
| debate.positions[speaker] = position | |
| # Atualiza history do bot | |
| if speaker not in self.position_history: | |
| self.position_history[speaker] = [] | |
| self.position_history[speaker].append(position) | |
| # Detecta falácias na resposta do bot | |
| fallacies = self.detect_fallacies(resposta, speaker) | |
| debate.fallacies_detected.extend(fallacies) | |
| def get_debate_context_for_prompt(self, conversation_id: str, | |
| current_speaker: str) -> str: | |
| """Gera contexto de debate para injetar no prompt — mostra fluxo completo com nomes""" | |
| if conversation_id not in self.active_debates: | |
| return "" | |
| debate = self.active_debates[conversation_id] | |
| context_lines = [] | |
| context_lines.append("[DEBATE CONTEXT — FLUXO COMPLETO DA CONVERSA]") | |
| context_lines.append(f"Tópico: {debate.topic}") | |
| context_lines.append("") | |
| # ── FLUXO DA CONVERSA: O que cada pessoa disse, em ordem cronológica | |
| context_lines.append("=== FLUXO DO DEBATE (quem disse o quê) ===") | |
| # Juntar TODAS as posições de TODOS os speakers, ordenadas por timestamp | |
| all_positions = [] | |
| for speaker, pos in debate.positions.items(): | |
| all_positions.append(pos) | |
| # Adicionar do position_history (que pode ter mais entradas) | |
| for speaker, history in self.position_history.items(): | |
| for pos in history: | |
| # Evitar duplicatas (mesmo timestamp) | |
| if not any(abs(pos.timestamp - p.timestamp) < 0.5 for p in all_positions): | |
| all_positions.append(pos) | |
| # Ordenar por timestamp | |
| all_positions.sort(key=lambda p: p.timestamp) | |
| # Mostrar as últimas 10 entradas (não inundar o prompt) | |
| for pos in all_positions[-10:]: | |
| name = pos.speaker_name or pos.speaker | |
| is_bot = pos.speaker == "Akira" | |
| role_label = "[BOT — Akira]" if is_bot else f"[USER — {name}]" | |
| text_preview = pos.full_text[:250] if pos.full_text else pos.position[:250] | |
| context_lines.append(f" {role_label}: \"{text_preview}\"") | |
| context_lines.append(f" → Stance: {pos.stance.upper()} | Claims: {'; '.join(pos.claims[:3])}") | |
| context_lines.append("") | |
| # ── RESUMO DAS POSIÇÕES ATUAIS | |
| context_lines.append("=== RESUMO: QUEM ESTÁ A DEFENDER O QUÊ ===") | |
| for speaker, pos in debate.positions.items(): | |
| name = pos.speaker_name or speaker | |
| is_bot = speaker == "Akira" | |
| label = "AKIRA (VOCÊ)" if is_bot else name | |
| context_lines.append(f" {label}: {pos.stance.upper()} — \"{pos.position[:150]}\"") | |
| # ── CONTRADIÇÕES DETECTADAS | |
| if debate.contradictions: | |
| context_lines.append("") | |
| context_lines.append("=== ⚠️ CONTRADIÇÕES DETECTADAS ===") | |
| for c in debate.contradictions[-3:]: | |
| speaker = c.get('speaker', '?') | |
| name = next((p.speaker_name for p in all_positions if p.speaker == speaker), speaker) | |
| is_bot = speaker == "Akira" | |
| who = "VOCÊ (Akira)" if is_bot else name | |
| context_lines.append(f" - {who}: {c.get('type')} sobre '{c.get('topic', '?')}'") | |
| # ── FALÁCIAS DETECTADAS | |
| if debate.fallacies_detected: | |
| context_lines.append("") | |
| context_lines.append("=== FALÁCIAS DETECTADAS ===") | |
| for f in debate.fallacies_detected[-3:]: | |
| speaker = f.get('speaker', '?') | |
| name = next((p.speaker_name for p in all_positions if p.speaker == speaker), speaker) | |
| context_lines.append(f" - {name}: {f.get('type')}") | |
| # ── REGRAS DE DEBATE (OBRIGATÓRIAS) | |
| context_lines.append("") | |
| context_lines.append("[REGRAS OBRIGATÓRIAS DE DEBATE]") | |
| context_lines.append("1. Leia o FLUXO ACIMA — a Akira já disse O QUÊ. NÃO contradigas.") | |
| context_lines.append("2. Se a Akira defendeu 'X é Y', NÃO digas agora 'X não é Y'.") | |
| context_lines.append("3. Se o oponente tem razão factualmente, admite com ironia — mas mantém coerência.") | |
| context_lines.append("4. Use NOMES REAIS (Isaac, Akira) — nunca 'o outro', 'ele', 'ela'.") | |
| context_lines.append("5. Use LÓGICA para refutar. NUNCA ataques pessoais ou generalizações.") | |
| return "\n".join(context_lines) | |
| def should_maintain_position(self, conversation_id: str, speaker: str) -> bool: | |
| """Verifica se o speaker deve manter sua posição atual""" | |
| if conversation_id not in self.active_debates: | |
| return False | |
| debate = self.active_debates[conversation_id] | |
| current_position = debate.positions.get(speaker) | |
| if not current_position: | |
| return False | |
| # Se tem contradições, deve manter para evitar mais contradições | |
| speaker_contradictions = [ | |
| c for c in debate.contradictions | |
| if c.get("speaker") == speaker | |
| ] | |
| return len(speaker_contradictions) > 0 | |
| def get_position_coherence_score(self, conversation_id: str, | |
| speaker: str) -> float: | |
| """Calcula quão coerente é a posição do speaker (0.0 a 1.0)""" | |
| if conversation_id not in self.active_debates: | |
| return 1.0 | |
| debate = self.active_debates[conversation_id] | |
| speaker_positions = self.position_history.get(speaker, []) | |
| if len(speaker_positions) < 2: | |
| return 1.0 # Pouca data para avaliar | |
| # Penaliza por contradições | |
| contradictions = len([ | |
| c for c in debate.contradictions | |
| if c.get("speaker") == speaker | |
| ]) | |
| # Penaliza por falácias | |
| fallacies = len([ | |
| f for f in debate.fallacies_detected | |
| if f.get("speaker") == speaker | |
| ]) | |
| # Score base = 1.0, penaliza por contradições e falácias | |
| score = 1.0 - (contradictions * 0.3) - (fallacies * 0.2) | |
| return max(0.0, min(1.0, score)) | |
| def reset_debate(self, conversation_id: str): | |
| """Reseta o estado do debate para uma conversa""" | |
| self.active_debates.pop(conversation_id, None) | |
| # Singleton global | |
| _debate_manager_instance: Optional[DebateManager] = None | |
| def get_debate_manager() -> DebateManager: | |
| """Retorna instância singleton do DebateManager""" | |
| global _debate_manager_instance | |
| if _debate_manager_instance is None: | |
| _debate_manager_instance = DebateManager() | |
| return _debate_manager_instance |