flytoe commited on
Commit
d6c42b6
Β·
verified Β·
1 Parent(s): a263aa6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -36
app.py CHANGED
@@ -2,18 +2,35 @@ import os
2
  import streamlit as st
3
  import arxiv
4
  import random
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  # -------------------------------
7
  # Helper Functions
8
  # -------------------------------
9
- def retrieve_papers(query=None, max_results=10, random_search=False):
 
 
 
 
 
 
 
 
10
  """Retrieve academic papers from arXiv."""
11
- if random_search:
12
- search_query = "all:"
13
  else:
14
- search_query = query if query else ""
15
-
16
- search = arxiv.Search(query=search_query, max_results=max_results)
17
  papers = []
18
  for result in search.results():
19
  paper_id = result.entry_id.split("/")[-1]
@@ -23,62 +40,90 @@ def retrieve_papers(query=None, max_results=10, random_search=False):
23
  "url": result.pdf_url,
24
  "authors": [author.name for author in result.authors],
25
  "published": result.published,
 
26
  "doi": f"https://doi.org/10.48550/arXiv.{paper_id}",
27
- "arxiv_link": f"https://arxiv.org/abs/{paper_id}",
28
- "litmaps": f"https://app.litmaps.com/preview/{paper_id}",
29
  "bib_explorer": f"https://arxiv.org/abs/{paper_id}",
30
  "connected_papers": f"https://www.connectedpapers.com/{paper_id}",
31
- "scite": f"https://scite.ai/reports/{paper_id}",
32
- "trust_score": round(random.uniform(70, 99), 2),
33
- "relevance_score": round(random.uniform(60, 95), 2),
34
  }
35
  papers.append(paper)
36
  return papers
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  # -------------------------------
39
- # Streamlit Interface
40
  # -------------------------------
41
  st.title("πŸ“š PaperPilot – Intelligent Academic Navigator")
42
 
43
  with st.sidebar:
44
  st.header("πŸ” Search Parameters")
45
  query = st.text_input("Research topic or question:")
 
46
 
47
- col1, col2 = st.columns([3, 1])
48
- with col1:
49
- search_button = st.button("πŸš€ Find Articles")
50
- with col2:
51
- random_search_button = st.button("🎲 Random Papers")
52
-
53
- if search_button or random_search_button:
54
- with st.spinner("Fetching papers..."):
55
- if random_search_button:
56
- papers = retrieve_papers(max_results=random.randint(5, 15), random_search=True)
57
  else:
58
- papers = retrieve_papers(query=query, max_results=10)
59
 
60
  if papers:
61
  st.session_state.papers = papers
62
  st.success(f"Found {len(papers)} papers!")
 
63
  else:
64
- st.error("No papers found. Try a different keyword.")
65
 
66
- if "papers" in st.session_state and st.session_state.papers:
 
67
  st.header("πŸ“‘ Retrieved Papers")
68
- for idx, paper in enumerate(st.session_state.papers, 1):
69
  with st.expander(f"{idx}. {paper['title']}"):
 
70
  st.markdown(f"**Authors:** {', '.join(paper['authors'])}")
71
- pub_date = paper["published"].strftime('%Y-%m-%d') if paper["published"] else "Unknown"
72
  st.markdown(f"**Published:** {pub_date}")
73
- st.markdown(f"**[PDF Link]({paper['url']}) | [arXiv]({paper['arxiv_link']}) | [DOI]({paper['doi']})**")
74
- st.markdown(f"**Bibliographic Explorer:** [Link]({paper['bib_explorer']})")
75
- st.markdown(f"**Connected Papers:** [Link]({paper['connected_papers']})")
76
- st.markdown(f"**Litmaps:** [Link]({paper['litmaps']})")
77
- st.markdown(f"**scite.ai Citations:** [Link]({paper['scite']})")
78
- st.markdown(f"**Trust Score:** {paper['trust_score']}% | **Relevance Score:** {paper['relevance_score']}%")
79
- st.markdown("**Abstract:**")
80
- st.write(paper['summary'])
 
 
 
 
 
 
 
 
 
81
  else:
82
- st.info("Enter a query in the sidebar or click the 🎲 button to find papers.")
83
 
84
  st.caption("Built with ❀️ using AI")
 
2
  import streamlit as st
3
  import arxiv
4
  import random
5
+ import datetime
6
+ import networkx as nx
7
+ import matplotlib.pyplot as plt
8
+ from groq import Groq
9
+
10
+ # -------------------------------
11
+ # Initialize Groq API Client
12
+ # -------------------------------
13
+ client = Groq(
14
+ api_key=os.environ.get("GROQ_API_KEY"),
15
+ )
16
 
17
  # -------------------------------
18
  # Helper Functions
19
  # -------------------------------
20
+ def groq_summarize(text: str) -> str:
21
+ """Summarize the given text using Groq's chat completion API."""
22
+ response = client.chat.completions.create(
23
+ messages=[{"role": "user", "content": f"Summarize the following text:\n\n{text}"}],
24
+ model="llama-3.3-70b-versatile",
25
+ )
26
+ return response.choices[0].message.content.strip()
27
+
28
+ def retrieve_papers(query=None, max_results=5):
29
  """Retrieve academic papers from arXiv."""
