ikerua commited on
Commit
160ba62
·
1 Parent(s): c9eb958

api created

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