cmeneses99 Claude Sonnet 4.6 commited on
Commit
aea087a
·
1 Parent(s): d6a2338

Rewrite all docs in English

Browse files

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (3) hide show
  1. ARCHITECTURE.md +41 -41
  2. README.md +78 -77
  3. USAGE.md +43 -43
ARCHITECTURE.md CHANGED
@@ -1,79 +1,79 @@
1
- # Arquitectura
2
 
3
- ## Despliegue
4
 
5
  ```
6
- GitHub (código fuente)
7
  │
8
- └─► Hugging Face Spaces (runtime Docker)
9
- │ construye y ejecuta el contenedor FastAPI
10
  │
11
- ├─► al iniciar: descarga el modelo desde HF Hub
12
  │ huggingface.co/cmeneses99/sms-classifier
13
  │ (model.safetensors, tokenizer, config — ~520MB)
14
  │
15
- └─► expone la API en el puerto 7860
16
  https://cmeneses99-sms-classifier-api.hf.space
17
 
18
- cron-job.org ──GET /health cada 10min──► HF Spaces (keep-alive)
19
  ```
20
 
21
- ## Flujo de una solicitud
22
 
23
  ```
24
- Cliente
25
  │
26
  ▼
27
- FastAPI (routers/)
28
  │
29
- ├── pages.py → respuestas HTML (/, /classify, /classify/batch, /categories)
30
- ├── inference.py → POST /classify, POST /classify/batch
31
- └── meta.py → GET /health, GET /api/categories
32
  │
33
  ▼
34
  services/classifier.py
35
  │
36
- ├── Cache LRU (cache.py) ──hit──► retorna respuesta en caché
37
  │
38
- └── miss ──► model_loader.py (pipeline de HuggingFace)
39
  └── distilbert-base-multilingual-cased (fine-tuned)
40
- └── top_k=3 predicciones → PredictResponse
41
  ```
42
 
43
- ## Modelo
44
 
45
- | Detalle | Valor |
46
- |---|---|
47
- | Modelo base | `distilbert-base-multilingual-cased` |
48
- | Tarea | Clasificación de secuencias |
49
- | Categorías | 9 |
50
- | Datos de entrenamiento | 3.150 ejemplos sintéticos (350/categoría, ES + EN) |
51
- | Entrenamiento | 5 épocas, fine-tuning con HuggingFace Trainer API |
52
- | Runtime | Solo CPU (build CPU de PyTorch) |
53
- | Cache | LRU, máx. 512 entradas, thread-safe |
54
 
55
- ## Estructura del proyecto
56
 
57
  ```
58
  app/
59
- ├── main.py # Lifespan + registro de routers
60
  ├── utils.py # normalize(), read_static()
61
- ├── core/ # Infraestructura compartida
62
- │ ├── cache.py # Cache LRU thread-safe
63
- │ ├── model_loader.py # Descarga el modelo desde HF Hub al iniciar
64
- │ ├── schemas.py # Modelos Pydantic v2 para request/response
65
- │ └── category_meta.py # Labels, colores y ejemplos por categoría
66
  ├── services/
67
- │ └── classifier.py # Lógica de inferencia con integración de caché
68
- ├── api/ # Endpoints JSON
69
  │ ├── inference.py # POST /classify, POST /classify/batch
70
  │ └── meta.py # GET /health, GET /api/categories
71
- ├── web/ # Endpoints HTML
72
- │ └── pages.py # Rutas de UI
73
- └── templates/ # Archivos HTML
74
  ├── home.html
75
- ├── index.html # UI clasificador simple
76
- ├── batch.html # UI clasificador por lotes
77
  └── categories.html
78
  training/
79
  ├── config.py
 
1
+ # Architecture
2
 
3
+ ## Deployment
4
 
5
  ```
6
+ GitHub (source code)
7
  │
8
+ └─► Hugging Face Spaces (Docker runtime)
9
+ │ builds and runs the FastAPI container
10
  │
11
+ ├─► on startup: downloads model from HF Hub
12
  │ huggingface.co/cmeneses99/sms-classifier
13
  │ (model.safetensors, tokenizer, config — ~520MB)
14
  │
15
+ └─► serves API on port 7860
16
  https://cmeneses99-sms-classifier-api.hf.space
17
 
