danielgx300 commited on
Commit
ca2062e
·
verified ·
1 Parent(s): 25bb177

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -25
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
  import json
3
  import glob
 
4
  import threading
5
  import telebot
6
  import gradio as gr
@@ -17,15 +18,23 @@ def apreton_de_manos_gpu():
17
 
18
  print(f"🤖 {apreton_de_manos_gpu()}")
19
 
20
- # 2. CARGA DE CREDENCIALES
21
  TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")
22
  CEREBRAS_API_KEY = os.environ.get("CEREBRAS_API_KEY")
23
 
24
  if not TELEGRAM_TOKEN or not CEREBRAS_API_KEY:
25
  print("❌ ERROR: Faltan las variables de entorno TELEGRAM_TOKEN o CEREBRAS_API_KEY.")
 
26
 
27
  bot = telebot.TeleBot(TELEGRAM_TOKEN)
28
 
 
 
 
 
 
 
 
29
  # 3. PROCESAMIENTO MULTI-ARCHIVO DE HISTORIALES DE TELEGRAM
30
  def parse_telegram_text(text_obj):
31
  if isinstance(text_obj, str):
@@ -40,13 +49,12 @@ def parse_telegram_text(text_obj):
40
  return out
41
  return ""
42
 
43
- # Buscar automáticamente todos los archivos que coincidan con 'result*.json'
44
  json_files = glob.glob("result*.json")
45
  print(f"📥 Archivos de historial encontrados en el servidor: {json_files}")
46
 
47
  valid_messages = []
 
48
 
49
- # Leer y consolidar todos los JSONs detectados
50
  for file_path in sorted(json_files):
51
  print(f"📖 Leyendo {file_path}...")
52
  try:
@@ -65,12 +73,11 @@ for file_path in sorted(json_files):
65
 
66
  user = msg.get('from', 'Desconocido')
67
  date = msg.get('date', '').replace('T', ' ')
68
-
69
- # Formatear el mensaje
70
  msg_str = f"[{date}] {user}: {text}"
71
 
72
- # Evitar duplicados exactos si los JSONs se solapan
73
- if msg_str not in valid_messages:
 
74
  valid_messages.append(msg_str)
75
  file_messages_count += 1
76
 
@@ -78,7 +85,10 @@ for file_path in sorted(json_files):
78
  except Exception as e:
79
  print(f"❌ Error al procesar el archivo {file_path}: {e}")
80
 
81
- # Agrupación en Chunks de contexto (ventana de 15 mensajes con solape de 5)
 
 
 
82
  CHUNK_SIZE = 15
83
  OVERLAP = 5
84
  documents = []
@@ -89,7 +99,7 @@ for i in range(0, len(valid_messages), CHUNK_SIZE - OVERLAP):
89
 
90
  print(f"📊 Total consolidado: {len(documents)} bloques de conversación únicos listos para indexar.")
91
 
92
- # 4. CONFIGURACIÓN DE EMBEDDINGS (Procesado en CPU para evitar fallos de PyTorch)
93
  print("🚀 Cargando embeddings en dispositivo: CPU")
