ayman3000's picture
Update app.py
48b26e1 verified
Raw History Blame Contribute Delete
19.9 kB
import gradio as gr
import tempfile
from pathlib import Path
import os
from PIL import Image
from utils import temp_output
# --- Import all tools ---
from tools import (
apply_color_correction, apply_sharpening, reduce_noise,
upscale_resolution, auto_enhance
)
from basic_tools import (
resize_image, convert_grayscale, image_metadata, convert_format, blur_image,
rotate_image, crop_image, thumbnail_image, add_watermark, flip_image,
invert_colors, list_images_in_directory, get_image_metadata,
apply_random_color_variation, add_images, concat_images
)
from advanced_tools import (
detect_edges, apply_erosion, apply_dilation, blur_advanced,
find_contours, isolate_large_objects, extract_bounding_boxes,
add_noise, random_channel_remix
)
from utils import create_folder
# --- Create individual interfaces for each tool ---
def create_basics():
"""Create interfaces for basic tools"""
interfaces = []
# Color Correction
with gr.Tab("Color Correction"):
gr.Markdown("**Adjust brightness, contrast, and saturation of your image**")
with gr.Row():
with gr.Column():
cc_img = gr.Image(type="filepath", label="Input Image")
cc_brightness = gr.Slider(0.5, 2.0, value=1.0, step=0.05, label="Brightness")
cc_contrast = gr.Slider(0.5, 2.0, value=1.0, step=0.05, label="Contrast")
cc_saturation = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Saturation")
cc_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[cc_img],
label="Example Images"
)
cc_btn = gr.Button("Apply Color Correction", variant="primary")
with gr.Column():
cc_output = gr.Image(label="Enhanced Image")
cc_btn.click(apply_color_correction, [cc_img, cc_brightness, cc_contrast, cc_saturation,cc_output_path], cc_output)
# Sharpening
with gr.Tab("Sharpening"):
gr.Markdown("**Enhance image clarity and detail**")
with gr.Row():
with gr.Column():
sharp_img = gr.Image(type="filepath", label="Input Image")
sharp_strength = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Sharpening Strength")
sharp_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[sharp_img],
label="Example Images"
)
sharp_btn = gr.Button("Apply Sharpening", variant="primary")
with gr.Column():
sharp_output = gr.Image(label="Sharpened Image")
sharp_btn.click(apply_sharpening, [sharp_img, sharp_strength,sharp_output_path], sharp_output)
# Noise Reduction
with gr.Tab("Noise Reduction"):
gr.Markdown("**Remove unwanted noise from your image**")
with gr.Row():
with gr.Column():
noise_img = gr.Image(type="filepath", label="Input Image")
noise_strength = gr.Radio(["low", "medium", "high"], value="medium", label="Noise Reduction Strength")
noise_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[noise_img],
label="Example Images"
)
noise_btn = gr.Button("Reduce Noise", variant="primary")
with gr.Column():
noise_output = gr.Image(label="Denoised Image")
noise_btn.click(reduce_noise, [noise_img, noise_strength,noise_output_path], noise_output)
# Upscaling
with gr.Tab("Upscaling"):
gr.Markdown("**Increase image resolution using advanced interpolation**")
with gr.Row():
with gr.Column():
up_img = gr.Image(type="filepath", label="Input Image")
up_scale = gr.Radio([2, 3, 4], value=2, label="Scale Factor")
up_method = gr.Dropdown(["nearest", "bilinear", "bicubic", "lanczos"], value="bicubic",
label="Interpolation Method")
up_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[up_img],
label="Example Images"
)
up_btn = gr.Button("Upscale Image", variant="primary")
with gr.Column():
up_output = gr.Image(label="Upscaled Image")
up_btn.click(upscale_resolution, [up_img, up_scale, up_method,up_output_path], up_output)
# Auto Enhance
with gr.Tab("Auto Enhance"):
gr.Markdown("**Automatically optimize image quality**")
with gr.Row():
with gr.Column():
auto_img = gr.Image(type="filepath", label="Input Image")
auto_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[auto_img],
label="Example Images"
)
auto_btn = gr.Button("Auto Enhance", variant="primary")
with gr.Column():
auto_output = gr.Image(label="Enhanced Image")
auto_btn.click(auto_enhance, [auto_img,auto_output_path], auto_output)
# Resize
with gr.Tab("Resize"):
gr.Markdown("**Change image dimensions**")
with gr.Row():
with gr.Column():
resize_img = gr.Image(type="filepath", label="Input Image")
resize_width = gr.Number(value=512, label="Width")
resize_height = gr.Number(value=512, label="Height")
resize_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[resize_img],
label="Example Images"
)
resize_btn = gr.Button("Resize Image", variant="primary")
with gr.Column():
resize_output = gr.Image(label="Resized Image")
resize_btn.click(resize_image, [resize_img, resize_width, resize_height,resize_output_path], resize_output)
# Grayscale
with gr.Tab("Grayscale"):
gr.Markdown("**Convert image to grayscale**")
with gr.Row():
with gr.Column():
gray_img = gr.Image(type="filepath", label="Input Image")
gray_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[gray_img],
label="Example Images"
)
gray_btn = gr.Button("Convert to Grayscale", variant="primary")
with gr.Column():
gray_output = gr.Image(label="Grayscale Image")
gray_btn.click(convert_grayscale, [gray_img,gray_output_path], gray_output)
# Additional basic tools (simplified for space)
with gr.Tab("More Basic Tools"):
gr.Markdown("**Quick access to common image operations**")
with gr.Accordion("Blur & Effects", open=False):
with gr.Row():
with gr.Column():
blur_img = gr.Image(type="filepath", label="Input Image")
blur_radius = gr.Slider(0.1, 20.0, value=2.0, step=0.1, label="Blur Radius")
blur_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[blur_img],
label="Example Images"
)
blur_btn = gr.Button("Apply Blur")
with gr.Column():
blur_output = gr.Image(label="Blurred Image")
blur_btn.click(blur_image, [blur_img, blur_radius,blur_output_path], blur_output)
with gr.Accordion("Rotate & Flip", open=False):
with gr.Row():
with gr.Column():
rotate_img = gr.Image(type="filepath", label="Input Image")
rotate_angle = gr.Number(value=90.0, label="Rotation Angle")
rotate_output_path = gr.Text(temp_output(), label="Output Image")
gr.Examples(
examples=["cat.png","snake.png"],
inputs=[rotate_img],
label="Example Images"
)
rotate_btn = gr.Button("Rotate Image")
flip_mode = gr.Radio(["horizontal", "vertical"], value="horizontal", label="Flip Mode")
flip_output_path = gr.Text(temp_output(), label="Output Image")
flip_btn = gr.Button("Flip Image")
with gr.Column():
rotate_output = gr.Image(label="Rotated/Flipped Image")
rotate_btn.click(rotate_image, [rotate_img, rotate_angle,rotate_output_path], rotate_output)
flip_btn.click(flip_image, [rotate_img, flip_mode,flip_output_path], rotate_output)
def create_advanceds():
"""Create interfaces for advanced tools"""
# Edge Detection
with gr.Tab("Edge Detection"):
gr.Markdown("**Detect edges using Canny edge detection algorithm**")
with gr.Row():
with gr.Column():
edge_img = gr.Image(type="filepath", label="Input Image")
edge_t1 = gr.Number(value=100, label="Lower Threshold")
edge_t2 = gr.Number(value=200, label="Upper Threshold")
edge_output_path = gr.Text(temp_output(), label="Output Image")
edge_btn = gr.Button("Detect Edges", variant="primary")
with gr.Column():
edge_output = gr.Image(label="Edge Detection Result")
edge_btn.click(detect_edges, [edge_img, edge_t1, edge_t2,edge_output_path], edge_output)
# Morphological Operations
with gr.Tab("Morphological Ops"):
gr.Markdown("**Apply erosion and dilation operations**")
with gr.Row():
with gr.Column():
morph_img = gr.Image(type="filepath", label="Input Image")
morph_kernel = gr.Number(value=3, label="Kernel Size")
morph_iter = gr.Number(value=1, label="Iterations")
erosion_output_path = gr.Text(temp_output(), label="Output Erosion Image")
dilation_output_path = gr.Text(temp_output(), label="Output Dilation Image")
erosion_btn = gr.Button("Apply Erosion")
dilation_btn = gr.Button("Apply Dilation")
with gr.Column():
morph_output = gr.Image(label="Morphological Result")
erosion_btn.click(apply_erosion, [morph_img, morph_kernel, morph_iter,erosion_output_path], morph_output)
dilation_btn.click(apply_dilation, [morph_img, morph_kernel, morph_iter,dilation_output_path], morph_output)
# Contour Analysis
with gr.Tab("Contour Analysis"):
gr.Markdown("**Find and analyze contours in images**")
with gr.Row():
with gr.Column():
contour_img = gr.Image(type="filepath", label="Input Image")
contour_area = gr.Number(value=1000.0, label="Min Area Threshold")
contour_output_path = gr.Text(temp_output(), label="Countour Output Image")
isolate_output_path = gr.Text(temp_output(), label="Isolate Output Image")
contour_btn = gr.Button("Find Contours", variant="primary")
isolate_btn = gr.Button("Isolate Large Objects")
bbox_btn = gr.Button("Extract Bounding Boxes")
with gr.Column():
contour_output = gr.Image(label="Contour Result")
bbox_output = gr.JSON(label="Bounding Boxes")
contour_btn.click(find_contours, [contour_img,contour_output_path], contour_output,)
isolate_btn.click(isolate_large_objects, [contour_img, contour_area,isolate_output_path], contour_output)
bbox_btn.click(extract_bounding_boxes, [contour_img, contour_area], bbox_output)
# Noise and Effects
with gr.Tab("Noise & Effects"):
gr.Markdown("**Add noise and apply special effects**")
with gr.Row():
with gr.Column():
fx_img = gr.Image(type="filepath", label="Input Image")
noise_r = gr.Slider(1, 5, value=1, step=1, label="Red Noise Scale")
noise_g = gr.Slider(1, 5, value=1, step=1, label="Green Noise Scale")
noise_b = gr.Slider(1, 5, value=1, step=1, label="Blue Noise Scale")
noise_output_path =gr.Text(temp_output(), label="Noice Output Image")
remix_output_path = gr.Text(temp_output(), label="Remix Output Image")
noise_btn = gr.Button("Add Noise")
remix_btn = gr.Button("Random Channel Remix")
with gr.Column():
fx_output = gr.Image(label="Effect Result")
noise_btn.click(add_noise, [fx_img, noise_r, noise_g, noise_b,noise_output_path], fx_output)
remix_btn.click(random_channel_remix, [fx_img,remix_output_path], fx_output)
def create_utilitys():
"""Create interfaces for utility tools"""
# Metadata Tools
with gr.Tab("Metadata"):
gr.Markdown("**Extract and view image metadata**")
with gr.Row():
with gr.Column():
meta_img = gr.Image(type="filepath", label="Input Image")
meta_btn = gr.Button("Get Metadata (String)", variant="primary")
meta_dict_btn = gr.Button("Get Metadata (Dict)")
with gr.Column():
meta_output = gr.Textbox(label="Metadata String", lines=10)
meta_dict_output = gr.JSON(label="Metadata Dictionary")
meta_btn.click(image_metadata, [meta_img], meta_output)
meta_dict_btn.click(get_image_metadata, [meta_img], meta_dict_output)
# Format Conversion
with gr.Tab("Format Conversion"):
gr.Markdown("**Convert between different image formats**")
with gr.Row():
with gr.Column():
fmt_img = gr.Image(type="filepath", label="Input Image")
fmt_format = gr.Dropdown(["png", "jpeg", "bmp", "webp", "tiff"], value="png", label="Target Format")
fmt_output_path = gr.Text(temp_output(), label="Output Image")
fmt_btn = gr.Button("Convert Format", variant="primary")
with gr.Column():
fmt_output = gr.Image(label="Converted Image")
fmt_btn.click(convert_format, [fmt_img, fmt_format,fmt_output_path], fmt_output)
def create_extra_tools():
with gr.Tab("Image Merge"):
gr.Markdown("**Combine two images by addition or concatenation**")
with gr.Accordion("Add Images Pixel-wise", open=False):
with gr.Row():
with gr.Column():
img1_add = gr.Image(type="filepath", label="Image 1")
img2_add = gr.Image(type="filepath", label="Image 2")
add_output_path = gr.Text(temp_output(), label="Output Path")
add_btn = gr.Button("Add Images")
with gr.Column():
add_output = gr.Image(label="Added Image")
add_btn.click(add_images, [img1_add, img2_add, add_output_path], add_output)
with gr.Accordion("Concatenate Images", open=False):
with gr.Row():
with gr.Column():
img1_cat = gr.Image(type="filepath", label="Image 1")
img2_cat = gr.Image(type="filepath", label="Image 2")
concat_mode = gr.Radio(["horizontal", "vertical"], value="horizontal", label="Concatenation Mode")
concat_output_path = gr.Text(temp_output(), label="Output Path")
concat_btn = gr.Button("Concatenate")
with gr.Column():
concat_output = gr.Image(label="Concatenated Image")
concat_btn.click(concat_images, [img1_cat, img2_cat, concat_mode, concat_output_path], concat_output)
# Create the main application
with gr.Blocks(theme=gr.themes.Default(), title="Image Enhancer Pro Suite") as demo:
# Header
gr.Markdown("""
# πŸ–ΌοΈ Image Enhancer Pro Suite
### Professional Image Processing Tools - Organized & Easy to Use
Choose from our comprehensive collection of image processing tools organized by category.
""")
# Main tabbed interface
with gr.Tabs():
# Basic Tools Tab
with gr.TabItem("πŸ”§ Basic Tools", id="basic"):
gr.Markdown("## Essential image processing operations")
create_basics()
# Advanced Tools Tab
with gr.TabItem("⚑ Advanced Tools", id="advanced"):
gr.Markdown("## Computer vision and advanced image analysis")
create_advanceds()
# Utility Tools Tab
with gr.TabItem("πŸ› οΈ Utilities", id="utilities"):
gr.Markdown("## File management and metadata tools")
create_utilitys()
with gr.TabItem("🧩 Extra Tools", id="extra"):
gr.Markdown("## Custom tools for image merging and combination")
create_extra_tools()
# Help & Info Tab
with gr.TabItem("πŸ“š Help", id="help"):
gr.Markdown("""
## πŸš€ Quick Start Guide
### Basic Tools
- **Color Correction**: Adjust brightness, contrast, and saturation
- **Sharpening**: Enhance image clarity and detail
- **Noise Reduction**: Remove unwanted noise from images
- **Upscaling**: Increase resolution with various interpolation methods
- **Auto Enhance**: Automatically optimize image quality
### Advanced Tools
- **Edge Detection**: Find edges using Canny algorithm
- **Morphological Operations**: Erosion and dilation for shape analysis
- **Contour Analysis**: Find and analyze object contours
- **Noise & Effects**: Add artistic effects and noise
### Utilities
- **Metadata**: Extract EXIF and other image information
- **Format Conversion**: Convert between image formats
- **File Operations**: Manage directories and files
## πŸ’‘ Tips for Best Results
1. **Image Quality**: Upload high-resolution images for best results
2. **Parameter Tuning**: Experiment with different parameter values
3. **Preprocessing**: Use basic tools before advanced operations
4. **Batch Processing**: Use utility tools for managing multiple files
5. **Format Choice**: PNG for quality, JPEG for size optimization
## πŸ”§ Technical Notes
- All processing is done server-side for maximum quality
- Temporary files are automatically cleaned up
- Supports most common image formats
- MCP server integration for extended functionality
## πŸ“ž Support
If you encounter issues, check that:
- Your image file is in a supported format
- File permissions allow reading/writing
- Required tool modules are properly installed
""")
# Launch the application
if __name__ == "__main__":
demo.launch(
mcp_server=True,
allowed_paths=["/tmp", ".", "./output"],
show_error=True
)