prasad-gade05 commited on
Commit
87f6c7f
·
verified ·
1 Parent(s): 1aa86b4

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +64 -32
  2. app.py +165 -351
  3. requirements.txt +11 -7
  4. tools.py +856 -419
README.md CHANGED
@@ -1,32 +1,64 @@
1
- ---
2
- title: CHB BERTopic Analysis
3
- emoji: 🔬
4
- colorFrom: blue
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: "5.31.0"
8
- app_file: app.py
9
- pinned: false
10
- python_version: "3.11"
11
- ---
12
-
13
- # CHB Journal BERTopic Analysis
14
-
15
- Agentic AI topic modelling for "Computers in Human Behavior" journal using BERTopic and Braun & Clarke thematic analysis.
16
-
17
- ## Features
18
-
19
- - **BERTopic Discovery**: Sentence-level embeddings with clustering
20
- - **LLM Labeling**: Topic labels via Mistral-7B (HuggingFace)
21
- - **PAJAIS Mapping**: Taxonomy gap analysis (MAPPED vs NOVEL)
22
- - **Comparison**: Abstract vs Title theme analysis
23
-
24
- ## Setup
25
-
26
- 1. Add `HF_TOKEN` secret in Space Settings
27
- 2. Upload Scopus CSV
28
- 3. Run phases 1-7 sequentially
29
-
30
- ## Author
31
-
32
- Prasad Vijay Gade (2024301006) | MDM Assignment-4 | Prof. Shailaja Jha
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CHB BERTopic App v2
2
+
3
+ This is the draft_2 BERTopic rebuild for the CHB project.
4
+
5
+ ## What changed
6
+
7
+ 1. uses the full **7,553-paper** CHB corpus
8
+ 2. uses real **BERTopic**
9
+ 3. uses **SPECTER2** embeddings
10
+ 4. uses **UMAP** for dimensionality reduction
11
+ 5. uses **HDBSCAN** for topic discovery
12
+ 6. removes the old `Topic 3` / `Topic 26` style fallback from final labels
13
+ 7. keeps all new outputs inside `DRAFT_2`
14
+
15
+ ## Default input
16
+
17
+ `DRAFT_2\sources\corpus_7553\ComputersinHumanBehavior_TopicModelling_Export_7553_for_app.csv`
18
+
19
+ ## Default output
20
+
21
+ `DRAFT_2\bertopic_outputs_7553`
22
+
23
+ ## Run full pipeline
24
+
25
+ ```powershell
26
+ python app.py --mode pipeline
27
+ ```
28
+
29
+ By default the app now uses the local Ollama model:
30
+
31
+ `gemma4:e2b`
32
+
33
+ You can override that with environment variables if needed:
34
+
35
+ ```powershell
36
+ $env:CHB_OLLAMA_MODEL = "gemma4:e2b"
37
+ $env:CHB_OLLAMA_BASE_URL = "http://localhost:11434/v1"
38
+ $env:CHB_OLLAMA_TIMEOUT_SECONDS = "300"
39
+ python app.py --mode pipeline
40
+ ```
41
+
42
+ ## Launch UI
43
+
44
+ ```powershell
45
+ python app.py --mode ui
46
+ ```
47
+
48
+ ## Output highlights
49
+
50
+ The pipeline writes:
51
+
52
+ 1. cleaned paper file
53
+ 2. embeddings
54
+ 3. BERTopic models
55
+ 4. topic assignments
56
+ 5. human-readable topic labels
57
+ 6. consolidated themes
58
+ 7. PAJAIS taxonomy mapping
59
+ 8. abstract vs title comparison
60
+ 9. narrative and audit files
61
+
62
+ ## Important method note
63
+
64
+ For the abstract-side run, SPECTER2 embeddings are created from **title + abstract** because the model is trained for scientific paper title/abstract inputs. Topic words, representative texts, and labels are still derived from the cleaned abstract text so the output remains content-side rather than title-only.
app.py CHANGED
@@ -1,351 +1,165 @@
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.File(label="Files", file_count="multiple")
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")
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import gradio as gr
8
+
9
+ from tools import (
10
+ DEFAULT_INPUT_CSV,
11
+ OLLAMA_MODEL,
12
+ OUTPUT_DIR,
13
+ compare_with_taxonomy,
14
+ consolidate_into_themes,
15
+ export_narrative,
16
+ generate_comparison_csv,
17
+ label_topics_with_llm,
18
+ load_scopus_csv,
19
+ run_bertopic_discovery,
20
+ run_full_pipeline,
21
+ )
22
+
23
+
24
+ CUSTOM_CSS = """
25
+ .status-ok { color: #1b5e20; font-weight: 600; }
26
+ .status-note { color: #37474f; }
27
+ """
28
+
29
+
30
+ def _resolve_output_dir(value: str) -> Path:
31
+ return Path(value).resolve() if value else OUTPUT_DIR
32
+
33
+
34
+ def ui_load(file_path: str, output_dir: str) -> str:
35
+ stats = load_scopus_csv(file_path, _resolve_output_dir(output_dir))
36
+ return json.dumps(stats, indent=2)
37
+
38
+
39
+ def ui_discover(text_type: str, output_dir: str) -> str:
40
+ payload = run_bertopic_discovery(text_type, _resolve_output_dir(output_dir))
41
+ return json.dumps(payload, indent=2)
42
+
43
+
44
+ def ui_label(text_type: str, output_dir: str) -> str:
45
+ payload = label_topics_with_llm(text_type, _resolve_output_dir(output_dir))
46
+ return json.dumps(payload, indent=2)
47
+
48
+
49
+ def ui_theme(text_type: str, output_dir: str) -> str:
50
+ payload = consolidate_into_themes(text_type, 15, _resolve_output_dir(output_dir))
51
+ return json.dumps(payload, indent=2)
52
+
53
+
54
+ def ui_taxonomy(text_type: str, output_dir: str) -> str:
55
+ payload = compare_with_taxonomy(text_type, _resolve_output_dir(output_dir))
56
+ return json.dumps(payload, indent=2)
57
+
58
+
59
+ def ui_compare(output_dir: str) -> str:
60
+ payload = generate_comparison_csv(_resolve_output_dir(output_dir))
61
+ return json.dumps(payload, indent=2)
62
+
63
+
64
+ def ui_narrative(output_dir: str) -> str:
65
+ payload = export_narrative(_resolve_output_dir(output_dir))
66
+ return json.dumps(payload, indent=2)
67
+
68
+
69
+ def ui_full_pipeline(file_path: str, output_dir: str) -> str:
70
+ payload = run_full_pipeline(file_path=file_path, output_dir=_resolve_output_dir(output_dir))
71
+ return json.dumps(payload, indent=2)
72
+
73
+
74
+ def create_interface() -> gr.Blocks:
75
+ with gr.Blocks(css=CUSTOM_CSS, title="CHB BERTopic App v2") as app:
76
+ gr.Markdown(
77
+ f"""
78
+ # CHB BERTopic App v2
79
+ ### DRAFT_2 rebuild: SPECTER2 + UMAP + HDBSCAN + BERTopic
80
+
81
+ **Default input:** `{DEFAULT_INPUT_CSV}`
82
+ **Default output:** `{OUTPUT_DIR}`
83
+ **LLM backend:** `{OLLAMA_MODEL}`
84
+ """
85
+ )
86
+
87
+ with gr.Row():
88
+ file_path = gr.Textbox(label="Input CSV", value=str(DEFAULT_INPUT_CSV), lines=1)
89
+ output_dir = gr.Textbox(label="Output directory", value=str(OUTPUT_DIR), lines=1)
90
+
91
+ full_run = gr.Button("Run full pipeline", variant="primary")
92
+ full_output = gr.Textbox(label="Full pipeline result", lines=18)
93
+ full_run.click(ui_full_pipeline, inputs=[file_path, output_dir], outputs=[full_output])
94
+
95
+ with gr.Tabs():
96
+ with gr.Tab("Phase 1"):
97
+ load_btn = gr.Button("Load corpus")
98
+ load_out = gr.Textbox(lines=16, label="Load output")
99
+ load_btn.click(ui_load, inputs=[file_path, output_dir], outputs=[load_out])
100
+
101
+ with gr.Tab("Phase 2"):
102
+ abs_disc_btn = gr.Button("Discover abstract topics")
103
+ title_disc_btn = gr.Button("Discover title topics")
104
+ abs_disc_out = gr.Textbox(lines=16, label="Abstract discovery")
105
+ title_disc_out = gr.Textbox(lines=16, label="Title discovery")
106
+ abs_disc_btn.click(ui_discover, inputs=[gr.State("abstract"), output_dir], outputs=[abs_disc_out])
107
+ title_disc_btn.click(ui_discover, inputs=[gr.State("title"), output_dir], outputs=[title_disc_out])
108
+
109
+ with gr.Tab("Phase 3"):
110
+ abs_label_btn = gr.Button("Label abstract topics")
111
+ title_label_btn = gr.Button("Label title topics")
112
+ abs_label_out = gr.Textbox(lines=16, label="Abstract labels")
113
+ title_label_out = gr.Textbox(lines=16, label="Title labels")
114
+ abs_label_btn.click(ui_label, inputs=[gr.State("abstract"), output_dir], outputs=[abs_label_out])
115
+ title_label_btn.click(ui_label, inputs=[gr.State("title"), output_dir], outputs=[title_label_out])
116
+
117
+ with gr.Tab("Phase 4"):
118
+ abs_theme_btn = gr.Button("Consolidate abstract themes")
119
+ title_theme_btn = gr.Button("Consolidate title themes")
120
+ abs_theme_out = gr.Textbox(lines=16, label="Abstract themes")
121
+ title_theme_out = gr.Textbox(lines=16, label="Title themes")
122
+ abs_theme_btn.click(ui_theme, inputs=[gr.State("abstract"), output_dir], outputs=[abs_theme_out])
123
+ title_theme_btn.click(ui_theme, inputs=[gr.State("title"), output_dir], outputs=[title_theme_out])
124
+
125
+ with gr.Tab("Phase 5"):
126
+ abs_tax_btn = gr.Button("Map abstract themes to PAJAIS")
127
+ title_tax_btn = gr.Button("Map title themes to PAJAIS")
128
+ abs_tax_out = gr.Textbox(lines=16, label="Abstract taxonomy")
129
+ title_tax_out = gr.Textbox(lines=16, label="Title taxonomy")
130
+ abs_tax_btn.click(ui_taxonomy, inputs=[gr.State("abstract"), output_dir], outputs=[abs_tax_out])
131
+ title_tax_btn.click(ui_taxonomy, inputs=[gr.State("title"), output_dir], outputs=[title_tax_out])
132
+
133
+ with gr.Tab("Phase 6"):
134
+ compare_btn = gr.Button("Generate comparison")
135
+ compare_out = gr.Textbox(lines=16, label="Comparison")
136
+ compare_btn.click(ui_compare, inputs=[output_dir], outputs=[compare_out])
137
+
138
+ with gr.Tab("Phase 7"):
139
+ narrative_btn = gr.Button("Generate narrative")
140
+ narrative_out = gr.Textbox(lines=16, label="Narrative result")
141
+ narrative_btn.click(ui_narrative, inputs=[output_dir], outputs=[narrative_out])
142
+
143
+ return app
144
+
145
+
146
+ def main() -> None:
147
+ parser = argparse.ArgumentParser(description="CHB BERTopic draft_2 app")
148
+ parser.add_argument("--mode", choices=["ui", "pipeline"], default="ui")
149
+ parser.add_argument("--input", default=str(DEFAULT_INPUT_CSV))
150
+ parser.add_argument("--output-dir", default=str(OUTPUT_DIR))
151
+ parser.add_argument("--host", default="127.0.0.1")
152
+ parser.add_argument("--port", type=int, default=7861)
153
+ args = parser.parse_args()
154
+
155
+ if args.mode == "pipeline":
156
+ payload = run_full_pipeline(file_path=args.input, output_dir=Path(args.output_dir))
157
+ print(json.dumps(payload, indent=2))
158
+ return
159
+
160
+ app = create_interface()
161
+ app.launch(server_name=args.host, server_port=args.port)
162
+
163
+
164
+ if __name__ == "__main__":
165
+ main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,7 +1,11 @@
1
- gradio>=5.31.0
2
- huggingface-hub>=0.28.0
3
- sentence-transformers>=2.2.0
4
- scikit-learn>=1.3.0
5
- pandas>=2.0.0
6
- numpy>=1.24.0
7
- regex>=2023.0.0
 
 
 
 
 
