from flask import Flask, request, jsonify
import uuid
import os
import requests
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
OUTPUT_FOLDER = './output'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
@app.route('/process', methods=['POST'])
def process_file():
# 使用form接收所有参数
file_url = request.form.get('fileUrl')
sd_switch = request.form.get('sdSwitch', 'no') # 从form表单获取sd_switch参数 no或yes
# 接收到参数
print(f'接收到参数')
print(f'fileUrl: {file_url}')
print(f'sd_switch: {sd_switch}')
# 检查是否有文件上传
if 'file' in request.files:
file = request.files['file']
# 生成UUID标识本次处理任务
job_id = str(uuid.uuid4())
job_output_dir = os.path.join(app.config['OUTPUT_FOLDER'], job_id)
os.makedirs(job_output_dir, exist_ok=True)
# 保存上传的文件
filename = f'{job_id}{os.path.splitext(file.filename)[1]}'
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
file_to_process = file_path
print(f'文件已保存到: {file_path}') # 打印文件保存路径日志
else:
# 没有提供file参数,使用fileUrl下载文件
if not file_url:
return jsonify({'error': 'No file or fileUrl provided'}), 400
# Generate UUID for this processing job
job_id = str(uuid.uuid4())
job_output_dir = os.path.join(app.config['OUTPUT_FOLDER'], job_id)
os.makedirs(job_output_dir, exist_ok=True)
# Handle URL download
try:
response = requests.get(file_url, stream=True)
response.raise_for_status()
# 从URL获取文件扩展名,默认为.tmp
content_type = response.headers.get('content-type', '')
extension = '.tmp'
if 'video/' in content_type:
extension = f'.{content_type.split("/")[-1]}'
local_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{job_id}{extension}')
with open(local_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
file_to_process = local_path
print(f'文件已下载到: {local_path}') # 打印文件下载路径日志
except Exception as e:
return jsonify({'error': f'File download failed: {str(e)}'}), 500
# 执行命令
# Call videoclipper.py with stage 1 processing
cmd = f'python /app/funclip/videoclipper.py --stage 1 --file "{file_to_process}" --output_dir "{job_output_dir}" --sd_switch "{sd_switch}"'
try:
# 执行命令调用videoclipper.py进行阶段1处理
result = os.system(cmd)
if result != 0:
print(f'命令执行失败: {cmd}') # 打印命令执行失败日志
return jsonify({'error': 'Command execution failed'}), 500
# 读取total.srt内容
srt_path = os.path.join(job_output_dir, 'total.srt')
print(f'识别结果保存在: {srt_path}') # 打印识别结果保存路径日志
with open(srt_path, 'r') as f:
srt_content = f.read()
# 返回成功响应
return jsonify({
'job_id': job_id,
'status': 'success',
'output_directory': job_output_dir,
'srt_content': srt_content
})
except Exception as e:
# 返回错误响应
return jsonify({'error': f'Processing failed: {str(e)}'}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)