Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,22 +6,26 @@ import subprocess
|
|
| 6 |
from flask import Flask, request, jsonify, render_template
|
| 7 |
from yt_dlp import YoutubeDL
|
| 8 |
|
| 9 |
-
app = Flask(__name__, static_folder='static')
|
| 10 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
OUTPUT_FOLDER = os.path.join(BASE_DIR, 'static', 'downloads')
|
| 12 |
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
|
| 13 |
|
|
|
|
| 14 |
@app.route('/')
|
| 15 |
def index():
|
| 16 |
return render_template('templates/index.html')
|
| 17 |
|
|
|
|
| 18 |
def cleanup_old_files(folder, max_age_sec=1800):
|
|
|
|
| 19 |
now = time.time()
|
| 20 |
for f in os.listdir(folder):
|
| 21 |
path = os.path.join(folder, f)
|
| 22 |
if os.path.isfile(path) and now - os.path.getmtime(path) > max_age_sec:
|
| 23 |
os.remove(path)
|
| 24 |
|
|
|
|
| 25 |
@app.route('/service', methods=['POST'])
|
| 26 |
def process():
|
| 27 |
try:
|
|
@@ -33,21 +37,21 @@ def process():
|
|
| 33 |
if not url:
|
| 34 |
return jsonify({'status': 'error', 'message': '請提供有效的 YouTube 網址'})
|
| 35 |
|
| 36 |
-
#
|
| 37 |
timestamp = int(time.time())
|
| 38 |
output_base = os.path.join(OUTPUT_FOLDER, f'output_{timestamp}')
|
| 39 |
final_file = f"{output_base}.{fmt}"
|
| 40 |
|
| 41 |
-
# YT-DLP
|
| 42 |
ydl_opts = {
|
| 43 |
'outtmpl': f"{output_base}.%(ext)s",
|
| 44 |
'quiet': True,
|
| 45 |
'noplaylist': True,
|
| 46 |
-
'format': 'bestaudio/best',
|
| 47 |
}
|
| 48 |
|
| 49 |
-
# Format
|
| 50 |
if fmt == "mp3":
|
|
|
|
| 51 |
ydl_opts['postprocessors'] = [{
|
| 52 |
'key': 'FFmpegExtractAudio',
|
| 53 |
'preferredcodec': 'mp3',
|
|
@@ -58,15 +62,19 @@ def process():
|
|
| 58 |
elif fmt == "mp4":
|
| 59 |
ydl_opts['format'] = 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best'
|
| 60 |
|
|
|
|
| 61 |
with YoutubeDL(ydl_opts) as ydl:
|
| 62 |
ydl.download([url])
|
| 63 |
|
| 64 |
-
#
|
| 65 |
if fmt in ["m4a", "mp4"]:
|
|
|
|
| 66 |
matched = [f for f in os.listdir(OUTPUT_FOLDER) if f.startswith(f'output_{timestamp}')]
|
| 67 |
if not matched:
|
| 68 |
raise Exception("找不到下載檔案")
|
| 69 |
input_path = os.path.join(OUTPUT_FOLDER, matched[0])
|
|
|
|
|
|
|
| 70 |
if not input_path.endswith(f".{fmt}"):
|
| 71 |
subprocess.run([
|
| 72 |
'ffmpeg', '-y', '-i', input_path,
|
|
@@ -79,15 +87,21 @@ def process():
|
|
| 79 |
|
| 80 |
cleanup_old_files(OUTPUT_FOLDER)
|
| 81 |
|
| 82 |
-
|
| 83 |
return jsonify({
|
| 84 |
'status': 'success',
|
| 85 |
'message': f"{fmt.upper()} 檔案已完成!",
|
| 86 |
-
'download_links': {fmt:
|
| 87 |
})
|
|
|
|
| 88 |
except Exception as e:
|
| 89 |
return jsonify({'status': 'error', 'message': f'下載失敗:{str(e)}'})
|
| 90 |
|
|
|
|
| 91 |
@app.route('/ping')
|
| 92 |
def ping():
|
| 93 |
return "pong"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from flask import Flask, request, jsonify, render_template
|
| 7 |
from yt_dlp import YoutubeDL
|
| 8 |
|
| 9 |
+
app = Flask(__name__, static_folder='static', template_folder='templates')
|
| 10 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
OUTPUT_FOLDER = os.path.join(BASE_DIR, 'static', 'downloads')
|
| 12 |
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
|
| 13 |
|
| 14 |
+
|
| 15 |
@app.route('/')
|
| 16 |
def index():
|
| 17 |
return render_template('templates/index.html')
|
| 18 |
|
| 19 |
+
|
| 20 |
def cleanup_old_files(folder, max_age_sec=1800):
|
| 21 |
+
"""Remove files older than 30 minutes to save space"""
|
| 22 |
now = time.time()
|
| 23 |
for f in os.listdir(folder):
|
| 24 |
path = os.path.join(folder, f)
|
| 25 |
if os.path.isfile(path) and now - os.path.getmtime(path) > max_age_sec:
|
| 26 |
os.remove(path)
|
| 27 |
|
| 28 |
+
|
| 29 |
@app.route('/service', methods=['POST'])
|
| 30 |
def process():
|
| 31 |
try:
|
|
|
|
| 37 |
if not url:
|
| 38 |
return jsonify({'status': 'error', 'message': '請提供有效的 YouTube 網址'})
|
| 39 |
|
| 40 |
+
# Setup file names
|
| 41 |
timestamp = int(time.time())
|
| 42 |
output_base = os.path.join(OUTPUT_FOLDER, f'output_{timestamp}')
|
| 43 |
final_file = f"{output_base}.{fmt}"
|
| 44 |
|
| 45 |
+
# YT-DLP settings
|
| 46 |
ydl_opts = {
|
| 47 |
'outtmpl': f"{output_base}.%(ext)s",
|
| 48 |
'quiet': True,
|
| 49 |
'noplaylist': True,
|
|
|
|
| 50 |
}
|
| 51 |
|
| 52 |
+
# Format logic
|
| 53 |
if fmt == "mp3":
|
| 54 |
+
ydl_opts['format'] = 'bestaudio/best'
|
| 55 |
ydl_opts['postprocessors'] = [{
|
| 56 |
'key': 'FFmpegExtractAudio',
|
| 57 |
'preferredcodec': 'mp3',
|
|
|
|
| 62 |
elif fmt == "mp4":
|
| 63 |
ydl_opts['format'] = 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best'
|
| 64 |
|
| 65 |
+
# Download
|
| 66 |
with YoutubeDL(ydl_opts) as ydl:
|
| 67 |
ydl.download([url])
|
| 68 |
|
| 69 |
+
# Optional ffmpeg conversion
|
| 70 |
if fmt in ["m4a", "mp4"]:
|
| 71 |
+
# Find downloaded file
|
| 72 |
matched = [f for f in os.listdir(OUTPUT_FOLDER) if f.startswith(f'output_{timestamp}')]
|
| 73 |
if not matched:
|
| 74 |
raise Exception("找不到下載檔案")
|
| 75 |
input_path = os.path.join(OUTPUT_FOLDER, matched[0])
|
| 76 |
+
|
| 77 |
+
# Convert if extension mismatch
|
| 78 |
if not input_path.endswith(f".{fmt}"):
|
| 79 |
subprocess.run([
|
| 80 |
'ffmpeg', '-y', '-i', input_path,
|
|
|
|
| 87 |
|
| 88 |
cleanup_old_files(OUTPUT_FOLDER)
|
| 89 |
|
| 90 |
+
download_link = f"/static/downloads/{os.path.basename(final_file)}"
|
| 91 |
return jsonify({
|
| 92 |
'status': 'success',
|
| 93 |
'message': f"{fmt.upper()} 檔案已完成!",
|
| 94 |
+
'download_links': {fmt: download_link}
|
| 95 |
})
|
| 96 |
+
|
| 97 |
except Exception as e:
|
| 98 |
return jsonify({'status': 'error', 'message': f'下載失敗:{str(e)}'})
|
| 99 |
|
| 100 |
+
|
| 101 |
@app.route('/ping')
|
| 102 |
def ping():
|
| 103 |
return "pong"
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == '__main__':
|
| 107 |
+
app.run(host='0.0.0.0', port=7860)
|