Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -39,34 +39,14 @@ css_style = """
|
|
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 |
-
|
68 |
-
|
69 |
-
|
|
|
70 |
|
71 |
def get_pdf_text(pdf_docs):
|
72 |
text = ""
|
@@ -86,8 +66,7 @@ def get_vector_store(text_chunks):
|
|
86 |
|
87 |
def get_conversational_chain():
|
88 |
prompt_template = """
|
89 |
-
Responde en español exclusivamente con la información solicitada usando el contexto
|
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,75 +86,17 @@ def get_conversational_chain():
|
|
107 |
prompt=PromptTemplate(template=prompt_template,
|
108 |
input_variables=["context", "question"]))
|
109 |
|
110 |
-
def
|
111 |
-
|
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 |
-
|
141 |
-
|
142 |
-
|
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,25 +110,20 @@ def procesar_consulta(user_question):
|
|
189 |
return_only_outputs=True
|
190 |
)
|
191 |
|
192 |
-
respuesta_final = eliminar_proceso_pensamiento(response['output_text'])
|
193 |
-
|
|
|
|
|
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 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
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,89 +134,36 @@ def main():
|
|
218 |
label_visibility="collapsed"
|
219 |
)
|
220 |
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
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()
|
|
|
39 |
border-radius: 5px;
|
40 |
border: 1px solid #ccc;
|
41 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
</style>
|
43 |
"""
|
44 |
|
45 |
def eliminar_proceso_pensamiento(texto):
|
46 |
+
"""Extrae el proceso de pensamiento del modelo"""
|
47 |
+
pensamiento = re.findall(r'<think>(.*?)</think>', texto, flags=re.DOTALL)
|
48 |
+
texto_limpio = re.sub(r'<think>.*?</think>', '', texto, flags=re.DOTALL).strip()
|
49 |
+
return texto_limpio, pensamiento[0].strip() if pensamiento else "No disponible"
|
50 |
|
51 |
def get_pdf_text(pdf_docs):
|
52 |
text = ""
|
|
|
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 |
prompt=PromptTemplate(template=prompt_template,
|
87 |
input_variables=["context", "question"]))
|
88 |
|
89 |
+
def mostrar_respuesta(texto, pensamiento):
|
90 |
+
"""Muestra la respuesta y el proceso de pensamiento en un contenedor"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
with st.container():
|
92 |
st.markdown(f'<div class="response-box">{texto}</div>', unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
+
# Desplegable para mostrar el proceso de pensamiento del modelo
|
95 |
+
with st.expander("💭 Pensamiento del modelo"):
|
96 |
+
st.markdown(pensamiento)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
return_only_outputs=True
|
111 |
)
|
112 |
|
113 |
+
respuesta_final, pensamiento = eliminar_proceso_pensamiento(response['output_text'])
|
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 |
+
# Inicializa estados de sesión
|
124 |
+
if 'documento_cargado' not in st.session_state:
|
125 |
+
st.session_state.documento_cargado = False
|
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 |
label_visibility="collapsed"
|
135 |
)
|
136 |
|
137 |
+
# Procesamiento automático al cargar documentos
|
138 |
+
if pdf_docs and not st.session_state.documento_cargado:
|
139 |
+
with st.spinner("Procesando documento..."):
|
140 |
+
try:
|
141 |
+
raw_text = get_pdf_text(pdf_docs)
|
142 |
+
text_chunks = get_text_chunks(raw_text)
|
143 |
+
vector_store = get_vector_store(text_chunks)
|
144 |
+
st.session_state.vector_store = vector_store
|
145 |
+
st.session_state.documento_cargado = True
|
146 |
+
st.success("Documento procesado exitosamente.")
|
147 |
+
except Exception as e:
|
148 |
+
st.error(f"Error procesando documento: {str(e)}")
|
149 |
+
|
150 |
+
# Interfaz de consultas
|
151 |
+
if st.session_state.documento_cargado:
|
152 |
+
with st.form("consulta_form"):
|
153 |
+
col1, col2 = st.columns([5, 1])
|
154 |
+
with col1:
|
155 |
+
user_question = st.text_input(
|
156 |
+
"Escribe tu pregunta:",
|
157 |
+
placeholder="Ej: ¿Qué normativa regula este proceso?",
|
158 |
+
label_visibility="collapsed"
|
159 |
+
)
|
160 |
+
with col2:
|
161 |
+
enviar = st.form_submit_button("Enviar ▶")
|
162 |
+
|
163 |
+
if user_question and enviar:
|
164 |
+
procesar_consulta(user_question)
|
165 |
+
else:
|
166 |
+
st.info("Por favor sube un archivo PDF para comenzar.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
167 |
|
168 |
if __name__ == "__main__":
|
169 |
+
main()
|