Spaces:
Sleeping
Sleeping
hussein2000
commited on
Commit
•
0db0b4e
1
Parent(s):
df0bd78
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
from urllib.parse import quote
|
3 |
+
import requests
|
4 |
+
from bs4 import BeautifulSoup
|
5 |
+
|
6 |
+
app = Flask(__name__)
|
7 |
+
|
8 |
+
# DuckDuckGo search API
|
9 |
+
@app.route('/search', methods=['GET'])
|
10 |
+
def search_duckduckgo():
|
11 |
+
query = request.args.get('query')
|
12 |
+
if not query:
|
13 |
+
return jsonify([]), 400
|
14 |
+
|
15 |
+
url = 'https://duckduckgo.com/html/'
|
16 |
+
params = {'q': query}
|
17 |
+
headers = {'User-Agent': 'Mozilla/5.0'}
|
18 |
+
|
19 |
+
response = requests.get(url, params=params, headers=headers)
|
20 |
+
if response.status_code != 200:
|
21 |
+
return jsonify([]), response.status_code
|
22 |
+
|
23 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
24 |
+
results = []
|
25 |
+
for result in soup.find_all('a', class_='result__a'):
|
26 |
+
title = result.get_text()
|
27 |
+
link = result['href']
|
28 |
+
results.append({
|
29 |
+
'title': title,
|
30 |
+
'link': link
|
31 |
+
})
|
32 |
+
return jsonify(results)
|
33 |
+
|
34 |
+
# Google Image Search API
|
35 |
+
@app.route('/image_search', methods=['GET'])
|
36 |
+
def get_image_urls():
|
37 |
+
query = request.args.get('query')
|
38 |
+
num_images = int(request.args.get('num_images', 10))
|
39 |
+
|
40 |
+
if not query:
|
41 |
+
return jsonify([]), 400
|
42 |
+
|
43 |
+
query = quote(query)
|
44 |
+
url = f"https://www.google.com/search?hl=en&tbm=isch&q={query}"
|
45 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
46 |
+
|
47 |
+
response = requests.get(url, headers=headers)
|
48 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
49 |
+
|
50 |
+
image_urls = []
|
51 |
+
for img_tag in soup.find_all("img", limit=num_images):
|
52 |
+
img_url = img_tag.get("src")
|
53 |
+
if img_url and img_url.startswith("http"):
|
54 |
+
image_urls.append(img_url)
|
55 |
+
|
56 |
+
return jsonify(image_urls)
|
57 |
+
|
58 |
+
if __name__ == '__main__':
|
59 |
+
app.run(host="0.0.0.0", port=7860)
|