Spaces:
Running
Running
Upload 2 files
Browse files- app.py +79 -0
- requirements.txt +9 -0
app.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from PyPDF2 import PdfReader
|
4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
6 |
+
from langchain.vectorstores import FAISS
|
7 |
+
from langchain.llms import HuggingFaceHub
|
8 |
+
from langchain.chains.question_answering import load_qa_chain
|
9 |
+
from langchain.prompts import PromptTemplate
|
10 |
+
|
11 |
+
st.set_page_config(page_title='preguntaDOC')
|
12 |
+
st.header("Pregunta a tu PDF")
|
13 |
+
|
14 |
+
# Ya no necesitamos la clave de OpenAI
|
15 |
+
huggingface_api_token = st.text_input('Hugging Face API Token (opcional)', 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):
|
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,
|
28 |
+
length_function=len
|
29 |
+
)
|
30 |
+
chunks = text_splitter.split_text(text)
|
31 |
+
|
32 |
+
# Usando el mismo modelo de embeddings que ya estabas usando
|
33 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
|
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 user_question:
|
42 |
+
# Configurar el token de Hugging Face si se proporciona
|
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 |
+
# Mostrar un mensaje mientras se procesa
|
73 |
+
with st.spinner("Procesando tu pregunta..."):
|
74 |
+
try:
|
75 |
+
respuesta = chain.run(input_documents=docs, question=user_question)
|
76 |
+
st.write(respuesta)
|
77 |
+
except Exception as e:
|
78 |
+
st.error(f"Error al procesar tu pregunta: {str(e)}")
|
79 |
+
st.info("Si no has proporcionado un token de Hugging Face, considera hacerlo para evitar limitaciones de rate limit.")
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit==1.22.0
|
2 |
+
langchain==0.0.267
|
3 |
+
PyPDF2==3.0.1
|
4 |
+
huggingface-hub==0.16.4
|
5 |
+
transformers==4.30.2
|
6 |
+
sentence-transformers==2.2.2
|
7 |
+
faiss-cpu==1.7.4
|
8 |
+
accelerate==0.20.3
|
9 |
+
einops==0.6.1
|