Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,44 +3,38 @@ import os
|
|
| 3 |
import streamlit as st
|
| 4 |
import requests
|
| 5 |
import datetime
|
| 6 |
-
|
| 7 |
-
from duckduckgo_search import DDGS
|
| 8 |
import feedparser
|
| 9 |
-
import
|
| 10 |
-
from
|
|
|
|
|
|
|
|
|
|
| 11 |
|
|
|
|
| 12 |
load_dotenv()
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
"
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def get_sources(topic, domains):
|
| 36 |
-
with DDGS() as ddgs:
|
| 37 |
-
return [{
|
| 38 |
-
"title": r.get("title", "Untitled"),
|
| 39 |
-
"snippet": r.get("body", ""),
|
| 40 |
-
"url": r.get("href", "")
|
| 41 |
-
} for r in ddgs.text(topic + " site:" + domains if domains else topic, max_results=5)]
|
| 42 |
-
|
| 43 |
-
def get_arxiv_papers(query):
|
| 44 |
from urllib.parse import quote_plus
|
| 45 |
url = f"http://export.arxiv.org/api/query?search_query=all:{quote_plus(query)}&start=0&max_results=3"
|
| 46 |
feed = feedparser.parse(url)
|
|
@@ -50,112 +44,106 @@ def get_arxiv_papers(query):
|
|
| 50 |
"url": next((l.href for l in e.links if l.type == "application/pdf"), "")
|
| 51 |
} for e in feed.entries]
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
"
|
| 98 |
-
])
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
st.markdown(f"**{h['title']}** - [{h['url']}]({h['url']})")
|
| 157 |
-
else:
|
| 158 |
-
st.success("β
No major overlaps detected.")
|
| 159 |
-
|
| 160 |
-
except Exception as e:
|
| 161 |
-
st.error(f"Error: {e}")
|
|
|
|
| 3 |
import streamlit as st
|
| 4 |
import requests
|
| 5 |
import datetime
|
| 6 |
+
import openai
|
|
|
|
| 7 |
import feedparser
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
from tavily import TavilyClient
|
| 10 |
+
from PyPDF2 import PdfReader
|
| 11 |
+
import faiss
|
| 12 |
+
import numpy as np
|
| 13 |
|
| 14 |
+
# --- Load API Keys ---
|
| 15 |
load_dotenv()
|
| 16 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 17 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "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")
|
| 18 |
+
tavily = TavilyClient(api_key=TAVILY_API_KEY)
|
| 19 |
+
|
| 20 |
+
# --- Streamlit Config ---
|
| 21 |
+
st.set_page_config(page_title="GPT Researcher Agent", layout="wide")
|
| 22 |
+
st.title("π GPT-Powered Research Assistant")
|
| 23 |
+
|
| 24 |
+
# --- Helper: APA Citation ---
|
| 25 |
+
def generate_apa_citation(title, url, source):
|
| 26 |
+
year = datetime.datetime.now().year
|
| 27 |
+
label = {
|
| 28 |
+
"arxiv": "*arXiv*", "semantic": "*Semantic Scholar*", "web": "*Web*"
|
| 29 |
+
}.get(source, "*Web*")
|
| 30 |
+
return f"{title}. ({year}). {label}. {url}"
|
| 31 |
+
|
| 32 |
+
# --- Search Tools ---
|
| 33 |
+
def tavily_search(query):
|
| 34 |
+
results = tavily.search(query, search_depth="advanced", max_results=5)
|
| 35 |
+
return results.get("results", [])
|
| 36 |
+
|
| 37 |
+
def arxiv_search(query):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
from urllib.parse import quote_plus
|
| 39 |
url = f"http://export.arxiv.org/api/query?search_query=all:{quote_plus(query)}&start=0&max_results=3"
|
| 40 |
feed = feedparser.parse(url)
|
|
|
|
| 44 |
"url": next((l.href for l in e.links if l.type == "application/pdf"), "")
|
| 45 |
} for e in feed.entries]
|
| 46 |
|
| 47 |
+
# --- Document Embedding ---
|
| 48 |
+
def embed_document(file):
|
| 49 |
+
doc_text = ""
|
| 50 |
+
if file.name.endswith(".pdf"):
|
| 51 |
+
reader = PdfReader(file)
|
| 52 |
+
for page in reader.pages:
|
| 53 |
+
text = page.extract_text()
|
| 54 |
+
if text:
|
| 55 |
+
doc_text += text
|
| 56 |
+
else:
|
| 57 |
+
doc_text = file.read().decode("utf-8")
|
| 58 |
+
|
| 59 |
+
chunks = [doc_text[i:i+1000] for i in range(0, len(doc_text), 1000)]
|
| 60 |
+
embeddings = openai.Embedding.create(input=chunks, model="text-embedding-ada-002")
|
| 61 |
+
vectors = [np.array(rec["embedding"], dtype=np.float32) for rec in embeddings["data"]]
|
| 62 |
+
|
| 63 |
+
dim = len(vectors[0])
|
| 64 |
+
index = faiss.IndexFlatL2(dim)
|
| 65 |
+
index.add(np.vstack(vectors))
|
| 66 |
+
|
| 67 |
+
return chunks, index
|
| 68 |
+
|
| 69 |
+
# --- Streaming GPT Call ---
|
| 70 |
+
def stream_response(messages):
|
| 71 |
+
response = openai.ChatCompletion.create(
|
| 72 |
+
model="gpt-4",
|
| 73 |
+
messages=messages,
|
| 74 |
+
max_tokens=3000,
|
| 75 |
+
stream=True
|
| 76 |
+
)
|
| 77 |
+
collected = ""
|
| 78 |
+
placeholder = st.empty()
|
| 79 |
+
for chunk in response:
|
| 80 |
+
delta = chunk["choices"][0].get("delta", {})
|
| 81 |
+
if "content" in delta:
|
| 82 |
+
token = delta["content"]
|
| 83 |
+
collected += token
|
| 84 |
+
placeholder.markdown(collected + "β")
|
| 85 |
+
placeholder.markdown(collected)
|
| 86 |
+
return collected
|
| 87 |
+
|
| 88 |
+
# --- Sidebar Input ---
|
| 89 |
+
with st.sidebar:
|
| 90 |
+
topic = st.text_input("π Research Topic", "AI in Sustainable Agriculture")
|
| 91 |
+
report_type = st.selectbox("π Report Type", ["Summary", "Detailed", "Academic Paper"])
|
| 92 |
+
tone = st.selectbox("π― Tone", ["Objective", "Scientific", "Persuasive"])
|
| 93 |
+
sources = st.selectbox("π Sources", ["Web", "Documents", "Both"])
|
| 94 |
+
uploaded_file = st.file_uploader("π Upload Document (PDF/TXT)", type=["pdf", "txt"])
|
| 95 |
+
start_button = st.button("π Run Research")
|
| 96 |
+
|
| 97 |
+
# --- Main Agent Execution ---
|
| 98 |
+
if start_button and topic:
|
| 99 |
+
st.subheader("π§ Agent Log")
|
| 100 |
+
with st.container():
|
| 101 |
+
st.markdown("<div style='max-height:300px; overflow-y:auto; background:#222; padding:10px; border-radius:10px;'>", unsafe_allow_html=True)
|
| 102 |
+
st.markdown("π§ Starting research task...")
|
| 103 |
+
st.markdown(f"π Topic: **{topic}** | Tone: _{tone}_ | Type: _{report_type}_")
|
| 104 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 105 |
+
|
| 106 |
+
citations = []
|
| 107 |
+
context = ""
|
| 108 |
+
|
| 109 |
+
if sources in ["Web", "Both"]:
|
| 110 |
+
st.info("π Searching web sources via Tavily...")
|
| 111 |
+
web_results = tavily_search(topic)
|
| 112 |
+
for r in web_results:
|
| 113 |
+
context += f"{r.get('content','')}
|
| 114 |
+
"
|
| 115 |
+
citations.append(generate_apa_citation(r.get("title", "Untitled"), r.get("url", "#"), "web"))
|
| 116 |
+
|
| 117 |
+
if sources in ["Documents", "Both"] and uploaded_file:
|
| 118 |
+
st.info("π Embedding and retrieving from uploaded document...")
|
| 119 |
+
chunks, index = embed_document(uploaded_file)
|
| 120 |
+
q_embed = openai.Embedding.create(input=[topic], model="text-embedding-ada-002")
|
| 121 |
+
q_vector = np.array(q_embed["data"][0]["embedding"], dtype=np.float32).reshape(1, -1)
|
| 122 |
+
D, I = index.search(q_vector, k=3)
|
| 123 |
+
for idx in I[0]:
|
| 124 |
+
context += chunks[idx] + "
|
| 125 |
+
"
|
| 126 |
+
citations.append(generate_apa_citation(uploaded_file.name, "Uploaded", "local"))
|
| 127 |
+
|
| 128 |
+
st.info("βοΈ Generating final research report...")
|
| 129 |
+
messages = [
|
| 130 |
+
{"role": "system", "content": f"You are a research assistant. Write a {report_type.lower()} in a {tone.lower()} tone, citing sources."},
|
| 131 |
+
{"role": "user", "content": f"Topic: {topic}
|
| 132 |
+
|
| 133 |
+
Context:
|
| 134 |
+
{context}
|
| 135 |
+
|
| 136 |
+
Write a complete report in academic markdown format."}
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
final_output = stream_response(messages)
|
| 140 |
+
|
| 141 |
+
# --- Show Output and Citations ---
|
| 142 |
+
st.subheader("π Final Report")
|
| 143 |
+
st.markdown(final_output, unsafe_allow_html=True)
|
| 144 |
+
|
| 145 |
+
st.subheader("π References")
|
| 146 |
+
for cite in citations:
|
| 147 |
+
st.markdown(f"- {cite}")
|
| 148 |
+
|
| 149 |
+
st.download_button("πΎ Download Markdown", final_output, file_name="report.md", mime="text/markdown")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|