18
+ cron-job.org ──GET /health every 10min──► HF Spaces (keep-alive)
19
  ```
20
 
21
+ ## Request flow
22
 
23
  ```
24
+ Client
25
  │
26
  ▼
27
+ FastAPI
28
  │
29
+ ├── web/pages.py → HTML responses (/, /classify, /classify/batch, /categories)
30
+ ├── api/inference.py → POST /classify, POST /classify/batch
31
+ └── api/meta.py → GET /health, GET /api/categories
32
  │
33
  ▼
34
  services/classifier.py
35
  │
36
+ ├── LRU Cache (core/cache.py) ──hit──► return cached response
37
  │
38
+ └── miss ──► core/model_loader.py (HuggingFace pipeline)
39
  └── distilbert-base-multilingual-cased (fine-tuned)
40
+ └── top_k=3 predictions → PredictResponse
41
  ```
42
 
43
+ ## Model
44
 
45
+ | Detail | Value |
46
+ |------------------|--------------------------------------------------------|
47
+ | Base model | `distilbert-base-multilingual-cased` |
48
+ | Task | Sequence classification |
49
+ | Categories | 9 |
50
+ | Training data | 3,150 synthetic examples (350/category, ES + EN) |
51
+ | Training | 5 epochs, fine-tuned with HuggingFace Trainer API |
52
+ | Runtime | CPU-only (PyTorch CPU build) |
53
+ | Cache | LRU, max 512 entries, thread-safe |
54
 
55
+ ## Project structure
56
 
57
  ```
58
  app/
59
+ ├── main.py # Lifespan + router registration
60
  ├── utils.py # normalize(), read_static()
61
+ ├── core/ # Shared infrastructure
62
+ │ ├── cache.py # Thread-safe LRU cache
63
+ │ ├── model_loader.py # Downloads model from HF Hub on startup
64
+ │ ├── schemas.py # Pydantic v2 request/response models
65
+ │ └── category_meta.py # Labels, colors and examples per category
66
  ├── services/
67
+ │ └── classifier.py # Inference logic with cache integration
68
+ ├── api/ # JSON endpoints
69
  │ ├── inference.py # POST /classify, POST /classify/batch
70
  │ └── meta.py # GET /health, GET /api/categories
71
+ ├── web/ # HTML endpoints
72
+ │ └── pages.py # UI routes
73
+ └── templates/ # HTML files
74
  ├── home.html
75
+ ├── index.html # Single classifier UI
76
+ ├── batch.html # Batch classifier UI
77
  └── categories.html
78
  training/
79
  ├── config.py
README.md CHANGED
@@ -1,4 +1,4 @@
1
- ---
2
  title: SMS Classifier API
3
  emoji: 📱
4
  colorFrom: blue
@@ -10,135 +10,135 @@ pinned: false
10
 
11
  # SMS Classifier API
12
 
13
- API REST para clasificar mensajes SMS en categorías usando **DistilBERT multilingual** con fine-tuning sobre un dataset sintético multilingüe (ES + EN).
14
 
15
  **Live demo:** https://cmeneses99-sms-classifier-api.hf.space
16
 
17
- ## Categorías
18
 
19
- | Categoría | Descripción |
20
- | ---------------------- | ------------------------------------------------- |
21
- | `transaction` | Confirmaciones de pagos, débitos y transferencias |
22
- | `otp_verification` | Códigos de un solo uso para verificar identidad |
23
- | `promotion_offer` | Descuentos, cupones y ofertas de comercios |
24
- | `security_alert` | Accesos no reconocidos y actividad sospechosa |
25
- | `delivery_logistics` | Estado de envíos y seguimiento de pedidos |
26
- | `appointment_reminder` | Recordatorios de citas médicas y dentales |
27
- | `customer_service` | Tickets, reclamos y soporte |
28
- | `spam_advertising` | Mensajes fraudulentos y publicidad engañosa |
29
- | `billing_reminder` | Facturas pendientes y fechas de vencimiento |
30
 
31
- ## Stack tecnológico
32
 
33
  - **Python 3.11** + **FastAPI** + **Uvicorn**
34
- - **DistilBERT** (`distilbert-base-multilingual-cased`) vía HuggingFace Transformers
35
- - **PyTorch** (CPU-only en producción)
36
- - **Pydantic v2** para validación
37
- - **Docker** para contenedorización
38
- - **Hugging Face Spaces** para deployment
39
- - **Hugging Face Hub** para hosting del modelo
40
 