30
+ if query:
31
+ search = arxiv.Search(query=query, max_results=max_results)
32
  else:
33
+ search = arxiv.Search(sort_by=arxiv.SortCriterion.SubmittedDate, max_results=max_results)
 
 
34
  papers = []
35
  for result in search.results():
36
  paper_id = result.entry_id.split("/")[-1]
 
40
  "url": result.pdf_url,
41
  "authors": [author.name for author in result.authors],
42
  "published": result.published,
43
+ "arxiv_id": paper_id,
44
  "doi": f"https://doi.org/10.48550/arXiv.{paper_id}",
45
+ "abs_url": f"https://arxiv.org/abs/{paper_id}",
 
46
  "bib_explorer": f"https://arxiv.org/abs/{paper_id}",
47
  "connected_papers": f"https://www.connectedpapers.com/{paper_id}",
48
+ "litmaps": f"https://app.litmaps.com/preview/{paper_id}",
49
+ "scite_ai": f"https://scite.ai/reports/{paper_id}"
 
50
  }
51
  papers.append(paper)
52
  return papers
53
 
54
+ def calculate_scores(paper):
55
+ """Generate Trust & Relevance Scores."""
56
+ return {
57
+ "trust_score": round(random.uniform(60, 95), 1),
58
+ "relevance_score": round(random.uniform(50, 100), 1)
59
+ }
60
+
61
+ def get_cached_summary(paper_id, text):
62
+ """Retrieve or create a cached summary for a given paper."""
63
+ if 'summaries' not in st.session_state:
64
+ st.session_state.summaries = {}
65
+ if paper_id not in st.session_state.summaries:
66
+ full_summary = groq_summarize(text)
67
+ eli5_summary = groq_summarize(f"Explain the following like I'm 5:\n\n{text}")
68
+ key_takeaways = groq_summarize(f"Provide key takeaways for:\n\n{text}")
69
+ st.session_state.summaries[paper_id] = {
70
+ "full": full_summary,
71
+ "eli5": eli5_summary,
72
+ "takeaways": key_takeaways
73
+ }
74
+ return st.session_state.summaries[paper_id]
75
+
76
  # -------------------------------
77
+ # Streamlit UI
78
  # -------------------------------
79
  st.title("πŸ“š PaperPilot – Intelligent Academic Navigator")
80
 
81
  with st.sidebar:
82
  st.header("πŸ” Search Parameters")
83
  query = st.text_input("Research topic or question:")
84
+ random_search = st.button("🎲 Random Papers")
85
 
86
+ if st.button("πŸš€ Find Articles") or random_search:
87
+ with st.spinner("Searching arXiv..."):
88
+ if random_search:
89
+ papers = retrieve_papers(max_results=random.randint(5, 15))
 
 
 
 
 
 
90
  else:
91
+ papers = retrieve_papers(query)
92
 
93
  if papers:
94
  st.session_state.papers = papers
95
  st.success(f"Found {len(papers)} papers!")
96
+ st.session_state.active_section = "articles"
97
  else:
98
+ st.error("No papers found. Try different keywords.")
99
 
100
+ if 'papers' in st.session_state and st.session_state.papers:
101
+ papers = st.session_state.papers
102
  st.header("πŸ“‘ Retrieved Papers")
103
+ for idx, paper in enumerate(papers, 1):
104
  with st.expander(f"{idx}. {paper['title']}"):
105
+ scores = calculate_scores(paper)
106
  st.markdown(f"**Authors:** {', '.join(paper['authors'])}")
107
+ pub_date = paper['published'].strftime('%Y-%m-%d') if isinstance(paper['published'], datetime.datetime) else "n.d."
108
  st.markdown(f"**Published:** {pub_date}")
109
+ st.markdown(f"**DOI:** [Link]({paper['doi']})")
110
+ st.markdown(f"**Original Paper:** [arXiv]({paper['abs_url']})")
111
+ st.markdown(f"**Bibliographic Explorer:** [Explore]({paper['bib_explorer']})")
112
+ st.markdown(f"**Connected Papers:** [View]({paper['connected_papers']})")
113
+ st.markdown(f"**Litmaps:** [Preview]({paper['litmaps']})")
114
+ st.markdown(f"**scite.ai:** [Smart Citations]({paper['scite_ai']})")
115
+ st.markdown(f"**Trust Score:** {scores['trust_score']}% | **Relevance Score:** {scores['relevance_score']}%")
116
+
117
+ summary_data = get_cached_summary(paper['arxiv_id'], paper['summary'])
118
+ st.subheader("πŸ“Œ Summary")
119
+ st.write(summary_data['full'])
120
+
121
+ st.subheader("πŸ§’ ELI5 Explanation")
122
+ st.write(summary_data['eli5'])
123
+
124
+ st.subheader("πŸ”‘ Key Takeaways")
125
+ st.write(summary_data['takeaways'])
126
  else:
127
+ st.info("Enter a query or click the dice icon to fetch random papers!")
128
 
129
  st.caption("Built with ❀️ using AI")