from flask import Flask, render_template, request from duckduckgo_search import DDGS from urllib.parse import urlparse import time import random import threading import os app = Flask(__name__) search_lock = threading.Lock() def get_search_results(query): results_list = [] with search_lock: try: # Jitter delay to avoid being flagged as a bot time.sleep(random.uniform(0.5, 1.0)) with DDGS() as ddgs: # We use the 'text' method which is most stable ddgs_gen = ddgs.text(query, region='wt-wt', safesearch='moderate') counter = 0 for r in ddgs_gen: if counter >= 10: break domain = urlparse(r['href']).netloc results_list.append({ 'title': r['title'], 'url': r['href'], 'domain': domain, 'description': r['body'] }) counter += 1 return results_list except Exception as e: # This will show up in your Hugging Face Logs print(f"!!! LOGS ERROR: {e}", flush=True) return [] @app.route('/') def index(): query = request.args.get('q') if query: search_results = get_search_results(query) return render_template('index.html', results=search_results, query=query, searching=True) return render_template('index.html', searching=False) if __name__ == '__main__': # Hugging Face port requirement port = int(os.environ.get("PORT", 7860)) app.run(host='0.0.0.0', port=port)