CagliostroML commited on
Commit
1b5252f
verified
1 Parent(s): eaa7588

Upload train_email_classifier.py

Browse files
Files changed (1) hide show
  1. train_email_classifier.py +173 -0
train_email_classifier.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ \"\"\"
3
+ Entrenamiento de modelo clasificador de emails empresariales (espa帽ol)
4
+ Plan 3: Dataset Marketplace con Modelos Especializados
5
+ \"\"\"
6
+
7
+ import json
8
+ import logging
9
+ from datasets import Dataset
10
+ from transformers import (
11
+ AutoTokenizer,
12
+ AutoModelForSequenceClassification,
13
+ TrainingArguments,
14
+ Trainer,
15
+ EarlyStoppingCallback
16
+ )
17
+ import numpy as np
18
+
19
+ # ========================
20
+ # CONFIG
21
+ # ========================
22
+ MODEL_NAME = \"bert-base-multilingual-cased\"
23
+ OUTPUT_DIR = \"/tmp/email-classifier\"
24
+ HUB_MODEL_ID = \"CagliostroML/email-classifier-es\"
25
+
26
+ logging.basicConfig(level=logging.INFO)
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # ========================
30
+ # DATASET DE ENTRENAMIENTO
31
+ # ========================
32
+ TRAINING_DATA = [
33
+ {\"text\": \"Necesito el informe financiero del Q3 antes del viernes.\", \"label\": 0},
34
+ {\"text\": \"El servidor est谩 ca铆do, no podemos acceder a los datos.\", \"label\": 1},
35
+ {\"text\": \"Confirmo asistencia a la reuni贸n del lunes a las 10h.\", \"label\": 2},
36
+ {\"text\": \"El pedido #12345 ha sido enviado, tracking: TRK998877.\", \"label\": 3},
37
+ {\"text\": \"Por favor actualizar la direcci贸n de facturaci贸n.\", \"label\": 4},
38
+ {\"text\": \"El pago de la factura est谩 pendiente desde hace 15 d铆as.\", \"label\": 0},
39
+ {\"text\": \"No funciona el login en el portal, error 500.\", \"label\": 1},
40
+ {\"text\": \"Solicito vacaciones del 15 al 20 de diciembre.\", \"label\": 5},
41
+ {\"text\": \"El cliente XYZ ha rechazado la propuesta comercial.\", \"label\": 6},
42
+ {\"text\": \"Necesitamos m谩s stock del producto ABC.\", \"label\": 3},
43
+ {\"text\": \"El contrato con el proveedor est谩 listo para firma.\", \"label\": 7},
44
+ {\"text\": \"El proyecto muestra un retraso de 3 d铆as.\", \"label\": 8},
45
+ {\"text\": \"Solicito acceso al m贸dulo de reporting.\", \"label\": 1},
46
+ {\"text\": \"Los n煤meros de ventas del mes muestran incremento del 12%.\", \"label\": 6},
47
+ {\"text\": \"El evento de networking ser谩 el 22 de abril.\", \"label\": 9},
48
+ {\"text\": \"Necesito autorizaci贸n para la compra de software.\", \"label\": 4},
49
+ {\"text\": \"El cliente reported problemas with the shipment.\", \"label\": 3},
50
+ {\"text\": \"La auditor铆a interna est谩 programada para la pr贸xima semana.\", \"label\": 10},
51
+ {\"text\": \"El nuevo empleado necesita formaci贸n en el CRM.\", \"label\": 5},
52
+ {\"text\": \"La plataforma presenta lentitud significativa desde ayer.\", \"label\": 1},
53
+ {\"text\": \"Pueden ustedes confirmar el pago de la factura pendiente.\", \"label\": 0},
54
+ {\"text\": \"Error en el sistema de facturaci贸n, no genera PDF.\", \"label\": 1},
55
+ {\"text\": \"Reuni贸n de equipo a las 3pm en sala de conferencias.\", \"label\": 2},
56
+ {\"text\": \"El env铆o lleg贸 en mal estado, necesito reembolso.\", \"label\": 3},
57
+ {\"text\": \"Actualizar datos de contacto del proveedor.\", \"label\": 4},
58
+ {\"text\": \"Solicito aumento de presupuesto para marketing.\", \"label\": 0},
59
+ {\"text\": \"El website no carga correctamente en m贸vil.\", \"label\": 1},
60
+ {\"text\": \"Solicito permiso para trabajar desde casa ma帽ana.\", \"label\": 5},
61
+ {\"text\": \"Nuevo cliente potencial en el sector healthcare.\", \"label\": 6},
62
+ {\"text\": \"Reponer inventario del warehouse central.\", \"label\": 3},
63
+ {\"text\": \"El informe de gastos del mes est谩 listo para revisi贸n.\", \"label\": 0},
64
+ {\"text\": \"El software de CRM muestra errores constantemente.\", \"label\": 1},
65
+ {\"text\": \"La reuni贸n con proveedores fue muy productiva.\", \"label\": 2},
66
+ {\"text\": \"Paquete recibido en almac茅n, listo para distribuci贸n.\", \"label\": 3},
67
+ {\"text\": \"Actualizar la lista de precios del cat谩logo 2024.\", \"label\": 4},
68
+ {\"text\": \"La inversi贸n en publicidad digital rindi贸 muy bien.\", \"label\": 0},
69
+ {\"text\": \"El sistema de backups fall贸 esta noche.\", \"label\": 1},
70
+ {\"text\": \"Solicito formaci贸n en herramientas de data analytics.\", \"label\": 5},
71
+ {\"text\": \"El lead de Barcelona est谩 listo para cerrar negocio.\", \"label\": 6},
72
+ {\"text\": \"La mercanc铆a del contenedor #4421 lleg贸 da帽ada.\", \"label\": 3},
73
+ ]
74
+
75
+ LABEL_NAMES = [
76
+ \"finance\", \"it_support\", \"meeting\", \"logistics\", \"admin\",
77
+ \"hr\", \"sales\", \"legal\", \"project\", \"events\", \"compliance\"
78
+ ]
79
+
80
+ # ========================
81
+ # METRICAS
82
+ # ========================
83
+ def compute_metrics(eval_pred):
84
+ predictions, labels = eval_pred
85
+ predictions = np.argmax(predictions, axis=1)
86
+ accuracy = np.mean(labels == predictions)
87
+ return {\"accuracy\": float(accuracy)}
88
+
89
+ # ========================
90
+ # MAIN
91
+ # ========================
92
+ def main():
93
+ logger.info(\"=== Training Email Classifier (Spanish) ===\")
94
+
95
+ # Crear dataset
96
+ ds = Dataset.from_list(TRAINING_DATA)
97
+ ds = ds.train_test_split(test_size=0.2, seed=42)
98
+
99
+ logger.info(f\"Train samples: {len(ds['train'])}\")
100
+ logger.info(f\"Test samples: {len(ds['test'])}\")
101
+
102
+ # Tokenizer
103
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
104
+
105
+ def tokenize(batch):
106
+ return tokenizer(batch[\"text\"], padding=True, truncation=True, max_length=128)
107
+
108
+ ds = ds.map(tokenize, batched=True)
109
+
110
+ # Modelo
111
+ num_labels = len(LABEL_NAMES)
112
+ model = AutoModelForSequenceClassification.from_pretrained(
113
+ MODEL_NAME,
114
+ num_labels=num_labels
115
+ )
116
+
117
+ # Training args
118
+ training_args = TrainingArguments(
119
+ output_dir=OUTPUT_DIR,
120
+ num_train_epochs=10,
121
+ per_device_train_batch_size=8,
122
+ per_device_eval_batch_size=8,
123
+ warmup_steps=5,
124
+ logging_dir=\"/tmp/logs\",
125
+ logging_steps=5,
126
+ eval_strategy=\"epoch\",
127
+ save_strategy=\"epoch\",
128
+ load_best_model_at_end=True,
129
+ push_to_hub=True,
130
+ hub_model_id=HUB_MODEL_ID,
131
+ report_to=\"none\"
132
+ )
133
+
134
+ # Trainer
135
+ trainer = Trainer(
136
+ model=model,
137
+ args=training_args,
138
+ train_dataset=ds[\"train\"],
139
+ eval_dataset=ds[\"test\"],
140
+ compute_metrics=compute_metrics,
141
+ callbacks=[EarlyStoppingCallback(early_stopping_patience=3)]
142
+ )
143
+
144
+ logger.info(\"Starting training...\")
145
+ trainer.train()
146
+
147
+ logger.info(\"Evaluating...\")
148
+ results = trainer.evaluate()
149
+ logger.info(f\"Results: {results}\")
150
+
151
+ logger.info(\"Pushing to Hub...\")
152
+ trainer.push_to_hub()
153
+
154
+ # Guardar config
155
+ config = {
156
+ \"model_type\": \"text-classification\",
157
+ \"language\": \"es\",
158
+ \"labels\": LABEL_NAMES,
159
+ \"num_labels\": num_labels,
160
+ \"accuracy\": results.get(\"eval_accuracy\", 0),
161
+ \"f1\": results.get(\"eval_f1\", 0)
162
+ }
163
+
164
+ with open(\"/tmp/model_config.json\", \"w\") as f:
165
+ json.dump(config, f, indent=2)
166
+
167
+ logger.info(\"=== Training Complete ===\")
168
+ logger.info(f\"Model pushed to: https://huggingface.co/{HUB_MODEL_ID}\")
169
+
170
+ return results
171
+
172
+ if __name__ == \"__main__\":
173
+ main()