Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
-
import
|
| 2 |
from bs4 import BeautifulSoup
|
| 3 |
-
from flask import Flask, request, jsonify
|
| 4 |
from flask_cors import CORS
|
| 5 |
|
| 6 |
app = Flask(__name__)
|
|
@@ -8,7 +8,13 @@ CORS(app)
|
|
| 8 |
|
| 9 |
def scrape_startpage(query, n=10):
|
| 10 |
s = requests.Session()
|
| 11 |
-
s.headers.update({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
time.sleep(1)
|
| 14 |
r = s.get('https://www.startpage.com/sp/search', params={'query': query, 'cat': 'web', 'pl': 'opensearch'})
|
|
@@ -17,12 +23,16 @@ def scrape_startpage(query, n=10):
|
|
| 17 |
results = []
|
| 18 |
for c in soup.find_all('div', class_='result')[:n]:
|
| 19 |
t = c.find('a', class_='result-title')
|
| 20 |
-
if not t:
|
|
|
|
| 21 |
d = c.find('p', class_='result-description') or c.find('span', class_='result-description')
|
| 22 |
-
results.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
return results
|
| 24 |
-
except Exception
|
| 25 |
-
print(f"Error: {e}")
|
| 26 |
return []
|
| 27 |
|
| 28 |
def get_weather_from_ip(ip_address):
|
|
@@ -30,80 +40,98 @@ def get_weather_from_ip(ip_address):
|
|
| 30 |
ip_response = requests.get(f'https://ipinfo.io/{ip_address}/json')
|
| 31 |
ip_response.raise_for_status()
|
| 32 |
ip_data = ip_response.json()
|
| 33 |
-
|
| 34 |
if ip_data.get('error'):
|
| 35 |
-
return {'error': 'Invalid IP
|
| 36 |
-
|
| 37 |
loc = ip_data.get('loc', '')
|
| 38 |
if not loc:
|
| 39 |
-
return {'error': '
|
| 40 |
-
|
| 41 |
lat, lon = loc.split(',')
|
| 42 |
city = ip_data.get('city', 'Unknown')
|
| 43 |
country = ip_data.get('country', '')
|
| 44 |
-
|
| 45 |
if country != 'US':
|
| 46 |
-
return {'error': '
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
forecast_url = points_data['properties']['forecast']
|
| 53 |
-
forecast_response = requests.get(forecast_url)
|
| 54 |
-
forecast_response.raise_for_status()
|
| 55 |
-
forecast_data = forecast_response.json()
|
| 56 |
-
|
| 57 |
-
current_period = forecast_data['properties']['periods'][0]
|
| 58 |
-
|
| 59 |
return {
|
| 60 |
'ip': ip_address,
|
| 61 |
-
'location': {
|
| 62 |
-
'city': city,
|
| 63 |
-
'country': ip_data.get('country'),
|
| 64 |
-
'latitude': lat,
|
| 65 |
-
'longitude': lon
|
| 66 |
-
},
|
| 67 |
'weather': {
|
| 68 |
-
'temperature':
|
| 69 |
-
'
|
| 70 |
-
'humidity': None,
|
| 71 |
-
'description': current_period['detailedForecast'],
|
| 72 |
-
'icon': None
|
| 73 |
}
|
| 74 |
}
|
| 75 |
-
except requests.exceptions.RequestException as e:
|
| 76 |
-
if '429' in str(e):
|
| 77 |
-
return {'error': 'Rate limit exceeded. Please try again later.'}
|
| 78 |
-
return {'error': f'API request failed: {str(e)}'}
|
| 79 |
except Exception as e:
|
| 80 |
-
return {'error':
|
| 81 |
|
| 82 |
-
@app.route('/search'
|
| 83 |
def search():
|
| 84 |
-
|
| 85 |
-
if not
|
| 86 |
-
return jsonify({'error': 'Missing
|
| 87 |
-
|
| 88 |
n = request.args.get('n', default=10, type=int)
|
| 89 |
-
results
|
| 90 |
-
return jsonify({'query': query, 'results': results})
|
| 91 |
|
| 92 |
-
@app.route('/weather'
|
| 93 |
def weather():
|
| 94 |
ip = request.args.get('ip')
|
| 95 |
if not ip:
|
| 96 |
-
return jsonify({'error': 'Missing
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
return jsonify(weather_data)
|
| 103 |
|
| 104 |
-
@app.route('/'
|
| 105 |
def health():
|
| 106 |
return jsonify({'status': 'running', 'message': 'GridLock search API'})
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
if __name__ == '__main__':
|
| 109 |
-
app.run(host='0.0.0.0', port=7860, debug=True)
|
|
|
|
| 1 |
+
import os, time, json, base64, requests, itertools
|
| 2 |
from bs4 import BeautifulSoup
|
| 3 |
+
from flask import Flask, request, jsonify, Response, stream_with_context
|
| 4 |
from flask_cors import CORS
|
| 5 |
|
| 6 |
app = Flask(__name__)
|
|
|
|
| 8 |
|
| 9 |
def scrape_startpage(query, n=10):
|
| 10 |
s = requests.Session()
|
| 11 |
+
s.headers.update({
|
| 12 |
+
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
|
| 13 |
+
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
| 14 |
+
'Accept-Language': 'en-US,en;q=0.5',
|
| 15 |
+
'Accept-Encoding': 'gzip, deflate',
|
| 16 |
+
'Connection': 'keep-alive'
|
| 17 |
+
})
|
| 18 |
try:
|
| 19 |
time.sleep(1)
|
| 20 |
r = s.get('https://www.startpage.com/sp/search', params={'query': query, 'cat': 'web', 'pl': 'opensearch'})
|
|
|
|
| 23 |
results = []
|
| 24 |
for c in soup.find_all('div', class_='result')[:n]:
|
| 25 |
t = c.find('a', class_='result-title')
|
| 26 |
+
if not t:
|
| 27 |
+
continue
|
| 28 |
d = c.find('p', class_='result-description') or c.find('span', class_='result-description')
|
| 29 |
+
results.append({
|
| 30 |
+
'title': t.get_text(strip=True),
|
| 31 |
+
'url': t.get('href'),
|
| 32 |
+
'desc': d.get_text(strip=True) if d else ''
|
| 33 |
+
})
|
| 34 |
return results
|
| 35 |
+
except Exception:
|
|
|
|
| 36 |
return []
|
| 37 |
|
| 38 |
def get_weather_from_ip(ip_address):
|
|
|
|
| 40 |
ip_response = requests.get(f'https://ipinfo.io/{ip_address}/json')
|
| 41 |
ip_response.raise_for_status()
|
| 42 |
ip_data = ip_response.json()
|
|
|
|
| 43 |
if ip_data.get('error'):
|
| 44 |
+
return {'error': 'Invalid IP'}
|
|
|
|
| 45 |
loc = ip_data.get('loc', '')
|
| 46 |
if not loc:
|
| 47 |
+
return {'error': 'No location'}
|
|
|
|
| 48 |
lat, lon = loc.split(',')
|
| 49 |
city = ip_data.get('city', 'Unknown')
|
| 50 |
country = ip_data.get('country', '')
|
|
|
|
| 51 |
if country != 'US':
|
| 52 |
+
return {'error': 'US only'}
|
| 53 |
+
points = requests.get(f'https://api.weather.gov/points/{lat},{lon}').json()
|
| 54 |
+
forecast_url = points['properties']['forecast']
|
| 55 |
+
forecast = requests.get(forecast_url).json()
|
| 56 |
+
current = forecast['properties']['periods'][0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
return {
|
| 58 |
'ip': ip_address,
|
| 59 |
+
'location': {'city': city, 'country': country, 'latitude': lat, 'longitude': lon},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
'weather': {
|
| 61 |
+
'temperature': current['temperature'], 'feels_like': None, 'humidity': None,
|
| 62 |
+
'description': current['detailedForecast'], 'icon': None
|
|
|
|
|
|
|
|
|
|
| 63 |
}
|
| 64 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
except Exception as e:
|
| 66 |
+
return {'error': str(e)}
|
| 67 |
|
| 68 |
+
@app.route('/search')
|
| 69 |
def search():
|
| 70 |
+
q = request.args.get('q')
|
| 71 |
+
if not q:
|
| 72 |
+
return jsonify({'error': 'Missing q'}), 400
|
|
|
|
| 73 |
n = request.args.get('n', default=10, type=int)
|
| 74 |
+
return jsonify({'query': q, 'results': scrape_startpage(q, n)})
|
|
|
|
| 75 |
|
| 76 |
+
@app.route('/weather')
|
| 77 |
def weather():
|
| 78 |
ip = request.args.get('ip')
|
| 79 |
if not ip:
|
| 80 |
+
return jsonify({'error': 'Missing ip'}), 400
|
| 81 |
+
data = get_weather_from_ip(ip)
|
| 82 |
+
if 'error' in data:
|
| 83 |
+
return jsonify(data), 400
|
| 84 |
+
return jsonify(data)
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
@app.route('/')
|
| 87 |
def health():
|
| 88 |
return jsonify({'status': 'running', 'message': 'GridLock search API'})
|
| 89 |
|
| 90 |
+
def morsify_key():
|
| 91 |
+
b1 = "bnZhcGktd0"
|
| 92 |
+
b2 = "VIa0RZSnVpYU"
|
| 93 |
+
b3 = "FfVDktXNHVrU1E"
|
| 94 |
+
b4 = "2YzBfV085TjlCUFBIaDlGRnBpZW9PNlVLN"
|
| 95 |
+
b5 = "WliQ1NBZGl"
|
| 96 |
+
seq = [b1[::-1], b2[::2] + b3[1::2], b4[::-1], b5]
|
| 97 |
+
j = "".join(seq)
|
| 98 |
+
z = base64.b64encode(j.encode()).decode()
|
| 99 |
+
y = "".join(chr((ord(c) - i) % 126) for i, c in enumerate(z))
|
| 100 |
+
x = base64.b64decode(base64.b64encode(y.encode())).decode()
|
| 101 |
+
mix = "".join(chr(ord(a) ^ ord(b)) for a, b in zip(x, itertools.cycle("K3yMix")))
|
| 102 |
+
clean = base64.b64decode(base64.b64encode(mix.encode())).decode()
|
| 103 |
+
return "".join(reversed(clean))[40:]+clean[:40]
|
| 104 |
+
|
| 105 |
+
@app.route('/v1/chat/completions', methods=['POST'])
|
| 106 |
+
def chat_completions():
|
| 107 |
+
data = request.get_json(force=True)
|
| 108 |
+
if not data or 'messages' not in data:
|
| 109 |
+
return jsonify({'error': 'Missing messages'}), 400
|
| 110 |
+
stream = data.get('stream', True)
|
| 111 |
+
api_key = morsify_key()
|
| 112 |
+
payload = {
|
| 113 |
+
"model": data.get("model", "meta/llama-4-scout-17b-16e-instruct"),
|
| 114 |
+
"messages": data["messages"],
|
| 115 |
+
"max_tokens": data.get("max_tokens", 512),
|
| 116 |
+
"temperature": data.get("temperature", 1.0),
|
| 117 |
+
"top_p": data.get("top_p", 1.0),
|
| 118 |
+
"frequency_penalty": data.get("frequency_penalty", 0.0),
|
| 119 |
+
"presence_penalty": data.get("presence_penalty", 0.0),
|
| 120 |
+
"stream": stream
|
| 121 |
+
}
|
| 122 |
+
headers = {"Authorization": f"Bearer {api_key}", "Accept": "text/event-stream" if stream else "application/json"}
|
| 123 |
+
try:
|
| 124 |
+
r = requests.post("https://integrate.api.nvidia.com/v1/chat/completions", headers=headers, json=payload, stream=stream, timeout=120)
|
| 125 |
+
if stream:
|
| 126 |
+
def generate():
|
| 127 |
+
for line in r.iter_lines():
|
| 128 |
+
if line:
|
| 129 |
+
yield f"data: {line.decode('utf-8')}\n\n"
|
| 130 |
+
return Response(stream_with_context(generate()), content_type='text/event-stream')
|
| 131 |
+
else:
|
| 132 |
+
return jsonify(r.json())
|
| 133 |
+
except Exception as e:
|
| 134 |
+
return jsonify({'error': str(e)}), 500
|
| 135 |
+
|
| 136 |
if __name__ == '__main__':
|
| 137 |
+
app.run(host='0.0.0.0', port=7860, debug=True)
|