import gradio as gr import numpy as np import re from collections import defaultdict # ============================================================ # TRIBE Paper Reader - Cognitive State Highlighter # ============================================================ # Maps predicted brain activation patterns to cognitive/emotional # states and highlights research paper text accordingly. # # Color Mapping: # Red = Curiosity (prefrontal + anterior cingulate) # Blue = Questioning (dorsolateral prefrontal dominance) # Green = Confusion (high executive load, low coherence) # Yellow = Excitement (emotion + reward circuits) # Purple = Insight (associative cortex coherence) # Orange = Frustration (conflict monitoring, low reward) # ============================================================ # ---- Cognitive State Definitions ---- STATE_COLORS = { "curiosity": {"hex": "#ff4444", "bg": "rgba(255,68,68,0.15)", "label": "Curiosity", "emoji": "🔴"}, "questioning": {"hex": "#4488ff", "bg": "rgba(68,136,255,0.15)", "label": "Questioning", "emoji": "🔵"}, "confusion": {"hex": "#44aa44", "bg": "rgba(68,170,68,0.15)", "label": "Confusion", "emoji": "🟢"}, "excitement": {"hex": "#ffaa00", "bg": "rgba(255,170,0,0.15)", "label": "Excitement", "emoji": "🟡"}, "insight": {"hex": "#aa44ff", "bg": "rgba(170,68,255,0.15)", "label": "Insight", "emoji": "🟣"}, "frustration": {"hex": "#ff8844", "bg": "rgba(255,136,68,0.15)", "label": "Frustration", "emoji": "🟠"}, "neutral": {"hex": "#888888", "bg": "transparent", "label": "Neutral", "emoji": "⚪"}, } # ---- Text Analysis Heuristics (fallback when TRIBE not available) ---- CURIOSITY_MARKERS = [ "novel", "new", "previously unknown", "first time", "surprisingly", "unexpected", "interesting", "intriguing", "remarkable", "striking", "counterintuitive", "paradox", "mystery", "unknown", "unexplored", "hypothesis", "propose", "suggest", "may", "might", "could", "possibly", "?", "what if", "how does", "why do", "future work", "open question" ] QUESTIONING_MARKERS = [ "however", "but", "although", "nevertheless", "yet", "despite", "in contrast", "on the other hand", "contradict", "inconsistent", "unclear", "debated", "controversial", "challenge", "criticism", "limitation", "weakness", "fails to", "does not", "not significantly", "p > 0.05", "insufficient", "inconclusive" ] CONFUSION_MARKERS = [ "complex", "complicated", "difficult", "challenging", "intricate", "non-trivial", "subtle", "nuanced", "ambiguous", "uncertain", "unclear", "not well understood", "remains elusive", "poorly understood" ] EXCITEMENT_MARKERS = [ "breakthrough", "significant", "substantial", "dramatic", "remarkable", "outstanding", "excellent", "superior", "state-of-the-art", "sota", "achieves", "improves", "outperforms", "best", "top", "first place", "novel contribution", "key result", "important", "crucial" ] INSIGHT_MARKERS = [ "thus", "therefore", "hence", "consequently", "as a result", "we find that", "our results show", "demonstrate", "reveal", "discover", "found that", "this suggests", "this implies", "in summary", "to conclude", "overall", "taken together" ] FRUSTRATION_MARKERS = [ "failed", "failure", "error", "problem", "issue", "difficulty", "bottleneck", "degradation", "drops", "worse", "inferior", "not achieve", "unable to", "struggle", "limited by", "constrained" ] def detect_state_heuristic(sentence): """Fallback heuristic-based state detection when TRIBE model unavailable.""" s_lower = sentence.lower() scores = defaultdict(float) for marker in CURIOSITY_MARKERS: if marker.lower() in s_lower: scores["curiosity"] += 1.0 for marker in QUESTIONING_MARKERS: if marker.lower() in s_lower: scores["questioning"] += 1.5 for marker in CONFUSION_MARKERS: if marker.lower() in s_lower: scores["confusion"] += 1.2 for marker in EXCITEMENT_MARKERS: if marker.lower() in s_lower: scores["excitement"] += 1.3 for marker in INSIGHT_MARKERS: if marker.lower() in s_lower: scores["insight"] += 1.4 for marker in FRUSTRATION_MARKERS: if marker.lower() in s_lower: scores["frustration"] += 1.1 # Sentence structure heuristics if s_lower.endswith("?"): scores["questioning"] += 2.0 if "we hypothesize" in s_lower or "we propose" in s_lower: scores["curiosity"] += 1.5 if "p < 0.001" in s_lower or "p < 0.01" in s_lower: scores["excitement"] += 1.0 if "however" in s_lower or "but" in s_lower: scores["questioning"] += 0.8 if not scores: return "neutral", 0.0 best_state = max(scores, key=scores.get) return best_state, scores[best_state] def split_into_sentences(text): """Split text into sentences, preserving structure.""" # Handle common abbreviations text = re.sub(r'(?<=[A-Z])\.(?=[A-Z])', '.', text) # Split on sentence boundaries sentences = re.split(r'(?<=[.!?])\s+', text) return [s.strip() for s in sentences if s.strip()] def highlight_text(text, use_tribe=False): """Analyze text and return HTML with cognitive state highlights.""" sentences = split_into_sentences(text) highlighted = [] state_counts = defaultdict(int) for sent in sentences: if not sent: continue if use_tribe: # TODO: Integrate TRIBE v2 prediction here # For now, use heuristics state, confidence = detect_state_heuristic(sent) else: state, confidence = detect_state_heuristic(sent) state_counts[state] += 1 color_info = STATE_COLORS.get(state, STATE_COLORS["neutral"]) # Build highlighted sentence tooltip = f"{color_info['emoji']} {color_info['label']} (confidence: {confidence:.1f})" html_sent = ( f'' f'{sent}' ) highlighted.append(html_sent) # Join with spaces full_html = " ".join(highlighted) # Build legend legend_html = '
Read research papers with cognitive state highlighting powered by brain encoding