bano1 commited on
Commit
2bd8d2e
·
verified ·
1 Parent(s): a0e69bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +215 -423
app.py CHANGED
@@ -2,531 +2,323 @@
2
  import streamlit as st
3
  import os
4
  import pandas as pd
5
- import fitz # PyMuPDF for PDF parsing
6
  from gensim import corpora, models
7
  from gensim.utils import simple_preprocess
8
  from wordcloud import WordCloud, STOPWORDS
9
  import matplotlib.pyplot as plt
10
  from keybert import KeyBERT
11
- from deep_translator import GoogleTranslator
12
  import networkx as nx
13
  import plotly.graph_objects as go
14
- import io
15
- import bibtexparser
16
- from nltk.corpus import stopwords
17
- from groq import Groq
18
- client = Groq(api_key=st.secrets["GROQ_API_KEY"])
19
  import re
20
  import nltk
 
 
 
21
 
22
  # ================== CONFIG ==================
23
  st.set_page_config(page_title="LitReviewAI", page_icon="📚", layout="wide")
24
  st.title("📚 LitReviewAI: Automated Research Paper Reviewer")
25
 
26
- # ================== GLOBALS ==================
 
 
27
  from sentence_transformers import SentenceTransformer
28
  embedding_model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
29
  kw_model = KeyBERT(model=embedding_model)
30
 
 
31
  if "papers" not in st.session_state:
32
- st.session_state.papers = [] # store metadata & results
 
33
  if "collections" not in st.session_state:
34
  st.session_state.collections = {}
35
 
36
- # ensure nltk stopwords present
37
- nltk.download('stopwords')
 
 
 
38
  stop_words = set(stopwords.words("english"))
39
 
40
- # ================== HELPERS ==================
 
 
 
 
 
 
 
 
 
41
  def extract_text_from_pdf(pdf_file):
42
- """Extract all text from PDF. Resets pointer outside if needed."""
43
  data = pdf_file.read()
44
  pdf_file.seek(0)
45
  with fitz.open(stream=data, filetype="pdf") as doc:
46
- text = ""
47
- for page in doc:
48
- text += page.get_text("text")
49
- return text
50
-
51
 
52
  def extract_title(text):
53
- """Extracts paper title (before Abstract), avoiding citations and irrelevant headers."""
54
  lines = [l.strip() for l in text.split("\n") if l.strip()]
 
55
 
