Merlintxu commited on
Commit
a329012
1 Parent(s): 1dc6f8e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -41
app.py CHANGED
@@ -2,56 +2,69 @@ import gradio as gr
2
  from PIL import Image
3
  import os
4
  import tempfile
 
5
  from transformers import pipeline
6
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  def optimize_image(image, png_optimize, jpeg_quality, jpeg_resolution, webp_quality):
8
- img = Image.open(image)
 
 
 
 
 
 
 
 
9
 
10
  original_size = os.path.getsize(image.name) / 1024 # tamaño en KB
11
-
12
- # Crear un directorio seguro para almacenar las imágenes optimizadas
13
  output_dir = "/tmp/optimized_images"
14
  os.makedirs(output_dir, exist_ok=True)
15
 
16
- # Generar archivos temporales en un directorio seguro
17
- lossless_output_path = os.path.join(output_dir, "lossless.png")
18
- lossy_output_path = os.path.join(output_dir, "lossy.jpg")
19
- reduced_output_path = os.path.join(output_dir, "reduced_resolution.jpg")
20
- webp_lossy_output_path = os.path.join(output_dir, "lossy.webp")
21
-
22
- # 1. Compresión sin pérdida (PNG)
23
- img.save(lossless_output_path, format="PNG", optimize=png_optimize)
24
- lossless_size = os.path.getsize(lossless_output_path) / 1024
25
- lossless_diff = original_size - lossless_size
26
- lossless_img = Image.open(lossless_output_path)
27
 
