changeimage / app.py
Merlintxu's picture
Update app.py
1dc6f8e verified
raw
history blame
5.94 kB
import gradio as gr
from PIL import Image
import os
import tempfile
from transformers import pipeline
def optimize_image(image, png_optimize, jpeg_quality, jpeg_resolution, webp_quality):
img = Image.open(image)
original_size = os.path.getsize(image.name) / 1024 # tama帽o en KB
# Crear un directorio seguro para almacenar las im谩genes optimizadas
output_dir = "/tmp/optimized_images"
os.makedirs(output_dir, exist_ok=True)
# Generar archivos temporales en un directorio seguro
lossless_output_path = os.path.join(output_dir, "lossless.png")
lossy_output_path = os.path.join(output_dir, "lossy.jpg")
reduced_output_path = os.path.join(output_dir, "reduced_resolution.jpg")
webp_lossy_output_path = os.path.join(output_dir, "lossy.webp")
# 1. Compresi贸n sin p茅rdida (PNG)
img.save(lossless_output_path, format="PNG", optimize=png_optimize)
lossless_size = os.path.getsize(lossless_output_path) / 1024
lossless_diff = original_size - lossless_size
lossless_img = Image.open(lossless_output_path)
# 2. Compresi贸n con p茅rdida (JPEG)
img.save(lossy_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
lossy_size = os.path.getsize(lossy_output_path) / 1024
lossy_diff = original_size - lossy_size
lossy_img = Image.open(lossy_output_path)
# 3. Reducci贸n de resoluci贸n (JPEG)
new_resolution = (img.width * jpeg_resolution // 100, img.height * jpeg_resolution // 100)
reduced_img = img.resize(new_resolution, Image.LANCZOS)
reduced_img.save(reduced_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
reduced_size = os.path.getsize(reduced_output_path) / 1024
reduced_diff = original_size - reduced_size
reduced_img = Image.open(reduced_output_path)
# 4. Compresi贸n con WebP (con p茅rdida)
img.save(webp_lossy_output_path, format="WEBP", quality=webp_quality, optimize=True)
webp_lossy_size = os.path.getsize(webp_lossy_output_path) / 1024
webp_lossy_diff = original_size - webp_lossy_size
webp_lossy_img = Image.open(webp_lossy_output_path)
# Retornar las im谩genes optimizadas, tama帽os y rutas para descarga
return [
lossless_img, f"Sin p茅rdida: {lossless_size:.2f} KB \n(diferencia: {-lossless_diff:.2f} KB)", lossless_output_path,
lossy_img, f"Con p茅rdida: {lossy_size:.2f} KB \n(diferencia: {-lossy_diff:.2f} KB)", lossy_output_path,
reduced_img, f"Reducci贸n de resoluci贸n: {reduced_size:.2f} KB \n(diferencia: {-reduced_diff:.2f} KB)", reduced_output_path,
webp_lossy_img, f"WebP con p茅rdida: {webp_lossy_size:.2f} KB \n(diferencia: {-webp_lossy_diff:.2f} KB)", webp_lossy_output_path
]
# Funci贸n para aplicar un modelo seleccionado desde Hugging Face
def apply_model(image, model_name):
model_pipeline = pipeline("image-super-resolution", model=model_name)
return model_pipeline(image)
with gr.Blocks() as demo:
with gr.Tab("Optimizaci贸n Tradicional"):
image_input = gr.File(label="Sube tu imagen", file_types=['image'])
optimize_button = gr.Button("Optimizar")
with gr.Row():
with gr.Column():
optimized_output1 = gr.Image(label="Optimizaci贸n sin p茅rdida")
png_optimize = gr.Checkbox(label="Optimizar PNG", value=True)
download_button1 = gr.File(label="Descargar", visible=True)
optimized_size1 = gr.Text(value="", interactive=False, show_label=False)
with gr.Column():
optimized_output2 = gr.Image(label="Optimizaci贸n con p茅rdida (JPEG)")
jpeg_quality = gr.Slider(label="Calidad JPEG", minimum=10, maximum=100, value=50, step=1)
download_button2 = gr.File(label="Descargar", visible=True)
optimized_size2 = gr.Text(value="", interactive=False, show_label=False)
with gr.Column():
optimized_output3 = gr.Image(label="Reducci贸n de resoluci贸n (JPEG)")
jpeg_resolution = gr.Slider(label="Resoluci贸n JPEG (%)", minimum=10, maximum=100, value=50, step=1)
download_button3 = gr.File(label="Descargar", visible=True)
optimized_size3 = gr.Text(value="", interactive=False, show_label=False)
with gr.Column():
optimized_output4 = gr.Image(label="Optimizaci贸n WebP con p茅rdida")
webp_quality = gr.Slider(label="Calidad WebP", minimum=10, maximum=100, value=50, step=1)
download_button4 = gr.File(label="Descargar", visible=True)
optimized_size4 = gr.Text(value="", interactive=False, show_label=False)
# Conectar cada control a la funci贸n de optimizaci贸n
optimize_button.click(
fn=optimize_image,
inputs=[image_input, png_optimize, jpeg_quality, jpeg_resolution, webp_quality],
outputs=[
optimized_output1, optimized_size1, download_button1,
optimized_output2, optimized_size2, download_button2,
optimized_output3, optimized_size3, download_button3,
optimized_output4, optimized_size4, download_button4
]
)
with gr.Tab("Optimizaci贸n con Modelos de Hugging Face"):
hf_image_input = gr.File(label="Sube tu imagen para optimizaci贸n avanzada", file_types=['image'])
model_selector = gr.Dropdown(
label="Selecciona un modelo",
choices=["xinntao/Real-ESRGAN", "google/ddpm-cifar10-32", "facebook/ddpm"], # A帽ade los modelos disponibles
value="xinntao/Real-ESRGAN"
)
hf_output = gr.Image(label="Resultado")
hf_button = gr.Button("Aplicar Modelo")
hf_button.click(
fn=apply_model,
inputs=[hf_image_input, model_selector],
outputs=hf_output
)
demo.launch()