56
- # Find index of "Abstract" (case-insensitive) or common translations
57
- abs_index = None
58
- for i, line in enumerate(lines):
59
- low = line.lower()
60
- if low.startswith("abstract") or any(k in low for k in ["résumé", "resumen", "summary", "overview", "abstract—"]):
61
- abs_index = i
62
- break
63
-
64
- # If Abstract found, check lines before abstract; else check top area
65
- if abs_index is not None:
66
- candidate_lines = lines[:abs_index]
67
- else:
68
- candidate_lines = lines[:100]
69
-
70
- skip_words = ["journal", "doi", "copyright", "arxiv", "volume",
71
- "methods", "open access", "citation", "editor", "published"]
72
-
73
- candidates = []
74
- for line in candidate_lines:
75
- low = line.lower()
76
- # Skip unwanted lines
77
- if any(w in low for w in skip_words):
78
- continue
79
- # Skip author-like lists (many commas) or emails
80
- if "@" in line or re.search(r"\bjournal\b", low):
81
- continue
82
- # Skip short/very long lines
83
- if 5 <= len(line.split()) <= 30:
84
- # avoid lines that look like "Editor: Name" etc
85
- if re.match(r"^(editor|edited by|edited).+", low):
86
- continue
87
- candidates.append(line)
88
-
89
- # Prefer line with colon (typical title: subtitle)
90
- for line in candidates:
91
- if ":" in line:
92
- return line
93
-
94
- # fallback: longest candidate
95
- if candidates:
96
- return max(candidates, key=len)
97
- return "Untitled"
98
-
99
-
100
- def extract_authors(text, max_scan_lines=80):
101
- """
102
- Flexible author extraction:
103
- - Finds a likely title, then scans the following lines looking for names.
104
- - Handles comma-separated authors on one line or names on separate lines.
105
- """
106
- lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
107
- authors = []
108
-
109
- # 1) find a likely title index (first reasonably long line)
110
- title_idx = None
111
- for i, line in enumerate(lines[:40]):
112
- if len(line.split()) >= 4 and not any(k in line.lower() for k in ["journal", "doi", "copyright", "arxiv"]):
113
- title_idx = i
114
- break
115
- start = title_idx + 1 if title_idx is not None else 0
116
-
117
- # 2) scan lines after title until we hit abstract/keywords or a limit
118
- abstract_markers = ["abstract", "résumé", "resumen", "summary", "overview", "introduction", "keywords"]
119
- for line in lines[start:start + max_scan_lines]:
120
- low = line.lower()
121
- if any(m in low for m in abstract_markers):
122
- break
123
-
124
- # If line contains commas or " and ", likely multiple authors
125
- if "," in line or " and " in low or ";" in line:
126
- parts = re.split(r",|;|\sand\s", line)
127
- for part in parts:
128
- part = part.strip()
129
- if not part:
130
- continue
131
- # match typical name patterns: "First Last", "First M. Last", "Last, First"
132
- # handle "Last, First" by swapping
133
- if re.match(r"^[A-Z][a-z]+,\s*[A-Z][a-z]+", part):
134
- # swap "Last, First" -> "First Last"
135
- t = re.split(r",\s*", part)
136
- name = t[1] + " " + t[0]
137
- else:
138
- name = part
139
-
140
- # require at least two capitalized tokens to be considered a name
141
- cap_tokens = [t for t in name.split() if re.match(r"^[A-Z][a-z]+\.?$", t) or re.match(r"^[A-Z]\.$", t)]
142
- if len(cap_tokens) >= 2 and not looks_like_affiliation(name):
143
- authors.append(name)
144
- if authors:
145
- continue
146
- else:
147
- # attempt single-line name extraction
148
- matches = re.findall(r'\b[A-Z][a-z]+(?:\s[A-Z]\.?\s?[A-Z][a-z]+){0,2}\b', line)
149
- for m in matches:
150
- if len(m.split()) >= 2 and not looks_like_affiliation(m):
151
- authors.append(m)
152
-
153
- # 3) fallback: check metadata-like "By X Y" lines
154
- if not authors:
155
- for line in lines[:40]:
156
- m = re.match(r"^(By|BY|by)\s+(.+)$", line)
157
- if m:
158
- parts = re.split(r",|;|\sand\s", m.group(2))
159
- for p in parts:
160
- p = p.strip()
161
- if p and not looks_like_affiliation(p):
162
- authors.append(p)
163
- if authors:
164
- break
165
-
166
- return authors if authors else ["Unknown"]
167
-
168
-
169
- AFFIL_KEYWORDS = [
170
- "university", "institute", "department", "school", "hospital",
171
- "clinic", "center", "centre", "laboratory", "lab", "college",
172
- "medicine", "research", "faculty", "division", "program", "department of"
173
- ]
174
-
175
- def looks_like_affiliation(line):
176
- low = line.lower()
177
- if any(k in low for k in AFFIL_KEYWORDS):
178
- return True
179
- if "@" in line or "http" in low or "www." in low:
180
- return True
181
- # if line has few capitalized tokens relative to total tokens, it's likely not a name
182
- toks = [t for t in line.split() if t.strip()]
183
- if len(toks) == 0:
184
- return True
185
- cap = sum(1 for t in toks if re.match(r"^[A-Z][a-z]+$", t))
186
- if cap / len(toks) < 0.4:
187
- return True
188
- return False
189
-
190
 
191
  def extract_abstract(text):
192
- """Extract abstract block (multiple formats supported). Gathers until next main heading."""
193
- lines = text.split("\n")
194
- abstract_lines = []
195
- capture = False
196
- abstract_markers = ["abstract", "résumé", "resumen", "summary", "overview"]
197
- stop_markers = ["introduction", "keywords", "1.", "methods", "materials", "results", "conclusion", "references"]
198
-
199
- for line in lines:
200
- l = line.lower().strip()
201
- if any(m in l for m in abstract_markers):
202
- capture = True
203
- continue
204
- if capture:
205
- # stop when a common section heading appears
206
- if any(re.match(rf"^{sm}\b", l) for sm in stop_markers):
207
- break
208
- abstract_lines.append(line.strip())
209
- abstract = " ".join(abstract_lines).strip()
210
- return abstract
211
-
212
 
