Spaces:
Sleeping
Sleeping
Commit ·
1a4e259
1
Parent(s): f9ac587
Add live URL, architecture doc and usage guide; remove render.yaml
Browse filesFiles changed (4)
- ARCHITECTURE.mdAdded+81
- README.md+14-7
- USAGE.mdAdded+138
- render.yamlDeleted-9
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# Architecture
## Deployment Overview
```GitHub (source code) │ └─► Hugging Face Spaces (Docker runtime) │ builds & runs the FastAPI container │ ├─► on startup: pulls model from HF Hub │ huggingface.co/cmeneses99/sms-classifier │ (model.safetensors, tokenizer, config — ~520MB) │ └─► serves API on port 7860 https://cmeneses99-sms-classifier-api.hf.space
cron-job.org ──GET /health every 10min──► HF Spaces (keep-alive)```
## Request Flow
```Client │ ▼FastAPI (routers/) │ ├── pages.py → HTML responses (/, /classify, /classify/batch, /categories) ├── inference.py → POST /classify, POST /classify/batch └── meta.py → GET /health, GET /api/categories │ ▼services/classifier.py │ ├── LRU Cache (cache.py) ──hit──► return cached response │ └── miss ──► model_loader.py (HuggingFace pipeline) └── distilbert-base-multilingual-cased (fine-tuned) └── top_k=3 predictions → PredictResponse```
## Model
| Detail | Value ||---|---|| Base model | `distilbert-base-multilingual-cased` || Task | Sequence classification || Categories | 9 || Training data | 3,150 synthetic examples (350/category, ES + EN) || Training | 5 epochs, fine-tuned with HuggingFace Trainer API || Runtime | CPU-only (PyTorch CPU build) || Cache | LRU, max 512 entries, thread-safe |
## Project Structure
```app/├── main.py # Lifespan + router registration├── model_loader.py # Downloads model from HF Hub on startup├── schemas.py # Pydantic v2 request/response models├── category_meta.py # Labels, colors, examples per category├── cache.py # Thread-safe LRU cache├── utils.py # normalize(), read_static()├── routers/│ ├── pages.py # HTML routes│ ├── inference.py # Classification endpoints│ └── meta.py # Health + categories endpoints├── services/│ └── classifier.py # Inference logic with cache integration└── static/ ├── home.html ├── index.html # Single classifier UI ├── batch.html # Batch classifier UI └── categories.htmltraining/├── config.py├── generate_dataset.py├── train.py└── eval_report.py```11 unmodified lines12131415161715 unmodified lines33343536373839110 unmodified lines15015115215315415515615715815916011 unmodified linesAPI REST para clasificar mensajes SMS en categorías usando **DistilBERT multilingual** con fine-tuning sobre un dataset sintético multilingüe (ES + EN).## Categorías| Categoría | Descripción |15 unmodified lines- **PyTorch** (CPU-only en producción)- **Pydantic v2** para validación- **Docker** para contenedorización- **Render.com** para deployment## Estructura del proyecto110 unmodified lines}```## Deploy en RenderEl proyecto incluye `render.yaml` configurado para deploy automático vía Docker.1. Crear repositorio en GitHub y pushear el código2. En [Render.com](https://render.com): New → Web Service → conectar el repo3. Render detecta `render.yaml` automáticamente4. El primer deploy tarda ~5 min (imagen Docker ~700MB)11 unmodified lines121314151617181915 unmodified lines3536373839404142110 unmodified lines15315415515615715815916016116216316416516616711 unmodified linesAPI REST para clasificar mensajes SMS en categorías usando **DistilBERT multilingual** con fine-tuning sobre un dataset sintético multilingüe (ES + EN).**Live demo:** https://cmeneses99-sms-classifier-api.hf.space## Categorías| Categoría | Descripción |15 unmodified lines- **PyTorch** (CPU-only en producción)- **Pydantic v2** para validación- **Docker** para contenedorización- **Hugging Face Spaces** para deployment- **Hugging Face Hub** para hosting del modelo## Estructura del proyecto110 unmodified lines}```## Deploy en Hugging Face Spaces1. Crear un Space en [huggingface.co/new-space](https://huggingface.co/new-space) con SDK: **Docker**2. Pushear el código al repo del Space:```bashgit remote add hfspace https://USER:TOKEN@huggingface.co/spaces/USER/SPACE-NAMEgit push hfspace main```3. HF Spaces detecta el `Dockerfile` automáticamente y hace el build4. Al arrancar, el modelo se descarga desde HF Hub (~520MB, solo la primera vez)El modelo está hosteado en [huggingface.co/cmeneses99/sms-classifier](https://huggingface.co/cmeneses99/sms-classifier).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138# Usage Guide
Base URL: `https://cmeneses99-sms-classifier-api.hf.space`
---
## Via Browser (UI)
### HomeAbrí `https://cmeneses99-sms-classifier-api.hf.space` — vas a ver una descripción de la API con todos los endpoints disponibles y ejemplos de respuesta. Desde ahí podés navegar al resto de las vistas con los botones.
---
### Clasificar un mensaje1. Click en **"Clasificador Simple"** desde el home (o navegá directo a `/classify`)2. Escribí el mensaje en el campo de texto3. Click en **"Clasificar"** o presioná **Enter**4. El resultado muestra la categoría detectada, el nivel de confianza y el top 3 de categorías más probables5. Si el mismo texto ya fue consultado antes, aparece el badge **"caché activo"**
---
### Clasificar múltiples mensajes1. Click en **"Clasificador por Lotes"** desde el home (o navegá directo a `/classify/batch`)2. Escribí un mensaje por línea en el área de texto3. El contador en tiempo real te muestra cuántos mensajes cargaste (máx. 50)4. Click en **"Clasificar todo"**5. Los resultados aparecen uno por uno con su categoría y confianza6. En la barra de resumen inferior podés ver cuántos vinieron desde caché
---
### Ver categorías disponibles1. Click en **"Categorías"** desde el home (o navegá directo a `/categories`)2. Cada categoría muestra su descripción y un ejemplo en español e inglés
---
## Via API (curl)
### Clasificar un mensaje
```bashcurl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify \ -H "Content-Type: application/json" \ -d '{"text": "Tu código OTP es 482910. No lo compartas."}'```
```json{ "text": "Tu código OTP es 482910. No lo compartas.", "prediction": { "category": "otp_verification", "confidence": 0.9821 }, "top_3": [ { "category": "otp_verification", "confidence": 0.9821 }, { "category": "security_alert", "confidence": 0.0091 }, { "category": "customer_service", "confidence": 0.0044 } ], "cached": false}```
**Límite:** máx. 512 caracteres por mensaje.
---
### Clasificar múltiples mensajes
```bashcurl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify/batch \ -H "Content-Type: application/json" \ -d '{ "texts": [ "Se debitó $45.000 en Falabella.", "Your package will arrive tomorrow between 2-4pm.", "Pay your bill today and avoid penalties." ] }'```
```json{ "results": [ { "text": "Se debitó $45.000 en Falabella.", "prediction": { "category": "transaction", "confidence": 0.97 }, "top_3": [...], "cached": false }, { "text": "Your package will arrive tomorrow...", "prediction": { "category": "delivery_logistics", "confidence": 0.95 }, "top_3": [...], "cached": false }, { "text": "Pay your bill today...", "prediction": { "category": "billing_reminder", "confidence": 0.91 }, "top_3": [...], "cached": false } ], "total": 3, "from_cache": 0}```
**Límite:** máx. 50 mensajes por request.
---
### Listar categorías
```bashcurl https://cmeneses99-sms-classifier-api.hf.space/api/categories```
```json["transaction", "otp_verification", "promotion_offer", "security_alert", "delivery_logistics", "appointment_reminder", "customer_service", "spam_advertising", "billing_reminder"]```
---
### Health check
```bashcurl https://cmeneses99-sms-classifier-api.hf.space/health```
```json{ "status": "ok", "model_loaded": true, "cache": { "hits": 12, "misses": 5, "hit_rate": 0.71, "size": 5 }}```
---
## Categorías
| Categoría | Ejemplos ||---|---|| `transaction` | "Se debitó $45.000 en Falabella" / "Payment of $120 confirmed" || `otp_verification` | "Tu código OTP es 482910" / "Your verification code is 774321" || `promotion_offer` | "30% de descuento este fin de semana" / "Exclusive offer just for you" || `security_alert` | "Acceso no reconocido desde Berlín" / "Failed login attempt detected" || `delivery_logistics` | "Tu pedido está en camino" / "Your package will arrive tomorrow" || `appointment_reminder` | "Recordatorio: cita médica mañana a las 10am" / "Dental appointment confirmed" || `customer_service` | "Tu ticket #4821 fue resuelto" / "Your case has been escalated" || `spam_advertising` | "Ganaste un premio, haz clic aquí" / "You have been selected for a reward" || `billing_reminder` | "Tu factura vence el 15 de mayo" / "Pay your bill today and avoid penalties" |123456789services: - type: web name: sms-classifier-api runtime: docker plan: starter healthCheckPath: /health envVars: - key: PORT value: 8000ARCHITECTURE.mdAdded+81
README.md+14-7
USAGE.mdAdded+138
render.yamlDeleted-9