Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -39,14 +39,34 @@ css_style = """
|
|
39 |
border-radius: 5px;
|
40 |
border: 1px solid #ccc;
|
41 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
</style>
|
43 |
"""
|
44 |
|
45 |
def eliminar_proceso_pensamiento(texto):
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
return texto_limpio, pensamiento[0].strip() if pensamiento else "No disponible"
|
50 |
|
51 |
def get_pdf_text(pdf_docs):
|
52 |
text = ""
|
@@ -66,7 +86,8 @@ def get_vector_store(text_chunks):
|
|
66 |
|
67 |
def get_conversational_chain():
|
68 |
prompt_template = """
|
69 |
-
Responde en español exclusivamente con la información solicitada usando el contexto
|
|
|
70 |
Formato: Respuesta directa sin prefijos. Si no hay información, di "No disponible".
|
71 |
|
72 |
Contexto:
|
@@ -86,17 +107,75 @@ def get_conversational_chain():
|
|
86 |
prompt=PromptTemplate(template=prompt_template,
|
87 |
input_variables=["context", "question"]))
|
88 |
|
89 |
-
def
|
90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
with st.container():
|
92 |
st.markdown(f'<div class="response-box">{texto}</div>', unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
def procesar_consulta(user_question):
|
99 |
-
"""Procesa la consulta del usuario y muestra la respuesta"""
|
100 |
if 'vector_store' not in st.session_state:
|
101 |
st.error("Por favor carga un documento primero")
|
102 |
return
|
@@ -110,20 +189,25 @@ def procesar_consulta(user_question):
|
|
110 |
return_only_outputs=True
|
111 |
)
|
112 |
|
113 |
-
respuesta_final
|
114 |
-
|
115 |
-
# Mostrar respuesta y pensamiento
|
116 |
-
mostrar_respuesta(respuesta_final, pensamiento)
|
117 |
|
118 |
def main():
|
119 |
st.set_page_config(page_title="PDF Consultor 🔍", page_icon="🔍", layout="wide")
|
120 |
st.title("PDF Consultor 🔍")
|
121 |
st.markdown(css_style, unsafe_allow_html=True)
|
122 |
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
# Sidebar - Carga de documentos
|
128 |
with st.sidebar:
|
129 |
st.markdown('<p class="step-number">1 Subir archivos</p>', unsafe_allow_html=True)
|
@@ -134,36 +218,89 @@ def main():
|
|
134 |
label_visibility="collapsed"
|
135 |
)
|
136 |
|
137 |
-
|
138 |
if pdf_docs and not st.session_state.documento_cargado:
|
139 |
-
with st.spinner("
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
167 |
|
168 |
if __name__ == "__main__":
|
169 |
main()
|
|
|
39 |
border-radius: 5px;
|
40 |
border: 1px solid #ccc;
|
41 |
}
|
42 |
+
.suggestion-container {
|
43 |
+
border: 1px solid #e0e0e0;
|
44 |
+
border-radius: 8px;
|
45 |
+
padding: 15px;
|
46 |
+
margin: 10px 0;
|
47 |
+
background: #f8f9fa;
|
48 |
+
}
|
49 |
+
.suggestion-btn {
|
50 |
+
width: 100%;
|
51 |
+
margin: 3px 0;
|
52 |
+
padding: 8px;
|
53 |
+
border-radius: 5px;
|
54 |
+
border: 1px solid #252850;
|
55 |
+
background: white;
|
56 |
+
cursor: pointer;
|
57 |
+
transition: all 0.2s;
|
58 |
+
}
|
59 |
+
.suggestion-btn:hover {
|
60 |
+
background: #252850;
|
61 |
+
color: white;
|
62 |
+
}
|
63 |
</style>
|
64 |
"""
|
65 |
|
66 |
def eliminar_proceso_pensamiento(texto):
|
67 |
+
texto_limpio = re.sub(r'<.*?>', '', texto, flags=re.DOTALL)
|
68 |
+
lineas = [line.strip() for line in texto_limpio.split('\n') if line.strip()]
|
69 |
+
return lineas[-1] if lineas else "Respuesta no disponible"
|
|
|
70 |
|
71 |
def get_pdf_text(pdf_docs):
|
72 |
text = ""
|
|
|
86 |
|
87 |
def get_conversational_chain():
|
88 |
prompt_template = """
|
89 |
+
Responde en español exclusivamente con la información solicitada usando el contexto, además sé lo más extenso y detallado posible
|
90 |
+
siempre que se pueda desarollar, como explicando el contenido de referencias nombradas.
|
91 |
Formato: Respuesta directa sin prefijos. Si no hay información, di "No disponible".
|
92 |
|
93 |
Contexto:
|
|
|
107 |
prompt=PromptTemplate(template=prompt_template,
|
108 |
input_variables=["context", "question"]))
|
109 |
|
110 |
+
def extract_metadata(vector_store):
|
111 |
+
metadata_questions = {
|
112 |
+
"title": "¿Cuál es el título principal del documento? Formato: Respuesta simple con algunas letras en mayúscula si hiciera falta",
|
113 |
+
"entity": "¿A qué organización pertenece este documento?. Formato: Respuesta directa con el nombre de la entidad.",
|
114 |
+
"date": "¿A qué fecha corresponde el documento? Si existen indicios indica la fecha, sino di 'No disponible'"
|
115 |
+
}
|
116 |
+
|
117 |
+
metadata = {}
|
118 |
+
chain = get_conversational_chain()
|
119 |
+
|
120 |
+
for key, question in metadata_questions.items():
|
121 |
+
docs = vector_store.similarity_search(question, k=2)
|
122 |
+
response = chain(
|
123 |
+
{"input_documents": docs, "question": question},
|
124 |
+
return_only_outputs=True
|
125 |
+
)
|
126 |
+
clean_response = eliminar_proceso_pensamiento(response['output_text'])
|
127 |
+
metadata[key] = clean_response if clean_response else "No disponible"
|
128 |
+
|
129 |
+
return metadata
|
130 |
+
|
131 |
+
def mostrar_respuesta(texto):
|
132 |
with st.container():
|
133 |
st.markdown(f'<div class="response-box">{texto}</div>', unsafe_allow_html=True)
|
134 |
+
|
135 |
+
def generar_sugerencias():
|
136 |
+
"""Genera preguntas sugeridas simples y generales"""
|
137 |
+
if 'vector_store' not in st.session_state:
|
138 |
+
return
|
139 |
|
140 |
+
try:
|
141 |
+
docs = st.session_state.vector_store.similarity_search("", k=3)
|
142 |
+
context = "\n".join([doc.page_content for doc in docs])
|
143 |
+
|
144 |
+
prompt_template = """
|
145 |
+
Genera exactamente 3 preguntas en español basadas en el contexto.
|
146 |
+
Las preguntas deben ser en español, simples y sencillas de máximo 10 palabras.
|
147 |
+
Formato de respuesta:
|
148 |
+
1. [Pregunta completa en español]
|
149 |
+
2. [Pregunta completa en español]
|
150 |
+
3. [Pregunta completa en español]
|
151 |
+
|
152 |
+
Contexto:
|
153 |
+
{context}
|
154 |
+
"""
|
155 |
+
|
156 |
+
model = ChatGroq(
|
157 |
+
temperature=0.4,
|
158 |
+
model_name="deepseek-r1-distill-llama-70b",
|
159 |
+
groq_api_key=os.getenv("GROQ_API_KEY")
|
160 |
+
)
|
161 |
+
|
162 |
+
response = model.invoke(prompt_template.format(context=context))
|
163 |
+
|
164 |
+
preguntas = []
|
165 |
+
for line in response.content.split("\n"):
|
166 |
+
line = line.strip()
|
167 |
+
if line and line[0].isdigit():
|
168 |
+
pregunta = line.split('. ', 1)[1] if '. ' in line else line[2:]
|
169 |
+
if pregunta:
|
170 |
+
preguntas.append(pregunta)
|
171 |
+
|
172 |
+
return preguntas[:3]
|
173 |
+
|
174 |
+
except Exception as e:
|
175 |
+
st.error(f"Error generando sugerencias: {str(e)}")
|
176 |
+
return
|
177 |
|
178 |
def procesar_consulta(user_question):
|
|
|
179 |
if 'vector_store' not in st.session_state:
|
180 |
st.error("Por favor carga un documento primero")
|
181 |
return
|
|
|
189 |
return_only_outputs=True
|
190 |
)
|
191 |
|
192 |
+
respuesta_final = eliminar_proceso_pensamiento(response['output_text'])
|
193 |
+
mostrar_respuesta(respuesta_final)
|
|
|
|
|
194 |
|
195 |
def main():
|
196 |
st.set_page_config(page_title="PDF Consultor 🔍", page_icon="🔍", layout="wide")
|
197 |
st.title("PDF Consultor 🔍")
|
198 |
st.markdown(css_style, unsafe_allow_html=True)
|
199 |
|
200 |
+
# Estados de sesión
|
201 |
+
estados = {
|
202 |
+
'documento_cargado': False,
|
203 |
+
'sugerencias': [],
|
204 |
+
'pregunta_actual': "",
|
205 |
+
'respuestas': []
|
206 |
+
}
|
207 |
+
for key, value in estados.items():
|
208 |
+
if key not in st.session_state:
|
209 |
+
st.session_state[key] = value
|
210 |
+
|
211 |
# Sidebar - Carga de documentos
|
212 |
with st.sidebar:
|
213 |
st.markdown('<p class="step-number">1 Subir archivos</p>', unsafe_allow_html=True)
|
|
|
218 |
label_visibility="collapsed"
|
219 |
)
|
220 |
|
221 |
+
# Procesamiento de documentos
|
222 |
if pdf_docs and not st.session_state.documento_cargado:
|
223 |
+
with st.spinner("Analizando documento..."):
|
224 |
+
try:
|
225 |
+
raw_text = get_pdf_text(pdf_docs)
|
226 |
+
text_chunks = get_text_chunks(raw_text)
|
227 |
+
vector_store = get_vector_store(text_chunks)
|
228 |
+
|
229 |
+
st.session_state.metadata = extract_metadata(vector_store)
|
230 |
+
st.session_state.vector_store = vector_store
|
231 |
+
st.session_state.documento_cargado = True
|
232 |
+
st.session_state.sugerencias = generar_sugerencias()
|
233 |
+
|
234 |
+
st.rerun()
|
235 |
+
|
236 |
+
except Exception as e:
|
237 |
+
st.error(f"Error procesando documento: {str(e)}")
|
238 |
+
|
239 |
+
# Sección principal
|
240 |
+
if 'metadata' in st.session_state:
|
241 |
+
# Mostrar metadatos
|
242 |
+
st.markdown("---")
|
243 |
+
cols = st.columns(3)
|
244 |
+
campos_metadata = [
|
245 |
+
("📄 Título", "title"),
|
246 |
+
("🏛️ Entidad", "entity"),
|
247 |
+
("📅 Fecha", "date")
|
248 |
+
]
|
249 |
+
|
250 |
+
for col, (icono, key) in zip(cols, campos_metadata):
|
251 |
+
with col:
|
252 |
+
st.markdown(f"""
|
253 |
+
<div class="metadata-box">
|
254 |
+
<div style="font-size:16px; margin-bottom:10px;">{icono}</div>
|
255 |
+
{st.session_state.metadata[key]}
|
256 |
+
</div>
|
257 |
+
""", unsafe_allow_html=True)
|
258 |
+
|
259 |
+
# Sugerencias
|
260 |
+
if st.session_state.sugerencias:
|
261 |
+
st.markdown("---")
|
262 |
+
with st.container():
|
263 |
+
st.markdown("""
|
264 |
+
<div class="suggestion-container">
|
265 |
+
<div style="font-size:14px; color:#666; margin-bottom:8px;">💡 ¿Necesitas ideas?</div>
|
266 |
+
""", unsafe_allow_html=True)
|
267 |
+
|
268 |
+
cols_sugerencias = st.columns(3)
|
269 |
+
for i, (col, pregunta) in enumerate(zip(cols_sugerencias, st.session_state.sugerencias)):
|
270 |
+
with col:
|
271 |
+
if st.button(
|
272 |
+
pregunta,
|
273 |
+
key=f"sug_{i}",
|
274 |
+
help="Haz clic para usar esta pregunta",
|
275 |
+
use_container_width=True
|
276 |
+
):
|
277 |
+
st.session_state.pregunta_actual = pregunta
|
278 |
+
|
279 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
280 |
+
|
281 |
+
# Formulario de consulta
|
282 |
+
if st.session_state.documento_cargado:
|
283 |
+
with st.form(key="consulta_form"):
|
284 |
+
col1, col2 = st.columns([5, 1])
|
285 |
+
with col1:
|
286 |
+
pregunta_usuario = st.text_input(
|
287 |
+
"Escribe tu pregunta:",
|
288 |
+
value=st.session_state.get('pregunta_actual', ''),
|
289 |
+
placeholder="Ej: ¿De qué trata este documento?",
|
290 |
+
label_visibility="collapsed"
|
291 |
+
)
|
292 |
+
with col2:
|
293 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
294 |
+
enviar = st.form_submit_button("Enviar ▶")
|
295 |
+
|
296 |
+
if enviar or st.session_state.pregunta_actual:
|
297 |
+
pregunta_final = pregunta_usuario or st.session_state.pregunta_actual
|
298 |
+
procesar_consulta(pregunta_final)
|
299 |
+
if 'pregunta_actual' in st.session_state:
|
300 |
+
del st.session_state.pregunta_actual
|
301 |
+
|
302 |
+
elif not st.session_state.documento_cargado:
|
303 |
+
st.info("Por favor, sube un documento PDF para comenzar.")
|
304 |
|
305 |
if __name__ == "__main__":
|
306 |
main()
|