213
  def extract_metadata(pdf_file):
214
- """Extract title, authors, abstract from PDF file-like object."""
215
  text = extract_text_from_pdf(pdf_file)
216
- title = extract_title(text)
217
- authors = extract_authors(text)
218
- abstract = extract_abstract(text)
219
- return {"title": title or "Untitled", "authors": authors, "abstract": abstract or ""}
 
220
 
221
-
222
- # ---- LLM helpers: summarization, sections, gaps, limitations ----
223
  def get_summary(text):
224
- """Simple summary of abstract (concise)."""
225
  if not text:
226
  return "No abstract available."
227
- prompt = f"""
228
- You are an academic assistant. Summarize the abstract concisely in 3-5 sentences, focusing on contributions, methods and main findings. Use simple language suitable for a researcher.
229
- Abstract:
230
- {text}
231
- """
232
- response = client.chat.completions.create(
233
  model="llama-3.1-8b-instant",
234
- messages=[{"role": "user", "content": prompt}]
 
235
  )
236
- return response.choices[0].message.content.strip()
237
 
238
- def chunk_text(text, max_chars=4000):
239
- """Split text into smaller parts safely for Groq API."""
240
- return [text[i:i + max_chars] for i in range(0, len(text), max_chars)]
241
 
242
- def get_section_summaries(text):
243
- summaries = []
244
- chunks = chunk_text(text)
245
- for chunk in chunks:
246
- response = client.chat.completions.create(
247
- model="llama-3.1-8b-instant",
248
- messages=[{"role": "user", "content": f"Summarize this section:\n{chunk}"}],
249
- temperature=0.3,
250
- )
251
- summaries.append(response.choices[0].message.content)
252
- return "\n\n".join(summaries)
253
 
254
  def get_limitations(text):
255
  if not text:
256
  return "No abstract available."
257
- prompt = f"Extract only the limitations or challenges discussed in this abstract (if any). If none, write 'No explicit limitations mentioned'.\n\n{text}"
258
- response = client.chat.completions.create(
 
 
259
  model="llama-3.1-8b-instant",
260
- messages=[{"role": "user", "content": prompt}]
261
  )
262
- return response.choices[0].message.content.strip()
 
 
263
 
264
  def get_research_gaps(text):
265
- """Return 2-4 potential research gaps based on abstract."""
266
  if not text:
267
  return "No abstract available."
268
- prompt = f"""
269
- You are a research assistant. Based on this abstract, list 2–4 realistic research gaps or unexplored questions that follow logically from the study. Provide concise bullet points.
270
- Abstract:
271
- {text}
272
- """
273
- response = client.chat.completions.create(
274
  model="llama-3.1-8b-instant",
275
- messages=[{"role": "user", "content": prompt}]
276
  )
277
- return response.choices[0].message.content.strip()
 
278
 
279
 
280
- # ========== LDA TOPIC MODELING ==========
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  def lda_topic_modeling(papers, num_topics=3):
282
- # Preprocess abstracts with stopword removal
283
  texts = [
284
- [word for word in simple_preprocess(p["abstract"]) if word not in stop_words]
285
  for p in papers if p.get("abstract")
286
  ]
287
- # Guard: if no texts or empty docs
288
- if not texts or all(len(t) == 0 for t in texts):
289
- return pd.DataFrame([])
290
 
291
  dictionary = corpora.Dictionary(texts)
292
- corpus = [dictionary.doc2bow(text) for text in texts]
293
- lda_model = models.LdaModel(corpus, num_topics=num_topics, id2word=dictionary, passes=10)
294
 
295
- topics = lda_model.print_topics(num_words=6)
296
- topic_data = []
297
- for topic_id, words in topics:
298
- topic_data.append({"Topic ID": topic_id, "Keywords": words})
299
- df = pd.DataFrame(topic_data)
300
- return df
301
 
 
 
 
 
302
 
303
- # ========== WORDCLOUD ==========
304
  def generate_wordcloud(papers):
305
- text = " ".join([p.get("abstract", "") for p in papers if p.get("abstract")])
306
- if not text:
307
- st.info("No abstracts to build a word cloud.")
 