28
- # 2. Compresión con pérdida (JPEG)
29
- img.save(lossy_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
30
- lossy_size = os.path.getsize(lossy_output_path) / 1024
31
- lossy_diff = original_size - lossy_size
32
- lossy_img = Image.open(lossy_output_path)
33
-
34
- # 3. Reducción de resolución (JPEG)
35
- new_resolution = (img.width * jpeg_resolution // 100, img.height * jpeg_resolution // 100)
36
- reduced_img = img.resize(new_resolution, Image.LANCZOS)
37
- reduced_img.save(reduced_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
38
- reduced_size = os.path.getsize(reduced_output_path) / 1024
39
- reduced_diff = original_size - reduced_size
40
- reduced_img = Image.open(reduced_output_path)
 
 
 
 
 
 
 
 
 
41
 
42
- # 4. Compresión con WebP (con pérdida)
43
- img.save(webp_lossy_output_path, format="WEBP", quality=webp_quality, optimize=True)
44
- webp_lossy_size = os.path.getsize(webp_lossy_output_path) / 1024
45
- webp_lossy_diff = original_size - webp_lossy_size
46
- webp_lossy_img = Image.open(webp_lossy_output_path)
 
47
 
48
- # Retornar las imágenes optimizadas, tamaños y rutas para descarga
49
- return [
50
- lossless_img, f"Sin pérdida: {lossless_size:.2f} KB \n(diferencia: {-lossless_diff:.2f} KB)", lossless_output_path,
51
- lossy_img, f"Con pérdida: {lossy_size:.2f} KB \n(diferencia: {-lossy_diff:.2f} KB)", lossy_output_path,
52
- reduced_img, f"Reducción de resolución: {reduced_size:.2f} KB \n(diferencia: {-reduced_diff:.2f} KB)", reduced_output_path,
53
- webp_lossy_img, f"WebP con pérdida: {webp_lossy_size:.2f} KB \n(diferencia: {-webp_lossy_diff:.2f} KB)", webp_lossy_output_path
54
- ]
55
 
56
  # Función para aplicar un modelo seleccionado desde Hugging Face
57
  def apply_model(image, model_name):
@@ -60,7 +73,7 @@ def apply_model(image, model_name):
60
 
61
  with gr.Blocks() as demo:
62
  with gr.Tab("Optimización Tradicional"):
63
- image_input = gr.File(label="Sube tu imagen", file_types=['image'])
64
  optimize_button = gr.Button("Optimizar")
65
 
66
  with gr.Row():
@@ -101,7 +114,7 @@ with gr.Blocks() as demo:
101
  )
102
 
103
  with gr.Tab("Optimización con Modelos de Hugging Face"):
104
- hf_image_input = gr.File(label="Sube tu imagen para optimización avanzada", file_types=['image'])
105
  model_selector = gr.Dropdown(
106
  label="Selecciona un modelo",
107
  choices=["xinntao/Real-ESRGAN", "google/ddpm-cifar10-32", "facebook/ddpm"], # Añade los modelos disponibles
 
2
  from PIL import Image
3
  import os
4
  import tempfile
5
+ import pyheif
6
  from transformers import pipeline
7
 
8
+ def open_heic_image(image_path):
9
+ heif_file = pyheif.read(image_path)
10
+ img = Image.frombytes(
11
+ heif_file.mode,
12
+ heif_file.size,
13
+ heif_file.data,
14
+ "raw",
15
+ heif_file.mode,
16
+ heif_file.stride,
17
+ )
18
+ return img
19
+
20
  def optimize_image(image, png_optimize, jpeg_quality, jpeg_resolution, webp_quality):
21
+ # Manejar archivos HEIC
22
+ if image.name.lower().endswith(".heic"):
23
+ img = open_heic_image(image.name)
24
+ else:
25
+ img = Image.open(image)
26
+
27
+ # Convertir la imagen a RGB si está en RGBA
28
+ if img.mode == 'RGBA':
29
+ img = img.convert('RGB')
30
 
31
  original_size = os.path.getsize(image.name) / 1024 # tamaño en KB
 
 
32
  output_dir = "/tmp/optimized_images"
33
  os.makedirs(output_dir, exist_ok=True)
34
 
35
+ results = []
 
 
 
 
 
 
 
 
 
 
36
 
37
+ # Optimización para PNG
38
+ if png_optimize:
39
+ lossless_output_path = os.path.join(output_dir, "lossless.png")
40
+ img.save(lossless_output_path, format="PNG", optimize=True)
41
+ lossless_size = os.path.getsize(lossless_output_path) / 1024
42
+ results.append(("PNG", lossless_output_path, lossless_size, original_size))
43
+
44
+ # Optimización para JPEG
45
+ if jpeg_quality != 50:
46
+ lossy_output_path = os.path.join(output_dir, "lossy.jpg")
47
+ img.save(lossy_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
48
+ lossy_size = os.path.getsize(lossy_output_path) / 1024
49
+ results.append(("JPEG", lossy_output_path, lossy_size, original_size))
50
+
51
+ # Reducción de resolución (JPEG)
52
+ if jpeg_resolution != 50:
53
+ reduced_output_path = os.path.join(output_dir, "reduced_resolution.jpg")
54
+ new_resolution = (img.width * jpeg_resolution // 100, img.height * jpeg_resolution // 100)
55
+ reduced_img = img.resize(new_resolution, Image.LANCZOS)
56
+ reduced_img.save(reduced_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
57
+ reduced_size = os.path.getsize(reduced_output_path) / 1024
58
+ results.append(("JPEG (resolución reducida)", reduced_output_path, reduced_size, original_size))
59
 
60
+ # Optimización para WebP
61
+ if webp_quality != 50:
62
+ webp_lossy_output_path = os.path.join(output_dir, "lossy.webp")
63
+ img.save(webp_lossy_output_path, format="WEBP", quality=webp_quality, optimize=True)
64
+ webp_lossy_size = os.path.getsize(webp_lossy_output_path) / 1024
65
+ results.append(("WebP", webp_lossy_output_path, webp_lossy_size, original_size))
66
 
67
+ return results
 
 
 
 
 
 
68
 
69
  # Función para aplicar un modelo seleccionado desde Hugging Face
70
  def apply_model(image, model_name):
 
73
 
74
  with gr.Blocks() as demo:
75
  with gr.Tab("Optimización Tradicional"):
76
+ image_input = gr.File(label="Sube tu imagen", file_types=['image', 'heic'])
77
  optimize_button = gr.Button("Optimizar")
78
 
79
  with gr.Row():
 
114
  )
115
 
116
  with gr.Tab("Optimización con Modelos de Hugging Face"):
117
+ hf_image_input = gr.File(label="Sube tu imagen para optimización avanzada", file_types=['image', 'heic'])
118
  model_selector = gr.Dropdown(
119
  label="Selecciona un modelo",
120
  choices=["xinntao/Real-ESRGAN", "google/ddpm-cifar10-32", "facebook/ddpm"], # Añade los modelos disponibles