Spaces:
Sleeping
Sleeping
oscarwang2
commited on
Commit
•
656485a
1
Parent(s):
1bc0c9b
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
import requests
|
3 |
+
|
4 |
+
app = Flask(__name__)
|
5 |
+
|
6 |
+
# Define the SearXNG instance URL
|
7 |
+
SEARXNG_INSTANCE_URL = "https://oscarwang2-searxng.hf.space/search"
|
8 |
+
|
9 |
+
@app.route('/search', methods=['GET'])
|
10 |
+
def search():
|
11 |
+
# Get the search term from query parameters
|
12 |
+
search_term = request.args.get('q', '')
|
13 |
+
|
14 |
+
if not search_term:
|
15 |
+
return jsonify({'error': 'No search term provided'}), 400
|
16 |
+
|
17 |
+
# Define the query parameters for the SearXNG API
|
18 |
+
params = {
|
19 |
+
'q': search_term,
|
20 |
+
'format': 'json',
|
21 |
+
'categories': 'general'
|
22 |
+
}
|
23 |
+
|
24 |
+
try:
|
25 |
+
# Make the request to the SearXNG API
|
26 |
+
response = requests.get(SEARXNG_INSTANCE_URL, params=params)
|
27 |
+
|
28 |
+
# Check the response status code
|
29 |
+
if response.status_code == 200:
|
30 |
+
data = response.json()
|
31 |
+
# Retrieve the first 3 snippets
|
32 |
+
results = data.get('results', [])[:3]
|
33 |
+
snippets = []
|
34 |
+
|
35 |
+
# Collect the snippets
|
36 |
+
for result in results:
|
37 |
+
snippet = {
|
38 |
+
'title': result.get('title', 'No title'),
|
39 |
+
'snippet': result.get('content', 'No snippet available'),
|
40 |
+
'url': result.get('url', 'No URL')
|
41 |
+
}
|
42 |
+
snippets.append(snippet)
|
43 |
+
|
44 |
+
# Return the snippets as a JSON response
|
45 |
+
return jsonify(snippets)
|
46 |
+
else:
|
47 |
+
return jsonify({'error': f'SearXNG API error: {response.status_code}'}), response.status_code
|
48 |
+
|
49 |
+
except Exception as e:
|
50 |
+
return jsonify({'error': str(e)}), 500
|
51 |
+
|
52 |
+
if __name__ == '__main__':
|
53 |
+
app.run(debug=True)
|