308
  return
309
 
310
- custom_stopwords = set(STOPWORDS).union(stop_words)
311
  wc = WordCloud(
312
  width=800,
313
  height=400,
314
- stopwords=custom_stopwords,
315
- background_color="white",
316
- colormap="viridis"
317
  ).generate(text)
318
 
319
  fig, ax = plt.subplots()
320
- ax.imshow(wc, interpolation="bilinear")
321
  ax.axis("off")
322
  st.pyplot(fig)
323
 
324
-
325
- # ========== CO-AUTHOR GRAPH ==========
326
  def build_coauthor_graph(papers):
327
  G = nx.Graph()
328
 
329
  for p in papers:
330
- authors = p.get("authors", ["Unknown"])
331
- # normalize
332
- authors = [a.strip() for a in authors if a and isinstance(a, str)]
333
- # filter obvious affiliation tokens
334
- authors = [a for a in authors if not looks_like_affiliation(a) and a.lower() != "unknown"]
335
-
336
- # add nodes
337
- for a in authors:
338
  G.add_node(a)
339
 
340
- # add edges (with weight)
341
- for i in range(len(authors)):
342
- for j in range(i + 1, len(authors)):
343
- u, v = authors[i], authors[j]
344
- if G.has_edge(u, v):
345
- G[u][v]['weight'] += 1
346
- else:
347
- G.add_edge(u, v, weight=1)
348
-
349
- if G.number_of_nodes() == 0:
350
- st.info("No author data available to build co-author graph.")
351
- return
352
-
353
- pos = nx.spring_layout(G, seed=42)
354
- edge_x, edge_y = [], []
355
- for u, v, data in G.edges(data=True):
356
- x0, y0 = pos[u]
357
- x1, y1 = pos[v]
358
- edge_x += [x0, x1, None]
359
- edge_y += [y0, y1, None]
360
-
361
- node_x, node_y, node_text = [], [], []
362
- for n in G.nodes():
363
- x, y = pos[n]
364
- node_x.append(x); node_y.append(y); node_text.append(n)
365
 
366
  fig = go.Figure()
367
- fig.add_trace(go.Scatter(
368
- x=edge_x, y=edge_y, mode='lines',
369
- line=dict(width=0.5, color='#888'),
370
- hoverinfo='none'
371
- ))
372
- fig.add_trace(go.Scatter(
373
- x=node_x, y=node_y, mode='markers+text',
374
- text=node_text, textposition="top center",
375
- marker=dict(size=12, color='skyblue')
376
- ))
377
- st.plotly_chart(fig, use_container_width=True)
378
-
379
-
380
- # ========== BIBTEX EXPORT ==========
381
- def export_bibtex(papers):
382
- db = {"entries": []}
383
- for i, p in enumerate(papers):
384
- title = p.get("title") or f"paper_{i}"
385
- authors = " and ".join(p.get("authors", ["Unknown"]))
386
- entry = {
387
- "ENTRYTYPE": "article",
388
- "ID": re.sub(r"\s+", "_", title)[:80],
389
- "title": title,
390
- "author": authors,
391
- "year": p.get("year", "2025"),
392
- "abstract": p.get("abstract", "")
393
- }
394
- db["entries"].append(entry)
395
- return bibtexparser.dumps(db)
396
-
397
-
398
- # ================== UI / TABS ==================
399
- tabs = st.tabs(["ℹ️ About", "📤 Upload Papers", "📑 Paper Summaries",
400
- "📊 Topic Modeling", "📂 Collections", "⚡ Trends & Insights", "💬 Chat with Papers"])
401
-
402
- # --- About ---
403
  with tabs[0]:
