Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,15 +4,12 @@ import requests
|
|
| 4 |
import datetime
|
| 5 |
import time
|
| 6 |
import json
|
|
|
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
from tavily import TavilyClient
|
| 9 |
import feedparser
|
| 10 |
from fuzzywuzzy import fuzz
|
| 11 |
-
from PIL import Image
|
| 12 |
-
from io import BytesIO
|
| 13 |
from fpdf import FPDF
|
| 14 |
-
import base64
|
| 15 |
-
import uuid
|
| 16 |
from duckduckgo_search import DDGS
|
| 17 |
|
| 18 |
# --- Load API Keys ---
|
|
@@ -21,7 +18,21 @@ OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
|
| 21 |
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 22 |
tavily = TavilyClient(api_key=TAVILY_API_KEY)
|
| 23 |
|
| 24 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
def call_llm(messages, model="deepseek/deepseek-chat-v3-0324:free", max_tokens=4000, temperature=0.7):
|
| 27 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
|
@@ -53,7 +64,7 @@ def call_llm(messages, model="deepseek/deepseek-chat-v3-0324:free", max_tokens=4
|
|
| 53 |
except json.JSONDecodeError:
|
| 54 |
pass
|
| 55 |
|
| 56 |
-
def get_image_urls(query, max_images=
|
| 57 |
with DDGS() as ddgs:
|
| 58 |
return [img["image"] for img in ddgs.images(query, max_results=max_images)]
|
| 59 |
|
|
@@ -141,34 +152,53 @@ def build_chronological_progression(sources):
|
|
| 141 |
summary += f"**{year}**\n{entries}\n\n"
|
| 142 |
return summary.strip()
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
if "memory_bank" not in st.session_state:
|
| 148 |
st.session_state.memory_bank = []
|
| 149 |
-
|
| 150 |
if "chat_threads" not in st.session_state:
|
| 151 |
st.session_state.chat_threads = {}
|
| 152 |
-
|
| 153 |
if "current_thread_id" not in st.session_state:
|
| 154 |
st.session_state.current_thread_id = None
|
| 155 |
|
| 156 |
-
|
|
|
|
|
|
|
| 157 |
with st.sidebar:
|
| 158 |
-
st.title("Deep Research Assistant
|
| 159 |
-
topic = st.text_input("π Enter
|
| 160 |
report_type = st.selectbox("π Report Type", ["Summary", "Detailed Report", "Thorough Academic Research"])
|
| 161 |
tone = st.selectbox("π― Tone", ["Objective", "Persuasive", "Narrative"])
|
| 162 |
source_type = st.selectbox("π Sources", ["Web Only", "Academic Only", "Hybrid"])
|
| 163 |
custom_domains = st.text_input("π Optional Domains", placeholder="example.com, nature.com")
|
| 164 |
research_button = st.button("π Start Research")
|
| 165 |
|
| 166 |
-
# --- Main
|
| 167 |
st.title("π Research Output")
|
| 168 |
|
| 169 |
if research_button and topic:
|
| 170 |
try:
|
| 171 |
-
with st.status("
|
| 172 |
all_sources = []
|
| 173 |
if source_type in ["Web Only", "Hybrid"]:
|
| 174 |
all_sources += get_sources(topic, custom_domains) if custom_domains.strip() else get_sources(topic)
|
|
@@ -183,8 +213,7 @@ if research_button and topic:
|
|
| 183 |
merged = sort_sources_chronologically(merged)
|
| 184 |
chronological_progress = build_chronological_progression(merged)
|
| 185 |
|
| 186 |
-
|
| 187 |
-
previous_learnings = "\n\n".join(st.session_state.memory_bank[-5:]) # last 5 learnings
|
| 188 |
|
| 189 |
citations = [f"- {s['title']} ({s['year']}) [{s['source']}]({s['url']})" for s in merged]
|
| 190 |
sources_text = "\n".join([
|
|
@@ -198,35 +227,31 @@ if research_button and topic:
|
|
| 198 |
"Thorough Academic Research": "Craft a full academic paper >1000 words."
|
| 199 |
}[report_type]
|
| 200 |
|
| 201 |
-
# Create Thread ID
|
| 202 |
thread_id = str(uuid.uuid4())
|
| 203 |
st.session_state.current_thread_id = thread_id
|
| 204 |
st.session_state.chat_threads[thread_id] = []
|
| 205 |
|
| 206 |
-
# --- LLM Prompt ---
|
| 207 |
prompt = f"""
|
| 208 |
-
|
| 209 |
|
| 210 |
-
π΅ Past Knowledge:
|
| 211 |
{previous_learnings}
|
| 212 |
|
| 213 |
-
|
| 214 |
{topic}
|
| 215 |
|
| 216 |
-
|
| 217 |
{tone} tone, {length_instruction}
|
| 218 |
|
| 219 |
-
|
| 220 |
{chronological_progress}
|
| 221 |
|
| 222 |
-
|
| 223 |
{sources_text}
|
| 224 |
|
| 225 |
-
|
| 226 |
{chr(10).join(citations)}
|
| 227 |
"""
|
| 228 |
|
| 229 |
-
# --- Generate Report ---
|
| 230 |
st.subheader(f"π {report_type} on '{topic}'")
|
| 231 |
output_placeholder = st.empty()
|
| 232 |
final_output = ""
|
|
@@ -237,10 +262,12 @@ You are an expert research assistant.
|
|
| 237 |
st.session_state.memory_bank.append(final_output)
|
| 238 |
st.session_state.chat_threads[thread_id].append({"role": "assistant", "content": final_output})
|
| 239 |
|
|
|
|
|
|
|
| 240 |
except Exception as e:
|
| 241 |
st.error(f"β Error: {e}")
|
| 242 |
|
| 243 |
-
# ---
|
| 244 |
st.divider()
|
| 245 |
st.subheader("π Your Research Threads")
|
| 246 |
|
|
@@ -250,6 +277,22 @@ for tid, chats in st.session_state.chat_threads.items():
|
|
| 250 |
role = "π§ You" if msg['role'] == 'user' else "π€ Assistant"
|
| 251 |
st.markdown(f"**{role}:** {msg['content']}")
|
| 252 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
|
| 255 |
# π§ Initialize session state
|
|
|
|
| 4 |
import datetime
|
| 5 |
import time
|
| 6 |
import json
|
| 7 |
+
import uuid
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
from tavily import TavilyClient
|
| 10 |
import feedparser
|
| 11 |
from fuzzywuzzy import fuzz
|
|
|
|
|
|
|
| 12 |
from fpdf import FPDF
|
|
|
|
|
|
|
| 13 |
from duckduckgo_search import DDGS
|
| 14 |
|
| 15 |
# --- Load API Keys ---
|
|
|
|
| 18 |
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 19 |
tavily = TavilyClient(api_key=TAVILY_API_KEY)
|
| 20 |
|
| 21 |
+
# --- Utility Functions ---
|
| 22 |
+
def save_session_data():
|
| 23 |
+
data = {
|
| 24 |
+
"memory_bank": st.session_state.get("memory_bank", []),
|
| 25 |
+
"chat_threads": st.session_state.get("chat_threads", {})
|
| 26 |
+
}
|
| 27 |
+
with open("session_memory.json", "w", encoding="utf-8") as f:
|
| 28 |
+
json.dump(data, f, ensure_ascii=False, indent=4)
|
| 29 |
+
|
| 30 |
+
def load_session_data():
|
| 31 |
+
if os.path.exists("session_memory.json"):
|
| 32 |
+
with open("session_memory.json", "r", encoding="utf-8") as f:
|
| 33 |
+
data = json.load(f)
|
| 34 |
+
st.session_state.memory_bank = data.get("memory_bank", [])
|
| 35 |
+
st.session_state.chat_threads = data.get("chat_threads", {})
|
| 36 |
|
| 37 |
def call_llm(messages, model="deepseek/deepseek-chat-v3-0324:free", max_tokens=4000, temperature=0.7):
|
| 38 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
|
|
|
| 64 |
except json.JSONDecodeError:
|
| 65 |
pass
|
| 66 |
|
| 67 |
+
def get_image_urls(query, max_images=3):
|
| 68 |
with DDGS() as ddgs:
|
| 69 |
return [img["image"] for img in ddgs.images(query, max_results=max_images)]
|
| 70 |
|
|
|
|
| 152 |
summary += f"**{year}**\n{entries}\n\n"
|
| 153 |
return summary.strip()
|
| 154 |
|
| 155 |
+
def download_threads_as_pdf(chat_threads):
|
| 156 |
+
pdf = FPDF()
|
| 157 |
+
pdf.add_page()
|
| 158 |
+
pdf.set_auto_page_break(auto=True, margin=15)
|
| 159 |
+
pdf.set_font("Arial", size=12)
|
| 160 |
+
for tid, chats in chat_threads.items():
|
| 161 |
+
pdf.cell(0, 10, f"Thread {tid[:8]}", ln=True)
|
| 162 |
+
for msg in chats:
|
| 163 |
+
role = "You" if msg["role"] == "user" else "Assistant"
|
| 164 |
+
text = f"{role}: {msg['content']}"
|
| 165 |
+
pdf.multi_cell(0, 10, text)
|
| 166 |
+
pdf.ln(5)
|
| 167 |
+
pdf_output = BytesIO()
|
| 168 |
+
pdf_bytes = pdf.output(dest='S').encode('latin-1')
|
| 169 |
+
pdf_output.write(pdf_bytes)
|
| 170 |
+
pdf_output.seek(0)
|
| 171 |
+
return pdf_output
|
| 172 |
+
|
| 173 |
+
# --- Streamlit UI ---
|
| 174 |
+
st.set_page_config(page_title="π§ Deep Research Assistant 3.0", layout="centered")
|
| 175 |
+
|
| 176 |
+
# --- Load Memory ---
|
| 177 |
if "memory_bank" not in st.session_state:
|
| 178 |
st.session_state.memory_bank = []
|
|
|
|
| 179 |
if "chat_threads" not in st.session_state:
|
| 180 |
st.session_state.chat_threads = {}
|
|
|
|
| 181 |
if "current_thread_id" not in st.session_state:
|
| 182 |
st.session_state.current_thread_id = None
|
| 183 |
|
| 184 |
+
load_session_data()
|
| 185 |
+
|
| 186 |
+
# --- Sidebar ---
|
| 187 |
with st.sidebar:
|
| 188 |
+
st.title("Deep Research Assistant 3.0 π")
|
| 189 |
+
topic = st.text_input("π Enter research topic")
|
| 190 |
report_type = st.selectbox("π Report Type", ["Summary", "Detailed Report", "Thorough Academic Research"])
|
| 191 |
tone = st.selectbox("π― Tone", ["Objective", "Persuasive", "Narrative"])
|
| 192 |
source_type = st.selectbox("π Sources", ["Web Only", "Academic Only", "Hybrid"])
|
| 193 |
custom_domains = st.text_input("π Optional Domains", placeholder="example.com, nature.com")
|
| 194 |
research_button = st.button("π Start Research")
|
| 195 |
|
| 196 |
+
# --- Main Area ---
|
| 197 |
st.title("π Research Output")
|
| 198 |
|
| 199 |
if research_button and topic:
|
| 200 |
try:
|
| 201 |
+
with st.status("π Gathering sources..."):
|
| 202 |
all_sources = []
|
| 203 |
if source_type in ["Web Only", "Hybrid"]:
|
| 204 |
all_sources += get_sources(topic, custom_domains) if custom_domains.strip() else get_sources(topic)
|
|
|
|
| 213 |
merged = sort_sources_chronologically(merged)
|
| 214 |
chronological_progress = build_chronological_progression(merged)
|
| 215 |
|
| 216 |
+
previous_learnings = "\n\n".join(st.session_state.memory_bank[-5:])
|
|
|
|
| 217 |
|
| 218 |
citations = [f"- {s['title']} ({s['year']}) [{s['source']}]({s['url']})" for s in merged]
|
| 219 |
sources_text = "\n".join([
|
|
|
|
| 227 |
"Thorough Academic Research": "Craft a full academic paper >1000 words."
|
| 228 |
}[report_type]
|
| 229 |
|
|
|
|
| 230 |
thread_id = str(uuid.uuid4())
|
| 231 |
st.session_state.current_thread_id = thread_id
|
| 232 |
st.session_state.chat_threads[thread_id] = []
|
| 233 |
|
|
|
|
| 234 |
prompt = f"""
|
| 235 |
+
Use past learnings:
|
| 236 |
|
|
|
|
| 237 |
{previous_learnings}
|
| 238 |
|
| 239 |
+
New Topic:
|
| 240 |
{topic}
|
| 241 |
|
| 242 |
+
Writing:
|
| 243 |
{tone} tone, {length_instruction}
|
| 244 |
|
| 245 |
+
Timeline:
|
| 246 |
{chronological_progress}
|
| 247 |
|
| 248 |
+
Sources:
|
| 249 |
{sources_text}
|
| 250 |
|
| 251 |
+
Citations:
|
| 252 |
{chr(10).join(citations)}
|
| 253 |
"""
|
| 254 |
|
|
|
|
| 255 |
st.subheader(f"π {report_type} on '{topic}'")
|
| 256 |
output_placeholder = st.empty()
|
| 257 |
final_output = ""
|
|
|
|
| 262 |
st.session_state.memory_bank.append(final_output)
|
| 263 |
st.session_state.chat_threads[thread_id].append({"role": "assistant", "content": final_output})
|
| 264 |
|
| 265 |
+
save_session_data()
|
| 266 |
+
|
| 267 |
except Exception as e:
|
| 268 |
st.error(f"β Error: {e}")
|
| 269 |
|
| 270 |
+
# --- Chat Threads and Follow-ups ---
|
| 271 |
st.divider()
|
| 272 |
st.subheader("π Your Research Threads")
|
| 273 |
|
|
|
|
| 277 |
role = "π§ You" if msg['role'] == 'user' else "π€ Assistant"
|
| 278 |
st.markdown(f"**{role}:** {msg['content']}")
|
| 279 |
|
| 280 |
+
followup = st.text_input(f"π¬ Ask more in Thread {tid[:8]}:", key=f"followup_{tid}")
|
| 281 |
+
if st.button(f"Ask Follow-up {tid}", key=f"button_{tid}"):
|
| 282 |
+
if followup:
|
| 283 |
+
response = ""
|
| 284 |
+
for chunk in call_llm(st.session_state.chat_threads[tid] + [{"role": "user", "content": followup}], max_tokens=2000):
|
| 285 |
+
response += chunk
|
| 286 |
+
st.session_state.chat_threads[tid].append({"role": "user", "content": followup})
|
| 287 |
+
st.session_state.chat_threads[tid].append({"role": "assistant", "content": response})
|
| 288 |
+
save_session_data()
|
| 289 |
+
st.experimental_rerun()
|
| 290 |
+
|
| 291 |
+
# --- Download Button ---
|
| 292 |
+
if st.session_state.chat_threads:
|
| 293 |
+
pdf_file = download_threads_as_pdf(st.session_state.chat_threads)
|
| 294 |
+
st.download_button("π₯ Download All Threads as PDF", data=pdf_file, file_name="Research_Threads.pdf", mime="application/pdf")
|
| 295 |
+
|
| 296 |
|
| 297 |
|
| 298 |
# π§ Initialize session state
|