Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,67 +3,84 @@ from transformers import pipeline
|
|
| 3 |
from langchain_community.llms import HuggingFacePipeline
|
| 4 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 5 |
from langchain_community.vectorstores import FAISS
|
| 6 |
-
from
|
| 7 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
from langchain.chains import ConversationalRetrievalChain
|
| 9 |
-
from langchain.
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
def carregar_documento_pdf(path):
|
| 13 |
-
loader = PyPDFLoader(path)
|
| 14 |
-
documentos = loader.load()
|
| 15 |
-
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
|
| 16 |
-
documentos_divididos = splitter.split_documents(documentos)
|
| 17 |
-
embeddings = HuggingFaceEmbeddings()
|
| 18 |
-
vectorstore = FAISS.from_documents(documentos_divididos, embeddings)
|
| 19 |
-
return vectorstore
|
| 20 |
-
|
| 21 |
-
# Inicializa vectorstore com PDF fixo
|
| 22 |
-
vectorstore = carregar_documento_pdf("meu_documento.pdf")
|
| 23 |
-
|
| 24 |
-
# Inicializa pipeline do Flan-Alpaca
|
| 25 |
pipe = pipeline(
|
| 26 |
"text2text-generation",
|
| 27 |
model="declare-lab/flan-alpaca-base",
|
| 28 |
-
max_new_tokens=
|
| 29 |
truncation=True,
|
| 30 |
max_length=512,
|
| 31 |
)
|
| 32 |
llm = HuggingFacePipeline(pipeline=pipe)
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
chat_chain = ConversationalRetrievalChain.from_llm(
|
| 39 |
llm=llm,
|
| 40 |
retriever=vectorstore.as_retriever(),
|
| 41 |
-
memory=
|
|
|
|
| 42 |
)
|
| 43 |
|
| 44 |
-
# Fun莽茫o para responder
|
| 45 |
-
def
|
| 46 |
-
if not pergunta or not pergunta.strip():
|
| 47 |
-
return "Por favor, insira uma pergunta v谩lida."
|
| 48 |
resposta = chat_chain.run({"question": pergunta})
|
|
|
|
|
|
|
|
|
|
| 49 |
return resposta
|
| 50 |
|
| 51 |
-
# Interface Gradio
|
| 52 |
with gr.Blocks() as demo:
|
| 53 |
-
gr.Markdown("## 馃 Chat com
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
| 57 |
|
| 58 |
-
def interagir(
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
|
| 66 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 67 |
|
| 68 |
|
| 69 |
|
|
|
|
| 3 |
from langchain_community.llms import HuggingFacePipeline
|
| 4 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 5 |
from langchain_community.vectorstores import FAISS
|
| 6 |
+
from langchain.document_loaders import TextLoader
|
| 7 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
from langchain.chains import ConversationalRetrievalChain
|
| 9 |
+
from langchain.prompts import PromptTemplate
|
| 10 |
|
| 11 |
+
# Configura o pipeline do modelo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
pipe = pipeline(
|
| 13 |
"text2text-generation",
|
| 14 |
model="declare-lab/flan-alpaca-base",
|
| 15 |
+
max_new_tokens=150,
|
| 16 |
truncation=True,
|
| 17 |
max_length=512,
|
| 18 |
)
|
| 19 |
llm = HuggingFacePipeline(pipeline=pipe)
|
| 20 |
|
| 21 |
+
# Carrega e divide documento em chunks maiores para contexto melhor
|
| 22 |
+
def carregar_documento_txt(path):
|
| 23 |
+
loader = TextLoader(path, encoding="latin-1")
|
| 24 |
+
documentos = loader.load()
|
| 25 |
+
# Chunk size maior e overlap para contexto mais coeso
|
| 26 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 27 |
+
documentos_divididos = splitter.split_documents(documentos)
|
| 28 |
+
embeddings = HuggingFaceEmbeddings()
|
| 29 |
+
vectorstore = FAISS.from_documents(documentos_divididos, embeddings)
|
| 30 |
+
return vectorstore
|
| 31 |
+
|
| 32 |
+
vectorstore = carregar_documento_txt("meu_documento.txt")
|
| 33 |
|
| 34 |
+
# Prompt customizado para garantir que o modelo responda com base no contexto
|
| 35 |
+
template = """
|
| 36 |
+
Voc锚 茅 um assistente que responde perguntas baseado no contexto a seguir.
|
| 37 |
+
Se n茫o souber a resposta, responda "N茫o sei com base nos documentos fornecidos."
|
| 38 |
+
Contexto:
|
| 39 |
+
{context}
|
| 40 |
+
|
| 41 |
+
Pergunta:
|
| 42 |
+
{question}
|
| 43 |
+
|
| 44 |
+
Resposta:
|
| 45 |
+
"""
|
| 46 |
+
QA_CHAIN_PROMPT = PromptTemplate(template=template, input_variables=["context", "question"])
|
| 47 |
+
|
| 48 |
+
# Cria o chain de busca sem mem贸ria
|
| 49 |
chat_chain = ConversationalRetrievalChain.from_llm(
|
| 50 |
llm=llm,
|
| 51 |
retriever=vectorstore.as_retriever(),
|
| 52 |
+
memory=None, # sem mem贸ria para simplificar
|
| 53 |
+
combine_docs_chain_kwargs={"prompt": QA_CHAIN_PROMPT}
|
| 54 |
)
|
| 55 |
|
| 56 |
+
# Fun莽茫o para responder perguntas com base no documento
|
| 57 |
+
def responder_documento(pergunta):
|
|
|
|
|
|
|
| 58 |
resposta = chat_chain.run({"question": pergunta})
|
| 59 |
+
# P贸s-processar: se resposta muito curta ou igual ao contexto, retorna fallback
|
| 60 |
+
if len(resposta.strip()) < 10 or resposta.lower().startswith("n茫o sei"):
|
| 61 |
+
return "N茫o sei com base nos documentos fornecidos."
|
| 62 |
return resposta
|
| 63 |
|
| 64 |
+
# Interface Gradio
|
| 65 |
with gr.Blocks() as demo:
|
| 66 |
+
gr.Markdown("## 馃 Chat IA com Documento TXT - Flan-Alpaca e LangChain")
|
| 67 |
+
|
| 68 |
+
chatbot = gr.Chatbot(label="Chat com Documento")
|
| 69 |
+
entrada = gr.Textbox(placeholder="Digite sua pergunta e aperte Enter", show_label=False)
|
| 70 |
+
estado_chat = gr.State([])
|
| 71 |
|
| 72 |
+
def interagir(msg, history):
|
| 73 |
+
try:
|
| 74 |
+
resposta = responder_documento(msg)
|
| 75 |
+
except Exception as e:
|
| 76 |
+
resposta = f"Erro ao gerar resposta: {e}"
|
| 77 |
+
history = history + [(msg, resposta)]
|
| 78 |
+
return "", history
|
| 79 |
|
| 80 |
+
entrada.submit(interagir, [entrada, estado_chat], [entrada, chatbot])
|
| 81 |
+
gr.Button("Enviar").click(interagir, [entrada, estado_chat], [entrada, chatbot])
|
| 82 |
|
| 83 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
|
| 84 |
|
| 85 |
|
| 86 |
|