404
- st.header("About LitReviewAI")
405
- st.write("""
406
- **LitReviewAI** helps researchers save time by:
407
- - Uploading and analyzing research papers
408
- - Extracting abstracts, keywords, and authors
409
- - Generating AI-powered summaries, limitations, and research gaps
410
- - Providing section-wise highlights (Intro / Methods / Results / Conclusions)
411
- - Chatting interactively with your papers
412
- - Building collaboration networks and topic clusters
413
- - Exporting citations in BibTeX format
414
- """)
415
-
416
- # --- Upload ---
417
- with tabs[1]:
418
- st.header("Upload PDFs")
419
- uploaded_files = st.file_uploader("Upload research papers (PDF)", type="pdf", accept_multiple_files=True)
420
- if uploaded_files:
421
- for file in uploaded_files:
422
- file.seek(0)
423
- meta = extract_metadata(file)
424
- # section-wise summary (model may be slower; optional)
425
- text_for_sections = extract_text_from_pdf(file)
426
- meta["section_summary"] = get_section_summaries(text_for_sections)
427
- meta["summary"] = get_summary(meta.get("abstract", ""))
428
- meta["limitations"] = get_limitations(meta.get("abstract", ""))
429
- meta["research_gaps"] = get_research_gaps(meta.get("abstract", ""))
430
- # Extract keywords
431
- try:
432
- keywords = kw_model.extract_keywords(meta.get("abstract", ""), top_n=5)
433
- meta["keywords"] = ", ".join([kw[0] for kw in keywords]) if keywords else ""
434
- except Exception:
435
- meta["keywords"] = ""
436
  st.session_state.papers.append(meta)
437
- st.success("Papers processed and added!")
438
 
439
- # --- Summaries ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  with tabs[2]:
441
- st.header("Paper Summaries")
442
- if st.session_state.papers:
443
- for i, paper in enumerate(st.session_state.papers, start=1):
444
- with st.expander(f"📄 {i}. {paper.get('title', 'Untitled')}"):
445
- st.markdown(f"**Authors:** {', '.join(paper.get('authors', ['Unknown']))}")
446
- st.markdown(f"**Summary:** {paper.get('summary', 'N/A')}")
447
- st.markdown(f"**Limitations:** {paper.get('limitations', 'N/A')}")
448
- st.markdown(f"**Research Gaps:** {paper.get('research_gaps', 'N/A')}")
449
- st.markdown("**Section-wise highlights (raw):**")
450
- st.code(paper.get('section_summary', 'N/A'))
451
- st.markdown(f"**Keywords:** {paper.get('keywords', 'N/A')}")
452
- else:
453
- st.info("Upload papers first.")
454
 
455
- if st.session_state.papers:
456
- df = pd.DataFrame(st.session_state.papers).astype(str)
457
- st.dataframe(df[["title", "summary", "research_gaps", "keywords"]])
458
- st.download_button("Download CSV", df.to_csv().encode("utf-8"), "summaries.csv")
459
- st.download_button("Download JSON", df.to_json(indent=2).encode("utf-8"), "summaries.json")
460
- st.download_button("Export BibTeX", export_bibtex(st.session_state.papers), "papers.bib")
461
 
462
- # --- Topic Modeling ---
 
 
463
  with tabs[3]:
464
- st.header("Topic Modeling & Word Cloud")
465
- if st.session_state.papers:
466
- topics_df = lda_topic_modeling(st.session_state.papers)
467
- if not topics_df.empty:
468
- st.dataframe(topics_df)
469
- else:
470
- st.info("Not enough text to build topics.")
471
- generate_wordcloud(st.session_state.papers)
472
- else:
473
- st.info("Upload papers first.")
474
 
475
- # --- Collections ---
 
 
 
 
 
 
476
  with tabs[4]:
477
- st.header("Collections")
478
- if st.session_state.papers:
479
- collection_name = st.text_input("Collection name")
480
- if st.button("Save to Collection") and collection_name:
481
- st.session_state.collections[collection_name] = st.session_state.papers.copy()
482
- st.success(f"Saved {len(st.session_state.papers)} papers to {collection_name}")
483
- if st.session_state.collections:
484
- st.write(list(st.session_state.collections.keys()))
485
- else:
486
- st.info("Upload papers first.")
487
 
488
- # --- Trends & Insights ---
489
  with tabs[5]:
490
- st.header("Trends & Insights")
491
- if st.session_state.papers:
492
- st.markdown("### Co-author Collaboration Network")
493
- build_coauthor_graph(st.session_state.papers)
494
-
495
- st.markdown("### Quick stats")
496
- # simple stats: number of papers, unique authors
497
- num_papers = len(st.session_state.papers)
498
- all_authors = []
499
- for p in st.session_state.papers:
500
- all_authors.extend([a for a in p.get("authors", []) if a and a.lower() != "unknown"])
501
- unique_authors = sorted(set(all_authors))
502
- st.write(f"Papers: **{num_papers}** — Unique authors: **{len(unique_authors)}**")
503
- if unique_authors:
504
- st.write(", ".join(unique_authors[:20]) + ("" if len(unique_authors) <= 20 else ", ..."))
505
- else:
506
- st.info("Upload papers first.")
507
 
