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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -105
app.py CHANGED
@@ -1,132 +1,84 @@
1
  import os
2
  import streamlit as st
3
  import arxiv
4
- import networkx as nx
5
- import matplotlib.pyplot as plt
6
- import datetime
7
 
8
  # -------------------------------
9
- # Groq API Client
10
  # -------------------------------
11
- from groq import Groq
12
-
13
- client = Groq(
14
- api_key=os.environ.get("GROQ_API_KEY"),
15
- )
16
-
17
- # -------------------------------
18
- # Helper Functions (Groq-based)
19
- # -------------------------------
20
- def groq_summarize(text: str) -> str:
21
- """
22
- Summarize the given text using Groq's chat completion API.
23
- """
24
- response = client.chat.completions.create(
25
- messages=[
26
- {"role": "user", "content": f"Summarize the following text in detail:\n\n{text}"}
27
- ],
28
- model="llama-3.3-70b-versatile",
29
- )
30
- return response.choices[0].message.content.strip()
31
-
32
- def groq_simplify(text: str) -> str:
33
- """
34
- Explain Like I'm 5 (ELI5) version of the summary.
35
- """
36
- response = client.chat.completions.create(
37
- messages=[
38
- {"role": "user", "content": f"Explain the following like I'm 5 years old:\n\n{text}"}
39
- ],
40
- model="llama-3.3-70b-versatile",
41
- )
42
- return response.choices[0].message.content.strip()
43
-
44
- def groq_generate_key_takeaways(text: str) -> str:
45
- """
46
- Generate key takeaways from the paper.
47
- """
48
- response = client.chat.completions.create(
49
- messages=[
50
- {"role": "user", "content": f"Provide key takeaways from this research paper:\n\n{text}"}
51
- ],
52
- model="llama-3.3-70b-versatile",
53
- )
54
- return response.choices[0].message.content.strip()
55
-
56
- def retrieve_papers(query, max_results=5):
57
- """Retrieve academic papers from arXiv, including DOI and tools for relevance/trust scoring."""
58
- search = arxiv.Search(query=query, max_results=max_results)
59
  papers = []
60
  for result in search.results():
 
61
  paper = {
62
  "title": result.title,
63
  "summary": result.summary,
64
  "url": result.pdf_url,
65
  "authors": [author.name for author in result.authors],
66
  "published": result.published,
67
- "doi": result.doi if hasattr(result, "doi") else f"https://doi.org/10.48550/arXiv.{result.entry_id.split('/')[-1]}",
68
- "litmaps": f"https://app.litmaps.com/preview/{result.entry_id.split('/')[-1]}",
69
- "connected_papers": f"https://www.connectedpapers.com/main/{result.entry_id.split('/')[-1]}",
70
- "scite_ai": f"https://scite.ai/reports/{result.entry_id.split('/')[-1]}",
71
- "biblio_explorer": f"https://arxiv.org/bib_explorer/{result.entry_id.split('/')[-1]}",
 
 
 
72
  }
73
  papers.append(paper)
74
  return papers
75
 
76
- def get_cached_summary(paper_id, text):
77
- """Retrieve or generate summaries, ELI5 explanations, and key takeaways."""
78
- if 'summaries' not in st.session_state:
79
- st.session_state.summaries = {}
80
- if paper_id not in st.session_state.summaries:
81
- st.session_state.summaries[paper_id] = {
82
- "summary": groq_summarize(text),
83
- "eli5": groq_simplify(text),
84
- "key_takeaways": groq_generate_key_takeaways(text),
85
- }
86
- return st.session_state.summaries[paper_id]
87
-
88
  st.title("πŸ“š PaperPilot – Intelligent Academic Navigator")
89
 
90
  with st.sidebar:
91
  st.header("πŸ” Search Parameters")
92
  query = st.text_input("Research topic or question:")
93
- if st.button("πŸš€ Find Articles"):
94
- if query.strip():
95
- with st.spinner("Searching arXiv..."):
96
- papers = retrieve_papers(query)
97
- if papers:
98
- st.session_state.papers = papers
99
- st.success(f"Found {len(papers)} papers!")
100
- st.session_state.active_section = "review"
101
- else:
102
- st.error("No papers found. Try different keywords.")
103
- else:
104
- st.warning("Please enter a search query")
105
-
106
- if 'active_section' not in st.session_state:
107
- st.session_state.active_section = "none"
108
-
109
- if 'papers' in st.session_state and st.session_state.papers:
110
- papers = st.session_state.papers
111
-
112
- if st.session_state.active_section == "review":
113
- st.header("πŸ“š Literature Review & Summary")
114
- for idx, paper in enumerate(papers, 1):
115
- with st.expander(f"Summary: {paper['title']}"):
116
- with st.spinner(f"Analyzing {paper['title']}..."):
117
- paper_id = f"paper_{idx}"
118
- summary_data = get_cached_summary(paper_id, paper['summary'])
119
- st.markdown(f"**Summary:** {summary_data['summary']}")
120
- st.markdown(f"**ELI5:** {summary_data['eli5']}")
121
- st.markdown("**Key Takeaways:**")
122
- st.write(summary_data['key_takeaways'])
123
- st.markdown(f"**DOI:** [Link]({paper['doi']})")
124
- st.markdown(f"**Bibliographic Explorer:** [View]({paper['biblio_explorer']})")
125
- st.markdown(f"**Connected Papers:** [View]({paper['connected_papers']})")
126
- st.markdown(f"**Litmaps:** [View]({paper['litmaps']})")
127
- st.markdown(f"**Scite.ai Citations:** [View]({paper['scite_ai']})")
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  else:
130
- st.info("Enter a query in the sidebar and click 'Find Articles' to get started.")
131
 
132
  st.caption("Built with ❀️ using AI")
 
1
  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]
20
  paper = {
21
  "title": result.title,
22
  "summary": result.summary,
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")