Ani14 commited on
Commit
3156a04
Β·
verified Β·
1 Parent(s): 6004802

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -36
app.py CHANGED
@@ -35,33 +35,38 @@ def call_llm(messages, model="deepseek/deepseek-chat-v3-0324:free", max_tokens=3
35
 
36
  response = requests.post(url, headers=headers, json=data)
37
 
 
 
 
 
 
38
  if response.status_code != 200:
39
- try:
40
- error_msg = response.json().get("error", {}).get("message", "Unknown error from LLM API.")
41
- except Exception:
42
- error_msg = response.text
43
  raise RuntimeError(f"LLM API error: {error_msg}")
44
 
45
- try:
46
- result = response.json()
47
- return result["choices"][0]["message"]["content"]
48
- except KeyError:
49
- raise RuntimeError("LLM API returned unexpected response format. Missing 'choices'.")
50
 
51
  def get_sources(topic, domains=None):
52
  query = topic
53
  if domains:
54
  domain_filters = [d.strip() for d in domains.split(",") if d.strip()]
55
  query += " site:" + " OR site:".join(domain_filters)
56
- response = tavily.search(query=query, search_depth="advanced", max_results=10)
57
- sources = []
58
- for item in response.get("results", []):
59
- sources.append({
60
- "title": item.get("title"),
61
- "url": item.get("url"),
62
- "snippet": item.get("content", "")
63
- })
64
- return sources
 
 
 
 
65
 
66
  def get_arxiv_papers(query):
67
  from urllib.parse import quote_plus
@@ -130,8 +135,8 @@ def generate_latex(text):
130
  def generate_download_button(file, label, mime_type):
131
  b64 = base64.b64encode(file.read()).decode()
132
  return f"""
133
- <a href="data:{mime_type};base64,{b64}" download="{label}">
134
- πŸ“₯ Download {label}
135
  </a>
136
  """
137
 
@@ -143,27 +148,27 @@ def fetch_related_image(topic):
143
  st.set_page_config("Deep Research Bot", layout="wide")
144
 
145
  with st.sidebar:
146
- st.title("🧠 Deep Research Assistant")
147
- topic = st.text_input("πŸ’‘ Topic to research")
148
- report_type = st.selectbox("πŸ“„ Type of report", [
149
  "Summary - Short and fast (~2 min)",
150
  "Detailed Report (~5 min)",
151
  "Thorough Academic Research (~10 min)"
152
  ])
153
- tone = st.selectbox("🎯 Tone of the report", [
154
  "Objective - Impartial and unbiased presentation of facts and findings",
155
  "Persuasive - Advocating a specific point of view",
156
  "Narrative - Storytelling tone for layperson readers"
157
  ])
158
- source_type = st.selectbox("🌐 Sources to include", ["Web Only", "Academic Only", "Hybrid"])
159
- custom_domains = st.text_input("πŸ” Query Domains (Optional)", placeholder="techcrunch.com, forbes.com")
160
- research_button = st.button("πŸš€ Start Research")
161
 
162
- st.title("πŸ“‘ Research Output")
163
 
164
  if research_button and topic:
165
  try:
166
- with st.status("πŸ” Gathering data..."):
167
  st.info("Fetching from sources...")
168
 
169
  all_sources = []
@@ -188,7 +193,7 @@ if research_button and topic:
188
  combined_text += f"- [{m['title']}]({m['url']})\n> {m.get('snippet', m.get('summary', ''))[:300]}...\n\n"
189
  citations.append(generate_apa_citation(m['title'], m['url'], m['source']))
190
 
191
- with st.spinner("✍️ Synthesizing report..."):
192
  prompt = f"""
193
  # Research Topic: {topic}
194
  Tone: {tone}
@@ -204,19 +209,19 @@ Write the report in academic markdown with paragraphs (use bullet points only wh
204
  """
205
  final_output = call_llm([{"role": "user", "content": prompt}])
206
 
207
- st.markdown(f"### πŸ“„ {report_type}")
208
  st.markdown(final_output, unsafe_allow_html=True)
209
 
210
  if report_type == "Thorough Academic Research (~10 min)":
211
  image_url = fetch_related_image(topic)
212
  st.image(image_url, caption="Related Image", use_column_width=True)
213
 
214
- st.markdown("### πŸ“š Citations (APA Format)")
215
  for cite in citations:
216
  st.markdown(f"- {cite}")
217
 
218
  if report_type == "Thorough Academic Research (~10 min)":
219
- with st.spinner("πŸ“¦ Preparing PDF and LaTeX..."):
220
  pdf_file = generate_pdf(final_output)
221
  latex_file = generate_latex(final_output)
222
  st.markdown(generate_download_button(pdf_file, "Research_Report.pdf", "application/pdf"), unsafe_allow_html=True)
@@ -224,11 +229,11 @@ Write the report in academic markdown with paragraphs (use bullet points only wh
224
 
225
  overlaps = check_plagiarism(final_output, topic)
226
  if overlaps:
227
- st.warning("⚠️ Potential overlaps detected:")
228
  for hit in overlaps:
229
  st.markdown(f"- [{hit['title']}]({hit['url']})")
230
  else:
231
- st.success("βœ… No major overlaps found.")
232
 
233
  except Exception as e:
234
- st.error(f"Error: {e}")
 
35
 
36
  response = requests.post(url, headers=headers, json=data)
37
 
38
+ try:
39
+ result = response.json()
40
+ except Exception:
41
+ raise RuntimeError(f"LLM API returned invalid JSON: {response.text}")
42
+
43
  if response.status_code != 200:
44
+ error_msg = result.get("error", {}).get("message", "Unknown error from LLM API.")
 
 
 
45
  raise RuntimeError(f"LLM API error: {error_msg}")
46
 
47
+ if "choices" not in result:
48
+ raise RuntimeError(f"LLM API returned unexpected response format. Full response:\n{result}")
49
+
50
+ return result["choices"][0]["message"]["content"]
 
51
 
52
  def get_sources(topic, domains=None):
53
  query = topic
54
  if domains:
55
  domain_filters = [d.strip() for d in domains.split(",") if d.strip()]
56
  query += " site:" + " OR site:".join(domain_filters)
57
+ try:
58
+ response = tavily.search(query=query, search_depth="advanced", max_results=10)
59
+ sources = []
60
+ for item in response.get("results", []):
61
+ sources.append({
62
+ "title": item.get("title"),
63
+ "url": item.get("url"),
64
+ "snippet": item.get("content", "")
65
+ })
66
+ return sources
67
+ except Exception as e:
68
+ st.error(f"Error retrieving sources: {e}")
69
+ return []
70
 
71
  def get_arxiv_papers(query):
72
  from urllib.parse import quote_plus
 
135
  def generate_download_button(file, label, mime_type):
136
  b64 = base64.b64encode(file.read()).decode()
137
  return f"""
138
+ <a href=\"data:{mime_type};base64,{b64}\" download=\"{label}\">
139
+ \ud83d\udce5 Download {label}
140
  </a>
141
  """
142
 
 
148
  st.set_page_config("Deep Research Bot", layout="wide")
149
 
150
  with st.sidebar:
151
+ st.title("\ud83e\udde0 Deep Research Assistant")
152
+ topic = st.text_input("\ud83d\udca1 Topic to research")
153
+ report_type = st.selectbox("\ud83d\udcc4 Type of report", [
154
  "Summary - Short and fast (~2 min)",
155
  "Detailed Report (~5 min)",
156
  "Thorough Academic Research (~10 min)"
157
  ])
158
+ tone = st.selectbox("\ud83c\udfaf Tone of the report", [
159
  "Objective - Impartial and unbiased presentation of facts and findings",
160
  "Persuasive - Advocating a specific point of view",
161
  "Narrative - Storytelling tone for layperson readers"
162
  ])
163
+ source_type = st.selectbox("\ud83c\udf10 Sources to include", ["Web Only", "Academic Only", "Hybrid"])
164
+ custom_domains = st.text_input("\ud83d\udd0d Query Domains (Optional)", placeholder="techcrunch.com, forbes.com")
165
+ research_button = st.button("\ud83d\ude80 Start Research")
166
 
167
+ st.title("\ud83d\udcc1 Research Output")
168
 
169
  if research_button and topic:
170
  try:
171
+ with st.status("\ud83d\udd0d Gathering data..."):
172
  st.info("Fetching from sources...")
173
 
174
  all_sources = []
 
193
  combined_text += f"- [{m['title']}]({m['url']})\n> {m.get('snippet', m.get('summary', ''))[:300]}...\n\n"
194
  citations.append(generate_apa_citation(m['title'], m['url'], m['source']))
195
 
196
+ with st.spinner("\u270d\ufe0f Synthesizing report..."):
197
  prompt = f"""
198
  # Research Topic: {topic}
199
  Tone: {tone}
 
209
  """
210
  final_output = call_llm([{"role": "user", "content": prompt}])
211
 
212
+ st.markdown(f"### \ud83d\udcc4 {report_type}")
213
  st.markdown(final_output, unsafe_allow_html=True)
214
 
215
  if report_type == "Thorough Academic Research (~10 min)":
216
  image_url = fetch_related_image(topic)
217
  st.image(image_url, caption="Related Image", use_column_width=True)
218
 
219
+ st.markdown("### \ud83d\udcda Citations (APA Format)")
220
  for cite in citations:
221
  st.markdown(f"- {cite}")
222
 
223
  if report_type == "Thorough Academic Research (~10 min)":
224
+ with st.spinner("\ud83d\udce6 Preparing PDF and LaTeX..."):
225
  pdf_file = generate_pdf(final_output)
226
  latex_file = generate_latex(final_output)
227
  st.markdown(generate_download_button(pdf_file, "Research_Report.pdf", "application/pdf"), unsafe_allow_html=True)
 
229
 
230
  overlaps = check_plagiarism(final_output, topic)
231
  if overlaps:
232
+ st.warning("\u26a0\ufe0f Potential overlaps detected:")
233
  for hit in overlaps:
234
  st.markdown(f"- [{hit['title']}]({hit['url']})")
235
  else:
236
+ st.success("\u2705 No major overlaps found.")
237
 
238
  except Exception as e:
239
+ st.error(f"Error: {e}")