lozanopastor commited on
Commit
81b3fa7
·
verified ·
1 Parent(s): 078f1f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -4
app.py CHANGED
@@ -39,6 +39,28 @@ css_style = """
39
  border-radius: 5px;
40
  border: 1px solid #ccc;
41
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  </style>
43
  """
44
 
@@ -89,7 +111,7 @@ def extract_metadata(vector_store):
89
  metadata_questions = {
90
  "title": "¿Cual es o podría ser el título del documento? Redacta una sola frase",
91
  "entity": "¿A qué entidad u organización pertenece este documento?",
92
- "date": "¿A qué fecha pertenece el documento?"
93
  }
94
 
95
  metadata = {}
@@ -127,14 +149,63 @@ def procesar_consulta(user_question):
127
  respuesta_final = eliminar_proceso_pensamiento(response['output_text'])
128
  mostrar_respuesta(respuesta_final)
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  def main():
131
  st.set_page_config(page_title="PDF Consultor 🔍", page_icon="🔍", layout="wide")
132
  st.title("PDF Consultor 🔍")
133
  st.markdown(css_style, unsafe_allow_html=True)
134
 
135
- # Inicializa estado de sesión
136
  if 'documento_cargado' not in st.session_state:
137
  st.session_state.documento_cargado = False
 
 
 
 
138
 
139
  # Sidebar - Carga de documentos
140
  with st.sidebar:
@@ -157,6 +228,7 @@ def main():
157
  st.session_state.metadata = extract_metadata(vector_store)
158
  st.session_state.vector_store = vector_store
159
  st.session_state.documento_cargado = True
 
160
 
161
  st.rerun()
162
 
@@ -170,7 +242,7 @@ def main():
170
  campos = [
171
  ("📄 Título", "title"),
172
  ("🏛️ Entidad", "entity"),
173
- ("📅 Fecha", "date")
174
  ]
175
 
176
  for col, (icono, key) in zip(cols, campos):
@@ -181,7 +253,23 @@ def main():
181
  {st.session_state.metadata[key]}
182
  </div>
183
  """, unsafe_allow_html=True)
184
- st.markdown("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
  # Interfaz de consultas
187
  if st.session_state.documento_cargado:
@@ -190,12 +278,17 @@ def main():
190
  with col1:
191
  user_question = st.text_input(
192
  "Escribe tu pregunta:",
 
193
  placeholder="Ej: ¿Qué normativa regula este proceso?",
194
  label_visibility="collapsed"
195
  )
196
  with col2:
197
  st.markdown("<br>", unsafe_allow_html=True)
198
  enviar = st.form_submit_button("Enviar ▶")
 
 
 
 
199
 
200
  if user_question and enviar:
201
  procesar_consulta(user_question)
 
39
  border-radius: 5px;
40
  border: 1px solid #ccc;
41
  }
42
+ .sugerencias-box {
43
+ padding: 15px;
44
+ background-color: #fff;
45
+ border-radius: 10px;
46
+ border: 1px solid #e0e0e0;
47
+ margin: 10px 0;
48
+ }
49
+ .suggestion-button {
50
+ width: 100%;
51
+ text-align: left;
52
+ margin: 5px 0;
53
+ padding: 10px;
54
+ border-radius: 5px;
55
+ border: 1px solid #e0e0e0;
56
+ background-color: #f8f9fa;
57
+ cursor: pointer;
58
+ transition: all 0.3s;
59
+ }
60
+ .suggestion-button:hover {
61
+ background-color: #e9ecef;
62
+ border-color: #ced4da;
63
+ }
64
  </style>
65
  """
66
 
 
111
  metadata_questions = {
112
  "title": "¿Cual es o podría ser el título del documento? Redacta una sola frase",
113
  "entity": "¿A qué entidad u organización pertenece este documento?",
114
+ "date": "¿En qué fecha se implantará el contenido? Si no se detalla responde \"No se especifica\""
115
  }
116
 
117
  metadata = {}
 
149
  respuesta_final = eliminar_proceso_pensamiento(response['output_text'])
150
  mostrar_respuesta(respuesta_final)
151
 
