Spaces:
Running
Running
Upload app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,7 @@ import streamlit as st
|
|
2 |
import os
|
3 |
from PyPDF2 import PdfReader
|
4 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
-
from langchain.embeddings import
|
6 |
from langchain.vectorstores import FAISS
|
7 |
from langchain.llms import HuggingFaceHub
|
8 |
from langchain.chains.question_answering import load_qa_chain
|
@@ -11,17 +11,24 @@ from langchain.prompts import PromptTemplate
|
|
11 |
st.set_page_config(page_title='preguntaDOC')
|
12 |
st.header("Pregunta a tu PDF")
|
13 |
|
14 |
-
#
|
15 |
-
huggingface_api_token = st.text_input('Hugging Face API Token (
|
16 |
|
17 |
pdf_obj = st.file_uploader("Carga tu documento", type="pdf", on_change=st.cache_resource.clear)
|
18 |
|
19 |
@st.cache_resource
|
20 |
-
def create_embeddings(pdf):
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
pdf_reader = PdfReader(pdf)
|
22 |
text = ""
|
23 |
for page in pdf_reader.pages:
|
24 |
text += page.extract_text()
|
|
|
25 |
text_splitter = RecursiveCharacterTextSplitter(
|
26 |
chunk_size=800,
|
27 |
chunk_overlap=100,
|
@@ -29,51 +36,54 @@ def create_embeddings(pdf):
|
|
29 |
)
|
30 |
chunks = text_splitter.split_text(text)
|
31 |
|
32 |
-
#
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
34 |
knowledge_base = FAISS.from_texts(chunks, embeddings)
|
35 |
return knowledge_base
|
36 |
|
37 |
-
if pdf_obj:
|
38 |
-
knowledge_base = create_embeddings(pdf_obj)
|
39 |
-
user_question = st.text_input("Haz una pregunta sobre tu PDF:")
|
40 |
|
41 |
-
if
|
42 |
-
|
43 |
-
if huggingface_api_token:
|
44 |
-
os.environ["HUGGINGFACEHUB_API_TOKEN"] = huggingface_api_token
|
45 |
-
|
46 |
-
docs = knowledge_base.similarity_search(user_question, 3)
|
47 |
-
|
48 |
-
# Usar un modelo gratuito de Hugging Face en lugar de OpenAI
|
49 |
-
llm = HuggingFaceHub(
|
50 |
-
repo_id="google/flan-t5-large", # Modelo gratuito con buenas capacidades para Q&A
|
51 |
-
model_kwargs={"temperature": 0.5, "max_length": 512}
|
52 |
-
)
|
53 |
-
|
54 |
-
# Crear un prompt template adecuado para modelos como T5
|
55 |
-
prompt_template = """
|
56 |
-
Responde a la siguiente pregunta basándote únicamente en el contexto proporcionado.
|
57 |
-
|
58 |
-
Contexto: {context}
|
59 |
-
|
60 |
-
Pregunta: {question}
|
61 |
-
|
62 |
-
Respuesta:
|
63 |
-
"""
|
64 |
-
|
65 |
-
PROMPT = PromptTemplate(
|
66 |
-
template=prompt_template,
|
67 |
-
input_variables=["context", "question"]
|
68 |
-
)
|
69 |
-
|
70 |
-
chain = load_qa_chain(llm, chain_type="stuff", prompt=PROMPT)
|
71 |
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import os
|
3 |
from PyPDF2 import PdfReader
|
4 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
+
from langchain.embeddings import HuggingFaceHubEmbeddings
|
6 |
from langchain.vectorstores import FAISS
|
7 |
from langchain.llms import HuggingFaceHub
|
8 |
from langchain.chains.question_answering import load_qa_chain
|
|
|
11 |
st.set_page_config(page_title='preguntaDOC')
|
12 |
st.header("Pregunta a tu PDF")
|
13 |
|
14 |
+
# Campo para el token de Hugging Face (ahora requerido para los embeddings)
|
15 |
+
huggingface_api_token = st.text_input('Hugging Face API Token (requerido)', type='password')
|
16 |
|
17 |
pdf_obj = st.file_uploader("Carga tu documento", type="pdf", on_change=st.cache_resource.clear)
|
18 |
|
19 |
@st.cache_resource
|
20 |
+
def create_embeddings(pdf, api_token):
|
21 |
+
if not api_token:
|
22 |
+
st.error("Se requiere un token de API de Hugging Face")
|
23 |
+
return None
|
24 |
+
|
25 |
+
os.environ["HUGGINGFACEHUB_API_TOKEN"] = api_token
|
26 |
+
|
27 |
pdf_reader = PdfReader(pdf)
|
28 |
text = ""
|
29 |
for page in pdf_reader.pages:
|
30 |
text += page.extract_text()
|
31 |
+
|
32 |
text_splitter = RecursiveCharacterTextSplitter(
|
33 |
chunk_size=800,
|
34 |
chunk_overlap=100,
|
|
|
36 |
)
|
37 |
chunks = text_splitter.split_text(text)
|
38 |
|
39 |
+
# Usar HuggingFaceHubEmbeddings en lugar de HuggingFaceEmbeddings
|
40 |
+
# Este enfoque no requiere sentence-transformers instalado localmente
|
41 |
+
embeddings = HuggingFaceHubEmbeddings(
|
42 |
+
repo_id="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
43 |
+
huggingfacehub_api_token=api_token
|
44 |
+
)
|
45 |
+
|
46 |
knowledge_base = FAISS.from_texts(chunks, embeddings)
|
47 |
return knowledge_base
|
48 |
|
49 |
+
if pdf_obj and huggingface_api_token:
|
50 |
+
knowledge_base = create_embeddings(pdf_obj, huggingface_api_token)
|
|
|
51 |
|
52 |
+
if knowledge_base:
|
53 |
+
user_question = st.text_input("Haz una pregunta sobre tu PDF:")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
+
if user_question:
|
56 |
+
docs = knowledge_base.similarity_search(user_question, 3)
|
57 |
+
|
58 |
+
# Usar un modelo gratuito de Hugging Face
|
59 |
+
llm = HuggingFaceHub(
|
60 |
+
repo_id="google/flan-t5-large",
|
61 |
+
huggingfacehub_api_token=huggingface_api_token,
|
62 |
+
model_kwargs={"temperature": 0.5, "max_length": 512}
|
63 |
+
)
|
64 |
+
|
65 |
+
prompt_template = """
|
66 |
+
Responde a la siguiente pregunta basándote únicamente en el contexto proporcionado.
|
67 |
+
|
68 |
+
Contexto: {context}
|
69 |
+
|
70 |
+
Pregunta: {question}
|
71 |
+
|
72 |
+
Respuesta:
|
73 |
+
"""
|
74 |
+
|
75 |
+
PROMPT = PromptTemplate(
|
76 |
+
template=prompt_template,
|
77 |
+
input_variables=["context", "question"]
|
78 |
+
)
|
79 |
+
|
80 |
+
chain = load_qa_chain(llm, chain_type="stuff", prompt=PROMPT)
|
81 |
+
|
82 |
+
with st.spinner("Procesando tu pregunta..."):
|
83 |
+
try:
|
84 |
+
respuesta = chain.run(input_documents=docs, question=user_question)
|
85 |
+
st.write(respuesta)
|
86 |
+
except Exception as e:
|
87 |
+
st.error(f"Error al procesar tu pregunta: {str(e)}")
|
88 |
+
elif not huggingface_api_token and pdf_obj:
|
89 |
+
st.warning("Por favor, ingresa tu token de API de Hugging Face para continuar.")
|