41
- ## Estructura del proyecto
42
 
43
  ```
44
  app/
45
- ├── main.py # App entry point
46
- ├── utils.py # normalize(), read_static()
47
- ├── core/ # Infraestructura compartida
48
- │ ├── cache.py # LRU cache thread-safe
49
- │ ├── model_loader.py # Carga del modelo al startup
50
- │ ├── schemas.py # Modelos Pydantic
51
- │ └── category_meta.py # Metadata de categorías
52
- ├── services/
53
- │ └── classifier.py # Lógica de inferencia + caché LRU
54
- ├── api/ # Endpoints JSON
55
- │ ├── inference.py # POST /classify, POST /classify/batch
56
- │ └── meta.py # GET /health, GET /api/categories
57
- ├── web/ # Endpoints HTML
58
- │ └── pages.py # Rutas de UI
59
- └── templates/ # Archivos HTML
60
- ├── home.html
61
- ├── index.html
62
- ├── batch.html
63
- └── categories.html
64
  training/
65
- ├── config.py # Hiperparámetros
66
- ├── generate_dataset.py # Genera training/data/sms_dataset.csv
67
- ├── train.py # Fine-tuning script
68
- └── eval_report.py # Reporte de métricas por categoría
69
  ```
70
 
71
- ## Correr localmente
72
 
73
- ### Requisitos
74
 
75
  - Python 3.11+
76
- - Modelo entrenado en `./model/` (ver sección de entrenamiento)
77
 
78
  ```bash
79
- # Crear entorno virtual
80
  python -m venv .venv
81
  .venv\Scripts\activate # Windows
82
  source .venv/bin/activate # Linux/Mac
83
 
84
- # Instalar dependencias
85
  pip install -r requirements.txt
86
  pip install torch --index-url https://download.pytorch.org/whl/cpu
87
 
88
- # Levantar API
89
  uvicorn app.main:app --reload
90
  ```
91
 
92
- API disponible en `http://localhost:8000`
93
 
94
- ### Con Docker
95
 
96
  ```bash
97
  docker compose up --build
98
  ```
99
 
100
- ## Entrenar el modelo
101
 
102
  ```bash
103
  pip install -r requirements-training.txt
104
 
105
  cd training
106
- python generate_dataset.py # genera training/data/sms_dataset.csv
107
- python train.py # fine-tuning → guarda modelo en ./model/
108
- python eval_report.py # reporte de métricas por categoría
109
  ```
110
 
111
  ## Endpoints
112
 
113
- | Método | Ruta | Descripción |
114
- | ------ | ----------------- | ------------------------------------ |
115
- | `GET` | `/` | Home con descripción de la API |
116
- | `GET` | `/classify` | Clasificador interactivo (UI) |
117
- | `GET` | `/classify/batch` | Clasificador por lotes (UI) |
118
- | `GET` | `/categories` | Vista de categorías con ejemplos |
119
- | `POST` | `/classify` | Clasificar un texto (JSON) |
120
- | `POST` | `/classify/batch` | Clasificar múltiples textos (JSON) |
121
- | `GET` | `/api/categories` | Lista de categorías (JSON) |
122
- | `GET` | `/health` | Estado del servicio y stats de caché |
123
 
124
  ### POST /classify
125
 
126
  ```bash
127
  curl -X POST http://localhost:8000/classify \
128
  -H "Content-Type: application/json" \
129
- -d '{"text": "Tu código OTP es 482910. No lo compartas."}'
130
  ```
131
 
132
  ```json
133
  {
134
- "text": "Tu código OTP es 482910. No lo compartas.",
135
  "prediction": {
136
  "category": "otp_verification",
137
  "confidence": 0.9821
138
  },
139
  "top_3": [
140
  { "category": "otp_verification", "confidence": 0.9821 },
141
- { "category": "security_alert", "confidence": 0.0091 },
142
  { "category": "customer_service", "confidence": 0.0044 }
143
  ],
144
  "cached": false
@@ -150,7 +150,7 @@ curl -X POST http://localhost:8000/classify \
150
  ```bash
151
  curl -X POST http://localhost:8000/classify/batch \
152
  -H "Content-Type: application/json" \
153
- -d '{"texts": ["Tu código OTP es 482910.", "Se debitó $45.000 en Falabella."]}'
154
  ```
155
 
156
  ```json
