File size: 1,688 Bytes
e332e3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db58b0
 
e332e3f
9db58b0
e332e3f
9db58b0
e332e3f
 
 
 
 
 
 
 
 
 
 
 
 
9db58b0
 
e332e3f
 
 
 
 
 
 
 
 
 
 
9db58b0
 
 
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
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)