JairoCesar commited on
Commit
53a4ac5
·
verified ·
1 Parent(s): 81e4bc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -49
app.py CHANGED
@@ -7,30 +7,39 @@ import re
7
  import logging
8
  import datetime
9
 
10
- # Configurar logging
11
  logging.basicConfig(
12
  level=logging.INFO,
13
  format='%(asctime)s - %(levelname)s - %(message)s',
14
- handlers=[logging.StreamHandler()]
 
 
15
  )
16
  logger = logging.getLogger("rorschach_app")
17
 
18
- # Configuración de Streamlit
19
- st.set_page_config(page_title="Interpretación Rorschach", page_icon="🧠")
 
 
 
20
 
21
- # === Configurar el cliente de Hugging Face ===
22
- HF_TOKEN = os.getenv("HF_TOKEN") # <-- Asegúrate de poner tu token aquí o definirlo como variable de entorno
23
- MODEL_ID = "mistralai/Mixtral-8x7B-Instruct-v0.1"
24
 
 
 
25
  try:
26
- client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
27
- logger.info(f"✅ Conexión con el modelo {MODEL_ID} establecida correctamente")
 
 
 
28
  except Exception as e:
29
- logger.error(f"❌ Error al inicializar cliente de Hugging Face: {str(e)}")
30
- client = None
31
- st.error("Error al conectar con el modelo de Hugging Face")
32
 
33
- # Función para construir el prompt
34
  def format_prompt(message):
35
  system_prompt = """Eres un experto en interpretación del Test de Rorschach.
36
  Analiza las respuestas del paciente a las láminas y proporciona una interpretación
@@ -43,18 +52,20 @@ def format_prompt(message):
43
  - Originalidad/popularidad
44
  - Funcionamiento cognitivo, afectivo e interpersonal
45
  """
 
46
  prompt = f"<s>[INST] {system_prompt} [/INST] Entendido. [INST] Interpretación Rorschach: {message} [/INST]"
47
  logger.info(f"Prompt generado con {len(prompt)} caracteres")
48
  return prompt
49
 
50
- # Función para generar la interpretación
51
  def generate(prompt):
52
  if not client:
53
- logger.error("❌ Cliente no disponible")
54
- return "Error de conexión con el modelo."
55
 
56
  try:
57
- logger.info("🔄 Iniciando generación de texto")
 
58
  generate_kwargs = dict(
59
  temperature=0.7,
60
  max_new_tokens=800,
@@ -65,22 +76,23 @@ def generate(prompt):
65
  )
66
 
67
  formatted_prompt = format_prompt(prompt)
68
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, return_full_text=False)
69
- output = ""
70
- token_count = 0
 
71
 
72
- for response in stream:
73
- output += response.token.text
74
- token_count += 1
75
 
76
- logger.info(f"✅ Respuesta generada: {token_count} tokens")
77
  return output
78
 
79
  except Exception as e:
80
- logger.error(f"❌ Error en la generación: {str(e)}")
81
- return f"Ocurrió un error: {str(e)}"
 
82
 
83
- # Reemplazar variables en Word
84
  def replace_variables_word(doc, variables):
85
  for paragraph in doc.paragraphs:
86
  for key, value in variables.items():
@@ -94,29 +106,32 @@ def replace_variables_word(doc, variables):
94
  if f'<{key}>' in paragraph.text:
95
  paragraph.text = re.sub(f'<{key}>', value, paragraph.text)
96
 
97
- # Generar documento Word
98
  def generate_word_document(interpretation):
99
  try:
100
  template_path = os.path.join('PLANTILLAS', 'PLANTILLA_INTERPRETACION.docx')
 
101
  if not os.path.exists(template_path):
102
  logger.warning(f"⚠️ No se encontró la plantilla en {template_path}")
103
  st.warning(f"No se encontró la plantilla en {template_path}")
104
  return None
105
 
106
  doc = Document(template_path)
107
- replace_variables_word(doc, {'INTERPRETACION': interpretation})
 
108
 
109
  with tempfile.NamedTemporaryFile(delete=False, suffix='.docx') as tmp:
110
  doc.save(tmp.name)