@@ -161,15 +161,16 @@ curl -X POST http://localhost:8000/classify/batch \
161
  }
162
  ```
163
 
164
- ## Despliegue en Hugging Face Spaces
165
 
166
- 1. Crea un Space en [huggingface.co/new-space](https://huggingface.co/new-space) con SDK: **Docker**
167
- 2. Sube el código al repo del Space:
168
  ```bash
169
  git remote add hfspace https://USER:TOKEN@huggingface.co/spaces/USER/SPACE-NAME
170
  git push hfspace main
171
  ```
172
- 3. HF Spaces detecta el `Dockerfile` automáticamente y hace el build
173
- 4. Al iniciar, el modelo se descarga desde HF Hub (~520MB, solo la primera vez)
 
 
174
 
175
- El modelo está en [huggingface.co/cmeneses99/sms-classifier](https://huggingface.co/cmeneses99/sms-classifier).
 
1
+ ---
2
  title: SMS Classifier API
3
  emoji: 📱
4
  colorFrom: blue
 
10
 
11
  # SMS Classifier API
12
 
13
+ REST API that classifies SMS messages into operational categories using **multilingual DistilBERT** fine-tuned on a synthetic bilingual dataset (ES + EN).
14
 
15
  **Live demo:** https://cmeneses99-sms-classifier-api.hf.space
16
 
17
+ ## Categories
18
 
19
+ | Category | Description |
20
+ | ---------------------- | ---------------------------------------------------- |
21
+ | `transaction` | Payment confirmations, debits and transfers |
22
+ | `otp_verification` | One-time codes for identity verification |
23
+ | `promotion_offer` | Discounts, coupons and merchant offers |
24
+ | `security_alert` | Unrecognized access and suspicious activity |
25
+ | `delivery_logistics` | Shipment status and order tracking |
26
+ | `appointment_reminder` | Medical and dental appointment reminders |
27
+ | `customer_service` | Tickets, claims and support updates |
28
+ | `spam_advertising` | Fraudulent messages and misleading advertising |
29
+ | `billing_reminder` | Pending invoices and payment due dates |
30
 
31
+ ## Tech stack
32
 
33
  - **Python 3.11** + **FastAPI** + **Uvicorn**
34
+ - **DistilBERT** (`distilbert-base-multilingual-cased`) via HuggingFace Transformers
35
+ - **PyTorch** (CPU-only in production)
36
+ - **Pydantic v2** for validation
37
+ - **Docker** for containerization
38
+ - **Hugging Face Spaces** for deployment
39
+ - **Hugging Face Hub** for model hosting
40
 
41
+ ## Project structure
42
 
43
  ```
44
  app/
45
+ ├── main.py # App entry point
46
+ ├── utils.py # normalize(), read_static()
47
+ ├── core/ # Shared infrastructure
48
+ │ ├── cache.py # Thread-safe LRU cache
49
+ │ ├── model_loader.py # Downloads and loads the model at startup
50
+ │ ├── schemas.py # Pydantic models
51
+ │ └── category_meta.py # Category metadata
52
+ ├── services/
53
+ │ └── classifier.py # Inference logic + LRU cache integration
54
+ ├── api/ # JSON endpoints
55
+ │ ├── inference.py # POST /classify, POST /classify/batch
56
+ │ └── meta.py # GET /health, GET /api/categories
57
+ ├── web/ # HTML endpoints
58
+ │ └── pages.py # UI routes
59
+ └── templates/ # HTML files
60
+ ├── home.html
61
+ ├── index.html
62
+ ├── batch.html
63
+ └── categories.html
64
  training/
65
+ ├── config.py # Hyperparameters
66
+ ├── generate_dataset.py # Generates training/data/sms_dataset.csv
67
+ ├── train.py # Fine-tuning script
68
+ └── eval_report.py # Per-category metrics report
69
  ```
70
 
71
+ ## Run locally
72
 
73
+ ### Requirements
74
 
75
  - Python 3.11+
76
+ - Trained model in `./model/` (see training section)
77
 
78
  ```bash
79
+ # Create virtual environment
80
  python -m venv .venv
81
  .venv\Scripts\activate # Windows
82
  source .venv/bin/activate # Linux/Mac
83
 
84
+ # Install dependencies
85
  pip install -r requirements.txt
