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