1
+ gradio>=4.44.0
2
+ bertopic>=0.16.0
3
+ umap-learn>=0.5.6
4
+ hdbscan>=0.8.33
5
+ transformers>=4.48.0
6
+ adapters>=1.0.0
7
+ scikit-learn>=1.3.0
8
+ pandas>=2.0.0
9
+ numpy>=1.24.0
10
+ torch>=2.2.0
11
+ openai>=1.30.0
tools.py CHANGED
@@ -1,33 +1,48 @@
1
- """
2
- tools.py - BERTopic Pipeline Tools for RQ5-7 (HuggingFace Deployment)
3
- =====================================================================
4
- Uses HuggingFace Inference API with free models.
5
- """
6
 
7
- import os
8
  import json
 
 
9
  import re
10
  import time
 
 
 
 
11
  import numpy as np
12
  import pandas as pd
13
- from datetime import datetime
14
- from sentence_transformers import SentenceTransformer
 
 
 
 
 
 
15
  from sklearn.cluster import AgglomerativeClustering
16
- from sklearn.metrics.pairwise import cosine_similarity
17
- from huggingface_hub import InferenceClient
18
-
19
- # ============================================================================
20
- # CONFIGURATION
21
- # ============================================================================
22
-
23
- # HuggingFace free model (Mistral 7B Instruct - free with HF token)
24
- HF_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"
25
- EMBEDDING_MODEL = "all-MiniLM-L6-v2"
26
- OUTPUT_DIR = "outputs"
27
- API_RETRY_DELAY = 2
 
 
 
 
 
 
 
 
28
  MAX_RETRIES = 3
 
29
 
