-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
132 lines (106 loc) · 5.05 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
from flask import Flask, render_template, request, jsonify, send_file
import os
import subprocess
import signal
import uuid
from modules.chunker import start_chunk_process, stop_chunk_process
from modules.logger import setup_logger
app = Flask(__name__)
logger = setup_logger()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/start', methods=['POST'])
def start():
data = request.json
url = data.get('url')
if not url:
return jsonify({'success': False, 'message': 'No se proporcionó la URL del video.'}), 400
try:
# Generar un identificador único para la carpeta de cada descarga
unique_id = str(uuid.uuid4()) # Crear un UUID único para evitar colisiones
chunk_folder = os.path.join('static', 'videos', 'chunks', unique_id)
os.makedirs(chunk_folder, exist_ok=True)
# Iniciar el proceso de descarga y chunking utilizando start_chunk_process
start_chunk_process(url, chunk_folder) # Llama a la función correcta para iniciar el proceso
logger.info(f"Proceso iniciado en la carpeta: {chunk_folder}")
return jsonify({'success': True, 'title': unique_id}) # Devolver el ID único de la carpeta
except Exception as e:
logger.error(f"Error al iniciar el proceso: {str(e)}")
return jsonify({'success': False, 'message': str(e)}), 500
@app.route('/stop', methods=['POST'])
def stop():
data = request.json
title = data.get('title')
if not title:
return jsonify({'success': False, 'message': 'No se proporcionó el título del video.'}), 400
chunk_folder = os.path.join('static', 'videos', 'chunks', title)
pid_file_path = os.path.join(chunk_folder, 'process.pid')
try:
if os.path.exists(pid_file_path):
with open(pid_file_path, 'r') as pid_file:
pid = int(pid_file.read())
logger.info(f"Intentando detener el proceso con PID {pid}")
os.kill(pid, signal.SIGTERM) # Enviar señal SIGTERM para detener el proceso
# Verificar si el proceso sigue corriendo
try:
os.kill(pid, 0)
logger.error(f"El proceso con PID {pid} aún está en ejecución.")
except OSError:
logger.info(f"El proceso con PID {pid} se ha detenido con éxito.")
os.remove(pid_file_path) # Eliminar el archivo PID
else:
logger.warning("Archivo PID no encontrado. No se pudo detener el proceso.")
stop_chunk_process() # Llama a la función que detiene el proceso
return jsonify({'success': True, 'message': 'Grabación detenida.'})
except Exception as e:
logger.error(f"Error al detener la grabación: {str(e)}")
return jsonify({'success': False, 'message': f'Error al detener la grabación: {str(e)}'}), 500
@app.route('/merge', methods=['POST'])
def merge():
data = request.json
title = data.get('title')
if not title:
chunk_folder = os.path.join('static', 'videos', 'chunks')
title = str(len(os.listdir(chunk_folder)))
output_folder = 'Output_video'
os.makedirs(output_folder, exist_ok=True)
output_file = os.path.join(output_folder, f'Video_{title}.mp4')
try:
merge_videos(title, output_file)
return jsonify({'success': True, 'output_file': output_file})
except Exception as e:
logger.error(f"Error al unir los videos: {str(e)}")
return jsonify({'success': False, 'message': f'Error al unir los videos: {str(e)}'}), 500
@app.route('/download/<title>/<filename>')
def download(title, filename):
file_path = os.path.join('Output_video', filename)
if os.path.exists(file_path):
return send_file(file_path, as_attachment=True)
else:
return jsonify({'success': False, 'message': 'Archivo no encontrado.'}), 404
@app.route('/output_videos/<title>/<filename>')
def output_video(title, filename):
file_path = os.path.join('static', 'videos', 'chunks', title, filename)
if os.path.exists(file_path):
return send_file(file_path)
else:
return jsonify({'success': False, 'message': 'Archivo no encontrado.'}), 404
def merge_videos(title, output_file):
chunk_folder = os.path.join('static', 'videos', 'chunks', title)
file_list_path = os.path.join(chunk_folder, 'mylist.txt')
with open(file_list_path, 'w') as file_list:
for file_name in sorted(os.listdir(chunk_folder)):
if file_name.endswith('.mp4'):
file_list.write(f"file '{file_name}'\n")
ffmpeg_command = [
'ffmpeg', '-f', 'concat', '-safe', '0', '-i', file_list_path, '-c', 'copy', output_file
]
try:
subprocess.run(ffmpeg_command, check=True)
print(f"Videos unidos en {output_file}")
except subprocess.CalledProcessError as e:
print(f"Error al unir los videos: {e}")
raise e
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)