Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,532 +1,80 @@
|
|
| 1 |
-
# app.py
|
| 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 |
-
|
| 23 |
-
|
| 24 |
-
|
| 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 |
-
|
| 57 |
-
|
| 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 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 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 |
-
|
| 154 |
-
|
| 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 |
-
|
| 176 |
-
|
| 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 |
-
|
| 200 |
-
|
| 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 |
-
|
| 214 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 243 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 496 |
-
|
| 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 |
-
|
| 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.")
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
from components.upload import upload_section
|
| 4 |
+
from components.summaries import summary_section
|
| 5 |
+
from components.insights import insights_section
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
from src.topic_modeling import lda_topic_modeling
|
| 8 |
+
from src.visualizations import generate_wordcloud
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
st.set_page_config(
|
| 12 |
+
page_title="LitReviewAI",
|
| 13 |
+
page_icon="📚",
|
| 14 |
+
layout="wide"
|
| 15 |
+
)
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
st.title("📚 LitReviewAI: Automated Research Paper Reviewer")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
if "papers" not in st.session_state:
|
| 22 |
+
st.session_state.papers = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
|
|
|
| 24 |
|
| 25 |
+
tabs = st.tabs([
|
| 26 |
+
"About",
|
| 27 |
+
"Upload",
|
| 28 |
+
"Summaries",
|
| 29 |
+
"Topics",
|
| 30 |
+
"Insights",
|
| 31 |
+
"Chat"
|
| 32 |
+
])
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
with tabs[0]:
|
| 36 |
+
st.header("About LitReviewAI")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
st.write("""
|
| 39 |
+
AI-powered research assistant for:
|
| 40 |
+
|
| 41 |
+
- Paper summarization
|
| 42 |
+
- Research gap detection
|
| 43 |
+
- Literature organization
|
| 44 |
+
- Topic discovery
|
| 45 |
+
- Citation export
|
| 46 |
+
- Paper Q&A
|
| 47 |
+
""")
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
with tabs[1]:
|
| 51 |
+
upload_section()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
+
with tabs[2]:
|
| 55 |
+
summary_section()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
|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