Merlintxu commited on
Commit
5c60085
1 Parent(s): 2e03b03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -43
app.py CHANGED
@@ -3,7 +3,7 @@ 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)
@@ -18,6 +18,10 @@ def open_heic_image(image_path):
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)
@@ -32,51 +36,50 @@ def optimize_image(image, png_optimize, jpeg_quality, jpeg_resolution, webp_qual
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
- lossy_output_path = os.path.join(output_dir, "lossy.jpg")
46
  img.save(lossy_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
47
  lossy_size = os.path.getsize(lossy_output_path) / 1024
48
- results.append(("JPEG", lossy_output_path, lossy_size, original_size))
 
49
 
50
  # Reducción de resolución (JPEG)
51
- reduced_output_path = os.path.join(output_dir, "reduced_resolution.jpg")
52
  new_resolution = (img.width * jpeg_resolution // 100, img.height * jpeg_resolution // 100)
53
  reduced_img = img.resize(new_resolution, Image.LANCZOS)
54
  reduced_img.save(reduced_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
55
  reduced_size = os.path.getsize(reduced_output_path) / 1024
56
- results.append(("JPEG (resolución reducida)", reduced_output_path, reduced_size, original_size))
 
57
 
58
  # Optimización para WebP
59
- webp_lossy_output_path = os.path.join(output_dir, "lossy.webp")
60
  img.save(webp_lossy_output_path, format="WEBP", quality=webp_quality, optimize=True)
61
  webp_lossy_size = os.path.getsize(webp_lossy_output_path) / 1024
62
- results.append(("WebP", webp_lossy_output_path, webp_lossy_size, original_size))
 
 
 
 
 
63
 
64
- # Preparar las salidas esperadas
65
  outputs = []
66
- for format_name, path, size, original_size in results:
67
- if format_name and path:
68
- img = Image.open(path)
69
- percent_reduction = 100 * (original_size - size) / original_size
70
- outputs.extend([img, f"{format_name}: {size:.2f} KB\n(diferencia: {-percent_reduction:.2f} KB)", path])
71
- else:
72
- outputs.extend([None, "", None])
73
-
74
- return outputs
75
 
76
- # Función para aplicar un modelo seleccionado desde Hugging Face
77
- def apply_model(image, model_name):
78
- model_pipeline = pipeline("image-super-resolution", model=model_name)
79
- return model_pipeline(image)
80
 
81
  with gr.Blocks() as demo:
82
  with gr.Tab("Optimización Tradicional"):
@@ -92,19 +95,19 @@ with gr.Blocks() as demo:
92
 
93
  with gr.Column():
94
  optimized_output2 = gr.Image(label="Optimización con pérdida (JPEG)")
95
- jpeg_quality = gr.Slider(label="Calidad JPEG", minimum=10, maximum=100, value=50, step=1)
96
  download_button2 = gr.File(label="Descargar", visible=True)
97
  optimized_size2 = gr.Text(value="", interactive=False, show_label=False)
98
 
99
  with gr.Column():
100
  optimized_output3 = gr.Image(label="Reducción de resolución (JPEG)")
101
- jpeg_resolution = gr.Slider(label="Resolución JPEG (%)", minimum=10, maximum=100, value=50, step=1)
102
  download_button3 = gr.File(label="Descargar", visible=True)
103
  optimized_size3 = gr.Text(value="", interactive=False, show_label=False)
104
 
105
  with gr.Column():
106
  optimized_output4 = gr.Image(label="Optimización WebP con pérdida")
107
- webp_quality = gr.Slider(label="Calidad WebP", minimum=10, maximum=100, value=50, step=1)
108
  download_button4 = gr.File(label="Descargar", visible=True)
109
  optimized_size4 = gr.Text(value="", interactive=False, show_label=False)
110
 
@@ -120,20 +123,4 @@ with gr.Blocks() as demo:
120
  ]
121
  )
122
 
123
- with gr.Tab("Optimización con Modelos de Hugging Face"):
124
- hf_image_input = gr.File(label="Sube tu imagen para optimización avanzada", file_types=['image', '.heic'])
125
- model_selector = gr.Dropdown(
126
- label="Selecciona un modelo",
127
- choices=["xinntao/Real-ESRGAN", "google/ddpm-cifar10-32", "facebook/ddpm"], # Añade los modelos disponibles
128
- value="xinntao/Real-ESRGAN"
129
- )
130
- hf_output = gr.Image(label="Resultado")
131
- hf_button = gr.Button("Aplicar Modelo")
132
-
133
- hf_button.click(
134
- fn=apply_model,
135
- inputs=[hf_image_input, model_selector],
136
- outputs=hf_output
137
- )
138
-
139
  demo.launch()
 
3
  import os
4
  import tempfile
5
  import pyheif
6
+ import ntpath
7
 
8
  def open_heic_image(image_path):
9
  heif_file = pyheif.read(image_path)
 
18
  return img
19
 
20
  def optimize_image(image, png_optimize, jpeg_quality, jpeg_resolution, webp_quality):
21
+ # Obtener el nombre del archivo original sin la extensión
22
+ original_filename = ntpath.basename(image.name)
23
+ base_name, ext = os.path.splitext(original_filename)
24
+
25
  # Manejar archivos HEIC
26
  if image.name.lower().endswith(".heic"):
27
  img = open_heic_image(image.name)
 
36
  output_dir = "/tmp/optimized_images"
37
  os.makedirs(output_dir, exist_ok=True)
38
 
39
+ # Lista para almacenar los resultados
40
  results = []
41
+
42
  # Optimización para PNG
43
  if png_optimize:
44
+ lossless_output_path = os.path.join(output_dir, f"{base_name}-lossless.png")
45
  img.save(lossless_output_path, format="PNG", optimize=True)
46
  lossless_size = os.path.getsize(lossless_output_path) / 1024
47
+ percent_reduction = 100 * (original_size - lossless_size) / original_size
48
+ results.append((Image.open(lossless_output_path), f"PNG: {lossless_size:.2f} KB (diferencia: {-percent_reduction:.2f} KB)", lossless_output_path))
49
 
50
  # Optimización para JPEG
51
+ lossy_output_path = os.path.join(output_dir, f"{base_name}-lossy.jpg")
52
  img.save(lossy_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
53
  lossy_size = os.path.getsize(lossy_output_path) / 1024
54
+ percent_reduction = 100 * (original_size - lossy_size) / original_size
55
+ results.append((Image.open(lossy_output_path), f"JPEG: {lossy_size:.2f} KB (diferencia: {-percent_reduction:.2f} KB)", lossy_output_path))
56
 
57
  # Reducción de resolución (JPEG)
58
+ reduced_output_path = os.path.join(output_dir, f"{base_name}-reduced_resolution.jpg")
59
  new_resolution = (img.width * jpeg_resolution // 100, img.height * jpeg_resolution // 100)
60
  reduced_img = img.resize(new_resolution, Image.LANCZOS)
61
  reduced_img.save(reduced_output_path, format="JPEG", quality=jpeg_quality, optimize=True)
62
  reduced_size = os.path.getsize(reduced_output_path) / 1024
63
+ percent_reduction = 100 * (original_size - reduced_size) / original_size
64
+ results.append((Image.open(reduced_output_path), f"JPEG (resolución reducida): {reduced_size:.2f} KB (diferencia: {-percent_reduction:.2f} KB)", reduced_output_path))
65
 
66
  # Optimización para WebP
67
+ webp_lossy_output_path = os.path.join(output_dir, f"{base_name}-lossy.webp")
68
  img.save(webp_lossy_output_path, format="WEBP", quality=webp_quality, optimize=True)
69
  webp_lossy_size = os.path.getsize(webp_lossy_output_path) / 1024
70
+ percent_reduction = 100 * (original_size - webp_lossy_size) / original_size
71
+ results.append((Image.open(webp_lossy_output_path), f"WebP: {webp_lossy_size:.2f} KB (diferencia: {-percent_reduction:.2f} KB)", webp_lossy_output_path))
72
+
73
+ # Asegurarse de que todos los resultados están presentes (4 entradas)
74
+ while len(results) < 4:
75
+ results.append((None, "", None))
76
 
77
+ # Dividir los resultados en imágenes, textos y rutas para descarga
78
  outputs = []
79
+ for result in results:
80
+ outputs.extend(result)
 
 
 
 
 
 
 
81
 
82
+ return outputs
 
 
 
83
 
84
  with gr.Blocks() as demo:
85
  with gr.Tab("Optimización Tradicional"):
 
95
 
96
  with gr.Column():
97
  optimized_output2 = gr.Image(label="Optimización con pérdida (JPEG)")
98
+ jpeg_quality = gr.Slider(label="Calidad JPEG", minimum=10, maximum=100, value=75, step=1)
99
  download_button2 = gr.File(label="Descargar", visible=True)
100
  optimized_size2 = gr.Text(value="", interactive=False, show_label=False)
101
 
102
  with gr.Column():
103
  optimized_output3 = gr.Image(label="Reducción de resolución (JPEG)")
104
+ jpeg_resolution = gr.Slider(label="Resolución JPEG (%)", minimum=10, maximum=100, value=75, step=1)
105
  download_button3 = gr.File(label="Descargar", visible=True)
106
  optimized_size3 = gr.Text(value="", interactive=False, show_label=False)
107
 
108
  with gr.Column():
109
  optimized_output4 = gr.Image(label="Optimización WebP con pérdida")
110
+ webp_quality = gr.Slider(label="Calidad WebP", minimum=10, maximum=100, value=75, step=1)
111
  download_button4 = gr.File(label="Descargar", visible=True)
112
  optimized_size4 = gr.Text(value="", interactive=False, show_label=False)
113
 
 
123
  ]
124
  )
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  demo.launch()