Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- app.py +351 -351
- requirements.txt +22 -21
app.py
CHANGED
|
@@ -1,351 +1,351 @@
|
|
| 1 |
-
"""
|
| 2 |
-
app.py - BERTopic Agentic AI Analysis for CHB Journal (HuggingFace Deployment)
|
| 3 |
-
===============================================================================
|
| 4 |
-
Gradio interface for RQ5-7 using HuggingFace Inference API.
|
| 5 |
-
|
| 6 |
-
Author: Prasad Vijay Gade (2024301006)
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import os
|
| 10 |
-
import gradio as gr
|
| 11 |
-
import pandas as pd
|
| 12 |
-
import json
|
| 13 |
-
from datetime import datetime
|
| 14 |
-
|
| 15 |
-
from tools import (
|
| 16 |
-
load_scopus_csv,
|
| 17 |
-
run_bertopic_discovery,
|
| 18 |
-
label_topics_with_llm,
|
| 19 |
-
consolidate_into_themes,
|
| 20 |
-
compare_with_taxonomy,
|
| 21 |
-
generate_comparison_csv,
|
| 22 |
-
export_narrative,
|
| 23 |
-
OUTPUT_DIR,
|
| 24 |
-
HF_MODEL
|
| 25 |
-
)
|
| 26 |
-
|
| 27 |
-
# ============================================================================
|
| 28 |
-
# STATE MANAGEMENT
|
| 29 |
-
# ============================================================================
|
| 30 |
-
|
| 31 |
-
class AnalysisState:
|
| 32 |
-
def __init__(self):
|
| 33 |
-
self.reset()
|
| 34 |
-
|
| 35 |
-
def reset(self):
|
| 36 |
-
self.phases_completed = {
|
| 37 |
-
"load": False,
|
| 38 |
-
"abstract_discovery": False,
|
| 39 |
-
"abstract_labels": False,
|
| 40 |
-
"abstract_themes": False,
|
| 41 |
-
"abstract_taxonomy": False,
|
| 42 |
-
"title_discovery": False,
|
| 43 |
-
"title_labels": False,
|
| 44 |
-
"title_themes": False,
|
| 45 |
-
"title_taxonomy": False,
|
| 46 |
-
"comparison": False,
|
| 47 |
-
"narrative": False
|
| 48 |
-
}
|
| 49 |
-
self.logs = []
|
| 50 |
-
|
| 51 |
-
def log(self, message):
|
| 52 |
-
timestamp = datetime.now().strftime("%H:%M:%S")
|
| 53 |
-
self.logs.append(f"[{timestamp}] {message}")
|
| 54 |
-
return "\n".join(self.logs[-20:])
|
| 55 |
-
|
| 56 |
-
state = AnalysisState()
|
| 57 |
-
|
| 58 |
-
# ============================================================================
|
| 59 |
-
# PHASE FUNCTIONS
|
| 60 |
-
# ============================================================================
|
| 61 |
-
|
| 62 |
-
def check_api():
|
| 63 |
-
token = os.environ.get("HF_TOKEN", "")
|
| 64 |
-
if not token:
|
| 65 |
-
return "❌ HF_TOKEN not set. Add in Settings > Secrets."
|
| 66 |
-
return f"✅ Using {HF_MODEL} via HuggingFace"
|
| 67 |
-
|
| 68 |
-
def phase_1_load(file):
|
| 69 |
-
state.log("Phase 1: Loading CSV...")
|
| 70 |
-
if file is None:
|
| 71 |
-
return "❌ Upload a CSV file first", state.log("Waiting...")
|
| 72 |
-
|
| 73 |
-
file_path = file.name if hasattr(file, 'name') else str(file)
|
| 74 |
-
result = load_scopus_csv(file_path)
|
| 75 |
-
state.phases_completed["load"] = True
|
| 76 |
-
|
| 77 |
-
summary = f"""✅ Phase 1 Complete
|
| 78 |
-
|
| 79 |
-
📊 Statistics:
|
| 80 |
-
- Papers: {result['total_papers']}
|
| 81 |
-
- Sentences: {result['total_sentences']}
|
| 82 |
-
- Years: {result['year_range']}
|
| 83 |
-
"""
|
| 84 |
-
return summary, state.log("Ready for Phase 2")
|
| 85 |
-
|
| 86 |
-
def phase_2_abstract():
|
| 87 |
-
state.log("Phase 2a: BERTopic on Abstracts...")
|
| 88 |
-
if not state.phases_completed["load"]:
|
| 89 |
-
return "❌ Complete Phase 1 first", state.log("Error")
|
| 90 |
-
|
| 91 |
-
result = run_bertopic_discovery("Abstract")
|
| 92 |
-
state.phases_completed["abstract_discovery"] = True
|
| 93 |
-
|
| 94 |
-
topics_preview = "\n".join([f" Topic {k}: {v['sample'][:80]}..."
|
| 95 |
-
for k, v in list(result['top_10_topics'].items())[:5]])
|
| 96 |
-
return f"""✅ Phase 2a Complete
|
| 97 |
-
|
| 98 |
-
Topics: {result['num_topics']}
|
| 99 |
-
Texts: {result['total_texts']}
|
| 100 |
-
|
| 101 |
-
Top 5:
|
| 102 |
-
{topics_preview}
|
| 103 |
-
""", state.log("Ready for labeling")
|
| 104 |
-
|
| 105 |
-
def phase_2_title():
|
| 106 |
-
state.log("Phase 2b: BERTopic on Titles...")
|
| 107 |
-
if not state.phases_completed["load"]:
|
| 108 |
-
return "❌ Complete Phase 1 first", state.log("Error")
|
| 109 |
-
|
| 110 |
-
result = run_bertopic_discovery("Title")
|
| 111 |
-
state.phases_completed["title_discovery"] = True
|
| 112 |
-
|
| 113 |
-
topics_preview = "\n".join([f" Topic {k}: {v['sample'][:80]}..."
|
| 114 |
-
for k, v in list(result['top_10_topics'].items())[:5]])
|
| 115 |
-
return f"""✅ Phase 2b Complete
|
| 116 |
-
|
| 117 |
-
Topics: {result['num_topics']}
|
| 118 |
-
Texts: {result['total_texts']}
|
| 119 |
-
|
| 120 |
-
Top 5:
|
| 121 |
-
{topics_preview}
|
| 122 |
-
""", state.log("Ready for labeling")
|
| 123 |
-
|
| 124 |
-
def phase_3_abstract():
|
| 125 |
-
state.log("Phase 3a: Labeling abstracts...")
|
| 126 |
-
if not state.phases_completed["abstract_discovery"]:
|
| 127 |
-
return "❌ Complete Phase 2a first", state.log("Error")
|
| 128 |
-
|
| 129 |
-
result = label_topics_with_llm("abstract")
|
| 130 |
-
state.phases_completed["abstract_labels"] = True
|
| 131 |
-
|
| 132 |
-
labels = "\n".join([f" {k}: {v}" for k, v in list(result['sample_labels'].items())[:10]])
|
| 133 |
-
return f"""✅ Phase 3a Complete
|
| 134 |
-
|
| 135 |
-
Labels: {result['num_labeled']}
|
| 136 |
-
|
| 137 |
-
{labels}
|
| 138 |
-
""", state.log("Ready for consolidation")
|
| 139 |
-
|
| 140 |
-
def phase_3_title():
|
| 141 |
-
state.log("Phase 3b: Labeling titles...")
|
| 142 |
-
if not state.phases_completed["title_discovery"]:
|
| 143 |
-
return "❌ Complete Phase 2b first", state.log("Error")
|
| 144 |
-
|
| 145 |
-
result = label_topics_with_llm("title")
|
| 146 |
-
state.phases_completed["title_labels"] = True
|
| 147 |
-
|
| 148 |
-
labels = "\n".join([f" {k}: {v}" for k, v in list(result['sample_labels'].items())[:10]])
|
| 149 |
-
return f"""✅ Phase 3b Complete
|
| 150 |
-
|
| 151 |
-
Labels: {result['num_labeled']}
|
| 152 |
-
|
| 153 |
-
{labels}
|
| 154 |
-
""", state.log("Ready for consolidation")
|
| 155 |
-
|
| 156 |
-
def phase_4_abstract():
|
| 157 |
-
state.log("Phase 4a: Consolidating abstracts...")
|
| 158 |
-
if not state.phases_completed["abstract_labels"]:
|
| 159 |
-
return "❌ Complete Phase 3a first", state.log("Error")
|
| 160 |
-
|
| 161 |
-
result = consolidate_into_themes("abstract", 15)
|
| 162 |
-
state.phases_completed["abstract_themes"] = True
|
| 163 |
-
|
| 164 |
-
themes = "\n".join([f" {k}: {v} items" for k, v in list(result['themes'].items())[:10]])
|
| 165 |
-
return f"""✅ Phase 4a Complete
|
| 166 |
-
|
| 167 |
-
Themes: {result['num_themes']}
|
| 168 |
-
|
| 169 |
-
{themes}
|
| 170 |
-
""", state.log("Ready for taxonomy")
|
| 171 |
-
|
| 172 |
-
def phase_4_title():
|
| 173 |
-
state.log("Phase 4b: Consolidating titles...")
|
| 174 |
-
if not state.phases_completed["title_labels"]:
|
| 175 |
-
return "❌ Complete Phase 3b first", state.log("Error")
|
| 176 |
-
|
| 177 |
-
result = consolidate_into_themes("title", 15)
|
| 178 |
-
state.phases_completed["title_themes"] = True
|
| 179 |
-
|
| 180 |
-
themes = "\n".join([f" {k}: {v} items" for k, v in list(result['themes'].items())[:10]])
|
| 181 |
-
return f"""✅ Phase 4b Complete
|
| 182 |
-
|
| 183 |
-
Themes: {result['num_themes']}
|
| 184 |
-
|
| 185 |
-
{themes}
|
| 186 |
-
""", state.log("Ready for taxonomy")
|
| 187 |
-
|
| 188 |
-
def phase_5_abstract():
|
| 189 |
-
state.log("Phase 5a: PAJAIS mapping abstracts...")
|
| 190 |
-
if not state.phases_completed["abstract_themes"]:
|
| 191 |
-
return "❌ Complete Phase 4a first", state.log("Error")
|
| 192 |
-
|
| 193 |
-
result = compare_with_taxonomy("abstract")
|
| 194 |
-
state.phases_completed["abstract_taxonomy"] = True
|
| 195 |
-
|
| 196 |
-
return f"""✅ Phase 5a Complete
|
| 197 |
-
|
| 198 |
-
MAPPED: {result['mapped_count']}
|
| 199 |
-
NOVEL: {result['novel_count']}
|
| 200 |
-
|
| 201 |
-
Novel themes:
|
| 202 |
-
{chr(10).join([' - ' + t for t in result['novel_themes'][:5]])}
|
| 203 |
-
""", state.log("Complete")
|
| 204 |
-
|
| 205 |
-
def phase_5_title():
|
| 206 |
-
state.log("Phase 5b: PAJAIS mapping titles...")
|
| 207 |
-
if not state.phases_completed["title_themes"]:
|
| 208 |
-
return "❌ Complete Phase 4b first", state.log("Error")
|
| 209 |
-
|
| 210 |
-
result = compare_with_taxonomy("title")
|
| 211 |
-
state.phases_completed["title_taxonomy"] = True
|
| 212 |
-
|
| 213 |
-
return f"""✅ Phase 5b Complete
|
| 214 |
-
|
| 215 |
-
MAPPED: {result['mapped_count']}
|
| 216 |
-
NOVEL: {result['novel_count']}
|
| 217 |
-
|
| 218 |
-
Novel themes:
|
| 219 |
-
{chr(10).join([' - ' + t for t in result['novel_themes'][:5]])}
|
| 220 |
-
""", state.log("Ready for comparison")
|
| 221 |
-
|
| 222 |
-
def phase_6():
|
| 223 |
-
state.log("Phase 6: Generating comparison...")
|
| 224 |
-
if not (state.phases_completed["abstract_taxonomy"] and state.phases_completed["title_taxonomy"]):
|
| 225 |
-
return "❌ Complete Phase 5a and 5b first", state.log("Error")
|
| 226 |
-
|
| 227 |
-
result = generate_comparison_csv()
|
| 228 |
-
state.phases_completed["comparison"] = True
|
| 229 |
-
|
| 230 |
-
return f"""✅ Phase 6 Complete
|
| 231 |
-
|
| 232 |
-
Unique Themes: {result['total_unique_themes']}
|
| 233 |
-
In Both: {result['themes_in_both']}
|
| 234 |
-
Abstract-Only: {result['abstract_only']}
|
| 235 |
-
Title-Only: {result['title_only']}
|
| 236 |
-
""", state.log("Ready for narrative")
|
| 237 |
-
|
| 238 |
-
def phase_7():
|
| 239 |
-
state.log("Phase 7: Generating narrative...")
|
| 240 |
-
if not state.phases_completed["comparison"]:
|
| 241 |
-
return "❌ Complete Phase 6 first", state.log("Error")
|
| 242 |
-
|
| 243 |
-
result = export_narrative()
|
| 244 |
-
state.phases_completed["narrative"] = True
|
| 245 |
-
|
| 246 |
-
return f"""✅ Phase 7 Complete
|
| 247 |
-
|
| 248 |
-
Words: {result['word_count']}
|
| 249 |
-
|
| 250 |
-
{result['preview']}...
|
| 251 |
-
""", state.log("✅ ANALYSIS COMPLETE")
|
| 252 |
-
|
| 253 |
-
def download_outputs():
|
| 254 |
-
files = ["comparison.csv", "themes_abstract.json", "themes_title.json",
|
| 255 |
-
"taxonomy_map_abstract.json", "taxonomy_map_title.json",
|
| 256 |
-
"narrative.txt", "comparison_summary.json"]
|
| 257 |
-
return [f"{OUTPUT_DIR}/{f}" for f in files if os.path.exists(f"{OUTPUT_DIR}/{f}")]
|
| 258 |
-
|
| 259 |
-
def reset():
|
| 260 |
-
state.reset()
|
| 261 |
-
return "🔄 Reset complete", state.log("Ready")
|
| 262 |
-
|
| 263 |
-
# ============================================================================
|
| 264 |
-
# GRADIO UI
|
| 265 |
-
# ============================================================================
|
| 266 |
-
|
| 267 |
-
def create_app():
|
| 268 |
-
with gr.Blocks(title="CHB BERTopic Analysis") as app:
|
| 269 |
-
gr.Markdown("""
|
| 270 |
-
# 🔬 CHB Journal BERTopic Analysis
|
| 271 |
-
**RQ5-7: Agentic AI Topic Discovery** | Mistral-7B via HuggingFace
|
| 272 |
-
""")
|
| 273 |
-
|
| 274 |
-
with gr.Row():
|
| 275 |
-
api_status = gr.Textbox(label="API Status", value=check_api(), interactive=False)
|
| 276 |
-
reset_btn = gr.Button("🔄 Reset")
|
| 277 |
-
|
| 278 |
-
file_input = gr.File(label="Upload Scopus CSV", file_types=[".csv"])
|
| 279 |
-
log_output = gr.Textbox(label="Log", lines=8, interactive=False)
|
| 280 |
-
|
| 281 |
-
with gr.Tabs():
|
| 282 |
-
with gr.Tab("1️⃣ Load"):
|
| 283 |
-
load_btn = gr.Button("▶️ Load CSV", variant="primary")
|
| 284 |
-
load_out = gr.Textbox(label="Output", lines=8)
|
| 285 |
-
|
| 286 |
-
with gr.Tab("2️⃣ Discovery"):
|
| 287 |
-
with gr.Row():
|
| 288 |
-
disc_abs_btn = gr.Button("▶️ 2a: Abstracts")
|
| 289 |
-
disc_title_btn = gr.Button("▶️ 2b: Titles")
|
| 290 |
-
with gr.Row():
|
| 291 |
-
disc_abs_out = gr.Textbox(label="Abstracts", lines=8)
|
| 292 |
-
disc_title_out = gr.Textbox(label="Titles", lines=8)
|
| 293 |
-
|
| 294 |
-
with gr.Tab("3️⃣ Labeling"):
|
| 295 |
-
with gr.Row():
|
| 296 |
-
label_abs_btn = gr.Button("▶️ 3a: Label Abstracts")
|
| 297 |
-
label_title_btn = gr.Button("▶️ 3b: Label Titles")
|
| 298 |
-
with gr.Row():
|
| 299 |
-
label_abs_out = gr.Textbox(label="Abstract Labels", lines=8)
|
| 300 |
-
label_title_out = gr.Textbox(label="Title Labels", lines=8)
|
| 301 |
-
|
| 302 |
-
with gr.Tab("4️⃣ Themes"):
|
| 303 |
-
with gr.Row():
|
| 304 |
-
cons_abs_btn = gr.Button("▶️ 4a: Abstract Themes")
|
| 305 |
-
cons_title_btn = gr.Button("▶️ 4b: Title Themes")
|
| 306 |
-
with gr.Row():
|
| 307 |
-
cons_abs_out = gr.Textbox(label="Abstract Themes", lines=8)
|
| 308 |
-
cons_title_out = gr.Textbox(label="Title Themes", lines=8)
|
| 309 |
-
|
| 310 |
-
with gr.Tab("5️⃣ PAJAIS"):
|
| 311 |
-
with gr.Row():
|
| 312 |
-
tax_abs_btn = gr.Button("▶️ 5a: Map Abstracts")
|
| 313 |
-
tax_title_btn = gr.Button("▶️ 5b: Map Titles")
|
| 314 |
-
with gr.Row():
|
| 315 |
-
tax_abs_out = gr.Textbox(label="Abstract Mapping", lines=8)
|
| 316 |
-
tax_title_out = gr.Textbox(label="Title Mapping", lines=8)
|
| 317 |
-
|
| 318 |
-
with gr.Tab("6️⃣ Compare"):
|
| 319 |
-
compare_btn = gr.Button("▶️ Compare", variant="primary")
|
| 320 |
-
compare_out = gr.Textbox(label="Comparison", lines=10)
|
| 321 |
-
|
| 322 |
-
with gr.Tab("7️⃣ Narrative"):
|
| 323 |
-
narrative_btn = gr.Button("▶️ Generate", variant="primary")
|
| 324 |
-
narrative_out = gr.Textbox(label="Narrative", lines=15)
|
| 325 |
-
|
| 326 |
-
with gr.Tab("📥 Downloads"):
|
| 327 |
-
download_btn = gr.Button("📥 Prepare")
|
| 328 |
-
download_files = gr.Files(label="Files")
|
| 329 |
-
|
| 330 |
-
gr.Markdown("**MDM Assignment-4** | Prasad Vijay Gade | Prof. Shailaja Jha")
|
| 331 |
-
|
| 332 |
-
# Wire buttons
|
| 333 |
-
reset_btn.click(reset, outputs=[load_out, log_output])
|
| 334 |
-
load_btn.click(phase_1_load, inputs=[file_input], outputs=[load_out, log_output])
|
| 335 |
-
disc_abs_btn.click(phase_2_abstract, outputs=[disc_abs_out, log_output])
|
| 336 |
-
disc_title_btn.click(phase_2_title, outputs=[disc_title_out, log_output])
|
| 337 |
-
label_abs_btn.click(phase_3_abstract, outputs=[label_abs_out, log_output])
|
| 338 |
-
label_title_btn.click(phase_3_title, outputs=[label_title_out, log_output])
|
| 339 |
-
cons_abs_btn.click(phase_4_abstract, outputs=[cons_abs_out, log_output])
|
| 340 |
-
cons_title_btn.click(phase_4_title, outputs=[cons_title_out, log_output])
|
| 341 |
-
tax_abs_btn.click(phase_5_abstract, outputs=[tax_abs_out, log_output])
|
| 342 |
-
tax_title_btn.click(phase_5_title, outputs=[tax_title_out, log_output])
|
| 343 |
-
compare_btn.click(phase_6, outputs=[compare_out, log_output])
|
| 344 |
-
narrative_btn.click(phase_7, outputs=[narrative_out, log_output])
|
| 345 |
-
download_btn.click(download_outputs, outputs=[download_files])
|
| 346 |
-
|
| 347 |
-
return app
|
| 348 |
-
|
| 349 |
-
if __name__ == "__main__":
|
| 350 |
-
app = create_app()
|
| 351 |
-
app.launch()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app.py - BERTopic Agentic AI Analysis for CHB Journal (HuggingFace Deployment)
|
| 3 |
+
===============================================================================
|
| 4 |
+
Gradio interface for RQ5-7 using HuggingFace Inference API.
|
| 5 |
+
|
| 6 |
+
Author: Prasad Vijay Gade (2024301006)
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import json
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
|
| 15 |
+
from tools import (
|
| 16 |
+
load_scopus_csv,
|
| 17 |
+
run_bertopic_discovery,
|
| 18 |
+
label_topics_with_llm,
|
| 19 |
+
consolidate_into_themes,
|
| 20 |
+
compare_with_taxonomy,
|
| 21 |
+
generate_comparison_csv,
|
| 22 |
+
export_narrative,
|
| 23 |
+
OUTPUT_DIR,
|
| 24 |
+
HF_MODEL
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# ============================================================================
|
| 28 |
+
# STATE MANAGEMENT
|
| 29 |
+
# ============================================================================
|
| 30 |
+
|
| 31 |
+
class AnalysisState:
|
| 32 |
+
def __init__(self):
|
| 33 |
+
self.reset()
|
| 34 |
+
|
| 35 |
+
def reset(self):
|
| 36 |
+
self.phases_completed = {
|
| 37 |
+
"load": False,
|
| 38 |
+
"abstract_discovery": False,
|
| 39 |
+
"abstract_labels": False,
|
| 40 |
+
"abstract_themes": False,
|
| 41 |
+
"abstract_taxonomy": False,
|
| 42 |
+
"title_discovery": False,
|
| 43 |
+
"title_labels": False,
|
| 44 |
+
"title_themes": False,
|
| 45 |
+
"title_taxonomy": False,
|
| 46 |
+
"comparison": False,
|
| 47 |
+
"narrative": False
|
| 48 |
+
}
|
| 49 |
+
self.logs = []
|
| 50 |
+
|
| 51 |
+
def log(self, message):
|
| 52 |
+
timestamp = datetime.now().strftime("%H:%M:%S")
|
| 53 |
+
self.logs.append(f"[{timestamp}] {message}")
|
| 54 |
+
return "\n".join(self.logs[-20:])
|
| 55 |
+
|
| 56 |
+
state = AnalysisState()
|
| 57 |
+
|
| 58 |
+
# ============================================================================
|
| 59 |
+
# PHASE FUNCTIONS
|
| 60 |
+
# ============================================================================
|
| 61 |
+
|
| 62 |
+
def check_api():
|
| 63 |
+
token = os.environ.get("HF_TOKEN", "")
|
| 64 |
+
if not token:
|
| 65 |
+
return "❌ HF_TOKEN not set. Add in Settings > Secrets."
|
| 66 |
+
return f"✅ Using {HF_MODEL} via HuggingFace"
|
| 67 |
+
|
| 68 |
+
def phase_1_load(file):
|
| 69 |
+
state.log("Phase 1: Loading CSV...")
|
| 70 |
+
if file is None:
|
| 71 |
+
return "❌ Upload a CSV file first", state.log("Waiting...")
|
| 72 |
+
|
| 73 |
+
file_path = file.name if hasattr(file, 'name') else str(file)
|
| 74 |
+
result = load_scopus_csv(file_path)
|
| 75 |
+
state.phases_completed["load"] = True
|
| 76 |
+
|
| 77 |
+
summary = f"""✅ Phase 1 Complete
|
| 78 |
+
|
| 79 |
+
📊 Statistics:
|
| 80 |
+
- Papers: {result['total_papers']}
|
| 81 |
+
- Sentences: {result['total_sentences']}
|
| 82 |
+
- Years: {result['year_range']}
|
| 83 |
+
"""
|
| 84 |
+
return summary, state.log("Ready for Phase 2")
|
| 85 |
+
|
| 86 |
+
def phase_2_abstract():
|
| 87 |
+
state.log("Phase 2a: BERTopic on Abstracts...")
|
| 88 |
+
if not state.phases_completed["load"]:
|
| 89 |
+
return "❌ Complete Phase 1 first", state.log("Error")
|
| 90 |
+
|
| 91 |
+
result = run_bertopic_discovery("Abstract")
|
| 92 |
+
state.phases_completed["abstract_discovery"] = True
|
| 93 |
+
|
| 94 |
+
topics_preview = "\n".join([f" Topic {k}: {v['sample'][:80]}..."
|
| 95 |
+
for k, v in list(result['top_10_topics'].items())[:5]])
|
| 96 |
+
return f"""✅ Phase 2a Complete
|
| 97 |
+
|
| 98 |
+
Topics: {result['num_topics']}
|
| 99 |
+
Texts: {result['total_texts']}
|
| 100 |
+
|
| 101 |
+
Top 5:
|
| 102 |
+
{topics_preview}
|
| 103 |
+
""", state.log("Ready for labeling")
|
| 104 |
+
|
| 105 |
+
def phase_2_title():
|
| 106 |
+
state.log("Phase 2b: BERTopic on Titles...")
|
| 107 |
+
if not state.phases_completed["load"]:
|
| 108 |
+
return "❌ Complete Phase 1 first", state.log("Error")
|
| 109 |
+
|
| 110 |
+
result = run_bertopic_discovery("Title")
|
| 111 |
+
state.phases_completed["title_discovery"] = True
|
| 112 |
+
|
| 113 |
+
topics_preview = "\n".join([f" Topic {k}: {v['sample'][:80]}..."
|
| 114 |
+
for k, v in list(result['top_10_topics'].items())[:5]])
|
| 115 |
+
return f"""✅ Phase 2b Complete
|
| 116 |
+
|
| 117 |
+
Topics: {result['num_topics']}
|
| 118 |
+
Texts: {result['total_texts']}
|
| 119 |
+
|
| 120 |
+
Top 5:
|
| 121 |
+
{topics_preview}
|
| 122 |
+
""", state.log("Ready for labeling")
|
| 123 |
+
|
| 124 |
+
def phase_3_abstract():
|
| 125 |
+
state.log("Phase 3a: Labeling abstracts...")
|
| 126 |
+
if not state.phases_completed["abstract_discovery"]:
|
| 127 |
+
return "❌ Complete Phase 2a first", state.log("Error")
|
| 128 |
+
|
| 129 |
+
result = label_topics_with_llm("abstract")
|
| 130 |
+
state.phases_completed["abstract_labels"] = True
|
| 131 |
+
|
| 132 |
+
labels = "\n".join([f" {k}: {v}" for k, v in list(result['sample_labels'].items())[:10]])
|
| 133 |
+
return f"""✅ Phase 3a Complete
|
| 134 |
+
|
| 135 |
+
Labels: {result['num_labeled']}
|
| 136 |
+
|
| 137 |
+
{labels}
|
| 138 |
+
""", state.log("Ready for consolidation")
|
| 139 |
+
|
| 140 |
+
def phase_3_title():
|
| 141 |
+
state.log("Phase 3b: Labeling titles...")
|
| 142 |
+
if not state.phases_completed["title_discovery"]:
|
| 143 |
+
return "❌ Complete Phase 2b first", state.log("Error")
|
| 144 |
+
|
| 145 |
+
result = label_topics_with_llm("title")
|
| 146 |
+
state.phases_completed["title_labels"] = True
|
| 147 |
+
|
| 148 |
+
labels = "\n".join([f" {k}: {v}" for k, v in list(result['sample_labels'].items())[:10]])
|
| 149 |
+
return f"""✅ Phase 3b Complete
|
| 150 |
+
|
| 151 |
+
Labels: {result['num_labeled']}
|
| 152 |
+
|
| 153 |
+
{labels}
|
| 154 |
+
""", state.log("Ready for consolidation")
|
| 155 |
+
|
| 156 |
+
def phase_4_abstract():
|
| 157 |
+
state.log("Phase 4a: Consolidating abstracts...")
|
| 158 |
+
if not state.phases_completed["abstract_labels"]:
|
| 159 |
+
return "❌ Complete Phase 3a first", state.log("Error")
|
| 160 |
+
|
| 161 |
+
result = consolidate_into_themes("abstract", 15)
|
| 162 |
+
state.phases_completed["abstract_themes"] = True
|
| 163 |
+
|
| 164 |
+
themes = "\n".join([f" {k}: {v} items" for k, v in list(result['themes'].items())[:10]])
|
| 165 |
+
return f"""✅ Phase 4a Complete
|
| 166 |
+
|
| 167 |
+
Themes: {result['num_themes']}
|
| 168 |
+
|
| 169 |
+
{themes}
|
| 170 |
+
""", state.log("Ready for taxonomy")
|
| 171 |
+
|
| 172 |
+
def phase_4_title():
|
| 173 |
+
state.log("Phase 4b: Consolidating titles...")
|
| 174 |
+
if not state.phases_completed["title_labels"]:
|
| 175 |
+
return "❌ Complete Phase 3b first", state.log("Error")
|
| 176 |
+
|
| 177 |
+
result = consolidate_into_themes("title", 15)
|
| 178 |
+
state.phases_completed["title_themes"] = True
|
| 179 |
+
|
| 180 |
+
themes = "\n".join([f" {k}: {v} items" for k, v in list(result['themes'].items())[:10]])
|
| 181 |
+
return f"""✅ Phase 4b Complete
|
| 182 |
+
|
| 183 |
+
Themes: {result['num_themes']}
|
| 184 |
+
|
| 185 |
+
{themes}
|
| 186 |
+
""", state.log("Ready for taxonomy")
|
| 187 |
+
|
| 188 |
+
def phase_5_abstract():
|
| 189 |
+
state.log("Phase 5a: PAJAIS mapping abstracts...")
|
| 190 |
+
if not state.phases_completed["abstract_themes"]:
|
| 191 |
+
return "❌ Complete Phase 4a first", state.log("Error")
|
| 192 |
+
|
| 193 |
+
result = compare_with_taxonomy("abstract")
|
| 194 |
+
state.phases_completed["abstract_taxonomy"] = True
|
| 195 |
+
|
| 196 |
+
return f"""✅ Phase 5a Complete
|
| 197 |
+
|
| 198 |
+
MAPPED: {result['mapped_count']}
|
| 199 |
+
NOVEL: {result['novel_count']}
|
| 200 |
+
|
| 201 |
+
Novel themes:
|
| 202 |
+
{chr(10).join([' - ' + t for t in result['novel_themes'][:5]])}
|
| 203 |
+
""", state.log("Complete")
|
| 204 |
+
|
| 205 |
+
def phase_5_title():
|
| 206 |
+
state.log("Phase 5b: PAJAIS mapping titles...")
|
| 207 |
+
if not state.phases_completed["title_themes"]:
|
| 208 |
+
return "❌ Complete Phase 4b first", state.log("Error")
|
| 209 |
+
|
| 210 |
+
result = compare_with_taxonomy("title")
|
| 211 |
+
state.phases_completed["title_taxonomy"] = True
|
| 212 |
+
|
| 213 |
+
return f"""✅ Phase 5b Complete
|
| 214 |
+
|
| 215 |
+
MAPPED: {result['mapped_count']}
|
| 216 |
+
NOVEL: {result['novel_count']}
|
| 217 |
+
|
| 218 |
+
Novel themes:
|
| 219 |
+
{chr(10).join([' - ' + t for t in result['novel_themes'][:5]])}
|
| 220 |
+
""", state.log("Ready for comparison")
|
| 221 |
+
|
| 222 |
+
def phase_6():
|
| 223 |
+
state.log("Phase 6: Generating comparison...")
|
| 224 |
+
if not (state.phases_completed["abstract_taxonomy"] and state.phases_completed["title_taxonomy"]):
|
| 225 |
+
return "❌ Complete Phase 5a and 5b first", state.log("Error")
|
| 226 |
+
|
| 227 |
+
result = generate_comparison_csv()
|
| 228 |
+
state.phases_completed["comparison"] = True
|
| 229 |
+
|
| 230 |
+
return f"""✅ Phase 6 Complete
|
| 231 |
+
|
| 232 |
+
Unique Themes: {result['total_unique_themes']}
|
| 233 |
+
In Both: {result['themes_in_both']}
|
| 234 |
+
Abstract-Only: {result['abstract_only']}
|
| 235 |
+
Title-Only: {result['title_only']}
|
| 236 |
+
""", state.log("Ready for narrative")
|
| 237 |
+
|
| 238 |
+
def phase_7():
|
| 239 |
+
state.log("Phase 7: Generating narrative...")
|
| 240 |
+
if not state.phases_completed["comparison"]:
|
| 241 |
+
return "❌ Complete Phase 6 first", state.log("Error")
|
| 242 |
+
|
| 243 |
+
result = export_narrative()
|
| 244 |
+
state.phases_completed["narrative"] = True
|
| 245 |
+
|
| 246 |
+
return f"""✅ Phase 7 Complete
|
| 247 |
+
|
| 248 |
+
Words: {result['word_count']}
|
| 249 |
+
|
| 250 |
+
{result['preview']}...
|
| 251 |
+
""", state.log("✅ ANALYSIS COMPLETE")
|
| 252 |
+
|
| 253 |
+
def download_outputs():
|
| 254 |
+
files = ["comparison.csv", "themes_abstract.json", "themes_title.json",
|
| 255 |
+
"taxonomy_map_abstract.json", "taxonomy_map_title.json",
|
| 256 |
+
"narrative.txt", "comparison_summary.json"]
|
| 257 |
+
return [f"{OUTPUT_DIR}/{f}" for f in files if os.path.exists(f"{OUTPUT_DIR}/{f}")]
|
| 258 |
+
|
| 259 |
+
def reset():
|
| 260 |
+
state.reset()
|
| 261 |
+
return "🔄 Reset complete", state.log("Ready")
|
| 262 |
+
|
| 263 |
+
# ============================================================================
|
| 264 |
+
# GRADIO UI
|
| 265 |
+
# ============================================================================
|
| 266 |
+
|
| 267 |
+
def create_app():
|
| 268 |
+
with gr.Blocks(title="CHB BERTopic Analysis") as app:
|
| 269 |
+
gr.Markdown("""
|
| 270 |
+
# 🔬 CHB Journal BERTopic Analysis
|
| 271 |
+
**RQ5-7: Agentic AI Topic Discovery** | Mistral-7B via HuggingFace
|
| 272 |
+
""")
|
| 273 |
+
|
| 274 |
+
with gr.Row():
|
| 275 |
+
api_status = gr.Textbox(label="API Status", value=check_api(), interactive=False)
|
| 276 |
+
reset_btn = gr.Button("🔄 Reset")
|
| 277 |
+
|
| 278 |
+
file_input = gr.File(label="Upload Scopus CSV", file_types=[".csv"])
|
| 279 |
+
log_output = gr.Textbox(label="Log", lines=8, interactive=False)
|
| 280 |
+
|
| 281 |
+
with gr.Tabs():
|
| 282 |
+
with gr.Tab("1️⃣ Load"):
|
| 283 |
+
load_btn = gr.Button("▶️ Load CSV", variant="primary")
|
| 284 |
+
load_out = gr.Textbox(label="Output", lines=8)
|
| 285 |
+
|
| 286 |
+
with gr.Tab("2️⃣ Discovery"):
|
| 287 |
+
with gr.Row():
|
| 288 |
+
disc_abs_btn = gr.Button("▶️ 2a: Abstracts")
|
| 289 |
+
disc_title_btn = gr.Button("▶️ 2b: Titles")
|
| 290 |
+
with gr.Row():
|
| 291 |
+
disc_abs_out = gr.Textbox(label="Abstracts", lines=8)
|
| 292 |
+
disc_title_out = gr.Textbox(label="Titles", lines=8)
|
| 293 |
+
|
| 294 |
+
with gr.Tab("3️⃣ Labeling"):
|
| 295 |
+
with gr.Row():
|
| 296 |
+
label_abs_btn = gr.Button("▶️ 3a: Label Abstracts")
|
| 297 |
+
label_title_btn = gr.Button("▶️ 3b: Label Titles")
|
| 298 |
+
with gr.Row():
|
| 299 |
+
label_abs_out = gr.Textbox(label="Abstract Labels", lines=8)
|
| 300 |
+
label_title_out = gr.Textbox(label="Title Labels", lines=8)
|
| 301 |
+
|
| 302 |
+
with gr.Tab("4️⃣ Themes"):
|
| 303 |
+
with gr.Row():
|
| 304 |
+
cons_abs_btn = gr.Button("▶️ 4a: Abstract Themes")
|
| 305 |
+
cons_title_btn = gr.Button("▶️ 4b: Title Themes")
|
| 306 |
+
with gr.Row():
|
| 307 |
+
cons_abs_out = gr.Textbox(label="Abstract Themes", lines=8)
|
| 308 |
+
cons_title_out = gr.Textbox(label="Title Themes", lines=8)
|
| 309 |
+
|
| 310 |
+
with gr.Tab("5️⃣ PAJAIS"):
|
| 311 |
+
with gr.Row():
|
| 312 |
+
tax_abs_btn = gr.Button("▶️ 5a: Map Abstracts")
|
| 313 |
+
tax_title_btn = gr.Button("▶️ 5b: Map Titles")
|
| 314 |
+
with gr.Row():
|
| 315 |
+
tax_abs_out = gr.Textbox(label="Abstract Mapping", lines=8)
|
| 316 |
+
tax_title_out = gr.Textbox(label="Title Mapping", lines=8)
|
| 317 |
+
|
| 318 |
+
with gr.Tab("6️⃣ Compare"):
|
| 319 |
+
compare_btn = gr.Button("▶️ Compare", variant="primary")
|
| 320 |
+
compare_out = gr.Textbox(label="Comparison", lines=10)
|
| 321 |
+
|
| 322 |
+
with gr.Tab("7️⃣ Narrative"):
|
| 323 |
+
narrative_btn = gr.Button("▶️ Generate", variant="primary")
|
| 324 |
+
narrative_out = gr.Textbox(label="Narrative", lines=15)
|
| 325 |
+
|
| 326 |
+
with gr.Tab("📥 Downloads"):
|
| 327 |
+
download_btn = gr.Button("📥 Prepare")
|
| 328 |
+
download_files = gr.Files(label="Files")
|
| 329 |
+
|
| 330 |
+
gr.Markdown("**MDM Assignment-4** | Prasad Vijay Gade | Prof. Shailaja Jha")
|
| 331 |
+
|
| 332 |
+
# Wire buttons
|
| 333 |
+
reset_btn.click(reset, outputs=[load_out, log_output])
|
| 334 |
+
load_btn.click(phase_1_load, inputs=[file_input], outputs=[load_out, log_output])
|
| 335 |
+
disc_abs_btn.click(phase_2_abstract, outputs=[disc_abs_out, log_output])
|
| 336 |
+
disc_title_btn.click(phase_2_title, outputs=[disc_title_out, log_output])
|
| 337 |
+
label_abs_btn.click(phase_3_abstract, outputs=[label_abs_out, log_output])
|
| 338 |
+
label_title_btn.click(phase_3_title, outputs=[label_title_out, log_output])
|
| 339 |
+
cons_abs_btn.click(phase_4_abstract, outputs=[cons_abs_out, log_output])
|
| 340 |
+
cons_title_btn.click(phase_4_title, outputs=[cons_title_out, log_output])
|
| 341 |
+
tax_abs_btn.click(phase_5_abstract, outputs=[tax_abs_out, log_output])
|
| 342 |
+
tax_title_btn.click(phase_5_title, outputs=[tax_title_out, log_output])
|
| 343 |
+
compare_btn.click(phase_6, outputs=[compare_out, log_output])
|
| 344 |
+
narrative_btn.click(phase_7, outputs=[narrative_out, log_output])
|
| 345 |
+
download_btn.click(download_outputs, outputs=[download_files])
|
| 346 |
+
|
| 347 |
+
return app
|
| 348 |
+
|
| 349 |
+
if __name__ == "__main__":
|
| 350 |
+
app = create_app()
|
| 351 |
+
app.launch(server_name="0.0.0.0")
|
requirements.txt
CHANGED
|
@@ -1,21 +1,22 @@
|
|
| 1 |
-
# RQ5-7 BERTopic Agentic AI Application
|
| 2 |
-
# Dependencies for HuggingFace Spaces deployment
|
| 3 |
-
|
| 4 |
-
# Core Gradio UI
|
| 5 |
-
gradio==4.44.1
|
| 6 |
-
gradio_client
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
| 1 |
+
# RQ5-7 BERTopic Agentic AI Application
|
| 2 |
+
# Dependencies for HuggingFace Spaces deployment
|
| 3 |
+
|
| 4 |
+
# Core Gradio UI
|
| 5 |
+
gradio==4.44.1
|
| 6 |
+
# Pin gradio_client to match gradio 4.44.1 — newer versions (1.x) break API schema parsing
|
| 7 |
+
gradio_client==0.7.3
|
| 8 |
+
|
| 9 |
+
# HuggingFace Inference API
|
| 10 |
+
# Pin to pre-1.0 to keep Gradio 4.44 OAuth compatibility (HfFolder import)
|
| 11 |
+
huggingface-hub==0.25.2
|
| 12 |
+
|
| 13 |
+
# BERTopic and embeddings
|
| 14 |
+
sentence-transformers>=2.2.0
|
| 15 |
+
scikit-learn>=1.3.0
|
| 16 |
+
|
| 17 |
+
# Data processing
|
| 18 |
+
pandas>=2.0.0
|
| 19 |
+
numpy>=1.24.0
|
| 20 |
+
|
| 21 |
+
# Text processing
|
| 22 |
+
regex>=2023.0.0
|