Spaces:
Sleeping
Sleeping
| 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(theme="CultriX/gradio-theme") as app: | |
| gr.Markdown("# 📷 Photo Filter App") | |
| # Khởi tạo components | |
| controls = create_filter_controls() | |
| filter_names = list(registry.filters.keys()) | |
| filter_groups = {} # Store filter groups | |
| 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 = [] | |
| filter_groups = controls # Assign controls directly to filter_groups | |
| for filter_name, group in filter_groups.items(): | |
| for component in group.children: # Iterate over children of the group | |
| control_components.append(component) # Collect sliders for event handling | |
| apply_button = gr.Button("Apply Filter") # Add Apply button | |
| with gr.Column(): | |
| output_image = gr.Image(label="Filtered Image") | |
| # Xử lý cập nhật UI | |
| def update_controls(filter_name): | |
| updates = [] | |
| for group_name, group in filter_groups.items(): | |
| visibility = (group_name == filter_name) | |
| updates.append(gr.update(visible=visibility)) # Changed from gr.Group.update | |
| return updates | |
| # Xử lý ảnh khi button click | |
| def process(image, filter_name, *args): # Update process function to take image, filter_name and *args | |
| if image is None: | |
| return None | |
| try: | |
| image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) | |
| params = {} | |
| param_names = list(registry.params_map.get(filter_name, {}).keys()) | |
| for i, param_name in enumerate(param_names): | |
| params[param_name] = args[i] # Get parameter values from args | |
| 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(filter_groups.values()), # Pass list of groups as outputs | |
| api_name=False | |
| ) | |
| input_components = [input_image, filter_select] + control_components # Input components for button click | |
| apply_button.click( # Attach click event to Apply button | |
| process, | |
| inputs=input_components, # Use all input components | |
| outputs=output_image, | |
| ) | |
| return app | |
| if __name__ == "__main__": | |
| app = create_app() | |
| app.launch(share=True) |