File size: 1,475 Bytes
23f321d
5774bbe
3736fe7
23f321d
 
3736fe7
23f321d
3736fe7
21b9e96
3736fe7
5774bbe
21b9e96
3736fe7
 
 
 
 
 
 
 
 
 
21b9e96
5774bbe
3736fe7
 
 
 
 
 
 
 
5774bbe
 
 
3736fe7
 
 
 
 
 
 
 
5774bbe
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import os
from huggingface_hub import InferenceClient
import gradio as gr
from dotenv import load_dotenv

# Cargar variables del .env
load_dotenv()
HF_TOKEN = os.getenv("HF_TOKEN")

if HF_TOKEN is None:
    raise ValueError("❌ No se encontró la variable HF_TOKEN en el .env")

# Inicializar cliente de inferencia HF
client = InferenceClient(provider="hf-inference", api_key=HF_TOKEN)

def clasificar_imagen(imagen):
    if imagen is None:
        return "Sube una imagen para clasificar."

    # Guardar temporalmente la imagen para enviarla al cliente
    temp_path = "temp_image.jpg"
    imagen.save(temp_path)

    # Llamada a la API
    output = client.image_classification(temp_path, model="google/vit-base-patch16-224")

    # Retornar la clasificación más probable
    if isinstance(output, list) and len(output) > 0:
        resultado = "\n".join([f"{item['label']}: {item['score']:.2f}" for item in output])
    else:
        resultado = "No se pudo clasificar la imagen."
    return resultado

# Interfaz Gradio
with gr.Blocks() as demo:
    gr.Markdown("# 🖼️ Clasificador de Imágenes con ViT")
    gr.Markdown("Sube una imagen y el modelo ViT-base de Google la clasificará usando HF Inference API gratuita.")

    img_input = gr.Image(type="pil", label="Sube tu imagen aquí")
    boton = gr.Button("Clasificar Imagen")
    salida = gr.Textbox(label="Resultados")

    boton.click(fn=clasificar_imagen, inputs=img_input, outputs=salida)

demo.launch()