Web-Research / app.py
nazib61's picture
Create app.py
7cb0d67 verified
import gradio as gr
from gradio_client import Client
from bs4 import BeautifulSoup
import os
# Initialize the client for the OpenResearcher space
client = Client("OpenResearcher/OpenResearcher")
def research_topic(question):
# 1. Get the API Key from Hugging Face Secrets (Environment Variables)
# If testing locally, you can replace os.getenv with your actual string,
# but for HF Spaces, use the Secret to keep it safe.
api_key = os.getenv("SERPER_KEY")
if not api_key:
return "Error: SERPER_KEY not found in Environment Variables. Please add it in Space Settings."
print(f"Researching: {question}...")
try:
# 2. Call the OpenResearcher API
result = client.predict(
question=question,
serper_key=api_key,
max_rounds=50,
api_name="/start_research"
)
# The API returns [user_input, full_html_log] at indices 0 and 1
raw_html = result[1]
# 3. Parse the HTML to find only the "answer-section"
soup = BeautifulSoup(raw_html, 'html.parser')
# Look for the div containing the final conclusion
answer_section = soup.find('div', class_='answer-section')
if answer_section:
# Return the clean HTML
return str(answer_section)
else:
# Fallback: Sometimes the API fails or returns a different format
return f"<div>Could not extract a final answer. Raw output length: {len(raw_html)} characters.</div>"
except Exception as e:
return f"An error occurred: {str(e)}"
# 4. Create the Gradio Interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🧠 Deep Search Conclusion Generator")
gr.Markdown("Enter a question. This app searches the web using OpenResearcher and filters out the thinking process to give you **only the final result**.")
with gr.Row():
inp = gr.Textbox(label="Your Question", placeholder="e.g. Top 10 Closest Black Holes to Earth")
btn = gr.Button("Start Research", variant="primary")
# HTML component renders the links and bold text correctly
out = gr.HTML(label="Final Conclusion")
btn.click(fn=research_topic, inputs=inp, outputs=out)
if __name__ == "__main__":
demo.launch()