94
  embeddings = HuggingFaceEmbeddings(
95
  model_name="Qwen/Qwen3-Embedding-0.6B",
@@ -114,12 +124,6 @@ def obtener_respuesta_rag(user_query):
114
  docs = retriever.invoke(user_query)
115
  context_text = "\n\n---\n\n".join([doc.page_content for doc in docs])
116
 
117
- client = OpenAI(
118
- base_url = "https://api.cerebras.ai/v1",
119
- api_key = CEREBRAS_API_KEY,
120
- timeout = 30.0
121
- )
122
-
123
  MODELO_ELEGIDO = "gemma-4-31b"
124
 
125
  prompt = f"""Eres un asistente útil, respetuoso y analítico basado ÚNICAMENTE en el historial de chat provisto.
@@ -136,12 +140,12 @@ PREGUNTA DEL USUARIO:
136
  Responde de forma estructurada. Si no sabes la respuesta porque no está en el contexto, di que no hay información sobre eso en el grupo.
137
  """
138
 
139
- completion = client.chat.completions.create(
140
- model=MODELO_ELEGIDO,
141
- messages=[{"role":"user","content": prompt}],
142
- temperature=0.3,
143
- max_tokens=4096,
144
- stream=False
145
  )
146
  return completion.choices[0].message.content
147
 
@@ -161,10 +165,19 @@ def send_welcome(message):
161
 
162
  @bot.message_handler(func=lambda message: True)
163
  def handle_query(message):
164
- bot.send_chat_action(message.chat.id, 'typing')
165
- msg_espera = bot.reply_to(message, "🔍 Buscando en el historial unificado y procesando con Cerebras...")
166
- respuesta_ia = obtener_respuesta_rag(message.text)
167
- bot.edit_message_text(chat_id=message.chat.id, message_id=msg_espera.message_id, text=respuesta_ia)
 
 
 
 
 
 
 
 
 
168
 
169
  # 7. FUNCIÓN PARA CORRER EL BOT EN HILO SECUNDARIO
170
  def run_telegram_bot():
 
1
  import os
2
  import json
3
  import glob
4
+ import sys
5
  import threading
6
  import telebot
7
  import gradio as gr
 
18
 
19
  print(f"🤖 {apreton_de_manos_gpu()}")
20
 
21
+ # 2. CARGA DE CREDENCIALES Y VALIDACIÓN ESTRICTA
22
  TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")
23
  CEREBRAS_API_KEY = os.environ.get("CEREBRAS_API_KEY")
24
 
25
  if not TELEGRAM_TOKEN or not CEREBRAS_API_KEY:
26
  print("❌ ERROR: Faltan las variables de entorno TELEGRAM_TOKEN o CEREBRAS_API_KEY.")
27
+ sys.exit(1) # Detiene la ejecución antes de que rompa el bot
28
 
29
  bot = telebot.TeleBot(TELEGRAM_TOKEN)
30
 
31
+ # Reutilizamos el cliente de forma global
32
+ cerebras_client = OpenAI(
33
+ base_url="https://api.cerebras.ai/v1",
34
+ api_key=CEREBRAS_API_KEY,
35
+ timeout=30.0
36
+ )
37
+
38
  # 3. PROCESAMIENTO MULTI-ARCHIVO DE HISTORIALES DE TELEGRAM
39
  def parse_telegram_text(text_obj):
40
  if isinstance(text_obj, str):
 
49
  return out
50
  return ""
51
 
 
52
  json_files = glob.glob("result*.json")
53
  print(f"📥 Archivos de historial encontrados en el servidor: {json_files}")
54
 
55
  valid_messages = []
56
+ seen_messages = set() # Conjunto para búsquedas O(1) ultra rápidas
57
 
 
58
  for file_path in sorted(json_files):
59
  print(f"📖 Leyendo {file_path}...")
60
  try:
 
73
 
74
  user = msg.get('from', 'Desconocido')
75
  date = msg.get('date', '').replace('T', ' ')
 
 
76
  msg_str = f"[{date}] {user}: {text}"
77
 
78
+ # Optimización clave: la búsqueda en conjuntos es instantánea
79
+ if msg_str not in seen_messages:
80
+ seen_messages.add(msg_str)
81
  valid_messages.append(msg_str)
82
  file_messages_count += 1
83
 
 
85
  except Exception as e:
86
  print(f"❌ Error al procesar el archivo {file_path}: {e}")
87
 
88
+ # Liberamos memoria del set de control ya que no se usará más
89
+ del seen_messages
90
+
91
+ # Agrupación en Chunks de contexto
92
  CHUNK_SIZE = 15
93
  OVERLAP = 5
94
  documents = []
 
99
 
100
  print(f"📊 Total consolidado: {len(documents)} bloques de conversación únicos listos para indexar.")
101
 
102
+ # 4. CONFIGURACIÓN DE EMBEDDINGS (CPU)
103
  print("🚀 Cargando embeddings en dispositivo: CPU")
104
  embeddings = HuggingFaceEmbeddings(
105
  model_name="Qwen/Qwen3-Embedding-0.6B",
 
124
  docs = retriever.invoke(user_query)
125
  context_text = "\n\n---\n\n".join([doc.page_content for doc in docs])
126
 
 
 
 
 
 
 
127
  MODELO_ELEGIDO = "gemma-4-31b"
128
 
129
  prompt = f"""Eres un asistente útil, respetuoso y analítico basado ÚNICAMENTE en el historial de chat provisto.
 
140
  Responde de forma estructurada. Si no sabes la respuesta porque no está en el contexto, di que no hay información sobre eso en el grupo.
141
  """
142
 
143
+ completion = cerebras_client.chat.completions.create(
144
+ model=MODELO_ELEGIDO,
145
+ messages=[{"role": "user", "content": prompt}],
146
+ temperature=0.3,
147
+ max_tokens=4096,
148
+ stream=False
149
  )
150
  return completion.choices[0].message.content
151
 
 
165
 
166
  @bot.message_handler(func=lambda message: True)
167
  def handle_query(message):
168
+ try:
169
+ bot.send_chat_action(message.chat.id, 'typing')
170
+ msg_espera = bot.reply_to(message, "🔍 Buscando en el historial unificado y procesando con Cerebras...")
171
+
172
+ respuesta_ia = obtener_respuesta_rag(message.text)
173
+
174
+ # Control de longitud máxima de Telegram (4096 caracteres)
175
+ if len(respuesta_ia) > 4000:
176
+ respuesta_ia = respuesta_ia[:4000] + "\n\n⚠️ *Respuesta truncada por longitud máxima...*"
177
+
178
+ bot.edit_message_text(chat_id=message.chat.id, message_id=msg_espera.message_id, text=respuesta_ia)
179
+ except Exception as e:
180
+ print(f"❌ Error al gestionar mensaje de Telegram: {e}")
181
 
182
  # 7. FUNCIÓN PARA CORRER EL BOT EN HILO SECUNDARIO
183
  def run_telegram_bot():