30
- # PAJAIS 25 Categories for taxonomy mapping
31
  PAJAIS_CATEGORIES = [
32
  "Digital Innovation & Entrepreneurship",
33
  "Electronic Commerce",
@@ -53,10 +68,9 @@ PAJAIS_CATEGORIES = [
53
  "Cloud Computing",
54
  "Internet of Things",
55
  "Digital Platforms",
56
- "Future of Work"
57
  ]
58
 
59
- # Boilerplate patterns to remove
60
  BOILERPLATE_PATTERNS = [
61
  r"©\s*\d{4}.*?(?:Elsevier|Ltd|Inc|reserved)",
62
  r"All rights reserved\.?",
@@ -64,452 +78,875 @@ BOILERPLATE_PATTERNS = [
64
  r"https?://\S+",
65
  r"\S+@\S+\.\S+",
66
  r"doi:?\s*\S+",
 
 
67
  ]
68
 
69
- # ============================================================================
70
- # HELPER FUNCTIONS
71
- # ============================================================================
72
-
73
- def _get_hf_client():
74
- """Initialize HuggingFace Inference client."""
75
- token = os.environ.get("HF_TOKEN", "")
76
- if not token:
77
- raise ValueError("HF_TOKEN environment variable not set!")
78
- return InferenceClient(token=token)
79
-
80
- def _call_llm_with_retry(client, prompt, max_tokens=500):
81
- """Call HuggingFace model with retry logic."""
82
- last_error = None
83
- for attempt in range(MAX_RETRIES):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  try:
85
- response = client.text_generation(
86
- prompt,
87
- model=HF_MODEL,
88
- max_new_tokens=max_tokens,
 
 
89
  temperature=0.3,
90
- do_sample=True,
91
  )
92
- return response
93
- except Exception as e:
94
- last_error = e
95
- print(f"HF API error (attempt {attempt + 1}/{MAX_RETRIES}): {str(e)[:100]}")
96
- time.sleep(API_RETRY_DELAY * (attempt + 1))
97
- raise last_error
98
-
99
- def _ensure_output_dir():
100
- """Ensure output directory exists."""
101
- os.makedirs(OUTPUT_DIR, exist_ok=True)
102
- return OUTPUT_DIR
103
-
104
- def _clean_text(text):
105
- """Remove boilerplate from text."""
106
- result = str(text) if text else ""
107
- for pattern in BOILERPLATE_PATTERNS:
108
- result = re.sub(pattern, "", result, flags=re.IGNORECASE)
109
- return result.strip()
110
-
111
- def _split_sentences(text):
112
- """Split text into sentences."""
113
- sentences = re.split(r'(?<=[.!?])\s+', str(text))
114
- return [s.strip() for s in sentences if len(s.strip()) > 20]
115
-
116
- # ============================================================================
117
- # TOOL 1: load_scopus_csv
118
- # ============================================================================
119
-
120
- def load_scopus_csv(file_path: str) -> dict:
121
- """Load and clean Scopus CSV data."""
122
- _ensure_output_dir()
123
-
124
- df = pd.read_csv(file_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  df["Abstract_Clean"] = df["Abstract"].apply(_clean_text)
126
-
127
- all_sentences = []
128
- paper_ids = []
129
-
130
- for idx, row in df.iterrows():
131
- sentences = _split_sentences(row["Abstract_Clean"])
132
- all_sentences.extend(sentences)
133
- paper_ids.extend([idx] * len(sentences))
134
-
135
- sentences_df = pd.DataFrame({"sentence": all_sentences, "paper_id": paper_ids})
136
- sentences_df.to_csv(f"{OUTPUT_DIR}/sentences.csv", index=False)
137
- df.to_csv(f"{OUTPUT_DIR}/papers_clean.csv", index=False)
138
-
139
  stats = {
140
- "total_papers": len(df),
141
- "total_sentences": len(all_sentences),
142
  "columns": list(df.columns),
 
143
  "sample_abstracts": df["Abstract_Clean"].head(3).tolist(),
144
- "year_range": f"{df['Year'].min()} - {df['Year'].max()}" if "Year" in df.columns else "N/A",
145
- "timestamp": datetime.now().isoformat()
146
  }
147
-
148
- with open(f"{OUTPUT_DIR}/data_stats.json", "w") as f:
149
- json.dump(stats, f, indent=2)
150
-
151
  return stats
152
 
153
- # ============================================================================
154
- # TOOL 2: run_bertopic_discovery
155
- # ============================================================================
156
-
157
- def run_bertopic_discovery(column_name: str = "Abstract") -> dict:
158
- """Embed and cluster texts into topics."""
159
- _ensure_output_dir()
160
-
161
- papers_df = pd.read_csv(f"{OUTPUT_DIR}/papers_clean.csv")
162
-
163
- if column_name == "Title":
164
- texts = papers_df["Title"].apply(_clean_text).tolist()
165
- text_type = "title"
166
- else:
167
- sentences_df = pd.read_csv(f"{OUTPUT_DIR}/sentences.csv")
168
- texts = sentences_df["sentence"].tolist()
169
- text_type = "abstract"
170
-
171
- print(f"Embedding {len(texts)} texts...")
172
- model = SentenceTransformer(EMBEDDING_MODEL)
173
- embeddings = model.encode(texts, show_progress_bar=True, normalize_embeddings=True)
174
-
175
- np.save(f"{OUTPUT_DIR}/embeddings_{text_type}.npy", embeddings)
176
-
177
- print("Clustering...")
178
- clustering = AgglomerativeClustering(
179
- n_clusters=None,
180
- distance_threshold=0.7,
181
  metric="cosine",
182
- linkage="average"
 
183
  )
184
- labels = clustering.fit_predict(embeddings)
185
-
186
- unique_labels = set(labels)
187
- topics = {}
188
-
189
- for label in unique_labels:
190
- if label == -1:
191
- continue
192
- indices = [i for i, l in enumerate(labels) if l == label]
193
- cluster_embeddings = embeddings[indices]
194
- centroid = np.mean(cluster_embeddings, axis=0)
195
- similarities = cosine_similarity([centroid], cluster_embeddings)[0]
196
- top_indices = np.argsort(similarities)[-5:][::-1]
197
- representative_texts = [texts[indices[i]] for i in top_indices]
198
-
199
- topics[int(label)] = {
200
- "size": len(indices),
201
- "representative_texts": representative_texts,
202
- }
203
-
204
- topics = dict(sorted(topics.items(), key=lambda x: x[1]["size"], reverse=True))
205
-
206
- result = {
207
- "column": column_name,
208
- "text_type": text_type,
209
- "total_texts": len(texts),
210
- "num_topics": len(topics),
211
- "topics": topics,
212
- "timestamp": datetime.now().isoformat()
213
- }
214
-
215
- with open(f"{OUTPUT_DIR}/summaries_{text_type}.json", "w") as f:
216
- json.dump(result, f, indent=2, default=str)
217
-
218
- pd.DataFrame({"text": texts, "topic": labels}).to_csv(
219
- f"{OUTPUT_DIR}/topic_assignments_{text_type}.csv", index=False
220
  )
221
-
222
- return {
223
- "num_topics": len(topics),
224
- "total_texts": len(texts),
225
- "top_10_topics": {k: {"size": v["size"], "sample": v["representative_texts"][0][:100]}
226
- for k, v in list(topics.items())[:10]}
227
- }
228
 
229
- # ============================================================================
230
- # TOOL 3: label_topics_with_llm
231
- # ============================================================================
232
-
233
- def label_topics_with_llm(text_type: str = "abstract") -> dict:
234
- """Generate topic labels using HuggingFace LLM."""
235
- _ensure_output_dir()
236
- client = _get_hf_client()
237
-
238
- with open(f"{OUTPUT_DIR}/summaries_{text_type}.json", "r") as f:
239
- data = json.load(f)
240
-
241
- topics = data["topics"]
242
- labeled_topics = {}
243
-
244
- # Label top 20 topics to stay within free tier limits
245
- topics_to_label = list(topics.items())[:20]
246
-
247
- for idx, (topic_id, topic_data) in enumerate(topics_to_label):
248
- representative_texts = topic_data["representative_texts"]
249
- texts_str = "\n".join([f"- {t[:150]}" for t in representative_texts[:3]])
250
-
251
- prompt = f"""<s>[INST] Given these representative sentences from academic abstracts in "Computers in Human Behavior" journal, generate a concise topic label (3-5 words).
252
-
253
- Sentences:
254
- {texts_str}
255
-
256
- Respond with ONLY a JSON object: {{"label": "Your Topic Label"}} [/INST]"""
257
 
258
- try:
259
- response = _call_llm_with_retry(client, prompt, max_tokens=50)
260
- json_match = re.search(r'\{[^}]+\}', response)
261
- if json_match:
262
- label_data = json.loads(json_match.group())
263
- label = label_data.get("label", f"Topic {topic_id}")
264
- else:
265
- label = f"Topic {topic_id}"
266
- except Exception as e:
267
- print(f"Error labeling topic {topic_id}: {e}")
268
- label = f"Topic {topic_id}"
269
-
270
- labeled_topics[topic_id] = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  "label": label,
272
- "size": topic_data["size"],
273
- "representative_texts": representative_texts
 
 
274
  }
275
-
276
- print(f"Topic {topic_id}: {label}")
277
- time.sleep(1) # Rate limit
278
-
279
- result = {
280
  "text_type": text_type,
281
- "num_labeled": len(labeled_topics),
282
- "topics": labeled_topics,
283
- "timestamp": datetime.now().isoformat()
284
- }
285
-
286
- with open(f"{OUTPUT_DIR}/labels_{text_type}.json", "w") as f:
287
- json.dump(result, f, indent=2)
288
-
289
- return {
290
- "num_labeled": len(labeled_topics),
291
- "sample_labels": {k: v["label"] for k, v in list(labeled_topics.items())[:10]}
292
  }
 
 
293
 
294
- # ============================================================================
295
- # TOOL 4: consolidate_into_themes
296
- # ============================================================================
297
-
298
- def consolidate_into_themes(text_type: str = "abstract", target_themes: int = 15) -> dict:
299
- """Merge similar topics into broader themes."""
300
- _ensure_output_dir()
301
- client = _get_hf_client()
302
-
303
- with open(f"{OUTPUT_DIR}/labels_{text_type}.json", "r") as f:
304
- data = json.load(f)
305
-
306
- topics = data["topics"]
307
- labels_list = [{"id": k, "label": v["label"], "size": v["size"]} for k, v in topics.items()]
308
- labels_str = "\n".join([f"- {t['label']} (ID:{t['id']}, {t['size']} items)" for t in labels_list[:15]])
309
-
310
- prompt = f"""<s>[INST] Group these research topics into {target_themes} broader themes:
311
-
312
- {labels_str}
313
-
314
- Respond with ONLY a JSON object mapping theme names to topic IDs:
315
- {{"Theme Name": ["id1", "id2"], "Another Theme": ["id3"]}} [/INST]"""
316
 
317
- try:
318
- response = _call_llm_with_retry(client, prompt, max_tokens=500)
319
- json_match = re.search(r'\{[^{}]*(?:\[[^\]]*\][^{}]*)*\}', response, re.DOTALL)
320
- if json_match:
321
- theme_groups = json.loads(json_match.group())
322
- else:
323
- theme_groups = {topics[k]["label"]: [k] for k in list(topics.keys())[:target_themes]}
324
- except Exception as e:
325
- print(f"Consolidation error: {e}")
326
- theme_groups = {topics[k]["label"]: [k] for k in list(topics.keys())[:target_themes]}
327
-
328
- themes = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  for theme_name, topic_ids in theme_groups.items():
330
- total_size = sum(topics.get(str(tid), {}).get("size", 0) for tid in topic_ids)
331
- member_labels = [topics.get(str(tid), {}).get("label", "Unknown") for tid in topic_ids]
 
 
 
 
 
 
 
332
  themes[theme_name] = {
333
- "topic_ids": topic_ids,
 
 
334
  "total_size": total_size,
335
- "member_labels": member_labels
336
  }
337
-
338
- result = {
339
  "text_type": text_type,
340
  "num_themes": len(themes),
341
- "themes": themes,
342
- "timestamp": datetime.now().isoformat()
 
 
 
 
 
343
  }
344
-
345
- with open(f"{OUTPUT_DIR}/themes_{text_type}.json", "w") as f:
346
- json.dump(result, f, indent=2)
347
-
348
- return {"num_themes": len(themes), "themes": {k: v["total_size"] for k, v in themes.items()}}
349
-
350
- # ============================================================================
351
- # TOOL 5: compare_with_taxonomy
352
- # ============================================================================
353
-
354
- def compare_with_taxonomy(text_type: str = "abstract") -> dict:
355
- """Map themes to PAJAIS taxonomy."""
356
- _ensure_output_dir()
357
- client = _get_hf_client()
358
-
359
- with open(f"{OUTPUT_DIR}/themes_{text_type}.json", "r") as f:
360
- data = json.load(f)
361
-
362
- themes = data["themes"]
363
- taxonomy_map = {}
364
- pajais_str = "\n".join([f"{i+1}. {cat}" for i, cat in enumerate(PAJAIS_CATEGORIES)])
365
-
366
- for theme_name, theme_data in themes.items():
367
- prompt = f"""<s>[INST] Does this research theme map to a PAJAIS IS category or is it NOVEL?
368
-
369
- Theme: "{theme_name}"
370
- Topics: {', '.join(theme_data['member_labels'][:3])}
371
-
372
- PAJAIS Categories:
373
- {pajais_str}
374
 
375
- Respond with ONLY JSON: {{"mapping_type": "MAPPED" or "NOVEL", "pajais_category": "category name or null", "reasoning": "brief reason"}} [/INST]"""
376
 
377
- try:
378
- response = _call_llm_with_retry(client, prompt, max_tokens=150)
379
- json_match = re.search(r'\{[^}]+\}', response, re.DOTALL)
380
- if json_match:
381
- mapping = json.loads(json_match.group())
382
- else:
383
- mapping = {"mapping_type": "NOVEL", "pajais_category": None, "reasoning": "Parse error"}
384
- except Exception as e:
385
- mapping = {"mapping_type": "NOVEL", "pajais_category": None, "reasoning": str(e)[:50]}
386
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  taxonomy_map[theme_name] = {
388
- **mapping,
389
- "size": theme_data["total_size"],
390
- "member_labels": theme_data["member_labels"]
 
 
 
 
 
391
  }
392
-
393
- print(f"{theme_name}: {mapping.get('mapping_type')} -> {mapping.get('pajais_category')}")
394
- time.sleep(1)
395
-
396
- mapped_count = sum(1 for v in taxonomy_map.values() if v["mapping_type"] == "MAPPED")
397
  novel_count = len(taxonomy_map) - mapped_count
398
-
399
  result = {
400
  "text_type": text_type,
401
  "total_themes": len(taxonomy_map),
402
  "mapped_count": mapped_count,
403
  "novel_count": novel_count,
404
  "taxonomy_map": taxonomy_map,
405
- "timestamp": datetime.now().isoformat()
406
  }
407
-
408
- with open(f"{OUTPUT_DIR}/taxonomy_map_{text_type}.json", "w") as f:
409
- json.dump(result, f, indent=2)
410
-
411
  return {
412
  "mapped_count": mapped_count,
413
  "novel_count": novel_count,
414
- "mapped_themes": [k for k, v in taxonomy_map.items() if v["mapping_type"] == "MAPPED"],
415
- "novel_themes": [k for k, v in taxonomy_map.items() if v["mapping_type"] == "NOVEL"]
416
  }
417
 
418
- # ============================================================================
419
- # TOOL 6: generate_comparison_csv
420
- # ============================================================================
421
-
422
- def generate_comparison_csv() -> dict:
423
- """Compare abstract themes vs title themes."""
424
- _ensure_output_dir()
425
-
426
- with open(f"{OUTPUT_DIR}/taxonomy_map_abstract.json", "r") as f:
427
- abstract_data = json.load(f)
428
-
429
- with open(f"{OUTPUT_DIR}/taxonomy_map_title.json", "r") as f:
430
- title_data = json.load(f)
431
-
432
- abstract_themes = set(abstract_data["taxonomy_map"].keys())
433
- title_themes = set(title_data["taxonomy_map"].keys())
434
-
435
- both = abstract_themes & title_themes
436
- abstract_only = abstract_themes - title_themes
437
- title_only = title_themes - abstract_themes
438
-
439
  rows = []
440
- for theme in abstract_themes | title_themes:
441
- abs_info = abstract_data["taxonomy_map"].get(theme, {})
442
- title_info = title_data["taxonomy_map"].get(theme, {})
443
- rows.append({
444
- "Theme": theme,
445
- "In_Abstracts": "Yes" if theme in abstract_themes else "No",
446
- "In_Titles": "Yes" if theme in title_themes else "No",
447
- "Abstract_Size": abs_info.get("size", 0),
448
- "Title_Size": title_info.get("size", 0),
449
- "Abstract_Mapping": abs_info.get("mapping_type", "N/A"),
450
- "Title_Mapping": title_info.get("mapping_type", "N/A"),
451
- "PAJAIS_Category": abs_info.get("pajais_category") or title_info.get("pajais_category") or "NOVEL"
452
- })
453
-
454
- comparison_df = pd.DataFrame(rows).sort_values("Abstract_Size", ascending=False)
455
- comparison_df.to_csv(f"{OUTPUT_DIR}/comparison.csv", index=False)
456
-
 
 
 
 
 
 
 
 
 
 
457
  result = {
458
- "total_unique_themes": len(abstract_themes | title_themes),
459
- "themes_in_both": len(both),
460
- "abstract_only": len(abstract_only),
461
- "title_only": len(title_only),
462
- "timestamp": datetime.now().isoformat()
 
 
 
 
 
 
 
 
 
 
463
  }
464
-
465
- with open(f"{OUTPUT_DIR}/comparison_summary.json", "w") as f:
466
- json.dump(result, f, indent=2)
467
-
468
  return result
469
 
470
- # ============================================================================
471
- # TOOL 7: export_narrative
472
- # ============================================================================
473
-
474
- def export_narrative() -> dict:
475
- """Generate Section 7 narrative."""
476
- _ensure_output_dir()
477
- client = _get_hf_client()
478
-
479
- with open(f"{OUTPUT_DIR}/data_stats.json", "r") as f:
480
- stats = json.load(f)
481
-
482
- with open(f"{OUTPUT_DIR}/taxonomy_map_title.json", "r") as f:
483
- title_tax = json.load(f)
484
-
485
- with open(f"{OUTPUT_DIR}/comparison_summary.json", "r") as f:
486
- comparison = json.load(f)
487
-
488
- prompt = f"""<s>[INST] Write a 300-word academic methodology section for analyzing "Computers in Human Behavior" journal.
489
-
490
- Data: {stats['total_papers']} papers, {stats['total_sentences']} sentences, years {stats['year_range']}
491
- Themes: {title_tax['total_themes']} discovered, {title_tax['mapped_count']} MAPPED to PAJAIS, {title_tax['novel_count']} NOVEL
492
- Comparison: {comparison['themes_in_both']} themes in both abstracts/titles, {comparison['abstract_only']} abstract-only, {comparison['title_only']} title-only
493
-
494
- Include: methodology (BERTopic, sentence-transformers), key findings, PAJAIS mapping, limitations. [/INST]"""
495
 
496
- try:
497
- narrative = _call_llm_with_retry(client, prompt, max_tokens=800)
498
- except Exception as e:
499
- narrative = f"Narrative generation failed: {e}"
500
-
501
- with open(f"{OUTPUT_DIR}/narrative.txt", "w", encoding="utf-8") as f:
502
- f.write(narrative)
503
-
504
- return {"word_count": len(narrative.split()), "preview": narrative[:500]}
505
-
506
-
507
- if __name__ == "__main__":
508
- print("Tools module loaded. Available functions:")
509
- print("1. load_scopus_csv(file_path)")
510
- print("2. run_bertopic_discovery(column_name)")
511
- print("3. label_topics_with_llm(text_type)")
512
- print("4. consolidate_into_themes(text_type)")
513
- print("5. compare_with_taxonomy(text_type)")
514
- print("6. generate_comparison_csv()")
515
- print("7. export_narrative()")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
 
 
 
 
2
 
 
3
  import json
4
+ import math
5
+ import os
6
  import re
7
  import time
8
+ from collections import Counter
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
  import numpy as np
13
  import pandas as pd
14
+ import torch
15
+ from adapters import AutoAdapterModel
16
+ from bertopic import BERTopic
17
+ from bertopic.vectorizers import ClassTfidfTransformer
18
+ from hdbscan import HDBSCAN
19
+ from openai import OpenAI
20
+ from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS, CountVectorizer, TfidfVectorizer
21
+ from sklearn.metrics import silhouette_score
22
  from sklearn.cluster import AgglomerativeClustering
23
+ from transformers import AutoTokenizer
24
+ from umap import UMAP
25
+
26
+
27
+ APP_DIR = Path(__file__).resolve().parent
28
+ PROJECT_DIR = APP_DIR.parent
29
+ OUTPUT_DIR = PROJECT_DIR / "bertopic_outputs_7553"
30
+ DEFAULT_INPUT_CSV = (
31
+ PROJECT_DIR
32
+ / "sources"
33
+ / "corpus_7553"
34
+ / "ComputersinHumanBehavior_TopicModelling_Export_7553_for_app.csv"
35
+ )
36
+
37
+ SPECTER2_BASE_MODEL = "allenai/specter2_base"
38
+ SPECTER2_ADAPTER = "allenai/specter2"
39
+ OLLAMA_BASE_URL = os.environ.get("CHB_OLLAMA_BASE_URL", "http://localhost:11434/v1")
40
+ OLLAMA_MODEL = os.environ.get("CHB_OLLAMA_MODEL", "gemma4:e2b")
41
+ OLLAMA_TIMEOUT_SECONDS = int(os.environ.get("CHB_OLLAMA_TIMEOUT_SECONDS", "300"))
42
+ RANDOM_STATE = 42
43
  MAX_RETRIES = 3
44
+ API_RETRY_DELAY = 2
45
 
 
46
  PAJAIS_CATEGORIES = [
47
  "Digital Innovation & Entrepreneurship",
48
  "Electronic Commerce",
 
68
  "Cloud Computing",
69
  "Internet of Things",
70
  "Digital Platforms",
71
+ "Future of Work",
72
  ]
73
 
 
74
  BOILERPLATE_PATTERNS = [
75
  r"©\s*\d{4}.*?(?:Elsevier|Ltd|Inc|reserved)",
76
  r"All rights reserved\.?",
 
78
  r"https?://\S+",
79
  r"\S+@\S+\.\S+",
80
  r"doi:?\s*\S+",
81
+ r"Crown Copyright.*?reserved\.?",
82
+ r"Published by.*?(?:Elsevier|Springer|Wiley)",
83
  ]
84
 
85
+ EXTRA_STOPWORDS = {
86
+ "study",
87
+ "paper",
88
+ "research",
89
+ "results",
90
+ "finding",
91
+ "findings",
92
+ "article",
93
+ "author",
94
+ "authors",
95
+ "based",
96
+ "using",
97
+ "used",
98
+ "examines",
99
+ "examined",
100
+ "investigates",
101
+ "investigated",
102
+ "analysis",
103
+ "implications",
104
+ "effect",
105
+ "effects",
106
+ }
107
+
108
+ TEXT_TYPE_SETTINGS = {
109
+ "abstract": {
110
+ "vectorizer_min_df": 1,
111
+ "vectorizer_max_df": 1.0,
112
+ "ngram_range": (1, 2),
113
+ "umap_n_neighbors": 10,
114
+ "umap_n_components": 5,
115
+ "hdbscan_min_cluster_size": 30,
116
+ "hdbscan_min_samples": 8,
117
+ "target_themes": 15,
118
+ "target_topics_soft_max": 55,
119
+ },
120
+ "title": {
121
+ "vectorizer_min_df": 1,
122
+ "vectorizer_max_df": 1.0,
123
+ "ngram_range": (1, 2),
124
+ "umap_n_neighbors": 8,
125
+ "umap_n_components": 5,
126
+ "hdbscan_min_cluster_size": 20,
127
+ "hdbscan_min_samples": 5,
128
+ "target_themes": 15,
129
+ "target_topics_soft_max": 40,
130
+ },
131
+ }
132
+
133
+
134
+ def _ensure_output_dir(output_dir: Path = OUTPUT_DIR) -> Path:
135
+ output_dir.mkdir(parents=True, exist_ok=True)
136
+ return output_dir
137
+
138
+
139
+ def _write_json(path: Path, payload: dict[str, Any]) -> None:
140
+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
141
+
142
+
143
+ def _read_json(path: Path) -> dict[str, Any]:
144
+ return json.loads(path.read_text(encoding="utf-8"))
145
+
146
+ def _clean_text(text: Any) -> str:
147
+ value = "" if pd.isna(text) else str(text)
148
+ for pattern in BOILERPLATE_PATTERNS:
149
+ value = re.sub(pattern, " ", value, flags=re.IGNORECASE)
150
+ value = value.replace("\u00a9", " ")
151
+ value = re.sub(r"\s+", " ", value).strip()
152
+ return value
153
+
154
+
155
+ def _normalize_label(value: str) -> str:
156
+ label = re.sub(r"\s+", " ", str(value)).strip(" -:;,.")
157
+ label = re.sub(r"[/|]+", " ", label)
158
+ label = re.sub(r"\s+", " ", label).strip()
159
+ return label
160
+
161
+
162
+ def _slugify_label(value: str) -> str:
163
+ slug = re.sub(r"[^a-z0-9]+", "_", value.lower())
164
+ return slug.strip("_")
165
+
166
+
167
+ def _keywords_to_label(keywords: list[str], max_words: int = 4) -> str:
168
+ cleaned = [_normalize_label(kw.replace("_", " ")) for kw in keywords if kw.strip()]
169
+ if not cleaned:
170
+ return "Unlabeled Topic"
171
+
172
+ selected: list[str] = []
173
+ covered_tokens: set[str] = set()
174
+ for phrase in sorted(cleaned, key=lambda item: (-len(item.split()), item)):
175
+ tokens = [token for token in phrase.lower().split() if token]
176
+ if not tokens:
177
+ continue
178
+ if all(token in covered_tokens for token in tokens):
179
+ continue
180
+ selected.append(phrase)
181
+ covered_tokens.update(tokens)
182
+ if len(selected) >= 3:
183
+ break
184
+
185
+ if not selected:
186
+ selected = cleaned[:max_words]
187
+
188
+ if len(selected) == 1:
189
+ return selected[0].title()
190
+ if len(selected) == 2:
191
+ return f"{selected[0].title()} and {selected[1].title()}"
192
+ return f"{selected[0].title()}, {selected[1].title()}, and {selected[2].title()}"
193
+
194
+
195
+ def _get_llm_client() -> OpenAI:
196
+ return OpenAI(
197
+ base_url=OLLAMA_BASE_URL,
198
+ api_key="ollama",
199
+ timeout=OLLAMA_TIMEOUT_SECONDS,
200
+ max_retries=0,
201
+ )
202
+
203
+
204
+ def _call_llm_json(prompt: str, model: str = OLLAMA_MODEL, max_tokens: int = 300) -> dict[str, Any] | None:
205
+ client = _get_llm_client()
206
+ last_error: Exception | None = None
207
+ for _ in range(MAX_RETRIES):
208
+ try:
209
+ response = client.chat.completions.create(
210
+ model=model,
211
+ messages=[
212
+ {
213
+ "role": "system",
214
+ "content": (
215
+ "Return only valid JSON. Do not wrap it in markdown. "
216
+ "Do not include commentary outside the JSON object."
217
+ ),
218
+ },
219
+ {"role": "user", "content": prompt},
220
+ ],
221
+ temperature=0.2,
222
+ max_tokens=max_tokens,
223
+ )
224
+ text = response.choices[0].message.content.strip()
225
+ match = re.search(r"\{.*\}", text, flags=re.DOTALL)
226
+ if not match:
227
+ return None
228
+ return json.loads(match.group(0))
229
+ except Exception as exc: # nosec - explicit retry path
230
+ last_error = exc
231
+ time.sleep(API_RETRY_DELAY)
232
+ if last_error:
233
+ print(f"LLM JSON call failed: {last_error}")
234
+ return None
235
+
236
+
237
+ def _call_llm_text(prompt: str, model: str = OLLAMA_MODEL, max_tokens: int = 700) -> str:
238
+ client = _get_llm_client()
239
+ last_error: Exception | None = None
240
+ for _ in range(MAX_RETRIES):
241
  try:
242
+ response = client.chat.completions.create(
243
+ model=model,
244
+ messages=[
245
+ {"role": "system", "content": "Write clean academic text only."},
246
+ {"role": "user", "content": prompt},
247
+ ],
248
  temperature=0.3,
249
+ max_tokens=max_tokens,
250
  )
251
+ return response.choices[0].message.content.strip()
252
+ except Exception as exc: # nosec - explicit retry path
253
+ last_error = exc
254
+ time.sleep(API_RETRY_DELAY)
255
+ if last_error:
256
+ print(f"LLM text call failed: {last_error}")
257
+ return ""
258
+
259
+
260
+ class Specter2Embedder:
261
+ def __init__(
262
+ self,
263
+ model_name: str = SPECTER2_BASE_MODEL,
264
+ adapter_name: str = SPECTER2_ADAPTER,
265
+ batch_size: int = 8,
266
+ max_length: int = 512,
267
+ ) -> None:
268
+ self.model_name = model_name
269
+ self.adapter_name = adapter_name
270
+ self.batch_size = batch_size
271
+ self.max_length = max_length
272
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
273
+ self.tokenizer: AutoTokenizer | None = None
274
+ self.model: AutoAdapterModel | None = None
275
+
276
+ def _load(self) -> None:
277
+ if self.tokenizer is not None and self.model is not None:
278
+ return
279
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
280
+ self.model = AutoAdapterModel.from_pretrained(self.model_name)
281
+ self.model.load_adapter(self.adapter_name, source="hf", load_as="specter2", set_active=True)
282
+ self.model.set_active_adapters("specter2")
283
+ self.model.to(self.device)
284
+ self.model.eval()
285
+
286
+ def encode(self, texts: list[str], cache_path: Path | None = None) -> np.ndarray:
287
+ if cache_path and cache_path.exists():
288
+ cached = np.load(cache_path)
289
+ if len(cached) == len(texts):
290
+ return cached
291
+
292
+ self._load()
293
+ assert self.tokenizer is not None
294
+ assert self.model is not None
295
+
296
+ embeddings: list[np.ndarray] = []
297
+ total_batches = math.ceil(len(texts) / self.batch_size)
298
+ for batch_index in range(total_batches):
299
+ start = batch_index * self.batch_size
300
+ end = start + self.batch_size
301
+ batch = texts[start:end]
302
+ encoded = self.tokenizer(
303
+ batch,
304
+ padding=True,
305
+ truncation=True,
306
+ max_length=self.max_length,
307
+ return_token_type_ids=False,
308
+ return_tensors="pt",
309
+ )
310
+ encoded = {key: value.to(self.device) for key, value in encoded.items()}
311
+ with torch.no_grad():
312
+ outputs = self.model(**encoded)
313
+ batch_embeddings = outputs.last_hidden_state[:, 0, :]
314
+ batch_embeddings = torch.nn.functional.normalize(batch_embeddings, p=2, dim=1)
315
+ embeddings.append(batch_embeddings.cpu().numpy().astype(np.float32))
316
+ print(f"SPECTER2 batch {batch_index + 1}/{total_batches} complete")
317
+
318
+ matrix = np.vstack(embeddings)
319
+ if cache_path:
320
+ np.save(cache_path, matrix)
321
+ return matrix
322
+
323
+
324
+ def _prepare_embedding_text(df: pd.DataFrame, text_type: str, sep_token: str) -> list[str]:
325
+ if text_type == "title":
326
+ return df["Title_Clean"].tolist()
327
+ return [
328
+ f"{title}{sep_token}{abstract}".strip()
329
+ for title, abstract in zip(df["Title_Clean"], df["Abstract_Clean"], strict=True)
330
+ ]
331
+
332
+
333
+ def _load_clean_papers(output_dir: Path = OUTPUT_DIR) -> pd.DataFrame:
334
+ path = output_dir / "papers_clean.csv"
335
+ if not path.exists():
336
+ raise FileNotFoundError("Run load_scopus_csv first.")
337
+ return pd.read_csv(path, keep_default_na=False)
338
+
339
+
340
+ def load_scopus_csv(file_path: str, output_dir: Path = OUTPUT_DIR) -> dict[str, Any]:
341
+ output_dir = _ensure_output_dir(output_dir)
342
+ df = pd.read_csv(file_path, keep_default_na=False)
343
+ df["Title_Clean"] = df["Title"].apply(_clean_text)
344
  df["Abstract_Clean"] = df["Abstract"].apply(_clean_text)
345
+ df["Author Keywords"] = df["Author Keywords"].fillna("").astype(str)
346
+ df["Cited by"] = pd.to_numeric(df["Cited by"], errors="coerce").fillna(0).astype(int)
347
+ df["Year"] = pd.to_numeric(df["Year"], errors="coerce").astype(int)
348
+ if "Sr No" not in df.columns:
349
+ df.insert(0, "Sr No", range(1, len(df) + 1))
350
+ df.to_csv(output_dir / "papers_clean.csv", index=False, encoding="utf-8-sig")
351
+
 
 
 
 
 
 
352
  stats = {
353
+ "total_papers": int(len(df)),
354
+ "year_range": f"{int(df['Year'].min())} - {int(df['Year'].max())}",
355
  "columns": list(df.columns),
356
+ "sample_titles": df["Title_Clean"].head(3).tolist(),
357
  "sample_abstracts": df["Abstract_Clean"].head(3).tolist(),
358
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
 
359
  }
360
+ _write_json(output_dir / "data_stats.json", stats)
 
 
 
361
  return stats
362
 
363
+
364
+ def _build_topic_model(text_type: str) -> BERTopic:
365
+ settings = TEXT_TYPE_SETTINGS[text_type]
366
+ stop_words = sorted(ENGLISH_STOP_WORDS.union(EXTRA_STOPWORDS))
367
+ vectorizer_model = CountVectorizer(
368
+ stop_words=stop_words,
369
+ ngram_range=settings["ngram_range"],
370
+ min_df=settings["vectorizer_min_df"],
371
+ max_df=settings["vectorizer_max_df"],
372
+ )
373
+ umap_model = UMAP(
374
+ n_neighbors=settings["umap_n_neighbors"],
375
+ n_components=settings["umap_n_components"],
376
+ min_dist=0.0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  metric="cosine",
378
+ random_state=RANDOM_STATE,
379
+ low_memory=True,
380
  )
381
+ hdbscan_model = HDBSCAN(
382
+ min_cluster_size=settings["hdbscan_min_cluster_size"],
383
+ min_samples=settings["hdbscan_min_samples"],
384
+ metric="euclidean",
385
+ cluster_selection_method="eom",
386
+ prediction_data=True,
387
+ )
388
+ return BERTopic(
389
+ umap_model=umap_model,
390
+ hdbscan_model=hdbscan_model,
391
+ vectorizer_model=vectorizer_model,
392
+ ctfidf_model=ClassTfidfTransformer(reduce_frequent_words=True),
393
+ top_n_words=10,
394
+ verbose=True,
395
+ calculate_probabilities=False,
396
+ low_memory=True,
397
+ min_topic_size=settings["hdbscan_min_cluster_size"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
  )
 
 
 
 
 
 
 
399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
 
401
+ def _compute_topic_diversity(topic_model: BERTopic, top_n_words: int = 10) -> float:
402
+ words: list[str] = []
403
+ for topic_id, values in topic_model.get_topics().items():
404
+ if topic_id == -1:
405
+ continue
406
+ words.extend(word for word, _ in values[:top_n_words])
407
+ if not words:
408
+ return 0.0
409
+ return len(set(words)) / len(words)
410
+
411
+
412
+ def _compute_silhouette(embeddings: np.ndarray, topics: list[int]) -> float | None:
413
+ valid_indices = [idx for idx, topic_id in enumerate(topics) if topic_id != -1]
414
+ valid_labels = [topics[idx] for idx in valid_indices]
415
+ if len(set(valid_labels)) < 2 or len(valid_indices) < 200:
416
+ return None
417
+ sample_size = min(1500, len(valid_indices))
418
+ sampled = valid_indices[:sample_size]
419
+ try:
420
+ return float(
421
+ silhouette_score(
422
+ embeddings[sampled],
423
+ [topics[idx] for idx in sampled],
424
+ metric="cosine",
425
+ )
426
+ )
427
+ except Exception:
428
+ return None
429
+
430
+
431
+ def _topic_keywords(topic_model: BERTopic, topic_id: int, top_n_words: int = 8) -> list[str]:
432
+ return [word for word, _ in topic_model.get_topic(topic_id)[:top_n_words]]
433
+
434
+
435
+ def _representative_docs_map(topic_model: BERTopic) -> dict[int, list[str]]:
436
+ raw_docs = topic_model.get_representative_docs() or {}
437
+ return {int(topic_id): [str(doc) for doc in docs] for topic_id, docs in raw_docs.items()}
438
+
439
+
440
+ def _relabel_topics_with_fallback(topic_model: BERTopic, text_type: str, output_dir: Path) -> dict[str, Any]:
441
+ topic_info = topic_model.get_topic_info()
442
+ representative_docs = _representative_docs_map(topic_model)
443
+ labels: dict[str, Any] = {}
444
+
445
+ for _, row in topic_info.iterrows():
446
+ topic_id = int(row["Topic"])
447
+ if topic_id == -1:
448
+ continue
449
+ keywords = _topic_keywords(topic_model, topic_id)
450
+ base_label = _keywords_to_label(keywords)
451
+ docs = representative_docs.get(topic_id, [])[:3]
452
+ prompt = f"""
453
+ Create one concise human-readable research topic label for a BERTopic cluster from Computers in Human Behavior.
454
+
455
+ Rules:
456
+ 1. 3 to 6 words
457
+ 2. academic and specific
458
+ 3. do not output generic labels like "topic", "cluster", "research topic", or repeated stopwords
459
+ 4. prefer phenomenon or domain wording over raw keywords
460
+ 5. return the label only, no explanation
461
+
462
+ Topic keywords: {", ".join(keywords)}
463
+ Representative texts:
464
+ {chr(10).join("- " + doc[:500] for doc in docs)}
465
+ """
466
+ response_text = _call_llm_text(prompt, max_tokens=40)
467
+ label = base_label
468
+ confidence = 0.5
469
+ if response_text:
470
+ candidate = _normalize_label(response_text.splitlines()[0])
471
+ if (
472
+ candidate
473
+ and not re.fullmatch(r"topic\s*\d+", candidate, flags=re.IGNORECASE)
474
+ and " and of " not in candidate.lower()
475
+ ):
476
+ label = candidate
477
+ confidence = 0.8
478
+
479
+ labels[str(topic_id)] = {
480
  "label": label,
481
+ "confidence": confidence,
482
+ "topic_size": int(row["Count"]),
483
+ "keywords": keywords,
484
+ "representative_texts": docs,
485
  }
486
+
487
+ payload = {
 
 
 
488
  "text_type": text_type,
489
+ "num_labeled": len(labels),
490
+ "topics": labels,
491
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
 
 
 
 
 
 
 
 
492
  }
493
+ _write_json(output_dir / f"labels_{text_type}.json", payload)
494
+ return payload
495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
 
497
+ def _fallback_theme_groups(labels_payload: dict[str, Any], target_themes: int) -> dict[str, list[str]]:
498
+ rows = []
499
+ for topic_id, info in labels_payload["topics"].items():
500
+ corpus_text = " ".join([info["label"]] + info["keywords"][:6])
501
+ rows.append((topic_id, corpus_text, info["topic_size"]))
502
+ texts = [item[1] for item in rows]
503
+ ids = [item[0] for item in rows]
504
+
505
+ if len(texts) <= target_themes:
506
+ return {labels_payload["topics"][topic_id]["label"]: [topic_id] for topic_id in ids}
507
+
508
+ vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
509
+ matrix = vectorizer.fit_transform(texts)
510
+ clustering = AgglomerativeClustering(n_clusters=target_themes, metric="cosine", linkage="average")
511
+ cluster_ids = clustering.fit_predict(matrix.toarray())
512
+
513
+ groups: dict[int, list[str]] = {}
514
+ for topic_id, cluster_id in zip(ids, cluster_ids, strict=True):
515
+ groups.setdefault(int(cluster_id), []).append(topic_id)
516
+
517
+ theme_groups: dict[str, list[str]] = {}
518
+ for cluster_id, topic_ids in groups.items():
519
+ all_keywords = Counter()
520
+ for topic_id in topic_ids:
521
+ all_keywords.update(labels_payload["topics"][topic_id]["keywords"][:5])
522
+ label = _keywords_to_label([word for word, _ in all_keywords.most_common(4)])
523
+ theme_groups[f"{label} Theme {cluster_id + 1}"] = topic_ids
524
+ return theme_groups
525
+
526
+
527
+ def consolidate_into_themes(
528
+ text_type: str,
529
+ target_themes: int = 15,
530
+ output_dir: Path = OUTPUT_DIR,
531
+ ) -> dict[str, Any]:
532
+ output_dir = _ensure_output_dir(output_dir)
533
+ labels_payload = _read_json(output_dir / f"labels_{text_type}.json")
534
+ topics = labels_payload["topics"]
535
+ topic_rows = []
536
+ for topic_id, info in topics.items():
537
+ topic_rows.append(
538
+ {
539
+ "topic_id": topic_id,
540
+ "label": info["label"],
541
+ "size": info["topic_size"],
542
+ "keywords": ", ".join(info["keywords"][:6]),
543
+ }
544
+ )
545
+ topic_rows = sorted(topic_rows, key=lambda item: item["size"], reverse=True)
546
+ prompt = f"""
547
+ Group these CHB topic labels into approximately {target_themes} broader human-readable themes.
548
+
549
+ Topics:
550
+ {chr(10).join(f"- {row['topic_id']}: {row['label']} | size={row['size']} | keywords={row['keywords']}" for row in topic_rows)}
551
+
552
+ Return JSON only:
553
+ {{
554
+ "themes": [
555
+ {{
556
+ "theme_name": "Human-readable theme",
557
+ "topic_ids": ["0", "4", "18"]
558
+ }}
559
+ ]
560
+ }}
561
+ """
562
+ response = _call_llm_json(prompt, max_tokens=1200)
563
+ if response and isinstance(response.get("themes"), list):
564
+ theme_groups = {
565
+ _normalize_label(item["theme_name"]): [str(topic_id) for topic_id in item["topic_ids"]]
566
+ for item in response["themes"]
567
+ if item.get("theme_name") and item.get("topic_ids")
568
+ }
569
+ else:
570
+ theme_groups = _fallback_theme_groups(labels_payload, target_themes)
571
+
572
+ themes: dict[str, Any] = {}
573
  for theme_name, topic_ids in theme_groups.items():
574
+ member_labels = [topics[str(topic_id)]["label"] for topic_id in topic_ids if str(topic_id) in topics]
575
+ member_keywords = []
576
+ total_size = 0
577
+ for topic_id in topic_ids:
578
+ info = topics.get(str(topic_id))
579
+ if not info:
580
+ continue
581
+ member_keywords.extend(info["keywords"][:4])
582
+ total_size += int(info["topic_size"])
583
  themes[theme_name] = {
584
+ "topic_ids": [str(topic_id) for topic_id in topic_ids],
585
+ "member_labels": member_labels,
586
+ "keywords": [word for word, _ in Counter(member_keywords).most_common(8)],
587
  "total_size": total_size,
 
588
  }
589
+
590
+ payload = {
591
  "text_type": text_type,
592
  "num_themes": len(themes),
593
+ "themes": dict(sorted(themes.items(), key=lambda item: item[1]["total_size"], reverse=True)),
594
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
595
+ }
596
+ _write_json(output_dir / f"themes_{text_type}.json", payload)
597
+ return {
598
+ "num_themes": payload["num_themes"],
599
+ "themes": {name: info["total_size"] for name, info in payload["themes"].items()},
600
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
601
 
 
602
 
603
+ def _fallback_taxonomy(theme_name: str, keywords: list[str]) -> dict[str, Any]:
604
+ tokens = set(re.findall(r"[a-z]+", f"{theme_name} {' '.join(keywords)}".lower()))
605
+ category_tokens = {
606
+ category: set(re.findall(r"[a-z]+", category.lower()))
607
+ for category in PAJAIS_CATEGORIES
608
+ }
609
+ scored = []
610
+ for category, candidate_tokens in category_tokens.items():
611
+ overlap = len(tokens & candidate_tokens)
612
+ scored.append((category, overlap))
613
+ scored.sort(key=lambda item: item[1], reverse=True)
614
+ best_category, score = scored[0]
615
+ if score == 0:
616
+ return {
617
+ "mapping_type": "NOVEL",
618
+ "pajais_category": None,
619
+ "confidence": 0.45,
620
+ "reasoning": "No direct lexical overlap with PAJAIS categories.",
621
+ }
622
+ return {
623
+ "mapping_type": "MAPPED",
624
+ "pajais_category": best_category,
625
+ "confidence": round(min(0.85, 0.45 + 0.10 * score), 2),
626
+ "reasoning": "Fallback lexical match against PAJAIS categories.",
627
+ }
628
+
629
+
630
+ def compare_with_taxonomy(text_type: str, output_dir: Path = OUTPUT_DIR) -> dict[str, Any]:
631
+ output_dir = _ensure_output_dir(output_dir)
632
+ payload = _read_json(output_dir / f"themes_{text_type}.json")
633
+ themes = payload["themes"]
634
+ taxonomy_map: dict[str, Any] = {}
635
+ pajais_str = "\n".join(f"{index + 1}. {category}" for index, category in enumerate(PAJAIS_CATEGORIES))
636
+
637
+ for theme_name, info in themes.items():
638
+ prompt = f"""
639
+ Map this CHB research theme to the PAJAIS 25-category taxonomy.
640
+
641
+ Theme: {theme_name}
642
+ Member labels: {", ".join(info["member_labels"][:8])}
643
+ Keywords: {", ".join(info["keywords"][:8])}
644
+
645
+ PAJAIS categories:
646
+ {pajais_str}
647
+
648
+ Return JSON only:
649
+ {{
650
+ "mapping_type": "MAPPED or NOVEL",
651
+ "pajais_category": "Category name or null",
652
+ "confidence": 0.0,
653
+ "reasoning": "One short sentence"
654
+ }}
655
+ """
656
+ response = _call_llm_json(prompt, max_tokens=220)
657
+ mapping = response if response else _fallback_taxonomy(theme_name, info["keywords"])
658
  taxonomy_map[theme_name] = {
659
+ "mapping_type": mapping["mapping_type"],
660
+ "pajais_category": mapping.get("pajais_category"),
661
+ "confidence": float(mapping.get("confidence", 0.5)),
662
+ "reasoning": mapping.get("reasoning", ""),
663
+ "size": int(info["total_size"]),
664
+ "member_labels": info["member_labels"],
665
+ "keywords": info["keywords"],
666
+ "topic_ids": info["topic_ids"],
667
  }
668
+
669
+ mapped_count = sum(1 for item in taxonomy_map.values() if item["mapping_type"] == "MAPPED")
 
 
 
670
  novel_count = len(taxonomy_map) - mapped_count
 
671
  result = {
672
  "text_type": text_type,
673
  "total_themes": len(taxonomy_map),
674
  "mapped_count": mapped_count,
675
  "novel_count": novel_count,
676
  "taxonomy_map": taxonomy_map,
677
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
678
  }
679
+ _write_json(output_dir / f"taxonomy_map_{text_type}.json", result)
 
 
 
680
  return {
681
  "mapped_count": mapped_count,
682
  "novel_count": novel_count,
683
+ "mapped_themes": [name for name, info in taxonomy_map.items() if info["mapping_type"] == "MAPPED"],
684
+ "novel_themes": [name for name, info in taxonomy_map.items() if info["mapping_type"] == "NOVEL"],
685
  }
686
 
687
+
688
+ def generate_comparison_csv(output_dir: Path = OUTPUT_DIR) -> dict[str, Any]:
689
+ output_dir = _ensure_output_dir(output_dir)
690
+ abstract_tax = _read_json(output_dir / "taxonomy_map_abstract.json")
691
+ title_tax = _read_json(output_dir / "taxonomy_map_title.json")
692
+ abstract_themes = abstract_tax["taxonomy_map"]
693
+ title_themes = title_tax["taxonomy_map"]
694
+
695
+ normalized_abstract = {_slugify_label(name): name for name in abstract_themes}
696
+ normalized_title = {_slugify_label(name): name for name in title_themes}
697
+ overlap_keys = set(normalized_abstract) & set(normalized_title)
698
+
 
 
 
 
 
 
 
 
 
699
  rows = []
700
+ for norm_key in sorted(set(normalized_abstract) | set(normalized_title)):
701
+ abstract_name = normalized_abstract.get(norm_key)
702
+ title_name = normalized_title.get(norm_key)
703
+ abstract_info = abstract_themes.get(abstract_name, {})
704
+ title_info = title_themes.get(title_name, {})
705
+ rows.append(
706
+ {
707
+ "Normalized_Theme_Key": norm_key,
708
+ "Abstract_Theme": abstract_name or "",
709
+ "Title_Theme": title_name or "",
710
+ "In_Abstracts": "Yes" if abstract_name else "No",
711
+ "In_Titles": "Yes" if title_name else "No",
712
+ "Abstract_Size": abstract_info.get("size", 0),
713
+ "Title_Size": title_info.get("size", 0),
714
+ "Abstract_Mapping": abstract_info.get("mapping_type", ""),
715
+ "Title_Mapping": title_info.get("mapping_type", ""),
716
+ "Abstract_PAJAIS": abstract_info.get("pajais_category", ""),
717
+ "Title_PAJAIS": title_info.get("pajais_category", ""),
718
+ }
719
+ )
720
+
721
+ comparison_df = pd.DataFrame(rows).sort_values(
722
+ ["In_Abstracts", "In_Titles", "Abstract_Size", "Title_Size"],
723
+ ascending=[False, False, False, False],
724
+ )
725
+ comparison_df.to_csv(output_dir / "comparison.csv", index=False, encoding="utf-8-sig")
726
+
727
  result = {
728
+ "total_unique_themes": int(len(rows)),
729
+ "themes_in_both": int(len(overlap_keys)),
730
+ "abstract_only": int(len(set(normalized_abstract) - overlap_keys)),
731
+ "title_only": int(len(set(normalized_title) - overlap_keys)),
732
+ "abstract_only_themes": [normalized_abstract[key] for key in sorted(set(normalized_abstract) - overlap_keys)],
733
+ "title_only_themes": [normalized_title[key] for key in sorted(set(normalized_title) - overlap_keys)],
734
+ "themes_in_both_labels": [
735
+ {
736
+ "normalized_key": key,
737
+ "abstract_theme": normalized_abstract[key],
738
+ "title_theme": normalized_title[key],
739
+ }
740
+ for key in sorted(overlap_keys)
741
+ ],
742
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
743
  }
744
+ _write_json(output_dir / "comparison_summary.json", result)
 
 
 
745
  return result
746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747
 
748
+ def export_narrative(output_dir: Path = OUTPUT_DIR) -> dict[str, Any]:
749
+ output_dir = _ensure_output_dir(output_dir)
750
+ stats = _read_json(output_dir / "data_stats.json")
751
+ abstract_tax = _read_json(output_dir / "taxonomy_map_abstract.json")
752
+ title_tax = _read_json(output_dir / "taxonomy_map_title.json")
753
+ comparison = _read_json(output_dir / "comparison_summary.json")
754
+
755
+ prompt = f"""
756
+ Write a concise 500-word academic results narrative for the CHB BERTopic draft_2 pipeline.
757
+
758
+ Facts to use:
759
+ - Corpus size: {stats['total_papers']} papers
760
+ - Year range: {stats['year_range']}
761
+ - Abstract themes: {abstract_tax['total_themes']}
762
+ - Abstract mapped themes: {abstract_tax['mapped_count']}
763
+ - Abstract novel themes: {abstract_tax['novel_count']}
764
+ - Title themes: {title_tax['total_themes']}
765
+ - Title mapped themes: {title_tax['mapped_count']}
766
+ - Title novel themes: {title_tax['novel_count']}
767
+ - Theme overlap between abstract and title sets: {comparison['themes_in_both']}
768
+
769
+ Requirements:
770
+ 1. Mention SPECTER2, UMAP, HDBSCAN, BERTopic, and PAJAIS.
771
+ 2. Stay factual.
772
+ 3. Do not invent percentages not implied by the data.
773
+ 4. Use simple academic English.
774
+ """
775
+ narrative = _call_llm_text(prompt, max_tokens=900)
776
+ if not narrative:
777
+ narrative = (
778
+ f"This draft_2 BERTopic pipeline analyzed {stats['total_papers']} CHB papers across {stats['year_range']}. "
779
+ "The workflow used SPECTER2 embeddings, UMAP reduction, HDBSCAN clustering, BERTopic topic representation, "
780
+ "and PAJAIS taxonomy mapping. The resulting abstract-side and title-side themes are saved in the output folder "
781
+ "for direct inspection and later paper writing."
782
+ )
783
+ (output_dir / "narrative.txt").write_text(narrative, encoding="utf-8")
784
+ meta = {
785
+ "word_count": len(narrative.split()),
786
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
787
+ }
788
+ _write_json(output_dir / "narrative_meta.json", meta)
789
+ return {"word_count": meta["word_count"], "preview": narrative[:500]}
790
+
791
+
792
+ def run_bertopic_discovery(text_type: str, output_dir: Path = OUTPUT_DIR) -> dict[str, Any]:
793
+ text_type = text_type.lower()
794
+ if text_type not in TEXT_TYPE_SETTINGS:
795
+ raise ValueError("text_type must be 'abstract' or 'title'.")
796
+
797
+ output_dir = _ensure_output_dir(output_dir)
798
+ papers = _load_clean_papers(output_dir)
799
+ settings = TEXT_TYPE_SETTINGS[text_type]
800
+
801
+ analysis_docs = papers["Abstract_Clean"].tolist() if text_type == "abstract" else papers["Title_Clean"].tolist()
802
+ embedder = Specter2Embedder(batch_size=8)
803
+ sep_token = AutoTokenizer.from_pretrained(SPECTER2_BASE_MODEL).sep_token
804
+ embedding_texts = _prepare_embedding_text(papers, text_type, sep_token)
805
+ embeddings = embedder.encode(embedding_texts, cache_path=output_dir / f"embeddings_{text_type}.npy")
806
+
807
+ topic_model = _build_topic_model(text_type)
808
+ topics, _ = topic_model.fit_transform(analysis_docs, embeddings)
809
+
810
+ noise_rate = float(sum(topic_id == -1 for topic_id in topics) / len(topics))
811
+ discovered_topics = len(set(topic_id for topic_id in topics if topic_id != -1))
812
+ if noise_rate > 0.10 and discovered_topics >= 10:
813
+ reduced_topics = topic_model.reduce_outliers(
814
+ analysis_docs,
815
+ topics,
816
+ embeddings=embeddings,
817
+ strategy="embeddings",
818
+ )
819
+ if reduced_topics != topics:
820
+ topics = reduced_topics
821
+ topic_model.update_topics(
822
+ analysis_docs,
823
+ topics=topics,
824
+ vectorizer_model=topic_model.vectorizer_model,
825
+ ctfidf_model=topic_model.ctfidf_model,
826
+ )
827
+
828
+ topic_info = topic_model.get_topic_info()
829
+ representative_docs = _representative_docs_map(topic_model)
830
+
831
+ assignment_df = pd.DataFrame(
832
+ {
833
+ "paper_id": papers["Sr No"],
834
+ "year": papers["Year"],
835
+ "cited_by": papers["Cited by"],
836
+ "title": papers["Title_Clean"],
837
+ "text": analysis_docs,
838
+ "topic": topics,
839
+ }
840
+ )
841
+ assignment_df["topic_size"] = assignment_df["topic"].map(topic_info.set_index("Topic")["Count"]).fillna(0).astype(int)
842
+ assignment_df.to_csv(output_dir / f"topic_assignments_{text_type}.csv", index=False, encoding="utf-8-sig")
843
+
844
+ topic_rows = []
845
+ for _, row in topic_info.iterrows():
846
+ topic_id = int(row["Topic"])
847
+ topic_rows.append(
848
+ {
849
+ "topic_id": topic_id,
850
+ "count": int(row["Count"]),
851
+ "name": row.get("Name", ""),
852
+ "keywords": ", ".join(_topic_keywords(topic_model, topic_id)) if topic_id != -1 else "",
853
+ "representative_doc_1": representative_docs.get(topic_id, [""])[0] if representative_docs.get(topic_id) else "",
854
+ }
855
+ )
856
+ pd.DataFrame(topic_rows).to_csv(output_dir / f"topic_info_{text_type}.csv", index=False, encoding="utf-8-sig")
857
+
858
+ topic_model.save(output_dir / f"bertopic_model_{text_type}", serialization="safetensors", save_ctfidf=True)
859
+
860
+ silhouette = _compute_silhouette(embeddings, topics)
861
+ quality = {
862
+ "text_type": text_type,
863
+ "total_documents": int(len(analysis_docs)),
864
+ "num_topics_excluding_noise": int(sum(topic_id != -1 for topic_id in topic_info["Topic"])),
865
+ "noise_documents": int(sum(topic_id == -1 for topic_id in topics)),
866
+ "noise_rate": round(float(sum(topic_id == -1 for topic_id in topics) / len(topics)), 4),
867
+ "largest_topic_size": int(topic_info[topic_info["Topic"] != -1]["Count"].max()) if (topic_info["Topic"] != -1).any() else 0,
868
+ "topic_diversity": round(_compute_topic_diversity(topic_model), 4),
869
+ "silhouette_sample": round(silhouette, 4) if silhouette is not None else None,
870
+ "umap_n_neighbors": settings["umap_n_neighbors"],
871
+ "hdbscan_min_cluster_size": settings["hdbscan_min_cluster_size"],
872
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
873
+ }
874
+ _write_json(output_dir / f"quality_{text_type}.json", quality)
875
+
876
+ summary_topics = topic_info[topic_info["Topic"] != -1].head(10)
877
+ summaries = {}
878
+ for _, row in summary_topics.iterrows():
879
+ topic_id = int(row["Topic"])
880
+ summaries[str(topic_id)] = {
881
+ "size": int(row["Count"]),
882
+ "keywords": _topic_keywords(topic_model, topic_id),
883
+ "sample": (representative_docs.get(topic_id, [""])[0] or "")[:200],
884
+ }
885
+
886
+ payload = {
887
+ "column": "Abstract" if text_type == "abstract" else "Title",
888
+ "text_type": text_type,
889
+ "total_texts": int(len(analysis_docs)),
890
+ "num_topics": int(sum(topic_info["Topic"] != -1)),
891
+ "top_10_topics": summaries,
892
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
893
+ }
894
+ _write_json(output_dir / f"summaries_{text_type}.json", payload)
895
+ return payload
896
+
897
+
898
+ def label_topics_with_llm(text_type: str, output_dir: Path = OUTPUT_DIR) -> dict[str, Any]:
899
+ output_dir = _ensure_output_dir(output_dir)
900
+ topic_model = BERTopic.load(output_dir / f"bertopic_model_{text_type}")
901
+ payload = _relabel_topics_with_fallback(topic_model, text_type, output_dir)
902
+ return {
903
+ "num_labeled": payload["num_labeled"],
904
+ "sample_labels": {
905
+ topic_id: info["label"]
906
+ for topic_id, info in list(payload["topics"].items())[:10]
907
+ },
908
+ }
909
+
910
+
911
+ def run_full_pipeline(file_path: str | None = None, output_dir: Path = OUTPUT_DIR) -> dict[str, Any]:
912
+ output_dir = _ensure_output_dir(output_dir)
913
+ input_path = file_path or str(DEFAULT_INPUT_CSV)
914
+ stats = load_scopus_csv(input_path, output_dir=output_dir)
915
+ abstract = run_bertopic_discovery("abstract", output_dir=output_dir)
916
+ title = run_bertopic_discovery("title", output_dir=output_dir)
917
+ abstract_labels = label_topics_with_llm("abstract", output_dir=output_dir)
918
+ title_labels = label_topics_with_llm("title", output_dir=output_dir)
919
+ abstract_themes = consolidate_into_themes("abstract", TEXT_TYPE_SETTINGS["abstract"]["target_themes"], output_dir)
920
+ title_themes = consolidate_into_themes("title", TEXT_TYPE_SETTINGS["title"]["target_themes"], output_dir)
921
+ abstract_taxonomy = compare_with_taxonomy("abstract", output_dir=output_dir)
922
+ title_taxonomy = compare_with_taxonomy("title", output_dir=output_dir)
923
+ comparison = generate_comparison_csv(output_dir=output_dir)
924
+ narrative = export_narrative(output_dir=output_dir)
925
+
926
+ manifest = {
927
+ "input_file": str(input_path),
928
+ "output_dir": str(output_dir),
929
+ "method": {
930
+ "topic_model": "BERTopic",
931
+ "embedding_model": "SPECTER2",
932
+ "embedding_input_title_abstract_for_abstract_run": True,
933
+ "embedding_input_title_only_for_title_run": True,
934
+ "dimension_reduction": "UMAP",
935
+ "clustering": "HDBSCAN",
936
+ "llm_backend": OLLAMA_MODEL,
937
+ },
938
+ "stats": stats,
939
+ "abstract": abstract,
940
+ "title": title,
941
+ "abstract_labels": abstract_labels,
942
+ "title_labels": title_labels,
943
+ "abstract_themes": abstract_themes,
944
+ "title_themes": title_themes,
945
+ "abstract_taxonomy": abstract_taxonomy,
946
+ "title_taxonomy": title_taxonomy,
947
+ "comparison": comparison,
948
+ "narrative": narrative,
949
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
950
+ }
951
+ _write_json(output_dir / "run_manifest.json", manifest)
952
+ return manifest