111
- logger.info(f"✅ Documento Word generado: {tmp.name}")
112
  return tmp.name
113
 
114
  except Exception as e:
115
- logger.error(f"❌ Error generando documento: {str(e)}")
116
- st.error(f"Error generando documento: {str(e)}")
 
117
  return None
118
 
119
- # === Interfaz Streamlit ===
120
  st.title("Interpretación del Test de Rorschach")
121
  logger.info("🚀 Aplicación iniciada")
122
 
@@ -130,35 +145,39 @@ if st.button("Enviar", type="primary"):
130
  if not entrada_usuario:
131
  st.warning("Por favor ingrese texto para interpretar")
132
  else:
133
- logger.info(f"Procesando entrada de {len(entrada_usuario)} caracteres")
134
  with st.spinner("Generando interpretación..."):
135
  bot_response = generate(entrada_usuario)
136
-
137
  st.subheader("Interpretación")
138
  st.write(bot_response)
139
 
140
  document_path = generate_word_document(bot_response)
141
  if document_path:
142
  with open(document_path, "rb") as file:
143
- st.download_button(
144
- label="Descargar Interpretación",
145
- data=file.read(),
146
- file_name="Interpretacion_Rorschach.docx",
147
- mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
148
- )
149
- logger.info("📄 Botón de descarga mostrado")
 
150
  else:
151
- logger.error("❌ No se pudo generar el documento")
152
 
153
- # Mostrar logs
154
  if st.checkbox("Mostrar logs", value=False):
155
  class StreamlitLogHandler(logging.Handler):
156
  def emit(self, record):
157
- st.code(self.format(record))
 
158
 
159
  st.subheader("Logs del sistema")
160
- handler = StreamlitLogHandler()
161
- handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
162
- logger.addHandler(handler)
 
 
 
163
  logger.info("📊 Visualización de logs activada")
164
- logger.removeHandler(handler)
 
7
  import logging
8
  import datetime
9
 
10
+ # Configurar logging para monitorear las llamadas al API
11
  logging.basicConfig(
12
  level=logging.INFO,
13
  format='%(asctime)s - %(levelname)s - %(message)s',
14
+ handlers=[
15
+ logging.StreamHandler()
16
+ ]
17
  )
18
  logger = logging.getLogger("rorschach_app")
19
 
20
+ # Configuración mínima de Streamlit
21
+ st.set_page_config(
22
+ page_title="Interpretación Rorschach",
23
+ page_icon="🧠",
24
+ )
25
 
26
+ # Usar tu token de Hugging Face
27
+ hf_token = os.getenv("HF_TOKEN") # O reemplázalo directamente: hf_token = "tu_token_aquí"
 
28
 
29
+ # Inicializar cliente de Hugging Face
30
+ client = None
31
  try:
32
+ client = InferenceClient(
33
+ model="mistralai/Mixtral-8x7B-Instruct-v0.1",
34
+ token=hf_token
35
+ )
36
+ logger.info("✅ Conexión con modelo Mixtral-8x7B establecida correctamente")
37
  except Exception as e:
38
+ error_msg = f"❌ Error al inicializar cliente de Hugging Face: {str(e)}"
39
+ logger.error(error_msg)
40
+ st.error(error_msg)
41
 
42
+ # Formatear prompt para interpretación Rorschach
43
  def format_prompt(message):
44
  system_prompt = """Eres un experto en interpretación del Test de Rorschach.
45
  Analiza las respuestas del paciente a las láminas y proporciona una interpretación
 
52
  - Originalidad/popularidad
53
  - Funcionamiento cognitivo, afectivo e interpersonal
54
  """
55
+
56
  prompt = f"<s>[INST] {system_prompt} [/INST] Entendido. [INST] Interpretación Rorschach: {message} [/INST]"
57
  logger.info(f"Prompt generado con {len(prompt)} caracteres")
58
  return prompt
59
 
60
+ # Generar respuesta desde Hugging Face (modo no streaming)
61
  def generate(prompt):
62
  if not client:
63
+ logger.error("❌ No hay cliente disponible para generar respuesta")
64
+ return "Error de conexión con el modelo. Por favor, inténtelo de nuevo más tarde."
65
 
