SharryOG commited on
Commit
dc28452
1 Parent(s): bb68b02

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -89
app.py CHANGED
@@ -1,107 +1,230 @@
1
- from fastapi import FastAPI, Query
2
- from pydantic import BaseModel
3
- from typing import Optional, List
 
 
 
 
4
  from webscout import WEBS
5
-
6
- app = FastAPI()
7
-
8
- class SearchQuery(BaseModel):
9
- q: str
10
- max_results: int = 10
11
- timelimit: Optional[int] = None
12
- safesearch: str = 'moderate'
13
- region: str = 'wt-wt'
14
-
15
- class ImageSearchQuery(BaseModel):
16
- q: str
17
- max_results: int = 10
18
- safesearch: str = 'moderate'
19
- region: str = 'wt-wt'
20
-
21
- class VideoSearchQuery(BaseModel):
22
- q: str
23
- max_results: int = 10
24
- safesearch: str = 'moderate'
25
- region: str = 'wt-wt'
26
- timelimit: Optional[int] = None
27
- resolution: Optional[str] = None
28
- duration: Optional[str] = None
29
-
30
- class NewsSearchQuery(BaseModel):
31
- q: str
32
- max_results: int = 10
33
- safesearch: str = 'moderate'
34
- region: str = 'wt-wt'
35
- timelimit: Optional[int] = None
36
-
37
- class MapSearchQuery(BaseModel):
38
- q: str
39
- place: Optional[str] = None
40
- max_results: int = 10
41
-
42
- class TranslateQuery(BaseModel):
43
- q: str
44
- to: str = 'en'
45
-
46
- class SuggestionQuery(BaseModel):
47
- q: str
48
-
49
- @app.get("/api/search", response_model=List[dict])
50
- async def search_text(query: SearchQuery):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  results = []
52
  with WEBS() as webs:
53
- for result in webs.text(**query.dict()):
54
  results.append(result)
55
- return results
56
-
57
- @app.get("/api/images", response_model=List[dict])
58
- async def search_images(query: ImageSearchQuery):
 
 
 
 
 
 
59
  results = []
60
  with WEBS() as webs:
61
- for result in webs.images(**query.dict()):
62
  results.append(result)
63
- return results
64
-
65
- @app.get("/api/videos", response_model=List[dict])
66
- async def search_videos(query: VideoSearchQuery):
 
 
 
 
 
 
 
 
 
67
  results = []
68
  with WEBS() as webs:
69
- for result in webs.videos(**query.dict()):
70
  results.append(result)
71
- return results
72
-
73
- @app.get("/api/news", response_model=List[dict])
74
- async def search_news(query: NewsSearchQuery):
 
 
 
 
 
 
 
75
  results = []
76
  with WEBS() as webs:
77
- for result in webs.news(**query.dict()):
78
  results.append(result)
79
- return results
80
-
81
- @app.get("/api/maps", response_model=List[dict])
82
- async def search_maps(query: MapSearchQuery):
 
 
 
 
 
83
  results = []
84
  with WEBS() as webs:
85
- for result in webs.maps(**query.dict()):
86
  results.append(result)
87
- return results
88
-
89
- @app.get("/api/translate", response_model=dict)
90
- async def translate_text(query: TranslateQuery):
 
 
 
 
91
  with WEBS() as webs:
92
- translation = webs.translate(**query.dict())
93
- return {'translation': translation}
94
-
95
- @app.get("/api/suggestions", response_model=List[str])
96
- async def search_suggestions(query: SuggestionQuery):
97
- if not query.q:
98
- raise HTTPException(status_code=400, detail="Query parameter missing")
 
 
99
  results = []
