imeshuek commited on
Commit
f8b5641
·
verified ·
1 Parent(s): 2acfb68

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +249 -1
app.py CHANGED
@@ -3,4 +3,252 @@ import numpy as np
3
  import re
4
  from collections import defaultdict
5
 
6
- print("TRIBE Paper Reader starting...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import re
4
  from collections import defaultdict
5
 
6
+ # ============================================================
7
+ # TRIBE Paper Reader - Cognitive State Highlighter
8
+ # ============================================================
9
+ # Maps predicted brain activation patterns to cognitive/emotional
10
+ # states and highlights research paper text accordingly.
11
+ #
12
+ # Color Mapping:
13
+ # Red = Curiosity (prefrontal + anterior cingulate)
14
+ # Blue = Questioning (dorsolateral prefrontal dominance)
15
+ # Green = Confusion (high executive load, low coherence)
16
+ # Yellow = Excitement (emotion + reward circuits)
17
+ # Purple = Insight (associative cortex coherence)
18
+ # Orange = Frustration (conflict monitoring, low reward)
19
+ # ============================================================
20
+
21
+ # ---- Cognitive State Definitions ----
22
+ STATE_COLORS = {
23
+ "curiosity": {"hex": "#ff4444", "bg": "rgba(255,68,68,0.15)", "label": "Curiosity", "emoji": "🔴"},
24
+ "questioning": {"hex": "#4488ff", "bg": "rgba(68,136,255,0.15)", "label": "Questioning", "emoji": "🔵"},
25
+ "confusion": {"hex": "#44aa44", "bg": "rgba(68,170,68,0.15)", "label": "Confusion", "emoji": "🟢"},
26
+ "excitement": {"hex": "#ffaa00", "bg": "rgba(255,170,0,0.15)", "label": "Excitement", "emoji": "🟡"},
27
+ "insight": {"hex": "#aa44ff", "bg": "rgba(170,68,255,0.15)", "label": "Insight", "emoji": "🟣"},
28
+ "frustration": {"hex": "#ff8844", "bg": "rgba(255,136,68,0.15)", "label": "Frustration", "emoji": "🟠"},
29
+ "neutral": {"hex": "#888888", "bg": "transparent", "label": "Neutral", "emoji": "⚪"},
30
+ }
31
+
32
+ # ---- Text Analysis Heuristics (fallback when TRIBE not available) ----
33
+ CURIOSITY_MARKERS = [
34
+ "novel", "new", "previously unknown", "first time", "surprisingly",
35
+ "unexpected", "interesting", "intriguing", "remarkable", "striking",
36
+ "counterintuitive", "paradox", "mystery", "unknown", "unexplored",
37
+ "hypothesis", "propose", "suggest", "may", "might", "could", "possibly",
38
+ "?", "what if", "how does", "why do", "future work", "open question"
39
+ ]
40
+
41
+ QUESTIONING_MARKERS = [
42
+ "however", "but", "although", "nevertheless", "yet", "despite",
43
+ "in contrast", "on the other hand", "contradict", "inconsistent",
44
+ "unclear", "debated", "controversial", "challenge", "criticism",
45
+ "limitation", "weakness", "fails to", "does not", "not significantly",
46
+ "p > 0.05", "insufficient", "inconclusive"
47
+ ]
48
+
49
+ CONFUSION_MARKERS = [
50
+ "complex", "complicated", "difficult", "challenging", "intricate",
51
+ "non-trivial", "subtle", "nuanced", "ambiguous", "uncertain",
52
+ "unclear", "not well understood", "remains elusive", "poorly understood"
53
+ ]
54
+
55
+ EXCITEMENT_MARKERS = [
56
+ "breakthrough", "significant", "substantial", "dramatic", "remarkable",
57
+ "outstanding", "excellent", "superior", "state-of-the-art", "sota",
58
+ "achieves", "improves", "outperforms", "best", "top", "first place",
59
+ "novel contribution", "key result", "important", "crucial"
60
+ ]
61
+
62
+ INSIGHT_MARKERS = [
63
+ "thus", "therefore", "hence", "consequently", "as a result",
64
+ "we find that", "our results show", "demonstrate", "reveal",
65
+ "discover", "found that", "this suggests", "this implies",
66
+ "in summary", "to conclude", "overall", "taken together"
67
+ ]
68
+
69
+ FRUSTRATION_MARKERS = [
70
+ "failed", "failure", "error", "problem", "issue", "difficulty",
71
+ "bottleneck", "degradation", "drops", "worse", "inferior",
72
+ "not achieve", "unable to", "struggle", "limited by", "constrained"
73
+ ]
74
+
75
+
76
+ def detect_state_heuristic(sentence):
77
+ """Fallback heuristic-based state detection when TRIBE model unavailable."""
78
+ s_lower = sentence.lower()
79
+ scores = defaultdict(float)
80
+
81
+ for marker in CURIOSITY_MARKERS:
82
+ if marker.lower() in s_lower:
83
+ scores["curiosity"] += 1.0
84
+ for marker in QUESTIONING_MARKERS:
85
+ if marker.lower() in s_lower:
86
+ scores["questioning"] += 1.5
87
+ for marker in CONFUSION_MARKERS:
88
+ if marker.lower() in s_lower:
89
+ scores["confusion"] += 1.2
90
+ for marker in EXCITEMENT_MARKERS:
91
+ if marker.lower() in s_lower:
92
+ scores["excitement"] += 1.3
93
+ for marker in INSIGHT_MARKERS:
94
+ if marker.lower() in s_lower:
95
+ scores["insight"] += 1.4
96
+ for marker in FRUSTRATION_MARKERS:
97
+ if marker.lower() in s_lower:
98
+ scores["frustration"] += 1.1
99
+
100
+ # Sentence structure heuristics
101
+ if s_lower.endswith("?"):
102
+ scores["questioning"] += 2.0
103
+ if "we hypothesize" in s_lower or "we propose" in s_lower:
104
+ scores["curiosity"] += 1.5
105
+ if "p < 0.001" in s_lower or "p < 0.01" in s_lower:
106
+ scores["excitement"] += 1.0
107
+ if "however" in s_lower or "but" in s_lower:
108
+ scores["questioning"] += 0.8
109
+
110
+ if not scores:
111
+ return "neutral", 0.0
112
+
113
+ best_state = max(scores, key=scores.get)
114
+ return best_state, scores[best_state]
115
+
116
+
117
+ def split_into_sentences(text):
118
+ """Split text into sentences, preserving structure."""
119
+ # Handle common abbreviations
120
+ text = re.sub(r'(?<=[A-Z])\.(?=[A-Z])', '.', text)
121
+ # Split on sentence boundaries
122
+ sentences = re.split(r'(?<=[.!?])\s+', text)
123
+ return [s.strip() for s in sentences if s.strip()]
124
+
125
+
126
+ def highlight_text(text, use_tribe=False):
127
+ """Analyze text and return HTML with cognitive state highlights."""
128
+ sentences = split_into_sentences(text)
129
+ highlighted = []
130
+ state_counts = defaultdict(int)
131
+
132
+ for sent in sentences:
133
+ if not sent:
134
+ continue
135
+
136
+ if use_tribe:
137
+ # TODO: Integrate TRIBE v2 prediction here
138
+ # For now, use heuristics
139
+ state, confidence = detect_state_heuristic(sent)
140
+ else:
141
+ state, confidence = detect_state_heuristic(sent)
142
+
143
+ state_counts[state] += 1
144
+ color_info = STATE_COLORS.get(state, STATE_COLORS["neutral"])
145
+
146
+ # Build highlighted sentence
147
+ tooltip = f"{color_info['emoji']} {color_info['label']} (confidence: {confidence:.1f})"
148
+ html_sent = (
149
+ f'<span style="background-color: {color_info["bg"]}; '
150
+ f'border-bottom: 2px solid {color_info["hex"]}; '
151
+ f'padding: 1px 2px; border-radius: 2px; '
152
+ f'title="{tooltip}">'
153
+ f'{sent}</span>'
154
+ )
155
+ highlighted.append(html_sent)
156
+
157
+ # Join with spaces
158
+ full_html = " ".join(highlighted)
159
+
160
+ # Build legend
161
+ legend_html = '<div style="margin: 15px 0; padding: 10px; background: #1a1a1a; border-radius: 8px;">'
162
+ legend_html += '<h4 style="color: #fff; margin: 0 0 10px 0;">🧠 Cognitive State Legend</h4>'
163
+ legend_html += '<div style="display: flex; flex-wrap: wrap; gap: 10px;">'
164
+ for state, info in STATE_COLORS.items():
165
+ if state == "neutral":
166
+ continue
167
+ count = state_counts.get(state, 0)
168
+ if count > 0:
169
+ legend_html += (
170
+ f'<span style="background: {info["bg"]}; color: {info["hex"]}; '
171
+ f'padding: 4px 10px; border-radius: 12px; font-size: 0.85em; '
172
+ f'border: 1px solid {info["hex"]};">'
173
+ f'{info["emoji"]} {info["label"]} ({count})</span>'
174
+ )
175
+ legend_html += '</div></div>'
176
+
177
+ # Build stats
178
+ total = sum(state_counts.values())
179
+ stats_html = '<div style="margin: 15px 0; padding: 10px; background: #1a1a1a; border-radius: 8px;">'
180
+ stats_html += '<h4 style="color: #fff; margin: 0 0 10px 0;">📊 Reading Profile</h4>'
181
+ stats_html += '<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;">'
182
+ for state, info in STATE_COLORS.items():
183
+ if state == "neutral":
184
+ continue
185
+ count = state_counts.get(state, 0)
186
+ pct = (count / total * 100) if total > 0 else 0
187
+ bar_width = int(pct * 2)
188
+ stats_html += (
189
+ f'<div style="color: #ccc; font-size: 0.8em;">'
190
+ f'<div style="display: flex; justify-content: space-between;">'
191
+ f'<span>{info["emoji"]} {info["label"]}</span>'
192
+ f'<span>{pct:.0f}%</span></div>'
193
+ f'<div style="background: #333; height: 6px; border-radius: 3px; margin-top: 2px;">'
194
+ f'<div style="background: {info["hex"]}; width: {bar_width}px; height: 100%; border-radius: 3px;">'
195
+ f'</div></div></div>'
196
+ )
197
+ stats_html += '</div></div>'
198
+
199
+ return legend_html + stats_html + '<div style="line-height: 1.8; color: #e0e0e0; font-size: 1.05em;">' + full_html + '</div>'
200
+
201
+
202
+ # ---- Gradio UI ----
203
+ with gr.Blocks(title="TRIBE Paper Reader", css="""
204
+ body { background-color: #0d0d0d !important; }
205
+ .gradio-container { max-width: 1100px !important; }
206
+ """) as demo:
207
+ gr.HTML("""
208
+ <div style="text-align: center; padding: 20px 0; border-bottom: 1px solid #333; margin-bottom: 20px;">
209
+ <h1 style="color: #fff; font-size: 2.2rem; margin: 0;">🧠 TRIBE Paper Reader</h1>
210
+ <p style="color: #888; font-size: 1rem; margin: 8px 0 0 0;">
211
+ Read research papers with cognitive state highlighting powered by brain encoding
212
+ </p>
213
+ </div>
214
+ """)
215
+
216
+ with gr.Row():
217
+ with gr.Column(scale=1):
218
+ gr.Markdown("### 📄 Input")
219
+ input_text = gr.TextArea(
220
+ label="Paste paper text",
221
+ placeholder="Paste abstract, introduction, or full paper text here...",
222
+ lines=20,
223
+ value="""We introduce a novel architecture for visual recognition that achieves state-of-the-art results on ImageNet. However, our method requires significantly more compute than prior approaches. The key insight is that multi-scale feature aggregation improves representation quality, but this comes at the cost of increased model complexity. We hypothesize that future work could reduce this overhead through better optimization. Our experiments demonstrate a 15% improvement over the previous best, but we acknowledge limitations in our evaluation protocol."""
224
+ )
225
+ analyze_btn = gr.Button("🧠 Analyze Paper", variant="primary", size="lg")
226
+
227
+ with gr.Column(scale=1):
228
+ gr.Markdown("### ✨ Highlighted Output")
229
+ output_html = gr.HTML(label="Highlighted Text")
230
+
231
+ gr.Markdown("""
232
+ <div style="margin-top: 30px; padding: 15px; background: #1a1a1a; border-radius: 8px; color: #888; font-size: 0.85em;">
233
+ <strong>How it works:</strong> Each sentence is analyzed for cognitive markers.
234
+ In the full TRIBE integration, Meta's TRIBE v2 brain encoding model predicts
235
+ whole-brain fMRI responses to infer the reader's likely cognitive state.
236
+ <br><br>
237
+ <strong>Colors:</strong>
238
+ <span style="color:#ff4444">🔴 Curiosity</span> |
239
+ <span style="color:#4488ff">🔵 Questioning</span> |
240
+ <span style="color:#44aa44">🟢 Confusion</span> |
241
+ <span style="color:#ffaa00">🟡 Excitement</span> |
242
+ <span style="color:#aa44ff">🟣 Insight</span> |
243
+ <span style="color:#ff8844">🟠 Frustration</span>
244
+ </div>
245
+ """)
246
+
247
+ analyze_btn.click(
248
+ fn=highlight_text,
249
+ inputs=input_text,
250
+ outputs=output_html
251
+ )
252
+
253
+ if __name__ == "__main__":
254
+ demo.launch()