Spaces:
Running
Running
Update modules/chatbot/chat_process.py
Browse files- modules/chatbot/chat_process.py +77 -21
modules/chatbot/chat_process.py
CHANGED
@@ -14,41 +14,96 @@ class ChatProcessor:
|
|
14 |
)
|
15 |
self.conversation_history = []
|
16 |
self.semantic_context = None
|
|
|
17 |
|
18 |
-
def set_semantic_context(self, text, metrics, graph_data):
|
19 |
"""Configura el contexto semántico para el chat"""
|
20 |
self.semantic_context = {
|
21 |
-
'text_sample': text[:2000],
|
22 |
'key_concepts': metrics.get('key_concepts', []),
|
23 |
'graph_data': graph_data is not None
|
24 |
}
|
25 |
-
|
26 |
self.conversation_history = []
|
27 |
|
28 |
def clear_semantic_context(self):
|
29 |
"""Limpia el contexto semántico"""
|
30 |
self.semantic_context = None
|
31 |
self.conversation_history = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
|
34 |
"""Procesa el mensaje del usuario y genera la respuesta"""
|
35 |
try:
|
36 |
-
#
|
37 |
-
if self.
|
38 |
-
|
39 |
-
|
40 |
-
El usuario ha analizado un texto con los siguientes conceptos clave:
|
41 |
-
{', '.join([c[0] for c in self.semantic_context['key_concepts'][:5]])}
|
42 |
-
|
43 |
-
Responde preguntas específicas sobre este análisis, incluyendo:
|
44 |
-
- Interpretación de conceptos clave
|
45 |
-
- Relaciones entre conceptos
|
46 |
-
- Sugerencias para mejorar el texto
|
47 |
-
- Explicaciones sobre el gráfico semántico
|
48 |
-
"""
|
49 |
-
else:
|
50 |
-
system_prompt = "Eres un asistente útil. Responde preguntas generales."
|
51 |
|
|
|
|
|
|
|
52 |
# Agregar mensaje al historial
|
53 |
self.conversation_history.append({
|
54 |
"role": "user",
|
@@ -66,8 +121,9 @@ class ChatProcessor:
|
|
66 |
for text in stream.text_stream:
|
67 |
yield text
|
68 |
|
69 |
-
#
|
|
|
70 |
|
71 |
except Exception as e:
|
72 |
-
logger.error(f"Error
|
73 |
-
yield
|
|
|
14 |
)
|
15 |
self.conversation_history = []
|
16 |
self.semantic_context = None
|
17 |
+
self.current_lang = 'en' # Idioma por defecto
|
18 |
|
19 |
+
def set_semantic_context(self, text, metrics, graph_data, lang_code='en'):
|
20 |
"""Configura el contexto semántico para el chat"""
|
21 |
self.semantic_context = {
|
22 |
+
'text_sample': text[:2000],
|
23 |
'key_concepts': metrics.get('key_concepts', []),
|
24 |
'graph_data': graph_data is not None
|
25 |
}
|
26 |
+
self.current_lang = lang_code # Establece el idioma actual
|
27 |
self.conversation_history = []
|
28 |
|
29 |
def clear_semantic_context(self):
|
30 |
"""Limpia el contexto semántico"""
|
31 |
self.semantic_context = None
|
32 |
self.conversation_history = []
|
33 |
+
self.current_lang = 'en'
|
34 |
+
|
35 |
+
def _get_system_prompt(self):
|
36 |
+
"""Genera el prompt del sistema según el idioma y contexto"""
|
37 |
+
if not self.semantic_context:
|
38 |
+
return {
|
39 |
+
'en': "You are a helpful assistant. Answer general questions.",
|
40 |
+
'es': "Eres un asistente útil. Responde preguntas generales.",
|
41 |
+
'pt': "Você é um assistente útil. Responda a perguntas gerais.",
|
42 |
+
'fr': "Vous êtes un assistant utile. Répondez aux questions générales."
|
43 |
+
}.get(self.current_lang, "You are a helpful assistant.")
|
44 |
+
|
45 |
+
concepts = ', '.join([c[0] for c in self.semantic_context['key_concepts'][:5]])
|
46 |
+
|
47 |
+
prompts = {
|
48 |
+
'en': f"""You are an assistant specialized in semantic text analysis.
|
49 |
+
The user has analyzed a text with these key concepts: {concepts}
|
50 |
+
|
51 |
+
Answer specific questions about this analysis, including:
|
52 |
+
- Interpretation of key concepts
|
53 |
+
- Relationships between concepts
|
54 |
+
- Suggestions to improve the text
|
55 |
+
- Explanations about the semantic graph""",
|
56 |
+
|
57 |
+
'es': f"""Eres un asistente especializado en análisis semántico de textos.
|
58 |
+
El usuario ha analizado un texto con estos conceptos clave: {concepts}
|
59 |
+
|
60 |
+
Responde preguntas específicas sobre este análisis, incluyendo:
|
61 |
+
- Interpretación de conceptos clave
|
62 |
+
- Relaciones entre conceptos
|
63 |
+
- Sugerencias para mejorar el texto
|
64 |
+
- Explicaciones sobre el gráfico semántico""",
|
65 |
+
|
66 |
+
'pt': f"""Você é um assistente especializado em análise semântica de textos.
|
67 |
+
O usuário analisou um texto com estes conceitos-chave: {concepts}
|
68 |
+
|
69 |
+
Responda perguntas específicas sobre esta análise, incluindo:
|
70 |
+
- Interpretação de conceitos-chave
|
71 |
+
- Relações entre conceitos
|
72 |
+
- Sugestões para melhorar o texto
|
73 |
+
- Explicações sobre o gráfico semântico""",
|
74 |
+
|
75 |
+
'fr': f"""Vous êtes un assistant spécialisé dans l'analyse sémantique de textes.
|
76 |
+
L'utilisateur a analysé un texte avec ces concepts clés: {concepts}
|
77 |
+
|
78 |
+
Répondez aux questions spécifiques sur cette analyse, y compris:
|
79 |
+
- Interprétation des concepts clés
|
80 |
+
- Relations entre les concepts
|
81 |
+
- Suggestions pour améliorer le texte
|
82 |
+
- Explications sur le graphique sémantique"""
|
83 |
+
}
|
84 |
+
|
85 |
+
return prompts.get(self.current_lang, prompts['en'])
|
86 |
+
|
87 |
+
def _get_error_response(self):
|
88 |
+
"""Devuelve mensaje de error en el idioma correcto"""
|
89 |
+
return {
|
90 |
+
'en': "Sorry, an error occurred. Please try again.",
|
91 |
+
'es': "Lo siento, ocurrió un error. Por favor, inténtalo de nuevo.",
|
92 |
+
'pt': "Desculpe, ocorreu um erro. Por favor, tente novamente.",
|
93 |
+
'fr': "Désolé, une erreur s'est produite. Veuillez réessayer."
|
94 |
+
}.get(self.current_lang, "Sorry, an error occurred.")
|
95 |
|
96 |
def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
|
97 |
"""Procesa el mensaje del usuario y genera la respuesta"""
|
98 |
try:
|
99 |
+
# Actualizar idioma si es diferente
|
100 |
+
if lang_code != self.current_lang:
|
101 |
+
self.current_lang = lang_code
|
102 |
+
logger.info(f"Language changed to: {lang_code}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
+
# Construir prompt del sistema
|
105 |
+
system_prompt = self._get_system_prompt()
|
106 |
+
|
107 |
# Agregar mensaje al historial
|
108 |
self.conversation_history.append({
|
109 |
"role": "user",
|
|
|
121 |
for text in stream.text_stream:
|
122 |
yield text
|
123 |
|
124 |
+
# Registrar conversación exitosa
|
125 |
+
logger.info(f"Chat response generated for language: {self.current_lang}")
|
126 |
|
127 |
except Exception as e:
|
128 |
+
logger.error(f"Error in process_chat_input: {str(e)}", exc_info=True)
|
129 |
+
yield self._get_error_response()
|