152
+ def generar_sugerencias():
153
+ """Genera preguntas sugeridas usando los chunks más relevantes del documento"""
154
+ if 'vector_store' not in st.session_state:
155
+ return []
156
+
157
+ try:
158
+ # Obtener los fragmentos más relevantes
159
+ docs = st.session_state.vector_store.similarity_search("", k=3)
160
+ context = "\n".join([doc.page_content for doc in docs])
161
+
162
+ # Prompt para generación de sugerencias
163
+ prompt_template = """
164
+ Basado en el siguiente contexto, genera exactamente 3 preguntas relevantes en español.
165
+ Formato: Cada pregunta debe ser concisa y específica.
166
+ Las preguntas deben ser útiles para entender el contenido del documento.
167
+
168
+ Contexto:
169
+ {context}
170
+
171
+ Preguntas sugeridas:
172
+ 1.
173
+ """
174
+
175
+ model = ChatGroq(
176
+ temperature=0.7,
177
+ model_name="deepseek-r1-distill-llama-70b",
178
+ groq_api_key=os.getenv("GROQ_API_KEY")
179
+ )
180
+
181
+ response = model.invoke(prompt_template.format(context=context))
182
+
183
+ # Procesar la respuesta para extraer las preguntas
184
+ preguntas = []
185
+ for line in response.content.split("\n"):
186
+ if line.strip() and any(c.isdigit() for c in line[:3]):
187
+ pregunta = line.split('.', 1)[1].strip() if '.' in line else line.strip()
188
+ if pregunta:
189
+ preguntas.append(pregunta)
190
+
191
+ return preguntas[:3] # Asegurar máximo 3 preguntas
192
+
193
+ except Exception as e:
194
+ st.error(f"Error generando sugerencias: {str(e)}")
195
+ return []
196
+
197
  def main():
198
  st.set_page_config(page_title="PDF Consultor 🔍", page_icon="🔍", layout="wide")
199
  st.title("PDF Consultor 🔍")
200
  st.markdown(css_style, unsafe_allow_html=True)
201
 
202
+ # Inicializa estados de sesión
203
  if 'documento_cargado' not in st.session_state:
204
  st.session_state.documento_cargado = False
205
+ if 'sugerencias' not in st.session_state:
206
+ st.session_state.sugerencias = []
207
+ if 'pregunta_actual' not in st.session_state:
208
+ st.session_state.pregunta_actual = ""
209
 
210
  # Sidebar - Carga de documentos
211
  with st.sidebar:
 
228
  st.session_state.metadata = extract_metadata(vector_store)
229
  st.session_state.vector_store = vector_store
230
  st.session_state.documento_cargado = True
231
+ st.session_state.sugerencias = generar_sugerencias()
232
 
233
  st.rerun()
234
 
 
242
  campos = [
243
  ("📄 Título", "title"),
244
  ("🏛️ Entidad", "entity"),
245
+ ("📅 Fecha Implantación", "date")
246
  ]
247
 
248
  for col, (icono, key) in zip(cols, campos):
 
253
  {st.session_state.metadata[key]}
254
  </div>
255
  """, unsafe_allow_html=True)
256
+
257
+ # Mostrar sugerencias
258
+ if st.session_state.sugerencias:
259
+ st.markdown("---")
260
+ st.subheader("💡 Preguntas sugeridas:")
261
+
262
+ for i, pregunta in enumerate(st.session_state.sugerencias, 1):
263
+ if st.button(
264
+ pregunta,
265
+ key=f"sug_{i}",
266
+ help=f"Haz clic para usar esta pregunta",
267
+ use_container_width=True
268
+ ):
269
+ st.session_state.pregunta_actual = pregunta
270
+ st.rerun()
271
+
272
+ st.markdown("---")
273
 
274
  # Interfaz de consultas
275
  if st.session_state.documento_cargado:
 
278
  with col1:
279
  user_question = st.text_input(
280
  "Escribe tu pregunta:",
281
+ value=st.session_state.pregunta_actual,
282
  placeholder="Ej: ¿Qué normativa regula este proceso?",
283
  label_visibility="collapsed"
284
  )
285
  with col2:
286
  st.markdown("<br>", unsafe_allow_html=True)
287
  enviar = st.form_submit_button("Enviar ▶")
288
+
289
+ # Resetear pregunta actual después de mostrarla
290
+ if st.session_state.pregunta_actual:
291
+ st.session_state.pregunta_actual = ""
292
 
293
  if user_question and enviar:
294
  procesar_consulta(user_question)