Spaces:
Running
Running
from flask import Flask, request, jsonify | |
import requests | |
app = Flask(__name__) | |
# Define the SearXNG instance URL | |
SEARXNG_INSTANCE_URL = "https://oscarwang2-searxng.hf.space/search" | |
def search(): | |
# Get the search term from query parameters | |
search_term = request.args.get('q', '') | |
if not search_term: | |
return jsonify({'error': 'No search term provided'}), 400 | |
# Define the query parameters for the SearXNG API | |
params = { | |
'q': search_term, | |
'format': 'json', | |
'categories': 'general' | |
} | |
try: | |
# Make the request to the SearXNG API | |
response = requests.get(SEARXNG_INSTANCE_URL, params=params) | |
# Check the response status code | |
if response.status_code == 200: | |
data = response.json() | |
# Retrieve the first 3 snippets | |
results = data.get('results', [])[:30] | |
snippets = [] | |
# Collect the snippets | |
for result in results: | |
snippet = { | |
'title': result.get('title', 'No title'), | |
'snippet': result.get('content', 'No snippet available'), | |
'url': result.get('url', 'No URL') | |
} | |
snippets.append(snippet) | |
# Return the snippets as a JSON response | |
return jsonify(snippets) | |
else: | |
return jsonify({'error': f'SearXNG API error: {response.status_code}'}), response.status_code | |
except Exception as e: | |
return jsonify({'error': str(e)}), 500 | |
if __name__ == '__main__': | |
# Run the Flask app on port 7860 | |
app.run(host='0.0.0.0', port=7860, debug=True) |