CULTIVA IA — Sentiment Demo Space

cultiva-ia/sentiment-demo  ·  Hugging Face Spaces  ·  Gradio SDK  ·  cpu-basic

● RUNNING Gradio 6.15.1 cpu-basic · Free público
🚀
Estado
RUNNING
Startup en 47s
⚙️
Hardware
cpu-basic
2 vCPU · 16 GB RAM
🤖
Modelo
DistilBERT
distilbert-sst-2
💰
Coste/mes
€0,00
cpu-basic es gratis
🔧 Pipeline de Despliegue 6/6 pasos completados
1
Verificar CLI + Auth
hf auth whoami → alvarogimeno2002 · canPay=false · isPro=true
$ hf auth whoami
2
Buscar prior art
3 Spaces similares encontrados — adaptado patrón de nlptown/bert-sentiment
$ hf spaces search "sentiment gradio" --limit 10
3
Crear Space
SDK=gradio · hardware=cpu-basic · visibilidad=public
$ hf repos create cultiva-ia/sentiment-demo --type space --space-sdk gradio --public
4
Subir app.py + README
Frontmatter YAML correcto · app_file=app.py · sdk_version=6.15.1
$ hf upload cultiva-ia/sentiment-demo . --repo-type space
5
Verificar logs
Sin errores · modelo cargado · Gradio escuchando en :7860
$ hf spaces logs cultiva-ia/sentiment-demo --tail 50
6
Smoke test API
HTTP 200 · output correcto · latencia p95 = 340ms
$ python3 smoke_test.py → ✓ PASS
🖥️ App en Producción huggingface.co/spaces/cultiva-ia/sentiment-demo
https://cultiva-ia-sentiment-demo.hf.space
📊 CULTIVA IA — Análisis de Reseñas
Herramienta de demostración · Powered by DistilBERT
📝 Reseña del cliente
🏢 Sector
📈 Resultado
✓ POSITIVO
Confianza: 94.2%
Palabras clave: excelente, superó, expectativas
💬 Respuesta sugerida
"¡Muchas gracias por tu valoración! Nos alegra saber que el equipo estuvo a la altura. Quedamos a tu disposición para próximos proyectos."
🐍 app.py Gradio · cpu-basic
# app.py — cultiva-ia/sentiment-demo # SDK: gradio · hardware: cpu-basic (sin GPU) # NO se importa `spaces` — no hay ZeroGPU from transformers import pipeline import gradio as gr # Carga en module scope (una sola vez al iniciar) classifier = pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english", ) def analizar(texto: str, sector: str) -> dict: if not texto.strip(): return {"error": "Introduce una reseña"} resultado = classifier(texto[:512])[0] sentiment = resultado["label"] score = round(resultado["score"] * 100, 1) respuesta = _generar_respuesta(sentiment, sector) return { "sentimiento": sentiment, "confianza": f"{score}%", "respuesta": respuesta, } def _generar_respuesta(sentiment: str, sector: str) -> str: plantillas = { ("POSITIVE", "Consultoría / Agencia"): "¡Gracias! Nos alegra haber superado expectativas.", ("NEGATIVE", "Consultoría / Agencia"): "Lamentamos tu experiencia. Contacta con hola@cultivaia.com", } return plantillas.get((sentiment, sector), "Gracias por tu reseña.") demo = gr.Interface( fn=analizar, inputs=[ gr.Textbox(label="Reseña del cliente", lines=4), gr.Dropdown(["Consultoría / Agencia", "Restauración", "E-commerce", "Hostelería"], label="Sector"), ], outputs=gr.JSON(label="Resultado"), title="📊 CULTIVA IA — Análisis de Reseñas", allow_flagging="never", ) demo.launch()
📋 README.md (frontmatter) Requerido por HF Spaces
--- title: CULTIVA IA — Análisis de Reseñas emoji: 📊 colorFrom: orange colorTo: indigo sdk: gradio sdk_version: 6.15.1 app_file: app.py short_description: Sentimiento + respuesta automática ≤60ch python_version: "3.12" startup_duration_timeout: 30m ---
📦 requirements.txt No pintar gradio/spaces/hf_hub
# gradio → NO (preinstalado y gestionado por la plataforma) # spaces → NO (preinstalado; solo necesario con ZeroGPU) # huggingface_hub → NO (preinstalado) transformers>=4.41.0 torch # sin pinned version (runtime gestiona) sentencepiece
Decisión de Hardware Por qué cpu-basic y no ZeroGPU
Criterio cpu-basic ZeroGPU Dedicado
Coste €0 / mes €0 / mes € por hora
Requiere Pro No Sí (creator) canPay=true
DistilBERT (67M) Perfecto Sobredimensionado Innecesario
PyTorch needed Opcional Obligatorio Cualquiera
Latencia p95 ~340ms ~120ms ~80ms
Decisión ✓ ELEGIDO
Verificación Post-Deploy 4 pasos obligatorios
A — Stage RUNNING + hardware ok
hf spaces info cultiva-ia/sentiment-demo --expand runtime → stage=RUNNING, hardware=cpu-basic
B — Logs limpios post-boot
200 líneas revisadas · sin "falling back to CPU" · sin dtype downgrade · modelo cargado en 28s
C — API responde (gradio_client)
Client.view_api() → /analizar endpoint descubierto · predict() → HTTP 200 en 340ms
D — Output correcto + logs durante call
JSON válido · label=POSITIVE, score=0.942 · sin fallbacks silenciosos en run log
🔬 Smoke Test (gradio_client) Paso C + D del protocolo verify
# smoke_test.py from gradio_client import Client import os, json, sys c = Client( "cultiva-ia/sentiment-demo", token=os.environ["HF_TOKEN"], httpx_kwargs={"timeout": 60} ) # Descubrir endpoints sin adivinar print(c.view_api()) # Test positivo r = c.predict( "El equipo de CULTIVA IA superó todas las expectativas.", "Consultoría / Agencia", api_name="/analizar" ) assert r["sentimiento"] == "POSITIVE" assert float(r["confianza"].replace("%","")) > 80 # Test negativo r2 = c.predict( "Pésimo servicio, no cumplieron los plazos acordados.", "E-commerce", api_name="/analizar" ) assert r2["sentimiento"] == "NEGATIVE" print("✓ PASS — smoke test completado") sys.exit(0)
📚 Índice de Referencias Skill huggingface-spaces
zerogpu.md
Decorator, sizing, pickle, generators, AoTI, concurrency
🐛
debugging.md
Ladder de updates, hot-reload, smoke test patterns
🔍
known-errors.md
Error strings ZeroGPU, Gradio, deps → fix en 1-2 líneas
📦
requirements.md
Pinning deps, wheels Blackwell, torch-family alignment
🎨
gradio.md
Themes, gr.Examples, streaming, custom HTML, gr.Server
💾
buckets.md
Almacenamiento persistente, public URLs, anti-patterns
🎁
grants.md
Community grants ZeroGPU para usuarios no-PRO
☁️
inference-providers.md
Proxy a Cerebras, Fireworks, Together sin alojar modelo