Spaces:
Sleeping
Sleeping
Commit
•
6aa138d
1
Parent(s):
1aea8c1
inicio archivo
Browse files
app.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from langchain.document_loaders import PyPDFDirectoryLoader
|
4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
+
from langchain.vectorstores import Chroma
|
6 |
+
from langchain.embeddings import OpenAIEmbeddings
|
7 |
+
from langchain.llms import OpenAI
|
8 |
+
from langchain_core.output_parsers import StrOutputParser
|
9 |
+
from langchain_core.runnables import RunnablePassthrough
|
10 |
+
|
11 |
+
# Configuración inicial y variables de entorno
|
12 |
+
st.title("Busca en PDFs")
|
13 |
+
|
14 |
+
# Entradas de usuario para las API keys
|
15 |
+
OPENAI_API_KEY = st.text_input('OpenAI Api Key', type='password')
|
16 |
+
if OPENAI_API_KEY:
|
17 |
+
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
18 |
+
|
19 |
+
# Función principal
|
20 |
+
def main():
|
21 |
+
st.write("Aplicación en Streamlit ejecutándose correctamente")
|
22 |
+
|
23 |
+
# Configura las carpetas necesarias
|
24 |
+
source_data_folder = "src"
|
25 |
+
path_db = "VectorDB"
|
26 |
+
os.makedirs(source_data_folder, exist_ok=True)
|
27 |
+
os.makedirs(path_db, exist_ok=True)
|
28 |
+
|
29 |
+
# Carga de archivos PDF
|
30 |
+
uploaded_files = st.file_uploader("Sube archivos PDF", type="pdf", accept_multiple_files=True)
|
31 |
+
if uploaded_files:
|
32 |
+
for uploaded_file in uploaded_files:
|
33 |
+
with open(os.path.join(source_data_folder, uploaded_file.name), "wb") as f:
|
34 |
+
f.write(uploaded_file.getbuffer())
|
35 |
+
st.write(f"{len(uploaded_files)} archivos subidos exitosamente")
|
36 |
+
|
37 |
+
# Leer y procesar PDFs
|
38 |
+
loader = PyPDFDirectoryLoader(source_data_folder)
|
39 |
+
data_on_pdf = loader.load()
|
40 |
+
st.write(f"Se han cargado {len(data_on_pdf)} documentos")
|
41 |
+
|
42 |
+
# Particionar datos
|
43 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
44 |
+
separators=["\n\n", "\n", ". ", " ", ""],
|
45 |
+
chunk_size=1024,
|
46 |
+
chunk_overlap=200
|
47 |
+
)
|
48 |
+
splits = text_splitter.split_documents(data_on_pdf)
|
49 |
+
st.write(f"Se han creado {len(splits)} fragmentos")
|
50 |
+
|
51 |
+
# Embeddings
|
52 |
+
embeddings_model = OpenAIEmbeddings(model="text-embedding-ada-002")
|
53 |
+
|
54 |
+
# Base de datos vectorial
|
55 |
+
vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings_model, persist_directory=path_db)
|
56 |
+
|
57 |
+
# Configuración del LLM
|
58 |
+
llm = OpenAI(model_name="gpt-3.5-turbo-0125", openai_api_key=OPENAI_API_KEY, temperature=0.8)
|
59 |
+
|
60 |
+
retriever = vectorstore.as_retriever()
|
61 |
+
|
62 |
+
prompt_template = """
|
63 |
+
Responde en español como un experto en análisis de datos:
|
64 |
+
{context}
|
65 |
+
|
66 |
+
Pregunta: {question}
|
67 |
+
"""
|
68 |
+
|
69 |
+
def format_docs(docs):
|
70 |
+
return "\n\n".join(doc.page_content for doc in docs)
|
71 |
+
|
72 |
+
def create_prompt(context, question):
|
73 |
+
return prompt_template.format(context=context, question=question)
|
74 |
+
|
75 |
+
rag_chain = (
|
76 |
+
{"context": retriever | format_docs, "question": RunnablePassthrough()}
|
77 |
+
| create_prompt
|
78 |
+
| llm
|
79 |
+
| StrOutputParser()
|
80 |
+
)
|
81 |
+
|
82 |
+
# Interacción con el usuario
|
83 |
+
pregunta = st.text_input("Haz una pregunta sobre los documentos:")
|
84 |
+
if pregunta:
|
85 |
+
try:
|
86 |
+
response = rag_chain.invoke(pregunta)
|
87 |
+
st.markdown(response)
|
88 |
+
except Exception as e:
|
89 |
+
st.error(f"Error al procesar la pregunta: {e}")
|
90 |
+
|
91 |
+
if __name__ == "__main__":
|
92 |
+
main()
|
93 |
+
else:
|
94 |
+
st.write("Por favor, proporciona las API keys para continuar.")
|