Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import gradio as grimport roop.globalsimport roop.coreimport roop.processors.frame.coreimport osimport shutil# Ensure roop thinks it's headless so it doesn't try to launch its own GUIroop.globals.headless = Trueroop.globals.execution_providers = ['cpu'] # Default to CPU, can be changedroop.globals.execution_threads = 1roop.globals.frame_processors = ['face_swapper']roop.globals.keep_fps = Trueroop.globals.keep_frames = Falseroop.globals.skip_audio = Falseroop.globals.many_faces = Falseroop.globals.reference_face_position = 0roop.globals.reference_frame_number = 0roop.globals.similar_face_distance = 0.85roop.globals.temp_frame_format = 'png'roop.globals.temp_frame_quality = 100roop.globals.output_video_encoder = 'libx264'roop.globals.output_video_quality = 35roop.globals.max_memory = Nonedef swap_face(source_file, target_file, enable_enhancer):if source_file is None or target_file is None:return None, Nonesource_path = source_file if isinstance(source_file, str) else source_file.nametarget_path = target_file if isinstance(target_file, str) else target_file.name# Determine output path based on target extensiontarget_name, target_ext = os.path.splitext(os.path.basename(target_path))output_ext = target_extis_video_output = Falseif target_ext.lower() in ['.jpg', '.jpeg', '.png', '.bmp', '.webp']:output_ext = '.png'is_video_output = Falseelif target_ext.lower() in ['.mp4', '.avi', '.mov', '.mkv']:output_ext = '.mp4'is_video_output = Trueoutput_path = os.path.join(os.getcwd(), f"output_{target_name}{output_ext}")print(f"Source: {source_path}")print(f"Target: {target_path}")print(f"Output: {output_path}")print(f"Enhancer Enabled: {enable_enhancer}")# Set globalsroop.globals.source_path = source_pathroop.globals.target_path = target_pathroop.globals.output_path = output_pathroop.globals.execution_providers = ['cpu']# Configure processorsprocessors = ['face_swapper']if enable_enhancer:processors.append('face_enhancer')roop.globals.frame_processors = processors# CRITICAL FIX: Clear the cache of frame processors so it reloads based on the new list# invalidating the previous run's selection (e.g. if enhancer was disabled previously)roop.processors.frame.core.FRAME_PROCESSORS_MODULES = []# Use correct provider name to avoid ONNX Runtime warningsroop.globals.execution_providers = ['CPUExecutionProvider']try:roop.core.start()if os.path.exists(output_path):if is_video_output:return None, output_pathelse:return output_path, Noneelse:print("Error: Output file not created.")return None, Noneexcept Exception as e:print(f"Error during processing: {e}")return None, None# Define the interfacewith gr.Blocks(title="Roop Web UI") as demo:gr.Markdown("# Roop Face Swap Web Interface")gr.Markdown("Upload a source face and a target image/video to swap faces.")with gr.Row():with gr.Column():source_input = gr.Image(type="filepath", label="Source Face (Image)")target_input = gr.File(label="Target (Image or Video)", file_types=["image", "video"])enable_enhancer = gr.Checkbox(label="Enable Face Enhancer (GFPGAN)", value=False)submit_btn = gr.Button("Swap Face", variant="primary")with gr.Column():result_image = gr.Image(label="Result Image", interactive=False)result_video = gr.Video(label="Result Video", interactive=False, format="mp4")submit_btn.click(fn=swap_face,inputs=[source_input, target_input, enable_enhancer],outputs=[result_image, result_video])if __name__ == "__main__":demo.launch(inbrowser=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134import gradio as grimport roop.globalsimport roop.coreimport roop.processors.frame.coreimport osimport shutil# Ensure roop thinks it's headless so it doesn't try to launch its own GUIroop.globals.headless = Trueroop.globals.execution_providers = ['cpu'] # Default to CPU, can be changedroop.globals.execution_threads = 1roop.globals.frame_processors = ['face_swapper']roop.globals.keep_fps = Trueroop.globals.keep_frames = Falseroop.globals.skip_audio = Falseroop.globals.many_faces = Falseroop.globals.reference_face_position = 0roop.globals.reference_frame_number = 0roop.globals.similar_face_distance = 0.85roop.globals.temp_frame_format = 'png'roop.globals.temp_frame_quality = 100roop.globals.output_video_encoder = 'libx264'roop.globals.output_video_quality = 35roop.globals.max_memory = Nonedef swap_face(source_file, target_file, enable_enhancer):if source_file is None or target_file is None:return None, Nonesource_path = source_file if isinstance(source_file, str) else source_file.nametarget_path = target_file if isinstance(target_file, str) else target_file.name# Determine output path based on target extensiontarget_name, target_ext = os.path.splitext(os.path.basename(target_path))output_ext = target_extis_video_output = Falseif target_ext.lower() in ['.jpg', '.jpeg', '.png', '.bmp', '.webp']:output_ext = '.png'is_video_output = Falseelif target_ext.lower() in ['.mp4', '.avi', '.mov', '.mkv']:output_ext = '.mp4'is_video_output = Trueoutput_path = os.path.join(os.getcwd(), f"output_{target_name}{output_ext}")print(f"Source: {source_path}")print(f"Target: {target_path}")print(f"Output: {output_path}")print(f"Enhancer Enabled: {enable_enhancer}")# Set globalsroop.globals.source_path = source_pathroop.globals.target_path = target_pathroop.globals.output_path = output_pathroop.globals.execution_providers = ['cpu']# Configure processorsprocessors = ['face_swapper']if enable_enhancer:processors.append('face_enhancer')roop.globals.frame_processors = processors# CRITICAL FIX: Clear the cache of frame processors so it reloads based on the new list# invalidating the previous run's selection (e.g. if enhancer was disabled previously)roop.processors.frame.core.FRAME_PROCESSORS_MODULES = []# Use correct provider name to avoid ONNX Runtime warningsroop.globals.execution_providers = ['CPUExecutionProvider']try:roop.core.start()if os.path.exists(output_path):if is_video_output:return None, output_pathelse:return output_path, Noneelse:print("Error: Output file not created.")return None, Noneexcept Exception as e:print(f"Error during processing: {e}")return None, None# Define the interfacewith gr.Blocks(title="Roop Web UI") as demo:# Custom Banner for AI Gurujigr.HTML("""<div style="background-color: #0b0f19; padding: 20px; text-align: center; border-radius: 10px; margin-bottom: 20px;"><img src="https://aiguruji97-facefusion-by-ai-guruji.hf.space/gradio_api/file=/tmp/gradio/0c458ca1af97a9ebe14f501ce21d2ace96f2de6fba733486558e7639f8497832/logo.png" alt="AI Guruji Logo" style="width: 120px; height: 120px; border-radius: 50%; display: block; margin: 0 auto;"><h1 style="color: white; font-family: sans-serif; margin-top: 10px; font-size: 28px; font-weight: bold;">Al Guruji</h1><div style="margin-top: 15px; display: flex; justify-content: center; gap: 10px;"><a href="https://www.youtube.com/@AI_Guruji_97" target="_blank" style="background-color: #ff0000; color: white; padding: 8px 20px; border-radius: 20px; text-decoration: none; font-weight: bold; font-family: sans-serif;">YouTube</a><a href="https://buymeacoffee.com/bdas7906" target="_blank" style="background-color: #FFDD00; color: black; padding: 8px 20px; border-radius: 20px; text-decoration: none; font-weight: bold; font-family: sans-serif;">Buy me a coffee</a><a href="https://www.instagram.com/aiguruji97/" target="_blank" style="background-color: #E1306C; color: white; padding: 8px 20px; border-radius: 20px; text-decoration: none; font-weight: bold; font-family: sans-serif;">Instagram</a></div><div style="margin-top: 20px; color: white; font-family: sans-serif; font-size: 14px;"><p>If multiple users are using this space (3-4 users), generation might be slow.</p><p><strong>Duplicate this Space</strong> for faster generation without waiting!</p><p style="margin-top: 10px; font-size: 16px;">❤️ <strong>Please Like this Space if you find it useful!</strong> ❤️</p><div style="display: flex; justify-content: center; align-items: center; margin-top: 10px;"><a href="https://huggingface.co/spaces/huggingface/facefusion?duplicate=true" target="_blank" style="display: inline-flex; align-items: center; background-color: white; color: black; padding: 5px 15px; border-radius: 6px; text-decoration: none; font-weight: bold; border: 1px solid #ccc;"><img src="https://huggingface.co/datasets/huggingface/badges/raw/main/duplicate-this-space-md-dark.svg" alt="Duplicate this Space" style="height: 20px; margin-right: 5px;">Duplicate Space</a></div></div></div>""")# gr.Markdown("# Roop Face Swap Web Interface")gr.Markdown("### Upload a source face and a target image/video to swap faces.")with gr.Row():with gr.Column():source_input = gr.Image(type="filepath", label="Source Face (Image)")target_input = gr.File(label="Target (Image or Video)", file_types=["image", "video"])enable_enhancer = gr.Checkbox(label="Enable Face Enhancer (GFPGAN)", value=False)submit_btn = gr.Button("Swap Face", variant="primary")with gr.Column():result_image = gr.Image(label="Result Image", interactive=False)result_video = gr.Video(label="Result Video", interactive=False, format="mp4")submit_btn.click(fn=swap_face,inputs=[source_input, target_input, enable_enhancer],outputs=[result_image, result_video])if __name__ == "__main__":demo.launch(inbrowser=True)
app.py+134-109