flytoe commited on
Commit
7aa208d
Β·
verified Β·
1 Parent(s): f3f61db
Files changed (1) hide show
  1. app.py +68 -50
app.py CHANGED
@@ -1,7 +1,10 @@
1
  import os
2
  import streamlit as st
3
  import arxiv
 
4
  import datetime
 
 
5
 
6
  # -------------------------------
7
  # Groq API Client
@@ -16,47 +19,67 @@ client = Groq(
16
  # Helper Functions (Groq-based)
17
  # -------------------------------
18
  def groq_summarize(text: str) -> str:
 
 
 
19
  response = client.chat.completions.create(
20
  messages=[
21
- {"role": "user", "content": f"Summarize the following text concisely:\n\n{text}"}
22
  ],
23
  model="llama-3.3-70b-versatile",
24
  )
25
  return response.choices[0].message.content.strip()
26
 
27
- def groq_eli5(text: str) -> str:
28
- response = client.chat.completions.create(
29
- messages=[
30
- {"role": "user", "content": f"Explain this like I'm 5 years old:\n\n{text}"}
31
- ],
32
- model="llama-3.3-70b-versatile",
33
- )
34
- return response.choices[0].message.content.strip()
35
 
36
- def groq_key_takeaways(text: str) -> str:
37
- response = client.chat.completions.create(
38
- messages=[
39
- {"role": "user", "content": f"List the key takeaways from this research:\n\n{text}"}
40
- ],
41
- model="llama-3.3-70b-versatile",
42
- )
43
- return response.choices[0].message.content.strip()
 
 
 
 
 
 
 
 
 
44
 
45
  # -------------------------------
46
- # Paper Retrieval & Processing
47
  # -------------------------------
48
  def retrieve_papers(query, max_results=5):
 
49
  search = arxiv.Search(query=query, max_results=max_results)
50
  papers = []
 
51
  for result in search.results():
 
 
 
52
  paper = {
53
  "title": result.title,
54
  "summary": result.summary,
55
  "url": result.pdf_url,
56
  "authors": [author.name for author in result.authors],
57
- "published": result.published
 
 
 
 
58
  }
59
  papers.append(paper)
 
60
  return papers
61
 
62
  # -------------------------------
@@ -64,14 +87,11 @@ def retrieve_papers(query, max_results=5):
64
  # -------------------------------
65
  st.title("πŸ“š PaperPilot – Intelligent Academic Navigator")
66
 
67
- st.write("""
68
- PaperPilot helps you quickly analyze research papers by summarizing them, highlighting key takeaways, and explaining complex topics in simple terms.
69
- Enter a query and get structured insights instantly!
70
- """)
71
-
72
  with st.sidebar:
73
  st.header("πŸ” Search Parameters")
74
  query = st.text_input("Research topic or question:")
 
75
 
76
  if st.button("πŸš€ Find Articles"):
77
  if query.strip():
@@ -79,39 +99,37 @@ with st.sidebar:
79
  papers = retrieve_papers(query)
80
  if papers:
81
  st.session_state.papers = papers
 
82
  st.success(f"Found {len(papers)} papers!")
83
- st.session_state.active_section = "review"
84
  else:
85
  st.error("No papers found. Try different keywords.")
86
  else:
87
  st.warning("Please enter a search query")
88
 
 
89
  if 'papers' in st.session_state and st.session_state.papers:
90
  papers = st.session_state.papers
91
-
92
- if st.session_state.active_section == "review":
93
- st.header("πŸ“š Literature Review & Summary")
94
- for idx, paper in enumerate(papers, 1):
95
- with st.expander(f"{idx}. {paper['title']}"):
96
- st.markdown(f"**Authors:** {', '.join(paper['authors'])}")
97
- pub_date = paper['published'].strftime('%Y-%m-%d') if isinstance(paper['published'], datetime.datetime) else "n.d."
98
- st.markdown(f"**Published:** {pub_date}")
99
- st.markdown(f"**Link:** [PDF]({paper['url']})")
100
-
101
- with st.spinner("Generating insights..."):
102
- short_description = groq_summarize(paper['summary'])
103
- key_takeaways = groq_key_takeaways(paper['summary'])
104
- eli5_explanation = groq_eli5(paper['summary'])
105
-
106
- st.subheader("Short Description")
107
- st.write(short_description)
108
-
109
- st.subheader("Key Takeaways")
110
- st.write(key_takeaways)
111
 
112
- st.subheader("Explain Like I'm 5 (ELI5)")
113
- st.write(eli5_explanation)
114
- else:
115
- st.info("Enter a query in the sidebar and click 'Find Articles' to get started.")
 
 
 
 
116
 
117
- st.caption("Built with ❀️ using AI")
 
1
  import os
2
  import streamlit as st
3
  import arxiv
4
+ import requests
5
  import datetime
6
+ import networkx as nx
7
+ import matplotlib.pyplot as plt
8
 
9
  # -------------------------------
10
  # Groq API Client
 
19
  # Helper Functions (Groq-based)
20
  # -------------------------------
21
  def groq_summarize(text: str) -> str:
22
+ """
23
+ Summarize the given text using Groq's chat completion API.
24
+ """
25
  response = client.chat.completions.create(
26
  messages=[
27
+ {"role": "user", "content": f"Summarize the following text in detail:\n\n{text}"}
28
  ],
29
  model="llama-3.3-70b-versatile",
30
  )
31
  return response.choices[0].message.content.strip()
32
 
33
+ # -------------------------------
34
+ # Trust & Relevance Scores
35
+ # -------------------------------
36
+ def get_citation_metadata(arxiv_id):
37
+ """Fetch trust & relevance scores from external sources."""
38
+ metadata = {"citations": 0, "trust_score": 0, "relevance_score": 0, "links": {}}
 
 
39
 
40
+ # Fetch citation data from scite.ai
41
+ scite_url = f"https://api.scite.ai/papers/{arxiv_id}"
42
+ response = requests.get(scite_url)
43
+ if response.status_code == 200:
44
+ scite_data = response.json()
45
+ metadata["citations"] = scite_data.get("citation_count", 0)
46
+ metadata["trust_score"] = scite_data.get("trust_score", 0)
47
+
48
+ # Generate Connected Papers & Litmaps links
49
+ metadata["links"]["Connected Papers"] = f"https://www.connectedpapers.com/main/{arxiv_id}"
50
+ metadata["links"]["Bibliographic Explorer"] = f"https://arxiv.org/bib_explorer/{arxiv_id}"
51
+ metadata["links"]["Litmaps"] = f"https://www.litmaps.com/publications/{arxiv_id}"
52
+
53
+ # Calculate relevance score
54
+ metadata["relevance_score"] = metadata["citations"] * 0.8 + metadata["trust_score"] * 0.2
55
+
56
+ return metadata
57
 
58
  # -------------------------------
59
+ # Retrieve Papers
60
  # -------------------------------
61
  def retrieve_papers(query, max_results=5):
62
+ """Retrieve academic papers from arXiv & add Trust/Relevance scores."""
63
  search = arxiv.Search(query=query, max_results=max_results)
64
  papers = []
65
+
66
  for result in search.results():
67
+ paper_id = result.entry_id.split("/")[-1] # Extract arXiv ID
68
+ metadata = get_citation_metadata(paper_id)
69
+
70
  paper = {
71
  "title": result.title,
72
  "summary": result.summary,
73
  "url": result.pdf_url,
74
  "authors": [author.name for author in result.authors],
75
+ "published": result.published,
76
+ "citations": metadata["citations"],
77
+ "trust_score": metadata["trust_score"],
78
+ "relevance_score": metadata["relevance_score"],
79
+ "links": metadata["links"],
80
  }
81
  papers.append(paper)
82
+
83
  return papers
84
 
85
  # -------------------------------
 
87
  # -------------------------------
88
  st.title("πŸ“š PaperPilot – Intelligent Academic Navigator")
89
 
90
+ # Sidebar: Search & Toggle
 
 
 
 
91
  with st.sidebar:
92
  st.header("πŸ” Search Parameters")
93
  query = st.text_input("Research topic or question:")
94
+ show_scores = st.checkbox("Enable Trust & Relevance Scores", value=True)
95
 
96
  if st.button("πŸš€ Find Articles"):
97
  if query.strip():
 
99
  papers = retrieve_papers(query)
100
  if papers:
101
  st.session_state.papers = papers
102
+ st.session_state.active_section = "articles"
103
  st.success(f"Found {len(papers)} papers!")
 
104
  else:
105
  st.error("No papers found. Try different keywords.")
106
  else:
107
  st.warning("Please enter a search query")
108
 
109
+ # Main Content
110
  if 'papers' in st.session_state and st.session_state.papers:
111
  papers = st.session_state.papers
112
+
113
+ st.header("πŸ“‘ Retrieved Papers")
114
+ for idx, paper in enumerate(papers, 1):
115
+ with st.expander(f"{idx}. {paper['title']}"):
116
+ st.markdown(f"**Authors:** {', '.join(paper['authors'])}")
117
+ st.markdown(f"**Published:** {paper['published']}")
118
+ st.markdown(f"**Link:** [PDF]({paper['url']})")
119
+
120
+ # Show Trust & Relevance Scores if enabled
121
+ if show_scores:
122
+ st.markdown(f"πŸ“Š **Citations:** {paper['citations']}")
123
+ st.markdown(f"πŸ›‘οΈ **Trust Score:** {round(paper['trust_score'], 2)} / 10")
124
+ st.markdown(f"πŸ” **Relevance Score:** {round(paper['relevance_score'], 2)} / 10")
 
 
 
 
 
 
 
125
 
126
+ # External Links
127
+ st.markdown(f"[πŸ”— Connected Papers]({paper['links']['Connected Papers']})")
128
+ st.markdown(f"[πŸ“– Bibliographic Explorer]({paper['links']['Bibliographic Explorer']})")
129
+ st.markdown(f"[πŸ“Š Litmaps]({paper['links']['Litmaps']})")
130
+
131
+ # Display Summary
132
+ st.markdown("**Abstract:**")
133
+ st.write(paper['summary'])
134
 
135
+ st.caption("Built with ❀️ using AI")