508
- # --- Chat with Papers ---
509
- with tabs[6]:
510
- st.header("💬 Chat with Your Papers")
511
  if st.session_state.papers:
512
- combined_abstracts = "\n\n".join([p.get("abstract", "") for p in st.session_state.papers if p.get("abstract")])
513
- st.write("You can ask questions about the collection of uploaded abstracts.")
514
- user_q = st.text_area("Ask a question", height=120)
515
- if st.button("Ask"):
516
- if not user_q.strip():
517
- st.warning("Please type a question.")
518
- else:
519
- prompt = f"""You are an academic assistant. Use the following abstracts as context and answer the question concisely and precisely. If the required info is not available in the abstracts, say you don't have enough info.
520
- Context (abstracts):
521
- {combined_abstracts}
 
 
 
 
 
522
  Question:
523
  {user_q}
 
524
  """
525
- response = client.chat.completions.create(
526
- model="llama-3.1-8b-instant",
527
- messages=[{"role": "user", "content": prompt}]
528
- )
529
- st.markdown("### 🧠 Answer:")
530
- st.write(response.choices[0].message.content.strip())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  else:
532
- st.info("Upload papers first.")
 
2
  import streamlit as st
3
  import os
4
  import pandas as pd
5
+ import fitz # PyMuPDF
6
  from gensim import corpora, models
7
  from gensim.utils import simple_preprocess
8
  from wordcloud import WordCloud, STOPWORDS
9
  import matplotlib.pyplot as plt
10
  from keybert import KeyBERT
 
11
  import networkx as nx
12
  import plotly.graph_objects as go
 
 
 
 
 
13
  import re
14
  import nltk
15
+ import time
16
+ from nltk.corpus import stopwords
17
+ from groq import Groq
18
 
19
  # ================== CONFIG ==================
20
  st.set_page_config(page_title="LitReviewAI", page_icon="📚", layout="wide")
21
  st.title("📚 LitReviewAI: Automated Research Paper Reviewer")
22
 
23
+ client = Groq(api_key=st.secrets["GROQ_API_KEY"])
24
+
25
+ # ================== MODELS ==================
26
  from sentence_transformers import SentenceTransformer
27
  embedding_model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
28
  kw_model = KeyBERT(model=embedding_model)
29
 
30
+ # ================== STATE ==================
31
  if "papers" not in st.session_state:
32
+ st.session_state.papers = []
33
+
34
  if "collections" not in st.session_state:
35
  st.session_state.collections = {}
36
 
37
+ if "chat_history" not in st.session_state:
38
+ st.session_state.chat_history = []
39
+
40
+ # ================== NLTK ==================
41
+ nltk.download("stopwords")
42
  stop_words = set(stopwords.words("english"))
43
 
44
+ # ================== RATE LIMIT PROTECTION ==================
45
+ _last_call = 0
46
+ def throttle():
47
+ global _last_call
48
+ now = time.time()
49
+ if now - _last_call < 1.2:
50
+ time.sleep(1.2)
51
+ _last_call = time.time()
52
+
53
+ # ================== PDF EXTRACTION ==================
54
  def extract_text_from_pdf(pdf_file):
 
55
  data = pdf_file.read()
56
  pdf_file.seek(0)
57
  with fitz.open(stream=data, filetype="pdf") as doc:
58
+ return "\n".join(page.get_text() for page in doc)
 
 
 
 
59
 
60
  def extract_title(text):
 
61
  lines = [l.strip() for l in text.split("\n") if l.strip()]
62
+ return lines[0] if lines else "Untitled"
63
 