86
  pip install torch --index-url https://download.pytorch.org/whl/cpu
87
 
88
+ # Start API
89
  uvicorn app.main:app --reload
90
  ```
91
 
92
+ API available at `http://localhost:8000`
93
 
94
+ ### With Docker
95
 
96
  ```bash
97
  docker compose up --build
98
  ```
99
 
100
+ ## Train the model
101
 
102
  ```bash
103
  pip install -r requirements-training.txt
104
 
105
  cd training
106
+ python generate_dataset.py # generates training/data/sms_dataset.csv
107
+ python train.py # fine-tuning → saves model to ./model/
108
+ python eval_report.py # per-category metrics report
109
  ```
110
 
111
  ## Endpoints
112
 
113
+ | Method | Route | Description |
114
+ | ------ | ----------------- | ---------------------------------- |
115
+ | `GET` | `/` | Home with API description |
116
+ | `GET` | `/classify` | Interactive single classifier (UI) |
117
+ | `GET` | `/classify/batch` | Batch classifier (UI) |
118
+ | `GET` | `/categories` | Categories view with examples |
119
+ | `POST` | `/classify` | Classify one message (JSON) |
120
+ | `POST` | `/classify/batch` | Classify multiple messages (JSON) |
121
+ | `GET` | `/api/categories` | List categories (JSON) |
122
+ | `GET` | `/health` | Service status and cache stats |
123
 
124
  ### POST /classify
125
 
126
  ```bash
127
  curl -X POST http://localhost:8000/classify \
128
  -H "Content-Type: application/json" \
129
+ -d '{"text": "Your OTP code is 482910. Do not share it."}'
130
  ```
131
 
132
  ```json
133
  {
134
+ "text": "Your OTP code is 482910. Do not share it.",
135
  "prediction": {
136
  "category": "otp_verification",
137
  "confidence": 0.9821
138
  },
139
  "top_3": [
140
  { "category": "otp_verification", "confidence": 0.9821 },
141
+ { "category": "security_alert", "confidence": 0.0091 },
142
  { "category": "customer_service", "confidence": 0.0044 }
143
  ],
144
  "cached": false
 
150
  ```bash
151
  curl -X POST http://localhost:8000/classify/batch \
152
  -H "Content-Type: application/json" \
153
+ -d '{"texts": ["Your OTP code is 482910.", "Your card was charged $45 at Amazon."]}'
154
  ```
155
 
156
  ```json
 
161
  }
162
  ```
163
 
164
+ ## Deploy on Hugging Face Spaces
165
 
166
+ 1. Create a Space at [huggingface.co/new-space](https://huggingface.co/new-space) with SDK: **Docker**
167
+ 2. Push the code to the Space repo:
168
  ```bash
169
  git remote add hfspace https://USER:TOKEN@huggingface.co/spaces/USER/SPACE-NAME
170
  git push hfspace main
171
  ```
172
+ 3. HF Spaces detects the `Dockerfile` automatically and builds the image
173
+ 4. On startup, the model is downloaded from HF Hub (~520MB, first time only)
174
+
175
+ Model hosted at [huggingface.co/cmeneses99/sms-classifier](https://huggingface.co/cmeneses99/sms-classifier).
176
 
 
USAGE.md CHANGED
@@ -1,54 +1,54 @@
1
- # Guía de uso
2
 
3
- URL base: `https://cmeneses99-sms-classifier-api.hf.space`
4
 
5
  ---
6
 
7
- ## Desde el navegador (UI)
8
 
9
  ### Home
10
- Abre `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í puedes navegar al resto de las vistas con los botones.
11
 
12
  ---
13
 
14
- ### Clasificar un mensaje
15
- 1. Haz click en **"Clasificador Simple"** desde el home (o navega directo a `/classify`)
16
- 2. Escribe el mensaje en el campo de texto
17
- 3. Haz click en **"Clasificar"** o presiona **Enter**
18
- 4. El resultado muestra la categoría detectada, el nivel de confianza y el top 3 de categorías más probables
19
- 5. Si el mismo texto ya fue consultado antes, aparece el badge **"caché activo"**
20
 
21
  ---
22
 
23
- ### Clasificar múltiples mensajes
24
- 1. Haz click en **"Clasificador por Lotes"** desde el home (o navega directo a `/classify/batch`)
25
- 2. Escribe un mensaje por línea en el área de texto
26
- 3. El contador en tiempo real te muestra cuántos mensajes cargaste (máx. 50)
27
- 4. Haz click en **"Clasificar todo"**
28
- 5. Los resultados aparecen uno por uno con su categoría y confianza
29
- 6. En la barra de resumen inferior puedes ver cuántos vinieron desde caché
30
 
31
  ---
32
 
33
- ### Ver categorías disponibles
34
- 1. Haz click en **"Categorías"** desde el home (o navega directo a `/categories`)
35
- 2. Cada categoría muestra su descripción y un ejemplo en español e inglés
36
 
37
  ---
38
 
39
- ## Desde la API (curl)
40
 
41
- ### Clasificar un mensaje
42
 
43
  ```bash
