Spaces:
Sleeping
Sleeping
Daksh C Jain commited on
Commit Β·
eba181a
1
Parent(s): 822c198
Fix Gradio ValueError and improve UI visibility
Browse files
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 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
""
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
gr.
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
gr.
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 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)
|
|
|
|
|
|