Malaji71 commited on
Commit
e24ddbd
·
verified ·
1 Parent(s): 707bd20

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +21 -40
agent.py CHANGED
@@ -1,4 +1,4 @@
1
- # agent.py — AGENTE SEMÁNTICO CON FILTRADO DE FRASES COHERENTES
2
  import os
3
  import time
4
  import logging
@@ -99,61 +99,42 @@ class ImprovedSemanticAgent:
99
  logger.info(f"🔍 Analizando: '{user_prompt}'")
100
  query_embedding = self.embedding_model.encode([user_prompt], convert_to_numpy=True, normalize_embeddings=True)[0]
101
  query_embedding = query_embedding.astype('float32').reshape(1, -1)
102
- distances, indices = self.index.search(query_embedding, 8)
103
-
104
- # Extraer primer sustantivo del usuario (sujeto principal)
105
- user_doc = NLP(user_prompt.lower())
106
- user_first_noun = None
107
- for token in user_doc:
108
- if token.pos_ in ("NOUN", "PROPN"):
109
- user_first_noun = token.lemma_
110
- break
111
-
112
- user_words = set(user_prompt.lower().split())
113
- candidate_phrases = []
114
 
 
115
  for idx in indices[0]:
116
- if idx >= len(self.indexed_examples):
117
- continue
118
- caption = self.indexed_examples[idx]['caption']
119
- caption_lower = caption.lower()
120
-
121
- # Saltar si el caption comienza con el mismo sujeto
122
- if user_first_noun and caption_lower.startswith(user_first_noun):
123
- continue
124
 
125
- # Dividir por comas y procesar partes
126
- parts = [p.strip() for p in caption.split(',') if len(p.strip()) > 12 and len(p.strip()) < 120]
 
 
127
  for part in parts:
128
  part_lower = part.lower()
129
- part_words = set(part_lower.split())
130
- # Añadir solo si aporta al menos 3 palabras nuevas y no contiene el sujeto del usuario
131
- if (
132
- len(part_words - user_words) >= 3
133
- and (not user_first_noun or user_first_noun not in part_lower)
134
- ):
135
- candidate_phrases.append(part)
136
-
137
- # Eliminar duplicados
138
  seen = set()
139
- unique_phrases = []
140
- for p in candidate_phrases:
141
  if p not in seen:
142
- unique_phrases.append(p)
143
  seen.add(p)
144
 
145
- # Seleccionar hasta 3 frases
146
- selected = unique_phrases[:3]
147
  if selected:
148
  additions = ", ".join(selected)
149
  enhanced = f"{user_prompt}, {additions}"
150
- return enhanced, f"✨ Enriquecido con {len(selected)} frases coherentes"
151
  else:
152
- return self._structural_fallback(user_prompt, category), "🔧 Fallback estructural"
153
 
154
  except Exception as e:
155
  logger.error(f"❌ Error en _do_enhancement: {e}")
156
- return self._structural_fallback(user_prompt, category), f"❌ Error: {str(e)}"
157
 
158
  def _structural_fallback(self, prompt: str, category: str) -> str:
159
  enhancements = {
 
1
+ # agent.py — AGENTE SEMÁNTICO CON SÍNTESIS INTELIGENTE (versión estable)
2
  import os
3
  import time
4
  import logging
 
99
  logger.info(f"🔍 Analizando: '{user_prompt}'")
100
  query_embedding = self.embedding_model.encode([user_prompt], convert_to_numpy=True, normalize_embeddings=True)[0]
101
  query_embedding = query_embedding.astype('float32').reshape(1, -1)
102
+ distances, indices = self.index.search(query_embedding, 5)
 
 
 
 
 
 
 
 
 
 
 
103
 
104
+ candidates = []
105
  for idx in indices[0]:
106
+ if idx < len(self.indexed_examples):
107
+ candidates.append(self.indexed_examples[idx]['caption'])
108
+ if not candidates:
109
+ return self._structural_fallback(user_prompt, category), "🔧 Fallback estructural"
 
 
 
 
110
 
111
+ user_words = set(user_prompt.lower().split())
112
+ all_parts = []
113
+ for caption in candidates:
114
+ parts = [p.strip() for p in caption.split(',') if 8 <= len(p) <= 120]
115
  for part in parts:
116
  part_lower = part.lower()
117
+ if len(set(part_lower.split()) - user_words) >= 2:
118
+ all_parts.append(part)
119
+
 
 
 
 
 
 
120
  seen = set()
121
+ unique_parts = []
122
+ for p in all_parts:
123
  if p not in seen:
124
+ unique_parts.append(p)
125
  seen.add(p)
126
 
127
+ selected = unique_parts[:6]
 
128
  if selected:
129
  additions = ", ".join(selected)
130
  enhanced = f"{user_prompt}, {additions}"
131
+ return enhanced, f"✨ Prompt sintetizado con {len(candidates)} ejemplos"
132
  else:
133
+ return self._structural_fallback(user_prompt, category), "🔧 Fallback estructural (sin frases útiles)"
134
 
135
  except Exception as e:
136
  logger.error(f"❌ Error en _do_enhancement: {e}")
137
+ return user_prompt, f"❌ Error: {str(e)}"
138
 
139
  def _structural_fallback(self, prompt: str, category: str) -> str:
140
  enhancements = {