Spaces:
Sleeping
Sleeping
from flask import Flask, request, jsonify | |
from urllib.parse import quote | |
import requests | |
from bs4 import BeautifulSoup | |
app = Flask(__name__) | |
# DuckDuckGo search API | |
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 | |
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) | |