import gradio as gr import cv2 import numpy as np from registry import registry from filters import * from components import create_filter_controls def create_app(): with gr.Blocks() as app: gr.Markdown("# 📷 Real-Time Photo Filter App") # Khởi tạo components controls = create_filter_controls() filter_names = list(registry.filters.keys()) with gr.Row(): with gr.Column(): input_image = gr.Image(label="Input Image", type="numpy") filter_select = gr.Dropdown( label="Select Filter", choices=filter_names, value="Original" ) # Thêm các control vào UI control_components = [c for c in controls.values()] # for component in control_components: # Removed render() calls # component.render() with gr.Column(): output_image = gr.Image(label="Filtered Image") # Xử lý cập nhật UI def update_controls(filter_name): updates = [] for filter_name_ctrl, filter_ctrl_list in controls.items(): # Correctly unpack key-value pairs visibility = filter_name_ctrl == filter_name for component in filter_ctrl_list: # Iterate through the list of controls updates.append(gr.update(visible=visibility)) # Update visibility for each control return updates # Xử lý ảnh real-time def process(*args, **kwargs): image = args[0] if len(args) > 0 else None filter_name = args[1] if len(args) > 1 else "Original" # Default filter if image is None: return None try: image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) params = { k.split('_', 1)[1]: v for k, v in kwargs.items() if k.startswith(filter_name) } processed = registry.filters[filter_name](image, **params) if len(processed.shape) == 2: processed = cv2.cvtColor(processed, cv2.COLOR_GRAY2RGB) else: processed = cv2.cvtColor(processed, cv2.COLOR_BGR2RGB) return processed except Exception as e: print(f"Error processing image: {e}") return image # Kết nối sự kiện filter_select.change( update_controls, inputs=filter_select, outputs=list(controls.values()) ) control_components_list = list(controls.values()) input_components_process = [input_image, filter_select] + control_components_list for component in [input_image, filter_select] + control_components_list: component.change( process, inputs=input_components_process, outputs=output_image, show_progress=False ) return app if __name__ == "__main__": app = create_app() app.launch()