gerardocabrera commited on
Commit
610cb41
·
1 Parent(s): 44bf44b

Modificación del proceso de creación de tickets y se agregan dependencias necesarias

Browse files
Files changed (2) hide show
  1. app.py +39 -25
  2. requirements.txt +3 -1
app.py CHANGED
@@ -5,7 +5,6 @@ import json
5
  import random
6
  import requests
7
  import gradio as gr
8
- import pandas as pd
9
  import torch
10
  from dotenv import load_dotenv
11
  from transformers import pipeline, AutoTokenizer
@@ -13,8 +12,8 @@ from transformers import pipeline, AutoTokenizer
13
  # Cargar variables de entorno
14
  load_dotenv()
15
 
16
- # 1. Configuración del modelo
17
- MODEL_NAME = "MoritzLaurer/mDeBERTa-v3-base-mnli-xnli"
18
  CATEGORIES = ["logística", "pagos", "producto defectuoso", "cuenta", "facturación", "otros"]
19
  URGENCY_PATTERNS = [
20
  r"\b(urgente|inmediato|cr[íi]tico|asap)\b",
@@ -109,33 +108,52 @@ class TicketSystem:
109
  with open(filename, 'w') as f:
110
  json.dump(self.tickets, f, indent=2)
111
 
112
- # 3. Cargar modelo de clasificación
 
 
 
113
  try:
 
114
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
115
  classifier = pipeline(
116
  "zero-shot-classification",
117
  model=MODEL_NAME,
118
- tokenizer=tokenizer,
119
- device=0 if torch.cuda.is_available() else -1,
120
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
121
  )
122
  MODEL_LOADED = True
 
123
  except Exception as e:
124
- print(f"Error cargando el modelo: {e}")
125
- MODEL_LOADED = False
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  # 4. Funciones de clasificación
128
  def is_urgent(text: str) -> bool:
129
  text = text.lower()
130
- if any(re.search(pattern, text, flags=re.IGNORECASE) for pattern in URGENCY_PATTERNS):
131
- return True
132
- return False
133
 
134
  def classify_text(text: str) -> str:
135
- if not MODEL_LOADED:
 
 
 
 
 
 
 
136
  return random.choice(CATEGORIES)
137
- result = classifier(text, CATEGORIES, multi_label=False)
138
- return result['labels'][0]
139
 
140
  # 5. Inicializar sistema de tickets
141
  ticket_system = TicketSystem()
@@ -151,18 +169,14 @@ def process_ticket(text):
151
  # Crear ticket en el sistema
152
  ticket = ticket_system.create_ticket(text, category, urgent)
153
 
154
- # Manejar errores
155
- if isinstance(ticket, dict) and "error" in ticket:
156
- status = f"🔴 ERROR: {ticket['error']}"
157
- else:
158
- status = "🔴 URGENTE - Asignado a Agente Humano" if urgent else "🟢 Enviado a Sistema Automático"
159
 
160
  return category, "SÍ" if urgent else "NO", status
161
 
162
  # 7. Interfaz de usuario con Gradio
163
  with gr.Blocks(title="Sistema de Soporte Inteligente", theme=gr.themes.Soft()) as demo:
164
  gr.Markdown("# 🚀 Sistema Clasificador de Tickets")
165
- gr.Markdown(f"**Modo actual:** `{ticket_system.mode.upper()}` | [Documentación API](https://developer.zendesk.com/)")
166
 
167
  with gr.Row():
168
  with gr.Column():
@@ -194,10 +208,10 @@ with gr.Blocks(title="Sistema de Soporte Inteligente", theme=gr.themes.Soft()) a
194
  ticket_db = gr.JSON(label="Tickets Registrados")
195
  update_btn = gr.Button("Actualizar Base de Datos")
196
 
197
- with gr.Accordion("Configuración API", open=False):
198
- mode_info = gr.Markdown(f"Modo actual: **{ticket_system.mode}**")
199
- api_status = gr.Markdown("Credenciales Zendesk: " +
200
- (" Configuradas" if os.getenv("ZENDESK_SUBDOMAIN") else "❌ No configuradas"))
201
 
202
  # Event handlers
203
  submit_btn.click(
 
5
  import random
6
  import requests
7
  import gradio as gr
 
8
  import torch
9
  from dotenv import load_dotenv
10
  from transformers import pipeline, AutoTokenizer
 
12
  # Cargar variables de entorno
13
  load_dotenv()
14
 
15
+ # 1. Configuración del modelo VERIFICADO
16
+ MODEL_NAME = "facebook/bart-large-mnli" # Modelo verificado y disponible
17
  CATEGORIES = ["logística", "pagos", "producto defectuoso", "cuenta", "facturación", "otros"]
18
  URGENCY_PATTERNS = [
19
  r"\b(urgente|inmediato|cr[íi]tico|asap)\b",
 
108
  with open(filename, 'w') as f:
109
  json.dump(self.tickets, f, indent=2)
110
 
111
+ # 3. Cargar modelo de clasificación con manejo de errores
112
+ MODEL_LOADED = False
113
+ classifier = None
114
+
115
  try:
116
+ # Intentar cargar el modelo principal
117
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
118
  classifier = pipeline(
119
  "zero-shot-classification",
120
  model=MODEL_NAME,
121
+ device=0 if torch.cuda.is_available() else -1
 
 
122
  )
123
  MODEL_LOADED = True
124
+ print("✅ Modelo cargado exitosamente")
125
  except Exception as e:
126
+ print(f"⚠️ Error cargando modelo principal: {e}")
127
+ try:
128
+ # Intentar modelo alternativo
129
+ MODEL_NAME = "valhalla/distilbart-mnli-12-1"
130
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
131
+ classifier = pipeline(
132
+ "zero-shot-classification",
133
+ model=MODEL_NAME,
134
+ device=0 if torch.cuda.is_available() else -1
135
+ )
136
+ MODEL_LOADED = True
137
+ print("✅ Modelo alternativo cargado exitosamente")
138
+ except Exception as alt_e:
139
+ print(f"⚠️ Error cargando modelo alternativo: {alt_e}")
140
+ print("🔶 Usando clasificador aleatorio como fallback")
141
 
142
  # 4. Funciones de clasificación
143
  def is_urgent(text: str) -> bool:
144
  text = text.lower()
145
+ return any(re.search(pattern, text, flags=re.IGNORECASE) for pattern in URGENCY_PATTERNS)
 
 
146
 
147
  def classify_text(text: str) -> str:
148
+ if not MODEL_LOADED or classifier is None:
149
+ return random.choice(CATEGORIES)
150
+
151
+ try:
152
+ result = classifier(text, CATEGORIES, multi_label=False)
153
+ return result['labels'][0]
154
+ except Exception as e:
155
+ print(f"⚠️ Error en clasificación: {e}")
156
  return random.choice(CATEGORIES)
 
 
157
 
158
  # 5. Inicializar sistema de tickets
159
  ticket_system = TicketSystem()
 
169
  # Crear ticket en el sistema
170
  ticket = ticket_system.create_ticket(text, category, urgent)
171
 
172
+ status = "🔴 URGENTE - Asignado a Agente Humano" if urgent else "🟢 Enviado a Sistema Automático"
 
 
 
 
173
 
174
  return category, "SÍ" if urgent else "NO", status
175
 
176
  # 7. Interfaz de usuario con Gradio
177
  with gr.Blocks(title="Sistema de Soporte Inteligente", theme=gr.themes.Soft()) as demo:
178
  gr.Markdown("# 🚀 Sistema Clasificador de Tickets")
179
+ gr.Markdown(f"**Modo actual:** `{ticket_system.mode.upper()}` | **Modelo:** `{MODEL_NAME if MODEL_LOADED else 'RANDOM'}`")
180
 
181
  with gr.Row():
182
  with gr.Column():
 
208
  ticket_db = gr.JSON(label="Tickets Registrados")
209
  update_btn = gr.Button("Actualizar Base de Datos")
210
 
211
+ with gr.Accordion("Información del Sistema", open=False):
212
+ gr.Markdown(f"**Modelo de clasificación:** `{MODEL_NAME if MODEL_LOADED else 'ALEATORIO (fallback)'}`")
213
+ gr.Markdown(f"**Tickets procesados:** `{len(ticket_system.tickets)}`")
214
+ gr.Markdown(f"**Última actualización:** `{time.strftime('%Y-%m-%d %H:%M:%S')}`")
215
 
216
  # Event handlers
217
  submit_btn.click(
requirements.txt CHANGED
@@ -1,4 +1,6 @@
1
  torch
2
  transformers
3
  pandas
4
- gradio
 
 
 
1
  torch
2
  transformers
3
  pandas
4
+ gradio
5
+ python-dotenv
6
+ requests