Ani14 commited on
Commit
2b97b69
·
verified ·
1 Parent(s): 2fc6967

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -151
app.py CHANGED
@@ -2,24 +2,47 @@ import os
2
  import streamlit as st
3
  import requests
4
  import datetime
5
- from dotenv import load_dotenv
6
- from tavily import TavilyClient
7
  import feedparser
8
  import time
 
 
9
  from fuzzywuzzy import fuzz
 
10
  from PIL import Image
11
  from io import BytesIO
12
  from fpdf import FPDF
13
- import base64
14
 
15
- # Load environment variables
16
  load_dotenv()
17
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
18
- TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
19
  tavily = TavilyClient(api_key=TAVILY_API_KEY)
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  # --- Helper Functions ---
22
- def call_llm(messages, model="deepseek/deepseek-chat-v3-0324:free", max_tokens=3500, temperature=0.7):
23
  url = "https://openrouter.ai/api/v1/chat/completions"
24
  headers = {
25
  "Authorization": f"Bearer {OPENROUTER_API_KEY}",
@@ -43,6 +66,7 @@ def get_sources(topic, domains=None):
43
  if domains:
44
  domain_filters = [d.strip() for d in domains.split(",") if d.strip()]
45
  query += " site:" + " OR site:".join(domain_filters)
 
46
  response = tavily.search(query=query, search_depth="advanced", max_results=10)
47
  sources = []
48
  for item in response.get("results", []):
@@ -54,7 +78,6 @@ def get_sources(topic, domains=None):
54
  return sources
55
 
56
  def get_arxiv_papers(query):
57
- from urllib.parse import quote_plus
58
  url = f"http://export.arxiv.org/api/query?search_query=all:{quote_plus(query)}&start=0&max_results=5"
59
  feed = feedparser.parse(url)
60
  return [{
@@ -70,147 +93,4 @@ def get_semantic_papers(query):
70
  papers = response.json().get("data", [])
71
  return [{
72
  "title": p.get("title"),
73
- "summary": p.get("abstract", "No abstract available"),
74
- "url": p.get("url")
75
- } for p in papers]
76
-
77
- def check_plagiarism(text, topic):
78
- hits = []
79
- for r in get_sources(topic):
80
- similarity = fuzz.token_set_ratio(text, r["snippet"])
81
- if similarity >= 75:
82
- hits.append(r)
83
- return hits
84
-
85
- def generate_apa_citation(title, url, source):
86
- year = datetime.datetime.now().year
87
- label = {
88
- "arxiv": "*arXiv*", "semantic": "*Semantic Scholar*", "web": "*Web Source*"
89
- }.get(source, "*Web*")
90
- return f"{title}. ({year}). {label}. {url}"
91
-
92
- def merge_duplicates(entries):
93
- unique = []
94
- seen_titles = []
95
- for entry in entries:
96
- if all(fuzz.token_set_ratio(entry['title'], seen) < 90 for seen in seen_titles):
97
- unique.append(entry)
98
- seen_titles.append(entry['title'])
99
- return unique
100
-
101
- def generate_pdf(text):
102
- pdf = FPDF()
103
- pdf.add_page()
104
- pdf.set_auto_page_break(auto=True, margin=15)
105
- pdf.set_font("Arial", size=12)
106
- for line in text.split('\n'):
107
- pdf.multi_cell(0, 10, line)
108
- pdf_output = BytesIO()
109
- pdf.output(pdf_output)
110
- pdf_output.seek(0)
111
- return pdf_output
112
-
113
- def generate_latex(text):
114
- latex = "\\documentclass{article}\n\\usepackage{hyperref}\n\\begin{document}\n"
115
- for line in text.split('\n'):
116
- latex += line.replace('_', '\\_') + "\\\\\n"
117
- latex += "\\end{document}"
118
- return BytesIO(latex.encode("utf-8"))
119
-
120
- def generate_download_button(file, label, mime_type):
121
- b64 = base64.b64encode(file.read()).decode()
122
- return f"""
123
- <a href="data:{mime_type};base64,{b64}" download="{label}">
124
- 📥 Download {label}
125
- </a>
126
- """
127
-
128
- # --- Streamlit UI ---
129
- st.set_page_config("Deep Research Bot", layout="wide")
130
-
131
- with st.sidebar:
132
- st.title("🧠 Deep Research Assistant")
133
- topic = st.text_input("💡 Topic to research")
134
- report_type = st.selectbox("📄 Type of report", [
135
- "Summary - Short and fast (~2 min)",
136
- "Detailed Report (~5 min)",
137
- "Thorough Academic Research (~10 min)"
138
- ])
139
- tone = st.selectbox("🎯 Tone of the report", [
140
- "Objective - Impartial and unbiased presentation of facts and findings",
141
- "Persuasive - Advocating a specific point of view",
142
- "Narrative - Storytelling tone for layperson readers"
143
- ])
144
- source_type = st.selectbox("🌐 Sources to include", ["Web Only", "Academic Only", "Hybrid"])
145
- custom_domains = st.text_input("🔍 Query Domains (Optional)", placeholder="techcrunch.com, forbes.com")
146
- research_button = st.button("Research")
147
-
148
- st.title("📑 Research Output")
149
-
150
- if research_button and topic:
151
- try:
152
- with st.status("🔍 Gathering data..."):
153
- st.info("Fetching from sources...")
154
-
155
- all_sources = []
156
- citations = []
157
-
158
- if source_type in ["Web Only", "Hybrid"]:
159
- web_data = get_sources(topic, custom_domains)
160
- for item in web_data:
161
- all_sources.append(item | {"source": "web"})
162
-
163
- if source_type in ["Academic Only", "Hybrid"]:
164
- arxiv_data = get_arxiv_papers(topic)
165
- for item in arxiv_data:
166
- all_sources.append(item | {"source": "arxiv"})
167
- semantic_data = get_semantic_papers(topic)
168
- for item in semantic_data:
169
- all_sources.append(item | {"source": "semantic"})
170
-
171
- merged = merge_duplicates(all_sources)
172
- combined_text = ""
173
- for m in merged:
174
- combined_text += f"- [{m['title']}]({m['url']})\n> {m.get('snippet', m.get('summary', ''))[:300]}...\n\n"
175
- citations.append(generate_apa_citation(m['title'], m['url'], m['source']))
176
-
177
- with st.spinner("✍️ Synthesizing report..."):
178
- prompt = f"""
179
- # Research Topic: {topic}
180
- Tone: {tone}
181
- Type: {report_type}
182
- Sources:
183
- {combined_text}
184
- Write the report in academic markdown with paragraphs (use bullet points only when necessary). Include:
185
- 1. Introduction
186
- 2. Research Gap
187
- 3. Novel Insight
188
- 4. Application
189
- 5. Full Academic Writeup if Thorough Report
190
- """
191
- final_output = call_llm([{"role": "user", "content": prompt}])
192
-
193
- st.markdown(f"### 📄 {report_type}")
194
- st.markdown(final_output, unsafe_allow_html=True)
195
-
196
- st.markdown("### 📚 Citations (APA Format)")
197
- for cite in citations:
198
- st.markdown(f"- {cite}")
199
-
200
- if report_type == "Thorough Academic Research (~10 min)":
201
- with st.spinner("📦 Preparing PDF and LaTeX..."):
202
- pdf_file = generate_pdf(final_output)
203
- latex_file = generate_latex(final_output)
204
- st.markdown(generate_download_button(pdf_file, "Research_Report.pdf", "application/pdf"), unsafe_allow_html=True)
205
- st.markdown(generate_download_button(latex_file, "Research_Report.tex", "application/x-latex"), unsafe_allow_html=True)
206
-
207
- overlaps = check_plagiarism(final_output, topic)
208
- if overlaps:
209
- st.warning("⚠️ Potential overlaps detected:")
210
- for hit in overlaps:
211
- st.markdown(f"- [{hit['title']}]({hit['url']})")
212
- else:
213
- st.success("✅ No major overlaps found.")
214
-
215
- except Exception as e:
216
- st.error(f"Error: {e}")
 
2
  import streamlit as st
3
  import requests
4
  import datetime
 
 
5
  import feedparser
6
  import time
7
+ from dotenv import load_dotenv
8
+ from tavily import TavilyClient
9
  from fuzzywuzzy import fuzz
10
+ from urllib.parse import quote_plus
11
  from PIL import Image
12
  from io import BytesIO
13
  from fpdf import FPDF
 
14
 
15
+ # --- Load Keys ---
16
  load_dotenv()
17
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
18
+ TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "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")
19
  tavily = TavilyClient(api_key=TAVILY_API_KEY)
20
 
21
+ # --- Layout ---
22
+ st.set_page_config("Deep Research Bot", layout="wide")
23
+ with st.sidebar:
24
+ st.title("🧭 Research Input")
25
+ topic = st.text_input("💡 What would you like me to research next?")
26
+ report_type = st.selectbox("📄 Type of report", [
27
+ "Summary - Short and fast (~2 min)",
28
+ "Detailed Report (~5 min)",
29
+ "Thorough Academic Research (~10 min)"
30
+ ])
31
+ tone = st.selectbox("🎯 Tone of the report", [
32
+ "Objective - Impartial and unbiased presentation of facts and findings",
33
+ "Persuasive - Advocating a specific point of view",
34
+ "Narrative - Storytelling tone for layperson readers"
35
+ ])
36
+ source_type = st.selectbox("🌐 Sources to include", [
37
+ "Web Only", "Academic Only", "Hybrid"
38
+ ])
39
+ custom_domains = st.text_input("🔍 Query Domains (Optional)", placeholder="techcrunch.com, forbes.com")
40
+
41
+ st.title("🤖 Real-time Deep Research Agent (Tavily Edition)")
42
+ st.markdown("This powerful assistant autonomously gathers, analyzes, and synthesizes research from multiple sources in real-time using Tavily, ArXiv, and Semantic Scholar.")
43
+
44
  # --- Helper Functions ---
45
+ def call_llm(messages, model="deepseek/deepseek-chat-v3-0324:free", max_tokens=2048, temperature=0.7):
46
  url = "https://openrouter.ai/api/v1/chat/completions"
47
  headers = {
48
  "Authorization": f"Bearer {OPENROUTER_API_KEY}",
 
66
  if domains:
67
  domain_filters = [d.strip() for d in domains.split(",") if d.strip()]
68
  query += " site:" + " OR site:".join(domain_filters)
69
+
70
  response = tavily.search(query=query, search_depth="advanced", max_results=10)
71
  sources = []
72
  for item in response.get("results", []):
 
78
  return sources
79
 
80
  def get_arxiv_papers(query):
 
81
  url = f"http://export.arxiv.org/api/query?search_query=all:{quote_plus(query)}&start=0&max_results=5"
82
  feed = feedparser.parse(url)
83
  return [{
 
93
  papers = response.json().get("data", [])
94
  return [{
95
  "title": p.get("title"),
96
+ "summary":