ikerua commited on
Commit
2cccbaa
·
1 Parent(s): 8e76241

huggingface interface

Browse files
Files changed (2) hide show
  1. app.py +117 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from PIL import Image
4
+ import io
5
+
6
+ # URL de tu API
7
+ # Si estás ejecutando esto en local, suele ser http://127.0.0.1:8000
8
+ # Si la API está en Render, usa la URL de Render (ej: https://tuproyecto.onrender.com)
9
+ API_URL = "needto_replace_with_your_api_url"
10
+
11
+ def solicitar_prediccion(image_path):
12
+ """
13
+ Envía la imagen al endpoint /predict
14
+ """
15
+ if image_path is None:
16
+ return "Por favor, sube una imagen primero."
17
+
18
+ try:
19
+ # Abrimos la imagen en modo binario para enviarla
20
+ with open(image_path, "rb") as f:
21
+ files = {"file": f}
22
+ response = requests.post(f"{API_URL}/predict", files=files, timeout=10)
23
+
24
+ response.raise_for_status()
25
+ data = response.json()
26
+
27
+ # Devolvemos la predicción
28
+ return f"Predicción: {data.get('prediction')}"
29
+
30
+ except requests.exceptions.RequestException as e:
31
+ return f"Error en la conexión con la API: {str(e)}"
32
+ except Exception as e:
33
+ return f"Error desconocido: {str(e)}"
34
+
35
+ def solicitar_resize(image_path, width, height):
36
+ """
37
+ Envía la imagen y dimensiones al endpoint /resize
38
+ """
39
+ if image_path is None:
40
+ return None
41
+
42
+ try:
43
+ # Validar inputs
44
+ if width <= 0 or height <= 0:
45
+ print("El ancho y alto deben ser positivos.")
46
+ return None
47
+
48
+ payload = {"width": int(width), "height": int(height)}
49
+
50
+ with open(image_path, "rb") as f:
51
+ files = {"file": f}
52
+ # Nota: 'data' se usa para los campos del Form (width, height)
53
+ # y 'files' para el archivo
54
+ response = requests.post(f"{API_URL}/resize", data=payload, files=files, timeout=10)
55
+
56
+ response.raise_for_status()
57
+
58
+ # La API devuelve una imagen en bytes (StreamingResponse)
59
+ # La convertimos a objeto PIL Image para que Gradio la pueda mostrar
60
+ image_stream = io.BytesIO(response.content)
61
+ return Image.open(image_stream)
62
+
63
+ except requests.exceptions.RequestException as e:
64
+ print(f"Error API: {e}")
65
+ return None
66
+
67
+ # --- Construcción de la Interfaz con Blocks ---
68
+ with gr.Blocks(title="Predictor & Resizer API Client") as demo:
69
+ gr.Markdown("# Cliente para API de Imágenes")
70
+ gr.Markdown("Sube una imagen y elige si quieres obtener una predicción o redimensionarla.")
71
+
72
+ with gr.Row():
73
+ # Columna Izquierda: Entrada
74
+ with gr.Column():
75
+ gr.Markdown("### 1. Entrada")
76
+ # Selector de imágenes. 'type="filepath"' guarda la imagen temporalmente y nos da la ruta
77
+ input_image = gr.Image(label="Sube tu imagen", type="filepath")
78
+
79
+ # Columna Derecha: Acciones
80
+ with gr.Column():
81
+
82
+ # --- Sección de Predicción ---
83
+ gr.Markdown("### 2. Predicción")
84
+ predict_btn = gr.Button("🔍 Obtener Predicción", variant="primary")
85
+ predict_output = gr.Textbox(label="Resultado de la API")
86
+
87
+ # CORRECCIÓN AQUÍ: gr.HTML en mayúsculas
88
+ gr.HTML("<hr>")
89
+
90
+ # --- Sección de Resize ---
91
+ gr.Markdown("### 3. Redimensionar (Resize)")
92
+ with gr.Row():
93
+ w_input = gr.Number(label="Ancho (Width)", value=200, precision=0)
94
+ h_input = gr.Number(label="Alto (Height)", value=200, precision=0)
95
+
96
+ resize_btn = gr.Button("🖼️ Redimensionar Imagen")
97
+ resize_output = gr.Image(label="Imagen Redimensionada")
98
+
99
+ # --- Conectar la lógica ---
100
+
101
+ # Botón Predicción
102
+ predict_btn.click(
103
+ fn=solicitar_prediccion,
104
+ inputs=[input_image],
105
+ outputs=predict_output
106
+ )
107
+
108
+ # Botón Resize
109
+ resize_btn.click(
110
+ fn=solicitar_resize,
111
+ inputs=[input_image, w_input, h_input],
112
+ outputs=resize_output
113
+ )
114
+
115
+ # Lanzar la aplicación
116
+ if __name__ == "__main__":
117
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio>=3.40
2
+ requests>=2.30