100
- with WEBS() as webs:
101
- for result in webs.suggestions(query.q):
102
- results.append(result)
103
- return results
104
-
105
- @app.get("/api/health", response_model=dict)
106
- async def health_check():
107
- return {'status': 'working'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+ from flask import Flask, jsonify, request, abort, render_template
4
+ import json
5
+ import random
6
+ import string
7
+ import datetime
8
  from webscout import WEBS
9
+ from functools import wraps
10
+ import requests
11
+
12
+ app = Flask(__name__)
13
+
14
+ TIMEOUT = 10
15
+ PROXY = None
16
+
17
+ PRICING_PLANS = {
18
+ 'free': {
19
+ 'name': 'Free Plan',
20
+ 'price': '$0/month',
21
+ 'rate_limit': 1000
22
+ },
23
+ 'pro': {
24
+ 'name': 'Pro Plan',
25
+ 'price': 'Coming Soon',
26
+ 'rate_limit': None # Unlimited
27
+ }
28
+ }
29
+
30
+ # Function to generate a new API key based on the user's name and the current date
31
+ def generate_api_key(username):
32
+ """Generate a new API key starting with 'HUAI' and including the user's name and the current date."""
33
+ current_date = datetime.datetime.now().strftime("%Y%m%d")
34
+ return 'HUAI' + username + current_date + ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
35
+
36
+ # Function to validate an API key against the stored keys
37
+ def validate_api_key(api_key):
38
+ """Validate an API key against the stored keys."""
39
+ with open('api_keys.json', 'r') as file:
40
+ api_keys = json.load(file)
41
+ return api_key in api_keys.values()
42
+
43
+ # Middleware to require an API key for each request
44
+ def require_api_key(view_function):
45
+ @wraps(view_function)
46
+ def decorated_function(*args, **kwargs):
47
+ # Check if the API key is provided in the headers
48
+ api_key = request.headers.get('HUSI')
49
+
50
+ # If not provided in headers, check query parameters
51
+ if not api_key:
52
+ api_key = request.args.get('HUAI')
53
+
54
+ if not validate_api_key(api_key):
55
+ abort(401) # Unauthorized
56
+ return view_function(*args, **kwargs)
57
+ return decorated_function
58
+
59
+
60
+ # Routes with API key requirement
61
+
62
+ @app.route('/api/search', methods=['GET'])
63
+ @require_api_key
64
+ def search_text():
65
+
66
+ query = request.args.get('q', '')
67
+ max_results = request.args.get('max_results', 10, type=int)
68
+ timelimit = request.args.get('timelimit', None)
69
+ safesearch = request.args.get('safesearch', 'moderate')
70
+ region = request.args.get('region', 'wt-wt')
71
+ WEBS_instance = WEBS()
72
  results = []
73
  with WEBS() as webs:
74
+ for result in enumerate(WEBS_instance.text(query, max_results=max_results, timelimit=timelimit, safesearch=safesearch, region=region)):
75
  results.append(result)
76
+ return jsonify({'results': results})
77
+
78
+ @app.route('/api/images', methods=['GET'])
79
+ @require_api_key
80
+ def search_images():
81
+ query = request.args.get('q', '')
82
+ max_results = request.args.get('max_results', 10, type=int)
83
+ safesearch = request.args.get('safesearch', 'moderate')
84
+ region = request.args.get('region', 'wt-wt')
85
+ WEBS_instance = WEBS()
86
  results = []
87
  with WEBS() as webs:
88
+ for result in enumerate(WEBS_instance.images(query, max_results=max_results, safesearch=safesearch, region=region)):
89
  results.append(result)
90
+ return jsonify({'results': results})
91
+
92
+ @app.route('/api/videos', methods=['GET'])
93
+ @require_api_key
94
+ def search_videos():
95
+ query = request.args.get('q', '')
96
+ max_results = request.args.get('max_results', 10, type=int)
97
+ safesearch = request.args.get('safesearch', 'moderate')
98
+ region = request.args.get('region', 'wt-wt')
99
+ timelimit = request.args.get('timelimit', None)
100
+ resolution = request.args.get('resolution', None)
101
+ duration = request.args.get('duration', None)
102
+ WEBS_instance = WEBS()
103
  results = []
104
  with WEBS() as webs:
105
+ for result in enumerate(WEBS_instance.videos(query, max_results=max_results, safesearch=safesearch, region=region, timelimit=timelimit, resolution=resolution, duration=duration)):
106
  results.append(result)
107
+ return jsonify({'results': results})
108
+
109
+ @app.route('/api/news', methods=['GET'])
110
+ @require_api_key
111
+ def search_news():
112
+ query = request.args.get('q', '')
113
+ max_results = request.args.get('max_results', 10, type=int)
114
+ safesearch = request.args.get('safesearch', 'moderate')
115
+ region = request.args.get('region', 'wt-wt')
116
+ timelimit = request.args.get('timelimit', None)
117
+ WEBS_instance = WEBS()
118
  results = []
119
  with WEBS() as webs:
120
+ for result in enumerate(WEBS_instance.news(query, max_results=max_results, safesearch=safesearch, region=region, timelimit=timelimit)):
121
  results.append(result)
122
+ return jsonify({'results': results})
123
+
124
+ @app.route('/api/maps', methods=['GET'])
125
+ @require_api_key
126
+ def search_maps():
127
+ query = request.args.get('q', '')
128
+ place = request.args.get('place', None)
129
+ max_results = request.args.get('max_results', 10, type=int)
130
+ WEBS_instance = WEBS()
131
  results = []
132
  with WEBS() as webs:
133
+ for result in enumerate(WEBS_instance.maps(query, place=place, max_results=max_results)):
134
  results.append(result)
135
+ return jsonify({'results': results})
136
+
137
+ @app.route('/api/translate', methods=['GET'])
138
+ @require_api_key
139
+ def translate_text():
140
+ query = request.args.get('q', '')
141
+ to_lang = request.args.get('to', 'en')
142
+ WEBS_instance = WEBS()
143
  with WEBS() as webs:
144
+ translation = enumerate(WEBS_instance.translate(query, to=to_lang))
145
+ return jsonify({'translation': translation})
146
+
147
+ @app.route('/api/suggestions', methods=['GET'])
148
+ @require_api_key
149
+ def search_suggestions():
150
+ query = request.args.get('q', '')
151
+ if not query:
152
+ return jsonify({'error': 'Query parameter missing'})
153
  results = []
154
+ try:
155
+ with WEBS() as webs:
156
+ for result in webs.suggestions(query):
157
+ results.append(result)
158
+ except Exception as e:
159
+ return jsonify({'error': str(e)}), 500
160
+ return jsonify({'results': results})
161
+
162
+ @app.route('/api/health', methods=['GET'])
163
+ @require_api_key
164
+ def health_check():
165
+ return jsonify({'status': 'working'})
166
+
167
+ import json
168
+ from flask import jsonify, request, abort
169
+
170
+ @app.route('/pricing', methods=['GET'])
171
+ def pricing():
172
+ return render_template('pricing.html', plans=PRICING_PLANS)
173
+
174
+
175
+ @app.route('/generate_key', methods=['GET', 'POST'])
176
+ def generate_key():
177
+ if request.method == 'POST':
178
+ username = request.form['username']
179
+ plan = request.form['plan']
180
+ if plan not in PRICING_PLANS:
181
+ return jsonify({'error': 'Invalid plan'}), 400
182
+ if plan == 'free' and PRICING_PLANS['free']['rate_limit'] == 0:
183
+ return jsonify({'error': 'Free plan is out of limits'}), 400
184
+
185
+ # Check if the user already has an API key
186
+ with open('api_keys.json', 'r') as file:
187
+ try:
188
+ api_keys = json.load(file)
189
+ except json.JSONDecodeError:
190
+ # If the file is empty or contains invalid JSON, initialize api_keys as an empty dict
191
+ api_keys = {}
192
+
193
+ if username in api_keys:
194
+ return jsonify({'api_key': api_keys[username]})
195
+
196
+ # Generate a new API key
197
+ new_key = generate_api_key(username)
198
+ try:
199
+ with open('api_keys.json', 'w') as file:
200
+ api_keys[username] = new_key
201
+ json.dump(api_keys, file, indent=4)
202
+ return jsonify({'api_key': new_key})
203
+ except Exception as e:
204
+ # Handle any other exceptions that might occur
205
+ return jsonify({'error': str(e)}), 500
206
+ else:
207
+ return render_template('index.html', plans=PRICING_PLANS)
208
+ if __name__ == '__main__':
209
+ def get_public_ip():
210
+ try:
211
+ response = requests.get('https://api.ipify.org/?format=json')
212
+ response.raise_for_status() # Raises a HTTPError if the response status is 4xx, 5xx
213
+ data = response.json()
214
+ return data['ip']
215
+ except requests.exceptions.RequestException as e:
216
+ print(f"An error occurred: {e}")
217
+ return None
218
+ except Exception as e:
219
+ print(f"An unexpected error occurred: {e}")
220
+ return None
221
+
222
+ # Get public IP or use a fallback
223
+ public_ip = get_public_ip() or 'Fallback_IP'
224
+
225
+ if public_ip:
226
+ print(f"Public IP: {public_ip}")
227
+ else:
228
+ print("Failed to retrieve public IP. Using fallback IP.")
229
+
230
+ app.run(debug=True)