64
+ def extract_authors(text):
65
+ return ["Unknown"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  def extract_abstract(text):
68
+ return text[:1500]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  def extract_metadata(pdf_file):
 
71
  text = extract_text_from_pdf(pdf_file)
72
+ return {
73
+ "title": extract_title(text),
74
+ "authors": extract_authors(text),
75
+ "abstract": extract_abstract(text),
76
+ }
77
 
78
+ # ================== LLM HELPERS ==================
 
79
  def get_summary(text):
 
80
  if not text:
81
  return "No abstract available."
82
+
83
+ throttle()
84
+
85
+ prompt = f"Summarize this abstract in 3-5 sentences:\n\n{text}"
86
+
87
+ res = client.chat.completions.create(
88
  model="llama-3.1-8b-instant",
89
+ messages=[{"role": "user", "content": prompt}],
90
+ temperature=0.3,
91
  )
 
92
 
93
+ return res.choices[0].message.content.strip()
 
 
94
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  def get_limitations(text):
97
  if not text:
98
  return "No abstract available."
99
+
100
+ throttle()
101
+
102
+ res = client.chat.completions.create(
103
  model="llama-3.1-8b-instant",
104
+ messages=[{"role": "user", "content": f"Extract limitations:\n{text}"}]
105
  )
106
+
107
+ return res.choices[0].message.content.strip()
108
+
109
 
110
  def get_research_gaps(text):
 
111
  if not text:
112
  return "No abstract available."
113
+
114
+ throttle()
115
+
116
+ res = client.chat.completions.create(
 
 
117
  model="llama-3.1-8b-instant",
118
+ messages=[{"role": "user", "content": f"List research gaps:\n{text}"}]
119
  )
120
+
121
+ return res.choices[0].message.content.strip()
122
 
123
 
124
+ def get_section_summaries(text):
125
+ throttle()
126
+
127
+ chunks = text[:6000]
128
+
129
+ res = client.chat.completions.create(
130
+ model="llama-3.1-8b-instant",
131
+ messages=[{
132
+ "role": "user",
133
+ "content": f"Summarize sections:\n{chunks}"
134
+ }],
135
+ temperature=0.3,
136
+ )
137
+
138
+ return res.choices[0].message.content.strip()
139
+
140
+ # ================== TOPIC MODEL ==================
141
  def lda_topic_modeling(papers, num_topics=3):
 
142
  texts = [
143
+ [w for w in simple_preprocess(p["abstract"]) if w not in stop_words]
144
  for p in papers if p.get("abstract")
145
  ]
146
+
147
+ if not texts:
148
+ return pd.DataFrame()
149
 
150
  dictionary = corpora.Dictionary(texts)
151
+ corpus = [dictionary.doc2bow(t) for t in texts]
 
152
 
153
+ lda = models.LdaModel(corpus, num_topics=num_topics, id2word=dictionary, passes=10)
 
 
 
 
 
154
 
155
+ return pd.DataFrame([
156
+ {"Topic": i, "Keywords": words}
157
+ for i, words in lda.print_topics()
158
+ ])
159
 
160
+ # ================== WORDCLOUD ==================
161
  def generate_wordcloud(papers):
162
+ text = " ".join([p.get("abstract", "") for p in papers])
163
+
164
+ if not text.strip():
165
+ st.info("No text for wordcloud")
166
  return
167
 
 
168
  wc = WordCloud(
169
  width=800,
170
  height=400,
171
+ stopwords=STOPWORDS.union(stop_words),
172
+ background_color="white"
 
173
  ).generate(text)
174
 
175
  fig, ax = plt.subplots()
176
+ ax.imshow(wc)
177
  ax.axis("off")
178
  st.pyplot(fig)
179
 
180
+ # ================== GRAPH ==================
 
181
  def build_coauthor_graph(papers):
182
  G = nx.Graph()
183
 
184
  for p in papers:
185
+ for a in p.get("authors", ["Unknown"]):
 
 
 
 
 
 
 
186
  G.add_node(a)
187
 
188
+ pos = nx.spring_layout(G)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
  fig = go.Figure()
191
+ st.plotly_chart(fig)
192
+
193
+ # ================== UI ==================
194
+ tabs = st.tabs([
195
+ "Upload",
196
+ "Summaries",
197
+ "Topics",
198
+ "Collections",
199
+ "Trends",
200
+ "Chat AI"
201
+ ])
202
+
203
+ # ================== UPLOAD ==================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  with tabs[0]:
205
+ st.header("Upload Papers")
206
+
207
+ files = st.file_uploader("Upload PDFs", type="pdf", accept_multiple_files=True)
208
+
209
+ if files:
210
+ for f in files:
211
+ meta = extract_metadata(f)
212
+ text = extract_text_from_pdf(f)
213
+
214
+ meta["section_summary"] = "Click to generate"
215
+ meta["summary"] = "Click to generate"
216
+ meta["limitations"] = "Click to generate"
217
+ meta["research_gaps"] = "Click to generate"
218
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  st.session_state.papers.append(meta)
 
220
 
221
+ st.success("Uploaded successfully")
222
+
223
+ # ================== SUMMARIES ==================
224
+ with tabs[1]:
225
+ st.header("Paper Insights")
226
+
227
+ for i, p in enumerate(st.session_state.papers):
228
+
229
+ with st.expander(p["title"]):
230
+
231
+ if st.button(f"Generate Summary {i}"):
232
+ p["summary"] = get_summary(p["abstract"])
233
+ st.rerun()
234
+
235
+ if st.button(f"Generate Section Summary {i}"):
236
+ p["section_summary"] = get_section_summaries(p["abstract"])
237
+ st.rerun()
238
+
239
+ if st.button(f"Generate Limitations {i}"):
240
+ p["limitations"] = get_limitations(p["abstract"])
241
+ st.rerun()
242
+
243
+ if st.button(f"Generate Gaps {i}"):
244
+ p["research_gaps"] = get_research_gaps(p["abstract"])
245
+ st.rerun()
246
+
247
+ st.write("Summary:", p.get("summary"))
248
+ st.write("Limitations:", p.get("limitations"))
249
+ st.write("Gaps:", p.get("research_gaps"))
250
+ st.write("Section:", p.get("section_summary"))
251
+
252
+ # ================== TOPICS ==================
253
  with tabs[2]:
254
+ st.header("Topics")
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
+ df = lda_topic_modeling(st.session_state.papers)
257
+ st.dataframe(df)
 
 
 
 
258
 
259
+ generate_wordcloud(st.session_state.papers)
260
+
261
+ # ================== COLLECTIONS ==================
262
  with tabs[3]:
263
+ st.header("Collections")
264
+
265
+ name = st.text_input("Collection name")
 
 
 
 
 
 
 
266
 
267
+ if st.button("Save"):
268
+ st.session_state.collections[name] = st.session_state.papers.copy()
269
+ st.success("Saved")
270
+
271
+ st.write(st.session_state.collections.keys())
272
+
273
+ # ================== TRENDS ==================
274
  with tabs[4]:
275
+ st.header("Trends")
276
+
277
+ build_coauthor_graph(st.session_state.papers)
 
 
 
 
 
 
 
278
 
279
+ # ================== CHAT AI (NEW ADDED SECTION) ==================
280
  with tabs[5]:
281
+ st.header("💬 Chat with AI about your Papers")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
 
 
 
283
  if st.session_state.papers:
284
+
285
+ context = "\n\n".join([p.get("abstract", "") for p in st.session_state.papers])
286
+
287
+ user_q = st.text_input("Ask a question")
288
+
289
+ if st.button("Ask AI") and user_q.strip():
290
+
291
+ throttle()
292
+
293
+ prompt = f"""
294
+ You are an academic assistant.
295
+ Use ONLY the context below:
296
+ If answer not found say "Not enough information".
297
+ Context:
298
+ {context}
299
  Question:
300
  {user_q}
301
+ Answer:
302
  """
303
+
304
+ res = client.chat.completions.create(
305
+ model="llama-3.1-8b-instant",
306
+ messages=[{"role": "user", "content": prompt}],
307
+ temperature=0.3,
308
+ )
309
+
310
+ answer = res.choices[0].message.content.strip()
311
+
312
+ st.session_state.chat_history.append(("You", user_q))
313
+ st.session_state.chat_history.append(("AI", answer))
314
+
315
+ st.markdown("### Conversation")
316
+
317
+ for role, msg in st.session_state.chat_history:
318
+ if role == "You":
319
+ st.markdown(f"**🧑 You:** {msg}")
320
+ else:
321
+ st.markdown(f"**🤖 AI:** {msg}")
322
+
323
  else:
324
+ st.info("Upload papers first")