66
  try:
67
+ logger.info(f"🔄 Iniciando llamada al API de Hugging Face - {datetime.datetime.now()}")
68
+
69
  generate_kwargs = dict(
70
  temperature=0.7,
71
  max_new_tokens=800,
 
76
  )
77
 
78
  formatted_prompt = format_prompt(prompt)
79
+ start_time = datetime.datetime.now()
80
+
81
+ # Llamada sin streaming
82
+ output = client.text_generation(formatted_prompt, **generate_kwargs)
83
 
84
+ end_time = datetime.datetime.now()
85
+ duration = (end_time - start_time).total_seconds()
 
86
 
87
+ logger.info(f"✅ Respuesta generada en {duration:.2f} segundos")
88
  return output
89
 
90
  except Exception as e:
91
+ error_msg = f"❌ Error en la generación: {str(e)}"
92
+ logger.error(error_msg)
93
+ return f"Lo siento, ocurrió un error durante la interpretación. Detalles: {str(e)}"
94
 
95
+ # Reemplazo de variables en documento Word
96
  def replace_variables_word(doc, variables):
97
  for paragraph in doc.paragraphs:
98
  for key, value in variables.items():
 
106
  if f'<{key}>' in paragraph.text:
107
  paragraph.text = re.sub(f'<{key}>', value, paragraph.text)
108
 
109
+ # Generar documento Word con interpretación
110
  def generate_word_document(interpretation):
111
  try:
112
  template_path = os.path.join('PLANTILLAS', 'PLANTILLA_INTERPRETACION.docx')
113
+
114
  if not os.path.exists(template_path):
115
  logger.warning(f"⚠️ No se encontró la plantilla en {template_path}")
116
  st.warning(f"No se encontró la plantilla en {template_path}")
117
  return None
118
 
119
  doc = Document(template_path)
120
+ variables = {'INTERPRETACION': interpretation}
121
+ replace_variables_word(doc, variables)
122
 
123
  with tempfile.NamedTemporaryFile(delete=False, suffix='.docx') as tmp:
124
  doc.save(tmp.name)
125
+ logger.info(f"✅ Documento Word generado correctamente: {tmp.name}")
126
  return tmp.name
127
 
128
  except Exception as e:
129
+ error_msg = f"❌ Error al generar el documento: {str(e)}"
130
+ logger.error(error_msg)
131
+ st.error(error_msg)
132
  return None
133
 
134
+ # Interfaz Streamlit
135
  st.title("Interpretación del Test de Rorschach")
136
  logger.info("🚀 Aplicación iniciada")
137
 
 
145
  if not entrada_usuario:
146
  st.warning("Por favor ingrese texto para interpretar")
147
  else:
148
+ logger.info(f"🔄 Procesando entrada de {len(entrada_usuario)} caracteres")
149
  with st.spinner("Generando interpretación..."):
150
  bot_response = generate(entrada_usuario)
 
151
  st.subheader("Interpretación")
152
  st.write(bot_response)
153
 
154
  document_path = generate_word_document(bot_response)
155
  if document_path:
156
  with open(document_path, "rb") as file:
157
+ file_data = file.read()
158
+ st.download_button(
159
+ label="Descargar Interpretación",
160
+ data=file_data,
161
+ file_name="Interpretacion_Rorschach.docx",
162
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
163
+ )
164
+ logger.info("📄 Botón de descarga mostrado al usuario")
165
  else:
166
+ logger.error("❌ No se pudo generar el documento Word")
167
 
168
+ # Mostrar logs en la interfaz (opcional)
169
  if st.checkbox("Mostrar logs", value=False):
170
  class StreamlitLogHandler(logging.Handler):
171
  def emit(self, record):
172
+ log_entry = self.format(record)
173
+ st.code(log_entry)
174
 
175
  st.subheader("Logs del sistema")
176
+ log_output = st.empty()
177
+
178
+ stream_handler = StreamlitLogHandler()
179
+ stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
180
+ logger.addHandler(stream_handler)
181
+
182
  logger.info("📊 Visualización de logs activada")
183
+ logger.removeHandler(stream_handler)