44
  curl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify \
45
  -H "Content-Type: application/json" \
46
- -d '{"text": "Tu código OTP es 482910. No lo compartas."}'
47
  ```
48
 
49
  ```json
50
  {
51
- "text": "Tu código OTP es 482910. No lo compartas.",
52
  "prediction": { "category": "otp_verification", "confidence": 0.9821 },
53
  "top_3": [
54
  { "category": "otp_verification", "confidence": 0.9821 },
@@ -59,18 +59,18 @@ curl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify \
59
  }
60
  ```
61
 
62
- **Límite:** máx. 512 caracteres por mensaje.
63
 
64
  ---
65
 
66
- ### Clasificar múltiples mensajes
67
 
68
  ```bash
69
  curl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify/batch \
70
  -H "Content-Type: application/json" \
71
  -d '{
72
  "texts": [
73
- "Se debitó $45.000 en Falabella.",
74
  "Your package will arrive tomorrow between 2-4pm.",
75
  "Pay your bill today and avoid penalties."
76
  ]
@@ -80,7 +80,7 @@ curl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify/batch \
80
  ```json
81
  {
82
  "results": [
83
- { "text": "Se debitó $45.000 en Falabella.", "prediction": { "category": "transaction", "confidence": 0.97 }, "top_3": [...], "cached": false },
84
  { "text": "Your package will arrive tomorrow...", "prediction": { "category": "delivery_logistics", "confidence": 0.95 }, "top_3": [...], "cached": false },
85
  { "text": "Pay your bill today...", "prediction": { "category": "billing_reminder", "confidence": 0.91 }, "top_3": [...], "cached": false }
86
  ],
@@ -89,11 +89,11 @@ curl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify/batch \
89
  }
90
  ```
91
 
92
- **Límite:** máx. 50 mensajes por request.
93
 
94
  ---
95
 
96
- ### Listar categorías
97
 
98
  ```bash
99
  curl https://cmeneses99-sms-classifier-api.hf.space/api/categories
@@ -123,16 +123,16 @@ curl https://cmeneses99-sms-classifier-api.hf.space/health
123
 
124
  ---
125
 
126
- ## Categorías
127
-
128
- | Categoría | Ejemplos |
129
- |---|---|
130
- | `transaction` | "Se debitó $45.000 en Falabella" / "Payment of $120 confirmed" |
131
- | `otp_verification` | "Tu código OTP es 482910" / "Your verification code is 774321" |
132
- | `promotion_offer` | "30% de descuento este fin de semana" / "Exclusive offer just for you" |
133
- | `security_alert` | "Acceso no reconocido desde Berlín" / "Failed login attempt detected" |
134
- | `delivery_logistics` | "Tu pedido está en camino" / "Your package will arrive tomorrow" |
135
- | `appointment_reminder` | "Recordatorio: cita médica mañana a las 10am" / "Dental appointment confirmed" |
136
- | `customer_service` | "Tu ticket #4821 fue resuelto" / "Your case has been escalated" |
137
- | `spam_advertising` | "Ganaste un premio, haz clic aquí" / "You have been selected for a reward" |
138
- | `billing_reminder` | "Tu factura vence el 15 de mayo" / "Pay your bill today and avoid penalties" |
 
1
+ # Usage Guide
2
 
3
+ Base URL: `https://cmeneses99-sms-classifier-api.hf.space`
4
 
5
  ---
6
 
7
+ ## Via Browser (UI)
8
 
9
  ### Home
10
+ Open `https://cmeneses99-sms-classifier-api.hf.space` to see a description of the API with all available endpoints and response examples. From there you can navigate to any view using the buttons.
11
 
12
  ---
13
 
14
+ ### Classify a single message
15
+ 1. Click **"Clasificador Simple"** from the home (or navigate directly to `/classify`)
16
+ 2. Type the message in the text field
17
+ 3. Click **"Clasificar"** or press **Enter**
18
+ 4. The result shows the detected category, confidence score and the top 3 most likely categories
19
+ 5. If the same text was already classified before, a **"caché activo"** badge appears
20
 
21
  ---
22
 
23
+ ### Classify multiple messages
24
+ 1. Click **"Clasificador por Lotes"** from the home (or navigate directly to `/classify/batch`)
25
+ 2. Type one message per line in the text area
26
+ 3. A real-time counter shows how many messages you have loaded (max 50)
27
+ 4. Click **"Clasificar todo"**
28
+ 5. Results appear one by one with their category and confidence
29
+ 6. The summary bar at the bottom shows how many results came from cache
30
 
31
  ---
32
 
33
+ ### Browse available categories
34
+ 1. Click **"Categorías"** from the home (or navigate directly to `/categories`)
35
+ 2. Each category shows its description and an example in Spanish and English
36
 
37
  ---
38
 
39
+ ## Via API (curl)
40
 
41
+ ### Classify one message
42
 
43
  ```bash
44
  curl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify \
45
  -H "Content-Type: application/json" \
46
+ -d '{"text": "Your OTP code is 482910. Do not share it."}'
47
  ```
48
 
49
  ```json
50
  {
51
+ "text": "Your OTP code is 482910. Do not share it.",
52
  "prediction": { "category": "otp_verification", "confidence": 0.9821 },
53
  "top_3": [
54
  { "category": "otp_verification", "confidence": 0.9821 },
 
59
  }
60
  ```
61
 
62
+ **Limit:** max 512 characters per message.
63
 
64
  ---
65
 
66
+ ### Classify multiple messages
67
 
68
  ```bash
69
  curl -X POST https://cmeneses99-sms-classifier-api.hf.space/classify/batch \
70
  -H "Content-Type: application/json" \
71
  -d '{
72
  "texts": [
73
+ "Your card was charged $45 at Amazon.",
74
  "Your package will arrive tomorrow between 2-4pm.",
75
  "Pay your bill today and avoid penalties."
76
  ]
 
80
  ```json
81
  {
82
  "results": [
83
+ { "text": "Your card was charged $45 at Amazon.", "prediction": { "category": "transaction", "confidence": 0.97 }, "top_3": [...], "cached": false },
84
  { "text": "Your package will arrive tomorrow...", "prediction": { "category": "delivery_logistics", "confidence": 0.95 }, "top_3": [...], "cached": false },
85
  { "text": "Pay your bill today...", "prediction": { "category": "billing_reminder", "confidence": 0.91 }, "top_3": [...], "cached": false }
86
  ],
 
89
  }
90
  ```
91
 
92
+ **Limit:** max 50 messages per request.
93
 
94
  ---
95
 
96
+ ### List categories
97
 
98
  ```bash
99
  curl https://cmeneses99-sms-classifier-api.hf.space/api/categories
 
123
 
124
  ---
125
 
126
+ ## Categories
127
+
128
+ | Category | Examples |
129
+ |------------------------|-----------------------------------------------------------------------------------|
130
+ | `transaction` | "Your card was charged $45 at Amazon" / "Se debitó $45.000 en Falabella" |
131
+ | `otp_verification` | "Your OTP code is 482910" / "Tu código OTP es 482910" |
132
+ | `promotion_offer` | "Exclusive offer just for you" / "30% de descuento este fin de semana" |
133
+ | `security_alert` | "Failed login attempt detected" / "Acceso no reconocido desde Berlín" |
134
+ | `delivery_logistics` | "Your package will arrive tomorrow" / "Tu pedido está en camino" |
135
+ | `appointment_reminder` | "Dental appointment confirmed" / "Recordatorio: cita médica mañana a las 10am" |
136
+ | `customer_service` | "Your case has been escalated" / "Tu ticket #4821 fue resuelto" |
137
+ | `spam_advertising` | "You have been selected for a reward" / "Ganaste un premio, haz clic aquí" |
138
+ | `billing_reminder` | "Pay your bill today and avoid penalties" / "Tu factura vence el 15 de mayo" |