Spaces:
Sleeping

milindkamat0507 commited on
Commit
84d1dca
Β·
verified Β·
1 Parent(s): f6bbc5d

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +299 -0
app.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """app.py β€” Compact Gradio + Mistral + BERTopic. Version 2.1.0 | 4 April 2026. ZERO for/while/if.
2
+
3
+ FUNCTIONS IN THIS FILE:
4
+ _latest_output() β€” Scans /tmp for newest rq4_* file β†’ feeds download button
5
+ respond() β€” Core chat handler: takes message + history + file β†’ yields agent response
6
+ gr.Blocks() β€” One-page UI: header + upload + chatbot + input + download
7
+ """
8
+ import os
9
+ import glob
10
+ import gradio as gr
11
+ from langchain_mistralai import ChatMistralAI
12
+ from langgraph.prebuilt import create_react_agent
13
+ from langgraph.checkpoint.memory import MemorySaver
14
+ from agent import SYSTEM_PROMPT, get_local_tools
15
+
16
+ print(">>> app.py: imports complete")
17
+
18
+ # ═══════════════════════════════════════════════
19
+ # AGENT SETUP β€” Mistral brain + 5 BERTopic tools
20
+ # ═══════════════════════════════════════════════
21
+ llm = ChatMistralAI(model="mistral-small-latest", temperature=0, timeout=300)
22
+ tools = get_local_tools()
23
+ agent = create_react_agent(model=llm, tools=tools, prompt=SYSTEM_PROMPT, checkpointer=MemorySaver())
24
+ print(f">>> app.py: agent ready ({len(tools)} tools, Mistral Large)")
25
+
26
+ _msg_count = 0
27
+ _uploaded = {"path": ""}
28
+
29
+ # ═══════════════════════════════════════════════
30
+ # COMPACT HEADER β€” fits in ~60px
31
+ # ═══════════════════════════════════════════════
32
+ HEADER_HTML = """
33
+ <style>
34
+ @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap');
35
+ .gradio-container {font-family: 'DM Sans', sans-serif !important; padding: 4px 8px !important; max-width: 100% !important;}
36
+ footer {display: none !important;}
37
+ .section-box {border: 1px solid #e2e8f0; border-radius: 8px; padding: 8px 12px; margin-bottom: 6px; background: #fafbfc;}
38
+ .section-label {font-size: 0.75em; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;}
39
+ </style>
40
+ <div style="background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #334155 100%); border-radius: 8px; padding: 8px 16px; margin-bottom: 4px; color: white; display: flex; align-items: center; gap: 10px;">
41
+ <span style="font-size: 1.3em;">πŸ”¬</span>
42
+ <div>
43
+ <span style="font-size: 1em; font-weight: 700; color: #e0e0ff;">Topic Modelling β€” Agentic AI</span>
44
+ <span style="font-size: 0.65em; color: #94a3b8; margin-left: 8px;">Mistral πŸ‡«πŸ‡· Β· Cosine Clustering Β· 384d Β· B&C Thematic Analysis</span>
45
+ </div>
46
+ </div>
47
+ """
48
+
49
+ # ═══════════════════════════════════════════════
50
+ # FUNCTION 1: Find latest output for download
51
+ # ═══════════════════════════════════════════════
52
+ def _latest_output():
53
+ """Scan /tmp for most recent rq4_* file (CSV, HTML, or TXT).
54
+ Returns filepath string or None. Fed to gr.File download component."""
55
+ files = sorted(glob.glob("/tmp/rq4_*.csv") + glob.glob("/tmp/rq4_*.html") + glob.glob("/tmp/rq4_*.txt"), key=os.path.getmtime)
56
+ return (files and files[-1]) or None
57
+
58
+
59
+ # ═══════════════════════════════════════════════
60
+ # FUNCTION 2: Chat handler β€” core of the app
61
+ # ═══════════════════════════════════════════════
62
+ def respond(message, chat_history, uploaded_file):
63
+ """Handle one chat turn:
64
+ 1. Store uploaded file path (if new upload)
65
+ 2. Append file context to message so agent knows where CSV is
66
+ 3. Show progress bubble immediately (user sees instant feedback)
67
+ 4. Invoke agent (Mistral brain decides which tools to call)
68
+ 5. Replace progress bubble with agent's actual response
69
+ 6. Update download link to latest output file
70
+
71
+ Uses single thread_id="session" so agent remembers across turns.
72
+ Agent asks clarification FIRST (via SYSTEM_PROMPT) before running heavy tools."""
73
+ global _msg_count
74
+ _msg_count += 1
75
+
76
+ # Store file path β€” no if/else, uses `or` short-circuit
77
+ _uploaded["path"] = uploaded_file or _uploaded.get("path", "")
78
+
79
+ # Guard: tell agent when no file uploaded (prevents hallucinated filepath)
80
+ file_note = (f"\n[CSV file at: {_uploaded['path']}]" * bool(_uploaded["path"])
81
+ ) or "\n[No CSV uploaded yet β€” ask user to upload a file first]"
82
+
83
+ # Context: tell agent what phase we're in based on checkpoint files
84
+ phase_context = (
85
+ "\n[Phase context: labels exist]" * bool(glob.glob("/tmp/checkpoints/rq4_*_labels.json"))
86
+ or "\n[Phase context: embeddings exist]" * bool(glob.glob("/tmp/checkpoints/rq4_*_emb.npy"))
87
+ or "\n[Phase context: fresh start]"
88
+ )
89
+
90
+ text = ((message or "").strip() or "Analyze my Scopus CSV") + file_note + phase_context
91
+ print(f"\n{'='*60}\n>>> MSG #{_msg_count}: '{text[:120]}'\n{'='*60}")
92
+
93
+ # Yield progress bubble immediately β€” user sees instant response
94
+ chat_history = chat_history + [
95
+ {"role": "user", "content": (message or "").strip()},
96
+ {"role": "assistant", "content": "πŸ”¬ **Working...** _Agent is thinking..._"},
97
+ ]
98
+ yield chat_history, "", _latest_output()
99
+
100
+ # Shared session β€” agent remembers across messages (loaded CSV, phase, etc.)
101
+ # handle_tool_error=True on all tools prevents session poisoning from failures
102
+ result = agent.invoke(
103
+ {"messages": [("human", text)]},
104
+ config={"configurable": {"thread_id": "session"}},
105
+ )
106
+ response = result["messages"][-1].content
107
+ print(f">>> Response ({len(response)} chars)")
108
+
109
+ # Replace progress bubble with actual response
110
+ chat_history[-1] = {"role": "assistant", "content": response}
111
+ yield chat_history, "", _latest_output()
112
+
113
+
114
+ # ═══════════════════════════════════════════════
115
+ # UI LAYOUT β€” Everything fits ONE screen (~500px)
116
+ #
117
+ # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
118
+ # β”‚ πŸ”¬ BERTopic Agent (compact) β”‚ ~55px
119
+ # β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
120
+ # β”‚ [πŸ“‚ Upload CSV] β”‚ ~35px
121
+ # β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
122
+ # β”‚ πŸ’¬ Chat bubbles (cloud style) β”‚
123
+ # β”‚ User: "Analyze my data" β”‚ ~320px
124
+ # β”‚ Agent: "I found 1390 papers. β”‚
125
+ # β”‚ Which config? All 3?" β”‚
126
+ # β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
127
+ # β”‚ [Type message... ] [⏎] β”‚ ~35px
128
+ # β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
129
+ # β”‚ πŸ“₯ Download β”‚ ~35px
130
+ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
131
+ # TOTAL: ~480px β€” fits any screen
132
+ # ═══════════════════════════════════════════════
133
+ print(">>> Building UI...")
134
+ with gr.Blocks(title="Topic Modelling β€” Agentic AI") as demo:
135
+ gr.HTML(HEADER_HTML)
136
+
137
+ # ══════════════════════════════════════════
138
+ # SECTION 1: DATA INPUT
139
+ # ══════════════════════════════════════════
140
+ gr.HTML('<div class="section-label">β‘  DATA INPUT</div>')
141
+ with gr.Group():
142
+ with gr.Row():
143
+ upload = gr.File(label="πŸ“‚ Upload Scopus CSV", file_types=[".csv"])
144
+ gr.Markdown("**Upload your CSV** then type `run abstract only` in the chat below")
145
+
146
+ # ══════════════════════════════════════════
147
+ # SECTION 2: AGENT CONVERSATION
148
+ # ══════════════════════════════════════════
149
+ gr.HTML('<div class="section-label">β‘‘ AGENT CONVERSATION β€” follow the prompts below</div>')
150
+ with gr.Group():
151
+ chatbot = gr.Chatbot(height=250, show_label=False,
152
+ placeholder="Upload your Scopus CSV above, then type: run abstract only")
153
+ with gr.Row():
154
+ msg = gr.Textbox(
155
+ placeholder="run Β· approve Β· show topic 4 papers Β· group 0 1 5 Β· done",
156
+ show_label=False, scale=9, lines=1, max_lines=1, container=False)
157
+ send = gr.Button("Send", variant="primary", scale=1, min_width=70)
158
+
159
+ # ══════════════════════════════════════════
160
+ # SECTION 3: RESULTS
161
+ # ══════════════════════════════════════════
162
+ gr.HTML('<div class="section-label">β‘’ RESULTS β€” review table, charts, downloads</div>')
163
+ with gr.Group():
164
+ with gr.Tabs():
165
+ with gr.Tab("πŸ“‹ Review Table"):
166
+ gr.Markdown("*Edit Approve / Rename To / Your Reasoning β†’ click Submit. "
167
+ "Type `show topic 4 papers` in chat to see paper list.*")
168
+ review_table = gr.Dataframe(
169
+ headers=["#", "Topic Label", "Research Area", "Confidence",
170
+ "Sentences", "Papers", "Approve", "Rename To", "Your Reasoning"],
171
+ datatype=["number", "str", "str", "str", "number", "number", "str", "str", "str"],
172
+ column_count=(9, "fixed"),
173
+ interactive=True,
174
+ row_count=(1, "dynamic"),
175
+ )
176
+ submit_review = gr.Button("βœ… Submit Review to Agent", variant="primary")
177
+
178
+ with gr.Tab("πŸ“Š Charts"):
179
+ chart_selector = gr.Dropdown(choices=[], label="Select Chart", interactive=True)
180
+ chart_display = gr.HTML(
181
+ value="<div style='height:350px;display:flex;align-items:center;justify-content:center;"
182
+ "color:#94a3b8;border:1px dashed #cbd5e1;border-radius:8px;'>"
183
+ "Charts appear after BERTopic runs</div>")
184
+
185
+ with gr.Tab("πŸ“₯ Download"):
186
+ download = gr.File(label="Latest output file")
187
+
188
+ def _load_chart(chart_name):
189
+ """Load chart HTML into iframe β€” gr.HTML strips scripts, iframe executes them."""
190
+ import html as html_mod
191
+ path = f"/tmp/{chart_name}"
192
+ content = os.path.exists(path) and open(path).read() or ""
193
+ escaped = html_mod.escape(content) * bool(content)
194
+ return (f'<iframe srcdoc="{escaped}" width="100%" height="450" '
195
+ f'frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe>'
196
+ ) * bool(escaped) or "<div style='padding:20px;color:#94a3b8;'>Select a chart above</div>"
197
+
198
+ def _get_chart_choices():
199
+ """Find all rq4_*.html chart files in /tmp."""
200
+ files = sorted(glob.glob("/tmp/rq4_*.html"))
201
+ return list(map(os.path.basename, files))
202
+
203
+ def _load_review_table():
204
+ """Load review table from labels.json (if labeled) or summaries.json (if only discovered).
205
+ Returns list of rows: [#, Label, ResearchArea, Conf, Sent, Papers, Approve, Rename, Reasoning]"""
206
+ import json
207
+ # Try labels first (after Mistral labeling), fall back to summaries (after discovery)
208
+ label_files = sorted(glob.glob("/tmp/checkpoints/rq4_*_labels.json"))
209
+ summary_files = sorted(glob.glob("/tmp/checkpoints/rq4_*_summaries.json"))
210
+ path = (label_files and label_files[-1]) or (summary_files and summary_files[-1]) or ""
211
+ is_labeled = bool(label_files and label_files[-1] == path)
212
+ data = (os.path.exists(path) and json.load(open(path))) or []
213
+ rows = list(map(
214
+ lambda l: [
215
+ l.get("topic_id", 0),
216
+ l.get("label", l.get("top_words", "")[:60]), # label if labeled, top_words if summary
217
+ l.get("category", "pending labeling" * (not is_labeled)),
218
+ l.get("confidence", "β€”" * (not is_labeled)),
219
+ l.get("sentence_count", 0),
220
+ l.get("paper_count", 0),
221
+ "yes",
222
+ "",
223
+ "",
224
+ ], data))
225
+ return rows or [[0, "No data yet β€” upload CSV and run BERTopic", "", "", 0, 0, "", "", ""]]
226
+
227
+ def _submit_review(table_data, chat_history):
228
+ """Convert edited review table into a message for the agent.
229
+ Researcher's edits (approve/rename/reasoning) become natural language."""
230
+ rows = table_data.values.tolist()
231
+ lines = list(map(
232
+ lambda r: (
233
+ f"Topic {int(r[0])}: "
234
+ + (f"RENAME to '{r[7]}'" * bool(str(r[7]).strip()))
235
+ + (f"APPROVE '{r[1]}'" * (not bool(str(r[7]).strip())) * (str(r[6]).lower().startswith("y")))
236
+ + (f"REJECT" * (str(r[6]).lower().startswith("n")))
237
+ + (f" β€” reason: {r[8]}" * bool(str(r[8]).strip()))
238
+ ), rows))
239
+ review_msg = "Review decisions:\n" + "\n".join(lines)
240
+ debug(f">>> Review submitted: {review_msg[:200]}")
241
+
242
+ chat_history = chat_history + [
243
+ {"role": "user", "content": review_msg},
244
+ {"role": "assistant", "content": "πŸ”¬ **Processing review decisions...**"},
245
+ ]
246
+ yield chat_history, _latest_output(), gr.update(), gr.update()
247
+
248
+ result = agent.invoke(
249
+ {"messages": [("human", review_msg)]},
250
+ config={"configurable": {"thread_id": "session"}},
251
+ )
252
+ response = result["messages"][-1].content
253
+ chat_history[-1] = {"role": "assistant", "content": response}
254
+ yield chat_history, _latest_output(), gr.update(choices=_get_chart_choices()), gr.update()
255
+
256
+ chart_selector.change(_load_chart, [chart_selector], [chart_display])
257
+ submit_review.click(_submit_review, [review_table, chatbot],
258
+ [chatbot, download, chart_selector, chart_display])
259
+
260
+ def respond_with_viz(message, chat_history, uploaded_file):
261
+ """Wrap respond() and update chart dropdown + review table after each message."""
262
+ gen = respond(message, chat_history, uploaded_file)
263
+ # First yield (progress)
264
+ hist, txt, dl = next(gen)
265
+ yield hist, txt, dl, gr.update(choices=_get_chart_choices()), gr.update(), gr.update()
266
+ # Second yield (final response + populate table + charts)
267
+ hist, txt, dl = next(gen)
268
+ choices = _get_chart_choices()
269
+ first_chart = (choices and _load_chart(choices[-1])) or gr.update()
270
+ table_data = _load_review_table()
271
+ yield (hist, txt, dl,
272
+ gr.update(choices=choices, value=(choices and choices[-1]) or None),
273
+ first_chart,
274
+ gr.update(value=table_data))
275
+
276
+ msg.submit(respond_with_viz, [msg, chatbot, upload],
277
+ [chatbot, msg, download, chart_selector, chart_display, review_table])
278
+ send.click(respond_with_viz, [msg, chatbot, upload],
279
+ [chatbot, msg, download, chart_selector, chart_display, review_table])
280
+
281
+ def _auto_load_csv(uploaded_file, chat_history):
282
+ """Auto-trigger analysis when CSV is uploaded β€” stats appear without typing."""
283
+ gen = respond("Analyze my Scopus CSV", chat_history, uploaded_file)
284
+ hist, txt, dl = next(gen)
285
+ yield hist, dl, gr.update(), gr.update(), gr.update()
286
+ hist, txt, dl = next(gen)
287
+ choices = _get_chart_choices()
288
+ first_chart = (choices and _load_chart(choices[-1])) or gr.update()
289
+ table_data = _load_review_table()
290
+ yield (hist, dl,
291
+ gr.update(choices=choices, value=(choices and choices[-1]) or None),
292
+ first_chart,
293
+ gr.update(value=table_data))
294
+
295
+ upload.change(_auto_load_csv, [upload, chatbot],
296
+ [chatbot, download, chart_selector, chart_display, review_table])
297
+
298
+ print(">>> Launching...")
299
+ demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)