SearXNG-Engine / app.py
Shreyas094's picture
Update app.py
8b21f9c verified
raw
history blame
3.76 kB
import gradio as gr
import requests
def search_searx(query, instance_url='https://searx.org', lang='en_US', categories='general'):
"""
Perform a search using the Searx API.
:param query: The search query string.
:param instance_url: The URL of the Searx instance.
:param lang: Language for search results (e.g., 'en_US').
:param categories: Categories to search in (e.g., 'general', 'images', 'videos').
:return: A list of formatted search results or an error message.
"""
search_endpoint = f"{instance_url}/search"
params = {
'q': query,
'format': 'json',
'language': lang,
'categories': categories,
'pageno': 1, # Page number
'time_range': '', # Time range filter
'engines': '', # Specify search engines, comma-separated
'safesearch': '0' # Safe search (0: off, 1: moderate, 2: strict)
}
try:
response = requests.get(search_endpoint, params=params, timeout=10)
response.raise_for_status() # Raise an error for bad status codes
data = response.json()
if 'results' not in data or not data['results']:
return "No results found."
formatted_results = ""
for idx, result in enumerate(data['results'], start=1):
title = result.get('title', 'No Title')
url = result.get('url', 'No URL')
snippet = result.get('content', 'No Description')
formatted_results += f"**{idx}. {title}**\n{url}\n{snippet}\n\n"
return formatted_results
except requests.exceptions.RequestException as e:
return f"An error occurred while searching: {e}"
def create_gradio_interface():
"""
Creates and returns the Gradio interface.
"""
with gr.Blocks() as demo:
gr.Markdown("# πŸ•΅οΈβ€β™‚οΈ Private Search with Searx and Gradio")
gr.Markdown(
"This application allows you to perform private searches using the [Searx](https://searx.org/) metasearch engine."
)
with gr.Row():
with gr.Column():
query = gr.Textbox(
label="Search Query",
placeholder="Enter your search query here...",
lines=1
)
instance_url = gr.Textbox(
label="Searx Instance URL",
value="https://searx.org",
placeholder="https://searx.instance.url",
lines=1
)
lang = gr.Textbox(
label="Language",
value="en_US",
placeholder="e.g., en_US",
lines=1
)
categories = gr.Textbox(
label="Categories",
value="general",
placeholder="e.g., general, images, videos",
lines=1
)
search_button = gr.Button("Search")
with gr.Column():
results = gr.Markdown("### Search Results will appear here...")
def perform_search(q, url, language, cats):
return search_searx(q, instance_url=url, lang=language, categories=cats)
search_button.click(
perform_search,
inputs=[query, instance_url, lang, categories],
outputs=results
)
gr.Markdown(
"""
---
**Note:** This application uses the Searx metasearch engine to fetch results from multiple sources while preserving your privacy.
"""
)
return demo
iface = create_gradio_interface()
if __name__ == "__main__":
iface.launch()