Spaces:
Running
Running
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(""" | |
# 📷 Photo Filter App | |
### Chỉnh sửa ảnh với các bộ lọc chuyên nghiệp | |
""") | |
# Khởi tạo components | |
controls = create_filter_controls() | |
filter_names = list(registry.filters.keys()) | |
filter_groups = controls | |
with gr.Row(): | |
with gr.Column(): | |
input_image = gr.Image( | |
label="Ảnh gốc", | |
type="numpy" | |
) | |
filter_select = gr.Dropdown( | |
label="Chọn bộ lọc", | |
choices=filter_names, | |
value="Original" | |
) | |
# Các điều khiển bộ lọc | |
control_components = [] | |
for filter_name, group in filter_groups.items(): | |
for component in group.children: | |
control_components.append(component) | |
apply_button = gr.Button("Áp dụng bộ lọc") | |
filter_doc = gr.Markdown() | |
with gr.Column(): | |
output_image = gr.Image(label="Ảnh đã chỉnh sửa") | |
error_message = gr.Markdown(visible=False) | |
# Xử lý cập nhật UI | |
def update_controls(filter_name): | |
updates = [] | |
for group_name, group in filter_groups.items(): | |
updates.append(gr.update(visible=group_name == filter_name)) | |
doc = registry.filters[filter_name].__doc__ or "Không có mô tả chi tiết." | |
return updates + [doc] | |
# Xử lý ảnh | |
def process(image, filter_name, *args): | |
if image is None: | |
return None, gr.update(visible=True, value="⚠️ Vui lòng chọn ảnh trước khi áp dụng bộ lọc") | |
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] | |
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, gr.update(visible=False) | |
except Exception as e: | |
return None, gr.update(visible=True, value=f"❌ Lỗi xử lý ảnh: {str(e)}") | |
# Kết nối sự kiện | |
filter_select.change( | |
update_controls, | |
inputs=filter_select, | |
outputs=list(filter_groups.values()) + [filter_doc], | |
api_name=False | |
) | |
input_components = [input_image, filter_select] + control_components | |
apply_button.click( | |
process, | |
inputs=input_components, | |
outputs=[output_image, error_message], | |
) | |
return app | |
if __name__ == "__main__": | |
app = create_app() | |
app.launch(share=True) |