Daksh C Jain commited on
Commit
eba181a
Β·
1 Parent(s): 822c198

Fix Gradio ValueError and improve UI visibility

Browse files
Files changed (1) hide show
  1. app.py +170 -172
app.py CHANGED
@@ -1,172 +1,170 @@
1
- import os
2
- import glob
3
- import json
4
- import plotly.io as pio
5
- import gradio as gr
6
- from dotenv import load_dotenv
7
- from langchain_mistralai import ChatMistralAI
8
- from langgraph.prebuilt import create_react_agent
9
- from langgraph.checkpoint.memory import MemorySaver
10
- from agent import SYSTEM_PROMPT, get_local_tools
11
-
12
- os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
13
- load_dotenv()
14
-
15
- OUTPUT_DIR = "outputs"
16
- CHECKPOINT_DIR = os.path.join(OUTPUT_DIR, "checkpoints")
17
- os.makedirs(CHECKPOINT_DIR, exist_ok=True)
18
-
19
- llm = ChatMistralAI(model="mistral-small-latest", temperature=0, timeout=300)
20
- agent = create_react_agent(model=llm, tools=get_local_tools(), prompt=SYSTEM_PROMPT, checkpointer=MemorySaver())
21
- _msg_count = 0
22
- _uploaded = {"path": ""}
23
-
24
- theme = gr.themes.Soft(
25
- primary_hue="indigo",
26
- secondary_hue="violet",
27
- neutral_hue="slate",
28
- font=gr.themes.GoogleFont("Outfit"),
29
- font_mono=gr.themes.GoogleFont("JetBrains Mono"),
30
- ).set(
31
- body_background_fill="*neutral_50",
32
- block_title_text_weight="700",
33
- button_primary_background_fill="*primary_600",
34
- )
35
-
36
- def _latest_output():
37
- ord = {"summaries": 1, "labels": 2, "themes": 3, "taxonomy": 4, "comparison": 9, "narrative": 10}
38
- fs = glob.glob(f"{OUTPUT_DIR}/rq4_*.csv") + glob.glob(f"{CHECKPOINT_DIR}/rq4_*.json")
39
- scored = sorted([(sum(v * (k in f) for k, v in ord.items()), f) for f in fs], key=lambda x: x[0])
40
- return [x[1] for x in scored] or None
41
-
42
- def _build_progress():
43
- ps = [
44
- ("Load", bool(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_summaries.json"))),
45
- ("Codes", bool(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_labels.json"))),
46
- ("Themes", bool(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_themes.json"))),
47
- ("PAJAIS", bool(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_taxonomy_map.json"))),
48
- ("Report", bool(glob.glob(f"{OUTPUT_DIR}/rq4_comparison.csv"))),
49
- ]
50
- return " β†’ ".join(f"{'βœ…' if d else '⬜'} {n}" for n, d in ps)
51
-
52
- def respond(message, chat_history, uploaded_file):
53
- global _msg_count
54
- _msg_count += 1
55
- _uploaded["path"] = uploaded_file or _uploaded.get("path", "")
56
- text = (message or "Analyze") + (f"\n[CSV: {_uploaded['path']}]" if _uploaded["path"] else "\n[No CSV]")
57
-
58
- chat_history.append({"role": "user", "content": message or "Analyze"})
59
- chat_history.append({"role": "assistant", "content": "πŸ”¬ **Working...**"})
60
- yield chat_history, "", _latest_output()
61
-
62
- res = agent.invoke({"messages": [("human", text)]}, config={"configurable": {"thread_id": "session"}})
63
- chat_history[-1] = {"role": "assistant", "content": res["messages"][-1].content}
64
- yield chat_history, "", _latest_output()
65
-
66
- def _load_chart(name):
67
- if not name or not os.path.exists(os.path.join(OUTPUT_DIR, name)): return None
68
- return pio.from_json(open(os.path.join(OUTPUT_DIR, name)).read())
69
-
70
- def _get_chart_choices():
71
- return [os.path.basename(f) for f in sorted(glob.glob(f"{OUTPUT_DIR}/rq4_*.json"))]
72
-
73
- def _load_review_table():
74
- ps = sorted(glob.glob(f"{CHECKPOINT_DIR}/rq4_*.json"))
75
- if not ps: return [[0, "No data", "", 0, 0, False, "", ""]]
76
- data = json.load(open(ps[-1]))
77
- return [[i, d.get("label", d.get("top_words", ""))[:60], d.get("nearest", [{}])[0].get("sentence", "")[:120], d.get("sentence_count", 0), d.get("paper_count", 0), True, "", ""] for i, d in enumerate(data)]
78
-
79
- def _show_papers_by_select(table_data, evt: gr.SelectData):
80
- idx = int(table_data.iloc[evt.index[0], 0]) if hasattr(table_data, 'iloc') else int(table_data[evt.index[0]][0])
81
- fs = sorted(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_labels.json")) or sorted(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_summaries.json"))
82
- for f in fs:
83
- for t in json.load(open(f)):
84
- if t.get("topic_id") == idx:
85
- return f"Topic {idx}: {t.get('label', '')}\n\n" + "\n".join(f"- {p}" for p in t.get("paper_titles", []))
86
- return "Not found"
87
-
88
- def _submit_review(table_data, chat_history):
89
- ls = [f"Topic {int(r[0])}: {'RENAME to '+r[6] if r[6] else ('APPROVE' if r[5] else 'REJECT')}" for r in table_data.values.tolist()]
90
- msg = "Review decisions:\n" + "\n".join(ls)
91
- chat_history.append({"role": "user", "content": "Submitted review"})
92
- chat_history.append({"role": "assistant", "content": "πŸ”¬ **Processing...**"})
93
- yield chat_history, _latest_output(), gr.update(), gr.update(), _build_progress()
94
-
95
- res = agent.invoke({"messages": [("human", msg)]}, config={"configurable": {"thread_id": "session"}})
96
- chat_history[-1] = {"role": "assistant", "content": res["messages"][-1].content}
97
- yield chat_history, _latest_output(), gr.update(choices=_get_chart_choices()), _load_review_table(), _build_progress()
98
-
99
- CSS = """
100
- .gradio-container { background: #fcfcfc !important; }
101
- .sidebar { background: #ffffff !important; border-right: 1px solid #e2e8f0 !important; }
102
- .header-text { font-family: 'Outfit', sans-serif; color: #1e293b; letter-spacing: -0.02em; }
103
- .tab-nav { border-bottom: 2px solid #f1f5f9 !important; }
104
- .chatbot-container { border-radius: 12px !important; border: 1px solid #e2e8f0 !important; overflow: hidden; }
105
- .primary-btn { background: #4f46e5 !important; color: white !important; border-radius: 8px !important; font-weight: 600 !important; }
106
- .secondary-btn { background: #f8fafc !important; color: #475569 !important; border: 1px solid #e2e8f0 !important; border-radius: 8px !important; }
107
- """
108
-
109
- theme = gr.themes.Soft(
110
- primary_hue="indigo",
111
- secondary_hue="violet",
112
- neutral_hue="slate",
113
- font=gr.themes.GoogleFont("Outfit"),
114
- font_mono=gr.themes.GoogleFont("JetBrains Mono"),
115
- ).set(
116
- body_background_fill="*neutral_50",
117
- block_title_text_weight="700",
118
- button_primary_background_fill="*primary_600",
119
- button_primary_text_color="white",
120
- )
121
-
122
- with gr.Blocks(title="Thematic Analysis AI") as demo:
123
- with gr.Sidebar(label="Data Hub", open=True):
124
- gr.HTML("<h2 class='header-text'>πŸ“ Resource Center</h2>")
125
- upload = gr.File(label="Dataset (Scopus CSV)", file_types=[".csv"], elem_id="file-upload")
126
- progress = gr.Markdown(value=_build_progress(), elem_id="progress-display")
127
- gr.HTML("<hr>")
128
- gr.Markdown("### πŸ› οΈ Configuration\nModel: `mistral-small-latest`\nPipeline: `BERTopic + Agglomerative`")
129
-
130
- gr.HTML("<h1 class='header-text' style='margin-bottom: 20px;'>πŸ”¬ Topic Modelling Agentic AI</h1>")
131
-
132
- with gr.Tabs():
133
- with gr.Tab("πŸ’¬ Agent Chat"):
134
- chatbot = gr.Chatbot(height=450, show_label=False, elem_classes="chatbot-container")
135
- with gr.Row():
136
- msg = gr.Textbox(placeholder="Ask the agent to analyze, group, or export...", show_label=False, scale=9)
137
- send = gr.Button("Send", variant="primary", scale=1, elem_classes="primary-btn")
138
-
139
- with gr.Tab("πŸ“‹ Review & Refine"):
140
- gr.Markdown("### πŸ” Topic Validation Table\nReview the identified themes and rename or reject as needed.")
141
- table = gr.Dataframe(headers=["#", "Label", "Key Evidence", "Sents", "Papers", "Approve", "Rename", "Reasoning"], datatype=["number", "str", "str", "number", "number", "bool", "str", "str"], interactive=True)
142
- with gr.Row():
143
- submit = gr.Button("Submit Review Decisions", variant="primary", scale=2, elem_classes="primary-btn")
144
- clear = gr.Button("Refresh Table", variant="secondary", scale=1, elem_classes="secondary-btn")
145
- papers = gr.Textbox(label="Full Context: Papers in Selected Topic", lines=6, interactive=False)
146
-
147
- with gr.Tab("πŸ“Š Visual Analytics"):
148
- gr.Markdown("### πŸ“ˆ Interactive Topic Visualizations")
149
- with gr.Row():
150
- selector = gr.Dropdown(choices=[], label="Select Visualization Type", scale=7)
151
- refresh_viz = gr.Button("Refresh Charts", variant="secondary", scale=1)
152
- display = gr.Plot()
153
-
154
- with gr.Tab("πŸ“₯ Export Control"):
155
- gr.Markdown("### πŸ’Ύ Final Outputs\nDownload generated papers, narratives, and comparison matrices.")
156
- download = gr.File(label="Available Exports", file_count="multiple")
157
-
158
- def respond_with_viz(m, h, u):
159
- g = respond(m, h, u)
160
- for hist, _, dl in g:
161
- cs = _get_chart_choices()
162
- yield hist, "", dl, gr.update(choices=cs, value=cs[-1] if cs else None), _load_chart(cs[-1]) if cs else None, _load_review_table(), _build_progress()
163
-
164
- msg.submit(respond_with_viz, [msg, chatbot, upload], [chatbot, msg, download, selector, display, table, progress])
165
- send.click(respond_with_viz, [msg, chatbot, upload], [chatbot, msg, download, selector, display, table, progress])
166
- selector.change(_load_chart, [selector], [display])
167
- table.select(_show_papers_by_select, [table], [papers])
168
- submit.click(_submit_review, [table, chatbot], [chatbot, download, selector, table, progress])
169
- upload.change(lambda f, h: respond_with_viz("Analyze CSV", h, f), [upload, chatbot], [chatbot, msg, download, selector, display, table, progress])
170
-
171
- if __name__ == "__main__":
172
- demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False, theme=theme, css=CSS)
 
1
+ import os
2
+ import glob
3
+ import json
4
+ import plotly.io as pio
5
+ import gradio as gr
6
+ from dotenv import load_dotenv
7
+ from langchain_mistralai import ChatMistralAI
8
+ from langgraph.prebuilt import create_react_agent
9
+ from langgraph.checkpoint.memory import MemorySaver
10
+ from agent import SYSTEM_PROMPT, get_local_tools
11
+
12
+ os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
13
+ load_dotenv()
14
+
15
+ OUTPUT_DIR = "outputs"
16
+ CHECKPOINT_DIR = os.path.join(OUTPUT_DIR, "checkpoints")
17
+ os.makedirs(CHECKPOINT_DIR, exist_ok=True)
18
+
19
+ llm = ChatMistralAI(model="mistral-small-latest", temperature=0, timeout=300)
20
+ agent = create_react_agent(model=llm, tools=get_local_tools(), prompt=SYSTEM_PROMPT, checkpointer=MemorySaver())
21
+ _msg_count = 0
22
+ _uploaded = {"path": ""}
23
+
24
+
25
+ def _latest_output():
26
+ ord = {"summaries": 1, "labels": 2, "themes": 3, "taxonomy": 4, "comparison": 9, "narrative": 10}
27
+ fs = glob.glob(f"{OUTPUT_DIR}/rq4_*.csv") + glob.glob(f"{CHECKPOINT_DIR}/rq4_*.json")
28
+ scored = sorted([(sum(v * (k in f) for k, v in ord.items()), f) for f in fs], key=lambda x: x[0])
29
+ return [x[1] for x in scored] or []
30
+
31
+ def _build_progress():
32
+ ps = [
33
+ ("Load", bool(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_summaries.json"))),
34
+ ("Codes", bool(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_labels.json"))),
35
+ ("Themes", bool(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_themes.json"))),
36
+ ("PAJAIS", bool(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_taxonomy_map.json"))),
37
+ ("Report", bool(glob.glob(f"{OUTPUT_DIR}/rq4_comparison.csv"))),
38
+ ]
39
+ return " β†’ ".join(f"{'βœ…' if d else '⬜'} {n}" for n, d in ps)
40
+
41
+ def respond(message, chat_history, uploaded_file):
42
+ global _msg_count
43
+ _msg_count += 1
44
+ _uploaded["path"] = uploaded_file or _uploaded.get("path", "")
45
+ text = (message or "Analyze") + (f"\n[CSV: {_uploaded['path']}]" if _uploaded["path"] else "\n[No CSV]")
46
+
47
+ chat_history.append({"role": "user", "content": message or "Analyze"})
48
+ chat_history.append({"role": "assistant", "content": "πŸ”¬ **Working...**"})
49
+ yield chat_history, "", _latest_output()
50
+
51
+ res = agent.invoke({"messages": [("human", text)]}, config={"configurable": {"thread_id": "session"}})
52
+ chat_history[-1] = {"role": "assistant", "content": res["messages"][-1].content}
53
+ yield chat_history, "", _latest_output()
54
+
55
+ def _load_chart(name):
56
+ if not name or not os.path.exists(os.path.join(OUTPUT_DIR, name)): return None
57
+ return pio.from_json(open(os.path.join(OUTPUT_DIR, name)).read())
58
+
59
+ def _get_chart_choices():
60
+ return [os.path.basename(f) for f in sorted(glob.glob(f"{OUTPUT_DIR}/rq4_*.json"))]
61
+
62
+ def _load_review_table():
63
+ ps = sorted(glob.glob(f"{CHECKPOINT_DIR}/rq4_*.json"))
64
+ if not ps: return [[0, "No data", "", 0, 0, False, "", ""]]
65
+ data = json.load(open(ps[-1]))
66
+ return [[i, d.get("label", d.get("top_words", ""))[:60], d.get("nearest", [{}])[0].get("sentence", "")[:120], d.get("sentence_count", 0), d.get("paper_count", 0), True, "", ""] for i, d in enumerate(data)]
67
+
68
+ def _show_papers_by_select(table_data, evt: gr.SelectData):
69
+ idx = int(table_data.iloc[evt.index[0], 0]) if hasattr(table_data, 'iloc') else int(table_data[evt.index[0]][0])
70
+ fs = sorted(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_labels.json")) or sorted(glob.glob(f"{CHECKPOINT_DIR}/rq4_*_summaries.json"))
71
+ for f in fs:
72
+ for t in json.load(open(f)):
73
+ if t.get("topic_id") == idx:
74
+ return f"Topic {idx}: {t.get('label', '')}\n\n" + "\n".join(f"- {p}" for p in t.get("paper_titles", []))
75
+ return "Not found"
76
+
77
+ def _submit_review(table_data, chat_history):
78
+ ls = [f"Topic {int(r[0])}: {'RENAME to '+r[6] if r[6] else ('APPROVE' if r[5] else 'REJECT')}" for r in table_data.values.tolist()]
79
+ msg = "Review decisions:\n" + "\n".join(ls)
80
+ chat_history.append({"role": "user", "content": "Submitted review"})
81
+ chat_history.append({"role": "assistant", "content": "πŸ”¬ **Processing...**"})
82
+ yield chat_history, _latest_output(), gr.update(), gr.update(), _build_progress()
83
+
84
+ res = agent.invoke({"messages": [("human", msg)]}, config={"configurable": {"thread_id": "session"}})
85
+ chat_history[-1] = {"role": "assistant", "content": res["messages"][-1].content}
86
+ yield chat_history, _latest_output(), gr.update(choices=_get_chart_choices()), _load_review_table(), _build_progress()
87
+
88
+ CSS = """
89
+ .gradio-container { background: #fcfcfc !important; }
90
+ .sidebar { background: #ffffff !important; border-right: 1px solid #e2e8f0 !important; }
91
+ .header-text { font-family: 'Outfit', sans-serif; color: #000000 !important; letter-spacing: -0.02em; }
92
+ .tab-nav { border-bottom: 2px solid #f1f5f9 !important; }
93
+ .chatbot-container { border-radius: 12px !important; border: 1px solid #e2e8f0 !important; overflow: hidden; }
94
+ .primary-btn { background: #4f46e5 !important; color: #ffffff !important; border-radius: 8px !important; font-weight: 600 !important; }
95
+ .secondary-btn { background: #f8fafc !important; color: #000000 !important; border: 1px solid #e2e8f0 !important; border-radius: 8px !important; }
96
+ body, .gr-form, .gr-input, .gr-button, p, span, h1, h2, h3, h4, h5, h6, label {
97
+ color: #000000 !important;
98
+ }
99
+ .primary-btn span, .primary-btn {
100
+ color: #ffffff !important;
101
+ }
102
+ """
103
+
104
+ theme = gr.themes.Soft(
105
+ primary_hue="indigo",
106
+ secondary_hue="violet",
107
+ neutral_hue="slate",
108
+ font=gr.themes.GoogleFont("Outfit"),
109
+ font_mono=gr.themes.GoogleFont("JetBrains Mono"),
110
+ ).set(
111
+ body_background_fill="*neutral_50",
112
+ block_title_text_weight="700",
113
+ button_primary_background_fill="*primary_600",
114
+ button_primary_text_color="white",
115
+ )
116
+
117
+ with gr.Blocks(title="Thematic Analysis AI") as demo:
118
+ with gr.Sidebar(label="Data Hub", open=True):
119
+ gr.HTML("<h2 class='header-text'>πŸ“ Resource Center</h2>")
120
+ upload = gr.File(label="Dataset (Scopus CSV)", file_types=[".csv"], elem_id="file-upload")
121
+ progress = gr.Markdown(value=_build_progress(), elem_id="progress-display")
122
+ gr.HTML("<hr>")
123
+ gr.Markdown("### πŸ› οΈ Configuration\nModel: `mistral-small-latest`\nPipeline: `BERTopic + Agglomerative`")
124
+
125
+ gr.HTML("<h1 class='header-text' style='margin-bottom: 20px;'>πŸ”¬ Topic Modelling Agentic AI</h1>")
126
+
127
+ with gr.Tabs():
128
+ with gr.Tab("πŸ’¬ Agent Chat"):
129
+ chatbot = gr.Chatbot(height=450, show_label=False, elem_classes="chatbot-container")
130
+ with gr.Row():
131
+ msg = gr.Textbox(placeholder="Ask the agent to analyze, group, or export...", show_label=False, scale=9)
132
+ send = gr.Button("Send", variant="primary", scale=1, elem_classes="primary-btn")
133
+
134
+ with gr.Tab("πŸ“‹ Review & Refine"):
135
+ gr.Markdown("### πŸ” Topic Validation Table\nReview the identified themes and rename or reject as needed.")
136
+ table = gr.Dataframe(headers=["#", "Label", "Key Evidence", "Sents", "Papers", "Approve", "Rename", "Reasoning"], datatype=["number", "str", "str", "number", "number", "bool", "str", "str"], interactive=True)
137
+ with gr.Row():
138
+ submit = gr.Button("Submit Review Decisions", variant="primary", scale=2, elem_classes="primary-btn")
139
+ clear = gr.Button("Refresh Table", variant="secondary", scale=1, elem_classes="secondary-btn")
140
+ papers = gr.Textbox(label="Full Context: Papers in Selected Topic", lines=6, interactive=False)
141
+
142
+ with gr.Tab("πŸ“Š Visual Analytics"):
143
+ gr.Markdown("### πŸ“ˆ Interactive Topic Visualizations")
144
+ with gr.Row():
145
+ selector = gr.Dropdown(choices=[], label="Select Visualization Type", scale=7)
146
+ refresh_viz = gr.Button("Refresh Charts", variant="secondary", scale=1)
147
+ display = gr.Plot()
148
+
149
+ with gr.Tab("πŸ“₯ Export Control"):
150
+ gr.Markdown("### πŸ’Ύ Final Outputs\nDownload generated papers, narratives, and comparison matrices.")
151
+ download = gr.File(label="Available Exports", file_count="multiple")
152
+
153
+ def respond_with_viz(m, h, u):
154
+ g = respond(m, h, u)
155
+ for hist, _, dl in g:
156
+ cs = _get_chart_choices()
157
+ yield hist, "", dl, gr.update(choices=cs, value=cs[-1] if cs else None), _load_chart(cs[-1]) if cs else None, _load_review_table(), _build_progress()
158
+
159
+ def upload_handler(f, h):
160
+ yield from respond_with_viz("Analyze CSV", h, f)
161
+
162
+ msg.submit(respond_with_viz, [msg, chatbot, upload], [chatbot, msg, download, selector, display, table, progress])
163
+ send.click(respond_with_viz, [msg, chatbot, upload], [chatbot, msg, download, selector, display, table, progress])
164
+ selector.change(_load_chart, [selector], [display])
165
+ table.select(_show_papers_by_select, [table], [papers])
166
+ submit.click(_submit_review, [table, chatbot], [chatbot, download, selector, table, progress])
167
+ upload.change(upload_handler, [upload, chatbot], [chatbot, msg, download, selector, display, table, progress])
168
+
169
+ if __name__ == "__main__":
170
+ demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False, theme=theme, css=CSS)