-
Notifications
You must be signed in to change notification settings - Fork 7
/
app.py
1326 lines (1081 loc) · 45.2 KB
/
app.py
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import random
import base64
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# import google.generativeai as genai
import json
import requests
import yt_dlp
import sys
import uuid
import time
from datetime import datetime
import re
import subprocess
from deep_translator import GoogleTranslator
# from vercel_kv import VercelKV
from flask import (
Flask,
request,
render_template,
redirect,
flash,
url_for,
get_flashed_messages,
jsonify,
send_file,
abort,
Response,
)
# kv = VercelKV()
app = Flask(__name__)
@app.route('/')
def homepage():
return send_file('index.html')
# Hàm xác thực URL
def validate_url(url):
regex = re.compile(
r"^(http://www\.|https://www\.|http://|https://)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,}(:[0-9]{1,5})?(\/.*)?$"
)
# Trả về True nếu URL hợp lệ, ngược lại trả về False
return re.match(regex, url) is not None
def send_request(long_url):
if validate_url(long_url):
choice = random.choice(["TinyURL", "isgd", "vgd"])
if choice == "isgd":
return shorten_url_isgd(long_url)
elif choice == "TinyURL":
return shorten_url_tinyurl(long_url)
elif choice == "vgd":
return shorten_url_vgd(long_url)
else:
print("Invalid URL!")
return None
def shorten_url_isgd(long_url):
try:
# URL encode the long URL
encoded_long_url = requests.utils.quote(long_url)
# Construct the request URL for is.gd
request_url = f"https://is.gd/create.php?format=simple&url={encoded_long_url}"
# Send the GET request to is.gd
response = requests.get(request_url)
# Check for successful response
if response.status_code == 200:
# The response should be the shortened URL in plain text
return response.text.strip()
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except requests.exceptions.RequestException as e:
# Handle request errors
print(f"Error while shortening URL with is.gd: {e}")
return None
def shorten_url_tinyurl(long_url):
try:
# URL encode the long URL
encoded_long_url = requests.utils.quote(long_url, safe="")
# Construct the request URL for TinyURL
request_url = f"http://tinyurl.com/api-create.php?url={encoded_long_url}"
# Send the GET request to TinyURL
response = requests.get(request_url)
response.raise_for_status() # Raise an exception for 4xx/5xx errors
# Return the shortened URL in plain text
return response.text.strip()
except requests.exceptions.RequestException as e:
# Handle request errors
print(f"Error while shortening URL with TinyURL: {e}")
return None
def shorten_url_vgd(long_url):
try:
# URL encode the long URL
encoded_long_url = requests.utils.quote(long_url, safe="")
# Construct the request URL for v.gd
request_url = f"https://v.gd/create.php?format=simple&url={encoded_long_url}"
# Send the GET request to v.gd
response = requests.get(request_url)
# Check for successful response
if response.status_code == 200:
# The response should be the shortened URL in plain text
return response.text.strip()
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except requests.exceptions.RequestException as e:
# Handle request errors
print(f"Error while shortening URL with v.gd: {e}")
return None
@app.route("/about-me")
def about_me():
return render_template("about_me.html")
@app.route("/dev")
def dev():
return render_template("dev.html")
@app.route("/shorten-link", methods=["GET", "POST"])
def shorten_link():
if request.method == "POST":
long_url = request.form.get("long_url").strip()
short_url = send_request(long_url)
if short_url:
return render_template(
"shorten_link.html", short_url=short_url
) # Truyền short_url tới template
else:
flash("Không thể rút gọn URL.")
return redirect(request.url)
return render_template("shorten_link.html") # Trả về trang rút gọn URL
UPLOAD_FOLDER = "/tmp/uploads"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.secret_key = "28a03d4e9561e85914da8e57f55f5bbe"
app.config["MAX_CONTENT_LENGTH"] = 100 * 1024 * 1024 # 100MB
PIXELDRAIN_API_KEY = "fba3e1f5-269b-4758-8e44-78326d0d7d95"
RETRY_LIMIT = 3
upload_history = []
download_history = []
def clean_filename(filename):
# Remove any non-word (non-alphanumeric + underscore) characters
filename = re.sub(r'[^\w\.-]', '', filename)
# Remove any runs of periods (as they're redundant)
filename = re.sub(r'\.+', '.', filename)
return filename
def upload_to_gofile(file_data, filename):
url = "https://store1.gofile.io/uploadFile"
files = {"file": (filename, file_data)}
try:
response = requests.post(url, files=files, timeout=600)
response.raise_for_status()
response_json = response.json()
if response_json.get("status") == "ok":
download_link = response_json.get("data", {}).get("downloadPage")
return {"message": "Upload successful!", "link": download_link}
else:
return {
"message": f"Failed to upload file. Error: {response_json.get('message')}"
}
except requests.exceptions.RequestException as e:
return {"message": f"Request error: {e}"}
except ValueError as e:
return {"message": f"Error decoding JSON response: {e}"}
def upload_to_pixeldrain(file_data, filename):
url = "https://pixeldrain.com/api/file"
headers = {
"Authorization": "Basic " + base64.b64encode(f":{PIXELDRAIN_API_KEY}".encode()).decode()
}
files = {"file": (filename, file_data)}
try:
response = requests.post(url, files=files, headers=headers, timeout=600)
response.raise_for_status()
response_json = response.json()
file_id = response_json.get("id")
if file_id:
download_link = f"https://pixeldrain.com/u/{file_id}"
return {"message": "Upload successful!", "link": download_link}
else:
return {"message": "Failed to upload file. No file ID returned."}
except requests.exceptions.RequestException as e:
return {"message": f"Request error: {e}"}
except ValueError as e:
return {"message": f"Error decoding JSON response: {e}"}
@app.route("/upload_file", methods=["GET", "POST"])
def upload_file():
if request.method == "POST":
if "file" not in request.files:
return jsonify({"success": False, "message": "No file part"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"success": False, "message": "No selected file"}), 400
if file:
filename = clean_filename(file.filename)
file_data = file.read()
# Update upload history
upload_history.append(filename)
# Upload to a random service
upload_service = random.choice(["gofile", "pixeldrain"])
if upload_service == "gofile":
response = upload_to_gofile(file_data, filename)
else:
response = upload_to_pixeldrain(file_data, filename)
if "link" in response:
download_link = response["link"]
download_history.append(download_link)
flash(response['message']) #Flash the message for later use
return jsonify({
"success": True,
"message": response['message'],
"redirect_url": url_for('upload_result', filename=filename, link=download_link)
})
else:
return jsonify({"success": False, "message": response['message']}), 500
return render_template("chat.html")
@app.route("/upload-result")
def upload_result():
filename = request.args.get('filename')
link = request.args.get('link')
response_message = get_flashed_messages()
return render_template("upload_result.html", filename=filename, download_link=link, response=response_message)
@app.route("/upload-history")
def upload_history_page():
return render_template(
"history.html", history=upload_history, title="Lịch sử tải lên"
)
@app.route("/download-history")
def download_history_page():
return render_template(
"history.html", history=download_history, title="Lịch sử tải xuống"
)
@app.route("/about")
def about():
return render_template("about.html") # Tạo trang about.html
@app.route("/api-check", methods=["GET", "POST"])
def api_check():
if request.method == "POST":
data = request.json
url = data.get("url")
method = data.get("method")
headers = data.get("headers")
payload = data.get("payload")
timeout = int(data.get("timeout", 30))
# Parse headers
try:
headers = json.loads(headers) if headers else {}
except json.JSONDecodeError:
return jsonify({"error": "Invalid JSON in headers"}), 400
# Parse payload
try:
payload = json.loads(payload) if payload else {}
except json.JSONDecodeError:
return jsonify({"error": "Invalid JSON in payload"}), 400
# Prepare request kwargs
kwargs = {
"url": url,
"headers": headers,
"timeout": timeout
}
if method in ["POST", "PUT", "PATCH"]:
kwargs["json"] = payload
# Send request
try:
response = requests.request(method, **kwargs)
# Prepare response data
response_data = {
"status": response.status_code,
"statusText": response.reason,
"headers": dict(response.headers),
"body": response.json() if response.headers.get("Content-Type") == "application/json" else response.text
}
return jsonify(response_data), 200
except requests.exceptions.RequestException as e:
return jsonify({"error": str(e)}), 500
# If it's a GET request, render the api_check.html template
return render_template("api_check.html")
@app.route("/qrcode")
def qrcode_page():
return render_template("qrcode.html")
# Error handler for file size limit
@app.errorhandler(413)
def request_entity_too_large(error):
flash("File is too large! The limit is 100MB.")
return redirect(request.url), 413
@app.route("/clipython")
def clipython():
return render_template("clipython.html")
@app.route("/run-python", methods=["POST"])
def run_python_code():
data = request.json
code = data.get("code", "")
input_values = data.get("input_values", [])
# Create a temporary file to store the Python code
temp_file = f"/tmp/temp_{uuid.uuid4().hex}.py"
with open(temp_file, "w") as f:
f.write(code)
try:
# Run the Python code with the provided input
process = subprocess.Popen(
[sys.executable, temp_file],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
stdout, stderr = process.communicate(input="\n".join(input_values))
if stderr:
return jsonify({"output": stderr, "error": True})
else:
return jsonify({"output": stdout, "error": False})
except Exception as e:
return jsonify({"output": str(e), "error": True})
finally:
# Remove the temporary file
if os.path.exists(temp_file):
os.remove(temp_file)
@app.route("/share-code", methods=["POST"])
def share_code():
data = request.json
code = data.get("code", "")
# Create a unique ID for the shared code
share_id = uuid.uuid4().hex
# Save the code to a file (in a real application, you'd use a database)
with open(f"/tmp/shared_code_{share_id}.py", "w") as f:
f.write(code)
# Create the share URL
share_url = f"/view/{share_id}"
return jsonify({"share_url": share_url})
@app.route("/view/<share_id>")
def view_shared_code(share_id):
# Read the code from the file (in a real application, you'd use a database)
try:
with open(f"/tmp/shared_code_{share_id}.py", "r") as f:
code = f.read()
return render_template("view_shared_code.html", code=code)
except FileNotFoundError:
return "Code does not exist or has expired", 404
@app.route("/install-library", methods=["POST"])
def install_library():
# Note: Installing libraries on-the-fly is not recommended in a production environment
# This is just for demonstration purposes
data = request.json
library = data.get("library", "")
if not library:
return jsonify({"success": False, "error": "Library name cannot be empty"})
try:
# Install the library using pip
result = subprocess.run(
[sys.executable, "-m", "pip", "install", library],
capture_output=True,
text=True,
)
if result.returncode == 0:
return jsonify({"success": True})
else:
return jsonify({"success": False, "error": result.stderr})
except Exception as e:
return jsonify({"success": False, "error": str(e)})
# Route để hiển thị trang facts.html
@app.route("/facts", methods=["GET"])
def facts_page():
return render_template("fact.html")
# Route để lấy fact từ Numbers API và dịch sang tiếng Việt
@app.route("/get-fact/<string:type>/<string:number>", methods=["GET"])
def get_fact(type, number):
# Gọi đến Numbers API để lấy fact
response = requests.get(f"http://numbersapi.com/{number}/{type}")
if response.status_code != 200:
return jsonify({"error": "Không thể lấy thông tin từ API"}), 500
# Lấy dữ liệu từ phản hồi
fact = response.text
# Dịch fact sang tiếng Việt
translated_fact = GoogleTranslator(source="en", target="vi").translate(fact)
return jsonify(
{
"original_fact": fact, # Trả về văn bản gốc
"translated_fact": translated_fact, # Trả về văn bản đã dịch
}
)
# Route để lấy cat fact
@app.route("/get-cat-fact", methods=["GET"])
def get_cat_fact():
response = requests.get("https://catfact.ninja/fact")
if response.status_code != 200:
return jsonify({"error": "Không thể lấy thông tin từ Cat Fact API"}), 500
# Lấy dữ liệu từ phản hồi
cat_fact = response.json().get("fact", "Không có thông tin")
# Dịch cat fact sang tiếng Việt
translated_cat_fact = GoogleTranslator(source="en", target="vi").translate(cat_fact)
return jsonify({"cat_fact": cat_fact, "translated_cat_fact": translated_cat_fact})
# Route để lấy Joke với category
@app.route("/get-joke/<string:category>", methods=["GET"])
def get_joke(category):
response = requests.get(f"https://v2.jokeapi.dev/joke/{category}")
if response.status_code != 200:
return jsonify({"error": "Không thể lấy thông tin từ JokeAPI"}), 500
joke_data = response.json()
if joke_data["type"] == "single":
joke = joke_data["joke"]
else:
joke = f"{joke_data['setup']} - {joke_data['delivery']}"
translated_joke = GoogleTranslator(source="en", target="vi").translate(joke)
return jsonify({"joke": joke, "translated_joke": translated_joke})
@app.route("/get-useless-fact")
def get_useless_fact():
response = requests.get("https://uselessfacts.jsph.pl/random.json")
data = response.json()
fact = data.get("text", "Không có thông tin.") # Lấy text từ response
# Dịch sang tiếng Việt
translated_fact = GoogleTranslator(source="en", target="vi").translate(fact)
return jsonify({"useless_fact": fact, "translated_useless_fact": translated_fact})
# Route dịch văn bản từ tiếng Anh sang tiếng Việt
@app.route("/translate", methods=["POST"])
def translate_text():
data = request.get_json()
text = data.get("text")
if not text:
return jsonify({"error": "Văn bản không được để trống"}), 400
# Dịch văn bản sang tiếng Việt
translated_text = GoogleTranslator(source="en", target="vi").translate(text)
return jsonify({"translated_text": translated_text})
@app.route("/ipconfig")
def ipconfig():
trace_url = "https://one.one.one.one/cdn-cgi/trace"
geolocation_url = "https://speed.cloudflare.com/meta"
try:
# Lấy dữ liệu từ Cloudflare Trace API
trace_response = requests.get(trace_url)
trace_data = dict(
line.split("=") for line in trace_response.text.strip().split("\n")
)
# Lấy dữ liệu từ Cloudflare Geolocation API
geo_response = requests.get(geolocation_url)
geo_data = geo_response.json()
# Trả dữ liệu cho ipconfig.html
return render_template("ipconfig.html", trace=trace_data, geo=geo_data)
except Exception as e:
return jsonify({"error": str(e)}), 500
API_KEY_WEATHER = "714c27439667f61cbf15f7ab466525a0"
@app.route("/weather", methods=["GET", "POST"])
def weather():
if request.method == "POST":
latitude = request.form.get("latitude")
longitude = request.form.get("longitude")
if latitude and longitude:
weather_url = f"http://api.openweathermap.org/data/2.5/weather?lat={latitude}&lon={longitude}&appid={API_KEY_WEATHER}&units=metric"
weather_response = requests.get(weather_url)
weather_data = weather_response.json()
forecast_url = f"http://api.openweathermap.org/data/2.5/forecast?lat={latitude}&lon={longitude}&appid={API_KEY_WEATHER}&units=metric"
forecast_response = requests.get(forecast_url)
forecast_data = forecast_response.json()
if (
weather_response.status_code == 200
and forecast_response.status_code == 200
):
current_weather = {
"city": weather_data["name"],
"temperature": weather_data["main"]["temp"],
"description": weather_data["weather"][0]["description"],
"humidity": weather_data["main"]["humidity"],
"wind_speed": weather_data["wind"]["speed"],
}
forecast_info = []
for entry in forecast_data["list"][:5]:
forecast_info.append(
{
"time": entry["dt_txt"],
"temperature": entry["main"]["temp"],
"description": entry["weather"][0]["description"],
"humidity": entry["main"]["humidity"],
"wind_speed": entry["wind"]["speed"],
}
)
return jsonify(
{"current_weather": current_weather, "forecast_info": forecast_info}
)
else:
return jsonify({"error": "Could not retrieve weather data."}), 400
return jsonify({"error": "Invalid latitude or longitude."}), 400
return render_template("weather.html")
@app.route("/load_more_forecasts", methods=["GET"])
def load_more_forecasts():
latitude = request.args.get("latitude")
longitude = request.args.get("longitude")
last_forecast_index = int(request.args.get("last_forecast_index", 0))
# Gọi API để lấy dữ liệu dự báo
forecast_url = f"http://api.openweathermap.org/data/2.5/forecast?lat={latitude}&lon={longitude}&appid={API_KEY_WEATHER}&units=metric"
forecast_response = requests.get(forecast_url)
forecast_data = forecast_response.json()
if forecast_response.status_code == 200:
forecasts = []
for entry in forecast_data["list"][
last_forecast_index : last_forecast_index + 5
]: # Lấy 5 bản ghi tiếp theo
forecasts.append(
{
"time": entry["dt_txt"],
"temperature": entry["main"]["temp"],
"description": entry["weather"][0]["description"],
"humidity": entry["main"]["humidity"],
"wind_speed": entry["wind"]["speed"],
}
)
# Trả về dữ liệu dự báo mới
return jsonify({"forecasts": forecasts})
else:
return jsonify({"error": "Unable to fetch forecast data."}), 400
@app.route("/weather_by_location", methods=["POST"])
def weather_by_location():
province = request.form.get("province")
district = request.form.get("district")
ward = request.form.get("ward")
country = request.form.get("country")
country_code = request.form.get("country_code")
# Xây dựng chuỗi địa điểm
location = f"{ward}, {district}, {province}, {country}"
if country_code:
location += f" ({country_code})"
base_url = "http://api.openweathermap.org/data/2.5/forecast"
params = {
"q": location,
"appid": API_KEY_WEATHER,
"units": "metric",
"lang": "vi",
}
try:
response = requests.get(base_url, params=params)
data = response.json()
if response.status_code == 200:
current_weather = data["list"][0]
city_name = data["city"]["name"]
# Xử lý thời tiết hiện tại
current_weather_data = {
"city": city_name,
"temperature": round(current_weather["main"]["temp"], 1),
"description": current_weather["weather"][0]["description"],
"humidity": current_weather["main"]["humidity"],
"wind_speed": round(
current_weather["wind"]["speed"] * 3.6, 1
), # Chuyển đổi từ m/s sang km/h
}
# Xử lý dự báo
forecast_data = []
for forecast in data["list"][1:6]: # 5 dự báo tiếp theo
forecast_data.append(
{
"time": datetime.fromtimestamp(forecast["dt"]).strftime(
"%Y-%m-%d %H:%M:%S"
),
"temperature": round(forecast["main"]["temp"], 1),
"description": forecast["weather"][0]["description"],
"humidity": forecast["main"]["humidity"],
"wind_speed": round(
forecast["wind"]["speed"] * 3.6, 1
), # Chuyển đổi từ m/s sang km/h
}
)
return jsonify(
{
"current_weather": current_weather_data,
"forecast_info": forecast_data,
}
)
else:
return jsonify({"error": f"Lỗi: {data['message']}"}), 400
except requests.RequestException as e:
return jsonify({"error": f"Yêu cầu thất bại: {str(e)}"}), 500
@app.route("/urldownload", methods=["GET", "POST"])
def urldownload():
if request.method == "POST":
url = request.form.get("url")
if url:
try:
ydl_opts = {
"format": "bestvideo+bestaudio/best",
"noplaylist": True,
"quiet": True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(url, download=False)
formats = info_dict.get("formats", [])
# Check for supported platforms
if (
"youtube" in info_dict["webpage_url"]
or "facebook" in info_dict["webpage_url"]
):
return jsonify(
{
"title": info_dict.get("title"),
"formats": formats,
"url": url,
}
)
else:
return jsonify(
{
"error": "Unsupported platform. Please provide a YouTube or Facebook URL."
}
)
except Exception as e:
return jsonify({"error": str(e)})
else:
return jsonify({"error": "No URL provided."})
return render_template("urldownload.html")
@app.route("/download")
def download_video():
url = request.args.get("url")
format_id = request.args.get("format")
if not url or not format_id:
return "Missing URL or format", 400
try:
ydl_opts = {
"format": format_id,
"outtmpl": "downloads/%(title)s.%(ext)s",
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(url, download=True)
filename = ydl.prepare_filename(info_dict)
return send_file(filename, as_attachment=True)
except Exception as e:
return str(e), 500
@app.route("/convert")
def convert_to_mp3():
url = request.args.get("url")
if not url:
return "Missing URL", 400
try:
ydl_opts = {
"format": "bestaudio/best",
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "192",
}
],
"outtmpl": "downloads/%(title)s.%(ext)s",
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(url, download=True)
filename = ydl.prepare_filename(info_dict)
mp3_filename = os.path.splitext(filename)[0] + ".mp3"
return send_file(mp3_filename, as_attachment=True)
except Exception as e:
return str(e), 500
PEXELS_API_KEY = "1RLKfe657NlpkTa6gv60FnAJDlncnMYy1g1zcvaM5OXXhpiAIZftxtbA"
@app.route("/random-image", methods=["GET", "POST"])
def random_image():
images = [] # Biến để lưu trữ danh sách hình ảnh
if request.method == "POST":
headers = {"Authorization": PEXELS_API_KEY}
# Thêm tham số page ngẫu nhiên để yêu cầu hình ảnh khác nhau
random_page = random.randint(1, 1000) # Có thể điều chỉnh theo tổng số trang
# Lấy số lượng hình ảnh ngẫu nhiên từ 9 đến 45
random_per_page = random.randint(9, 45)
response = requests.get(
f"https://api.pexels.com/v1/search?query=nature&per_page={random_per_page}&page={random_page}",
headers=headers,
)
if response.status_code == 200:
data = response.json()
# Lấy tất cả các hình ảnh từ dữ liệu
if data["photos"]:
for photo in data["photos"]:
images.append(
photo["src"]["large"]
) # Lấy URL của hình ảnh chất lượng cao hơn
return render_template("display_image.html", images=images)
NEWS_API_KEY = "372acef8e721441ca1a98732b031d253"
@app.route("/news", methods=["GET"])
def news():
response = requests.get(
f"https://newsapi.org/v2/top-headlines?country=us&apiKey={NEWS_API_KEY}"
)
articles = []
if response.status_code == 200:
data = response.json()
articles = data.get("articles", [])
return render_template("news.html", articles=articles)
@app.route("/math", methods=["GET", "POST"])
def math_operation():
if request.method == "POST":
# Get operation and expression from the form data
operation = request.form["operation"]
expression = request.form["expression"]
# URL encode the expression
encoded_expression = requests.utils.quote(expression)
# Form the API URL
url = f"https://newton.now.sh/api/v2/{operation}/{encoded_expression}"
# Send a request to Newton API
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
result = response.json()
return render_template(
"math.html",
result=result["result"],
expression=expression,
operation=operation,
)
else:
error = "Invalid request or operation"
return render_template("math.html", error=error)
# Render the form for GET request
return render_template("math.html")
@app.route("/projects")
def projects():
# Lấy dữ liệu từ GitHub API
response = requests.get("https://api.github.com/users/tanbaycu/repos")
repos = response.json()
return render_template("projects.html", repos=repos)
@app.route("/aichat", methods=["GET"])
def aichat():
return render_template("aichat.html")
@app.route("/pdf")
def pdf_page():
return render_template("pdf.html")
@app.route("/tools")
def tools():
return render_template("tools.html")
@app.route("/spotify")
def spotify_page():
return render_template("spotify.html")
API_KEY = "1373341a3e6d7cb9a723fff1"
BASE_URL = "https://v6.exchangerate-api.com/v6/{API_KEY}/latest/{base_currency}"
@app.route("/crypto")
def crypto():
response = requests.get(BASE_URL.format(API_KEY=API_KEY, base_currency="USD"))
if response.status_code == 200:
data = response.json()
currencies = list(data["conversion_rates"].keys())
else:
currencies = []
currency_symbols = {
"USD": "🇺🇸",
"EUR": "🇪🇺",
"GBP": "🇬🇧",
"JPY": "🇯🇵",
"AUD": "🇦🇺",
"CAD": "🇨🇦",
"CHF": "🇨🇭",
"CNY": "🇨🇳",
"HKD": "🇭🇰",
"NZD": "🇳🇿",
"SEK": "🇸🇪",
"KRW": "🇰🇷",
"SGD": "🇸🇬",
"NOK": "🇳🇴",
"MXN": "🇲🇽",
"INR": "🇮🇳",
"RUB": "🇷🇺",
"ZAR": "🇿🇦",
"TRY": "🇹🇷",
"BRL": "🇧🇷",
"TWD": "🇹🇼",
"DKK": "🇩🇰",
"PLN": "🇵🇱",
"THB": "🇹🇭",
"IDR": "🇮🇩",
"HUF": "🇭🇺",
"CZK": "🇨🇿",
"ILS": "🇮🇱",
"CLP": "🇨🇱",
"PHP": "🇵🇭",
"AED": "🇦🇪",
"COP": "🇨🇴",
"SAR": "🇸🇦",
"MYR": "🇲🇾",
"RON": "🇷🇴",
}
return render_template(
"crypto.html", currencies=currencies, currency_symbols=currency_symbols
)
@app.route("/get_exchange_rates/<base_currency>")
def get_exchange_rates(base_currency):
response = requests.get(
BASE_URL.format(API_KEY=API_KEY, base_currency=base_currency)
)
if response.status_code == 200:
return jsonify(response.json())
else:
return jsonify({"error": "Failed to fetch exchange rates"}), 400
@app.route("/formatcode")
def format_code():
return render_template("format.html")
@app.route("/password")
def password():
return render_template("password.html")
@app.route("/country", methods=["GET", "POST"])
def country():
if request.method == "POST":
country_name = request.form.get("country")
try:
country_url = f"https://restcountries.com/v3.1/name/{country_name}"
response = requests.get(country_url)
response.raise_for_status()
country_data = response.json()[0]
return jsonify(
{
"name": country_data["name"]["common"],
"official_name": country_data["name"]["official"],
"capital": (
country_data["capital"][0]
if "capital" in country_data
else "N/A"
),
"population": country_data["population"],