omaralaa2004's picture
Update app.py
c2ea759 verified
import gradio as gr
import cv2
import numpy as np
from PIL import Image, ImageFilter, ImageEnhance
import warnings
warnings.filterwarnings("ignore")
class RefinedEnhancer:
"""Refined photo enhancer - natural colors and clarity focused"""
def __init__(self):
print("πŸ€– Refined Photo Enhancer Ready!")
def enhance_image(self, image, scale=None, enhance_colors=True, enhance_clarity=True):
"""Main enhancement function - natural and clear"""
if image is None:
return None
print(f"🎯 Enhancing image...")
try:
# Convert to RGB if needed
if image.mode != 'RGB':
image = image.convert('RGB')
print(f"πŸ“Έ Original size: {image.size}")
# Step 1: Gentle noise reduction
print("πŸ”„ Step 1: Gentle cleanup...")
processed = self.gentle_cleanup(image)
# Step 2: Optional upscaling
if scale and scale > 1:
print(f"πŸ”„ Step 2: Upscaling to {scale}x...")
new_size = (int(image.width * scale), int(image.height * scale))
processed = processed.resize(new_size, Image.LANCZOS)
# Step 3: Natural color enhancement
if enhance_colors:
print("πŸ”„ Step 3: Natural color enhancement...")
processed = self.natural_color_enhancement(processed)
# Step 4: Clarity improvement
if enhance_clarity:
print("πŸ”„ Step 4: Clarity improvement...")
processed = self.clarity_improvement(processed)
print(f"βœ… Final size: {processed.size}")
return processed
except Exception as e:
print(f"Enhancement error: {e}")
return image # Return original if processing fails
def gentle_cleanup(self, image):
"""Very gentle cleanup - minimal noise reduction"""
try:
# Convert to OpenCV format
cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
# Ultra-gentle noise reduction
denoised = cv2.fastNlMeansDenoisingColored(cv_image, None, 3, 3, 7, 21)
# Convert back to PIL
return Image.fromarray(cv2.cvtColor(denoised, cv2.COLOR_BGR2RGB))
except:
return image
def natural_color_enhancement(self, image):
"""Natural color enhancement - subtle but noticeable"""
try:
# Convert to OpenCV format
cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
# Convert to HSV for better color control
hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)
# Enhance saturation naturally
saturation = hsv[:, :, 1].astype(np.float32)
mask = (saturation > 30) & (saturation < 200)
saturation[mask] = saturation[mask] * 1.08
saturation = np.clip(saturation, 0, 255).astype(np.uint8)
hsv[:, :, 1] = saturation
# Convert back to BGR
enhanced = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
# Subtle contrast enhancement
lab = cv2.cvtColor(enhanced, cv2.COLOR_BGR2LAB)
clahe = cv2.createCLAHE(clipLimit=1.1, tileGridSize=(8, 8))
lab[:, :, 0] = clahe.apply(lab[:, :, 0])
enhanced = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
# Convert back to PIL
return Image.fromarray(cv2.cvtColor(enhanced, cv2.COLOR_BGR2RGB))
except:
return image
def clarity_improvement(self, image):
"""Improve clarity without over-smoothing"""
try:
# Gentle unsharp mask
sharpened = image.filter(ImageFilter.UnsharpMask(radius=0.8, percent=40, threshold=3))
# Subtle detail enhancement
cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
gaussian = cv2.GaussianBlur(cv_image, (0, 0), 2.0)
detail_enhanced = cv2.addWeighted(cv_image, 1.3, gaussian, -0.3, 0)
detail_enhanced_pil = Image.fromarray(cv2.cvtColor(detail_enhanced, cv2.COLOR_BGR2RGB))
# Blend methods
final = Image.blend(sharpened, detail_enhanced_pil, 0.3)
result = Image.blend(image, final, 0.6)
return result
except:
return image
# Initialize enhancer
enhancer = RefinedEnhancer()
def process_image_auto(image):
"""Auto enhancement with smart defaults"""
if image is None:
return None, "❌ No image provided"
try:
# Get image info
w, h = image.size
total_pixels = w * h
# Smart scaling
if total_pixels < 500000:
scale = 3
scale_info = "Applied 3x upscaling (small image)"
elif total_pixels < 2000000:
scale = 2
scale_info = "Applied 2x upscaling (medium image)"
else:
scale = None
scale_info = "Kept original size (large image)"
# Enhance
enhanced = enhancer.enhance_image(image, scale=scale, enhance_colors=True, enhance_clarity=True)
# Info message
info = f"""Enhancement Complete!
Original: {w} Γ— {h} pixels
Enhanced: {enhanced.size[0]} Γ— {enhanced.size[1]} pixels
Enhancements Applied:
β€’ Natural color enhancement
β€’ Clarity improvement
β€’ {scale_info}
"""
return enhanced, info
except Exception as e:
return None, f"❌ Error: {str(e)}"
def process_image_custom(image, upscale, colors, clarity):
"""Custom enhancement"""
if image is None:
return None, "❌ No image provided"
try:
scale = int(upscale) if upscale > 1 else None
enhanced = enhancer.enhance_image(image, scale=scale, enhance_colors=colors, enhance_clarity=clarity)
enhancements = []
if scale:
enhancements.append(f"{scale}x upscaling")
if colors:
enhancements.append("Natural colors")
if clarity:
enhancements.append("Clarity improvement")
info = f"""Custom Enhancement Complete!
Original: {image.size[0]} Γ— {image.size[1]} pixels
Enhanced: {enhanced.size[0]} Γ— {enhanced.size[1]} pixels
Applied: {', '.join(enhancements) if enhancements else 'No enhancements'}
"""
return enhanced, info
except Exception as e:
return None, f"❌ Error: {str(e)}"
# Create interface - simplified version
def create_app():
# Use basic Blocks without theme to avoid compatibility issues
with gr.Blocks() as app:
gr.Markdown("# 🎨 Refined Photo Enhancer")
gr.Markdown("### Natural Colors & Clarity Enhancement")
# Auto tab
with gr.Tab("πŸš€ Smart Auto"):
with gr.Row():
with gr.Column():
input1 = gr.Image(type="pil", label="Upload Photo")
btn1 = gr.Button("✨ Auto Enhance")
with gr.Column():
output1 = gr.Image(label="Enhanced Photo")
info1 = gr.Textbox(label="Info", lines=8)
btn1.click(process_image_auto, inputs=[input1], outputs=[output1, info1])
# Custom tab
with gr.Tab("πŸŽ›οΈ Custom"):
with gr.Row():
with gr.Column():
input2 = gr.Image(type="pil", label="Upload Photo")
upscale = gr.Slider(1, 4, value=2, step=1, label="Upscale Factor")
colors = gr.Checkbox(value=True, label="Color Enhancement")
clarity = gr.Checkbox(value=True, label="Clarity Enhancement")
btn2 = gr.Button("🎯 Custom Enhance")
with gr.Column():
output2 = gr.Image(label="Enhanced Photo")
info2 = gr.Textbox(label="Info", lines=8)
btn2.click(process_image_custom, inputs=[input2, upscale, colors, clarity], outputs=[output2, info2])
gr.Markdown("""
**Tips:**
- Small images: Auto-upscaling recommended
- Large images: Usually no upscaling needed
- Best for: Natural photos, portraits, landscapes
""")
return app
# Launch
if __name__ == "__main__":
print("πŸš€ Starting Refined Photo Enhancer...")
try:
app = create_app()
app.launch(share=True)
except Exception as e:
print(f"Launch error: {e}")
print("Trying basic launch...")
app = create_app()
app.launch()