Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,173 +1,224 @@
|
|
| 1 |
-
from flask import Flask, render_template, request, session, redirect, url_for, flash, send_from_directory
|
| 2 |
-
import os
|
| 3 |
-
import secrets
|
| 4 |
-
from werkzeug.utils import secure_filename
|
| 5 |
-
import sys
|
| 6 |
-
import shutil
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
app.
|
| 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 |
-
return
|
| 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 |
app.run(debug=True)
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, session, redirect, url_for, flash, send_from_directory
|
| 2 |
+
import os
|
| 3 |
+
import secrets
|
| 4 |
+
from werkzeug.utils import secure_filename
|
| 5 |
+
import sys
|
| 6 |
+
import shutil
|
| 7 |
+
import logging # Import the logging module
|
| 8 |
+
|
| 9 |
+
# Configure logging
|
| 10 |
+
logging.basicConfig(level=logging.INFO, # Set the minimum logging level
|
| 11 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 12 |
+
handlers=[
|
| 13 |
+
logging.FileHandler("app.log"), # Log to a file
|
| 14 |
+
logging.StreamHandler() # Log to console
|
| 15 |
+
])
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
sys.path.append(os.path.dirname(__file__))
|
| 19 |
+
import inference2 # Import your refactored inference script
|
| 20 |
+
|
| 21 |
+
app = Flask(__name__)
|
| 22 |
+
app.secret_key = os.urandom(24)
|
| 23 |
+
app.config['UPLOAD_FOLDER'] = 'uploads'
|
| 24 |
+
app.config['RESULTS_FOLDER'] = 'results'
|
| 25 |
+
app.config['CHECKPOINTS_FOLDER'] = 'checkpoints'
|
| 26 |
+
app.config['TEMP_FOLDER'] = 'temp'
|
| 27 |
+
|
| 28 |
+
ALLOWED_FACE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'mp4', 'avi', 'mov'}
|
| 29 |
+
ALLOWED_AUDIO_EXTENSIONS = {'wav', 'mp3', 'aac', 'flac'}
|
| 30 |
+
ALLOWED_MODEL_EXTENSIONS = {'pth', 'pt'}
|
| 31 |
+
|
| 32 |
+
# Ensure directories exist
|
| 33 |
+
try:
|
| 34 |
+
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
|
| 35 |
+
os.makedirs(app.config['RESULTS_FOLDER'], exist_ok=True)
|
| 36 |
+
os.makedirs(app.config['CHECKPOINTS_FOLDER'], exist_ok=True)
|
| 37 |
+
os.makedirs(app.config['TEMP_FOLDER'], exist_ok=True)
|
| 38 |
+
logger.info("All necessary directories ensured to exist.")
|
| 39 |
+
except OSError as e:
|
| 40 |
+
logger.critical(f"Error creating essential directories: {e}")
|
| 41 |
+
# Depending on the severity, you might want to exit or disable functionality
|
| 42 |
+
sys.exit(1) # Exit if essential directories cannot be created
|
| 43 |
+
|
| 44 |
+
def allowed_file(filename, allowed_extensions):
|
| 45 |
+
"""Checks if a file's extension is allowed."""
|
| 46 |
+
return '.' in filename and \
|
| 47 |
+
filename.rsplit('.', 1)[1].lower() in allowed_extensions
|
| 48 |
+
|
| 49 |
+
@app.route('/')
|
| 50 |
+
def index():
|
| 51 |
+
"""Renders the main page, displaying available models."""
|
| 52 |
+
theme = session.get('theme', 'dark')
|
| 53 |
+
available_models = []
|
| 54 |
+
try:
|
| 55 |
+
model_files = [f for f in os.listdir(app.config['CHECKPOINTS_FOLDER'])
|
| 56 |
+
if allowed_file(f, ALLOWED_MODEL_EXTENSIONS)]
|
| 57 |
+
available_models = sorted(model_files)
|
| 58 |
+
logger.info(f"Successfully loaded {len(available_models)} models.")
|
| 59 |
+
except FileNotFoundError:
|
| 60 |
+
logger.warning(f"Checkpoints folder '{app.config['CHECKPOINTS_FOLDER']}' not found. Please create it.")
|
| 61 |
+
except Exception as e:
|
| 62 |
+
logger.error(f"Error loading models from '{app.config['CHECKPOINTS_FOLDER']}': {e}")
|
| 63 |
+
return render_template('index.html', theme=theme, models=available_models)
|
| 64 |
+
|
| 65 |
+
@app.route('/toggle_theme')
|
| 66 |
+
def toggle_theme():
|
| 67 |
+
"""Toggles the session theme between dark and light."""
|
| 68 |
+
current_theme = session.get('theme', 'dark')
|
| 69 |
+
if current_theme == 'dark':
|
| 70 |
+
session['theme'] = 'light'
|
| 71 |
+
logger.info("Theme toggled to light.")
|
| 72 |
+
else:
|
| 73 |
+
session['theme'] = 'dark'
|
| 74 |
+
logger.info("Theme toggled to dark.")
|
| 75 |
+
return redirect(request.referrer or url_for('index'))
|
| 76 |
+
|
| 77 |
+
@app.route('/infer', methods=['POST'])
|
| 78 |
+
def infer():
|
| 79 |
+
"""Handles the inference request, processing uploaded files and running the model."""
|
| 80 |
+
if request.method == 'POST':
|
| 81 |
+
logger.info("Inference request received.")
|
| 82 |
+
|
| 83 |
+
# Check for file presence
|
| 84 |
+
if 'face_file' not in request.files or 'audio_file' not in request.files:
|
| 85 |
+
logger.warning("Both face and audio files are required for inference.")
|
| 86 |
+
return redirect(url_for('index'))
|
| 87 |
+
|
| 88 |
+
face_file = request.files['face_file']
|
| 89 |
+
audio_file = request.files['audio_file']
|
| 90 |
+
selected_model = request.form.get('model_select')
|
| 91 |
+
|
| 92 |
+
if face_file.filename == '' or audio_file.filename == '':
|
| 93 |
+
logger.warning("No selected file for face or audio provided.")
|
| 94 |
+
return redirect(url_for('index'))
|
| 95 |
+
|
| 96 |
+
if not selected_model:
|
| 97 |
+
logger.warning("No model selected for inference.")
|
| 98 |
+
return redirect(url_for('index'))
|
| 99 |
+
|
| 100 |
+
# Validate file types
|
| 101 |
+
if not allowed_file(face_file.filename, ALLOWED_FACE_EXTENSIONS):
|
| 102 |
+
logger.warning(f"Invalid face file type: {face_file.filename}. Allowed: {', '.join(ALLOWED_FACE_EXTENSIONS)}")
|
| 103 |
+
return redirect(url_for('index'))
|
| 104 |
+
if not allowed_file(audio_file.filename, ALLOWED_AUDIO_EXTENSIONS):
|
| 105 |
+
logger.warning(f"Invalid audio file type: {audio_file.filename}. Allowed: {', '.join(ALLOWED_AUDIO_EXTENSIONS)}")
|
| 106 |
+
return redirect(url_for('index'))
|
| 107 |
+
|
| 108 |
+
face_filename = secure_filename(face_file.filename)
|
| 109 |
+
audio_filename = secure_filename(audio_file.filename)
|
| 110 |
+
|
| 111 |
+
face_uuid = secrets.token_hex(8)
|
| 112 |
+
audio_uuid = secrets.token_hex(8)
|
| 113 |
+
|
| 114 |
+
face_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{face_uuid}_{face_filename}")
|
| 115 |
+
audio_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{audio_uuid}_{audio_filename}")
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
face_file.save(face_path)
|
| 119 |
+
audio_file.save(audio_path)
|
| 120 |
+
logger.info(f"Successfully saved uploaded files: {face_path}, {audio_path}")
|
| 121 |
+
except Exception as e:
|
| 122 |
+
logger.error(f"Error saving uploaded files: {e}")
|
| 123 |
+
return redirect(url_for('index'))
|
| 124 |
+
|
| 125 |
+
checkpoint_path = os.path.join(app.config['CHECKPOINTS_FOLDER'], selected_model)
|
| 126 |
+
output_video_name = f"result_{face_uuid}.mp4"
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
logger.info(f"Starting inference with model: {selected_model}, face: {face_filename}, audio: {audio_filename}")
|
| 130 |
+
generated_video_path = inference2.run_inference(
|
| 131 |
+
checkpoint_path=checkpoint_path,
|
| 132 |
+
face_path=face_path,
|
| 133 |
+
audio_path=audio_path,
|
| 134 |
+
output_filename=output_video_name,
|
| 135 |
+
static=request.form.get('static_input') == 'on',
|
| 136 |
+
fps=float(request.form.get('fps', 25.0)),
|
| 137 |
+
resize_factor=int(request.form.get('resize_factor', 1)),
|
| 138 |
+
rotate=request.form.get('rotate') == 'on',
|
| 139 |
+
nosmooth=request.form.get('nosmooth') == 'on',
|
| 140 |
+
pads=[0, 10, 0, 0],
|
| 141 |
+
crop=[0, -1, 0, -1],
|
| 142 |
+
box=[-1, -1, -1, -1],
|
| 143 |
+
face_det_batch_size=16,
|
| 144 |
+
wav2lip_batch_size=128,
|
| 145 |
+
img_size=96
|
| 146 |
+
)
|
| 147 |
+
logger.info(f"Inference completed successfully. Generated video: {generated_video_path}")
|
| 148 |
+
return redirect(url_for('render_result_page', filename=os.path.basename(generated_video_path)))
|
| 149 |
+
|
| 150 |
+
except ValueError as e:
|
| 151 |
+
logger.error(f"Inference ValueError: {e}")
|
| 152 |
+
except RuntimeError as e:
|
| 153 |
+
logger.error(f"Runtime Error during inference: {e}")
|
| 154 |
+
except Exception as e:
|
| 155 |
+
logger.critical(f"An unexpected error occurred during inference: {e}", exc_info=True) # exc_info=True to log traceback
|
| 156 |
+
finally:
|
| 157 |
+
# Clean up uploaded files regardless of inference success or failure
|
| 158 |
+
if os.path.exists(face_path):
|
| 159 |
+
try:
|
| 160 |
+
os.remove(face_path)
|
| 161 |
+
logger.info(f"Cleaned up uploaded face file: {face_path}")
|
| 162 |
+
except OSError as e:
|
| 163 |
+
logger.error(f"Error removing face file {face_path}: {e}")
|
| 164 |
+
if os.path.exists(audio_path):
|
| 165 |
+
try:
|
| 166 |
+
os.remove(audio_path)
|
| 167 |
+
logger.info(f"Cleaned up uploaded audio file: {audio_path}")
|
| 168 |
+
except OSError as e:
|
| 169 |
+
logger.error(f"Error removing audio file {audio_path}: {e}")
|
| 170 |
+
|
| 171 |
+
return redirect(url_for('index'))
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
## Result Handling and File Serving
|
| 175 |
+
|
| 176 |
+
@app.route('/result_page/<filename>')
|
| 177 |
+
def render_result_page(filename):
|
| 178 |
+
"""Renders the result page with the generated video."""
|
| 179 |
+
theme = session.get('theme', 'dark')
|
| 180 |
+
result_video_path = os.path.join(app.config['RESULTS_FOLDER'], filename)
|
| 181 |
+
if not os.path.exists(result_video_path):
|
| 182 |
+
logger.warning(f"Attempted to access non-existent result video: {result_video_path}")
|
| 183 |
+
return redirect(url_for('index'))
|
| 184 |
+
logger.info(f"Rendering result page for video: {filename}")
|
| 185 |
+
return render_template('result.html', theme=theme, video_filename=filename)
|
| 186 |
+
|
| 187 |
+
@app.route('/results/<path:filename>')
|
| 188 |
+
def serve_result_video(filename):
|
| 189 |
+
"""Serves the generated video file from the results folder."""
|
| 190 |
+
logger.debug(f"Serving result video: {filename}")
|
| 191 |
+
try:
|
| 192 |
+
return send_from_directory(app.config['RESULTS_FOLDER'], filename)
|
| 193 |
+
except Exception as e:
|
| 194 |
+
logger.error(f"Error serving result video {filename}: {e}")
|
| 195 |
+
return "Error serving file", 500
|
| 196 |
+
|
| 197 |
+
@app.route('/download/<filename>')
|
| 198 |
+
def download_result(filename):
|
| 199 |
+
"""Allows downloading the generated video file."""
|
| 200 |
+
logger.info(f"Download request for video: {filename}")
|
| 201 |
+
try:
|
| 202 |
+
return send_from_directory(app.config['RESULTS_FOLDER'], filename, as_attachment=True)
|
| 203 |
+
except Exception as e:
|
| 204 |
+
logger.error(f"Error downloading video {filename}: {e}")
|
| 205 |
+
return "Error downloading file", 500
|
| 206 |
+
|
| 207 |
+
## Application Initialization
|
| 208 |
+
|
| 209 |
+
if __name__ == '__main__':
|
| 210 |
+
# Directories are already ensured at the top level of the script,
|
| 211 |
+
# but re-checking here for robustness in case app.run is called differently.
|
| 212 |
+
try:
|
| 213 |
+
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
|
| 214 |
+
os.makedirs(app.config['RESULTS_FOLDER'], exist_ok=True)
|
| 215 |
+
os.makedirs(app.config['CHECKPOINTS_FOLDER'], exist_ok=True)
|
| 216 |
+
os.makedirs(app.config['TEMP_FOLDER'], exist_ok=True)
|
| 217 |
+
logger.info("Application directories confirmed at startup.")
|
| 218 |
+
except OSError as e:
|
| 219 |
+
logger.critical(f"Critical error during startup: Could not create necessary directories: {e}")
|
| 220 |
+
sys.exit(1) # Exit if directories cannot be created
|
| 221 |
+
|
| 222 |
+
logger.info("Starting Flask application...")
|
| 223 |
+
# In a production environment, debug=True should be False
|
| 224 |
app.run(debug=True)
|