Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,19 +9,34 @@ from langchain.chains import ConversationalRetrievalChain
|
|
| 9 |
from langchain.memory import ConversationBufferMemory
|
| 10 |
from langchain.prompts import PromptTemplate
|
| 11 |
import os
|
|
|
|
| 12 |
|
| 13 |
-
#
|
| 14 |
DOC_PATH = "meu-documento.pdf"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# 🔁 Carrega e processa o PDF
|
| 17 |
def carregar_documento_pdf(path):
|
| 18 |
if not os.path.exists(path):
|
| 19 |
-
|
| 20 |
-
|
| 21 |
loader = PyMuPDFLoader(path)
|
| 22 |
documentos = loader.load()
|
| 23 |
splitter = RecursiveCharacterTextSplitter(
|
| 24 |
-
chunk_size=
|
| 25 |
chunk_overlap=100,
|
| 26 |
separators=["\n\n", "\n", ".", " "]
|
| 27 |
)
|
|
@@ -30,46 +45,48 @@ def carregar_documento_pdf(path):
|
|
| 30 |
vectorstore = FAISS.from_documents(documentos_divididos, embeddings)
|
| 31 |
return vectorstore
|
| 32 |
|
| 33 |
-
# ⚙️ Configura o pipeline com
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
# 🧠 Memória da conversação
|
| 44 |
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True, k=3)
|
| 45 |
|
| 46 |
-
# 📄 Indexação
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
chat_chain = ConversationalRetrievalChain.from_llm(
|
| 58 |
llm=llm,
|
| 59 |
retriever=vectorstore.as_retriever(search_kwargs={"k": 4}),
|
| 60 |
memory=memory,
|
| 61 |
-
combine_docs_chain_kwargs={"prompt": custom_prompt}
|
| 62 |
)
|
| 63 |
-
|
| 64 |
-
print(e)
|
| 65 |
-
vectorstore = None
|
| 66 |
-
chat_chain = None
|
| 67 |
-
# Adicionar uma mensagem de erro na interface, se necessário.
|
| 68 |
-
|
| 69 |
# 💬 Interface Gradio
|
| 70 |
with gr.Blocks() as demo:
|
| 71 |
gr.Markdown("## 🤖💼 CS Search Engine")
|
| 72 |
-
|
| 73 |
chatbot = gr.Chatbot(label="Assistente Técnico")
|
| 74 |
|
| 75 |
with gr.Row():
|
|
@@ -80,40 +97,24 @@ with gr.Blocks() as demo:
|
|
| 80 |
)
|
| 81 |
enviar_btn = gr.Button("Enviar")
|
| 82 |
|
| 83 |
-
# 🛠️ Ação de Interação corrigida
|
| 84 |
def interagir(msg, history):
|
| 85 |
if not chat_chain:
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
try:
|
| 89 |
-
# A função .invoke() ou .run() recebe o histórico no formato correto da LangChain
|
| 90 |
-
# O ConversationalRetrievalChain já gerencia o histórico internamente se ele for passado
|
| 91 |
-
# O `history` do Gradio é o histórico visual do chat
|
| 92 |
-
|
| 93 |
-
# Formata o histórico do Gradio para o formato da LangChain (tupla de (pergunta, resposta))
|
| 94 |
-
langchain_history = [
|
| 95 |
-
(h[0], h[1]) for h in history
|
| 96 |
-
]
|
| 97 |
-
|
| 98 |
-
resposta = chat_chain.invoke({
|
| 99 |
-
"question": msg,
|
| 100 |
-
"chat_history": langchain_history
|
| 101 |
-
})
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
|
|
|
| 105 |
|
| 106 |
except Exception as e:
|
| 107 |
resposta_texto = f"Erro ao gerar resposta: {e}"
|
| 108 |
-
|
| 109 |
history.append((msg, resposta_texto))
|
| 110 |
-
|
|
|
|
| 111 |
|
| 112 |
-
# Conecta a entrada e o botão à função de interação
|
| 113 |
-
# Removemos o estado_chat, pois o chatbot do Gradio já gerencia o histórico
|
| 114 |
entrada.submit(interagir, [entrada, chatbot], [entrada, chatbot])
|
| 115 |
enviar_btn.click(interagir, [entrada, chatbot], [entrada, chatbot])
|
| 116 |
|
| 117 |
demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
|
| 118 |
|
| 119 |
-
|
|
|
|
| 9 |
from langchain.memory import ConversationBufferMemory
|
| 10 |
from langchain.prompts import PromptTemplate
|
| 11 |
import os
|
| 12 |
+
from huggingface_hub import login
|
| 13 |
|
| 14 |
+
# --- Configurações Iniciais ---
|
| 15 |
DOC_PATH = "meu-documento.pdf"
|
| 16 |
+
MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.3"
|
| 17 |
+
|
| 18 |
+
# 🔑 Autenticação no Hugging Face Hub (Passo adicionado)
|
| 19 |
+
# Isso garante que o token seja usado para fazer o login antes de carregar o modelo.
|
| 20 |
+
huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
|
| 21 |
+
if huggingface_token:
|
| 22 |
+
try:
|
| 23 |
+
print("Tentando fazer login no Hugging Face Hub...")
|
| 24 |
+
login(token=huggingface_token)
|
| 25 |
+
print("Login bem-sucedido.")
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"Erro no login do Hugging Face: {e}")
|
| 28 |
+
else:
|
| 29 |
+
print("Aviso: Variável de ambiente HUGGINGFACE_TOKEN não encontrada. O carregamento do modelo pode falhar.")
|
| 30 |
|
| 31 |
# 🔁 Carrega e processa o PDF
|
| 32 |
def carregar_documento_pdf(path):
|
| 33 |
if not os.path.exists(path):
|
| 34 |
+
print(f"Erro: O arquivo {path} não foi encontrado.")
|
| 35 |
+
return None
|
| 36 |
loader = PyMuPDFLoader(path)
|
| 37 |
documentos = loader.load()
|
| 38 |
splitter = RecursiveCharacterTextSplitter(
|
| 39 |
+
chunk_size=512,
|
| 40 |
chunk_overlap=100,
|
| 41 |
separators=["\n\n", "\n", ".", " "]
|
| 42 |
)
|
|
|
|
| 45 |
vectorstore = FAISS.from_documents(documentos_divididos, embeddings)
|
| 46 |
return vectorstore
|
| 47 |
|
| 48 |
+
# ⚙️ Configura o pipeline com o modelo Mistral
|
| 49 |
+
try:
|
| 50 |
+
pipe = pipeline(
|
| 51 |
+
"text-generation",
|
| 52 |
+
model=MODEL_NAME,
|
| 53 |
+
max_new_tokens=256,
|
| 54 |
+
temperature=0.7,
|
| 55 |
+
do_sample=True
|
| 56 |
+
)
|
| 57 |
+
llm = HuggingFacePipeline(pipeline=pipe)
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f"Erro ao carregar o modelo HuggingFace: {e}")
|
| 60 |
+
llm = None
|
| 61 |
+
|
| 62 |
# 🧠 Memória da conversação
|
| 63 |
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True, k=3)
|
| 64 |
|
| 65 |
+
# 📄 Indexação do documento
|
| 66 |
+
vectorstore = carregar_documento_pdf(DOC_PATH)
|
| 67 |
+
|
| 68 |
+
# 🧾 Prompt otimizado para respostas claras
|
| 69 |
+
custom_prompt = PromptTemplate.from_template("""
|
| 70 |
+
Você é um assistente técnico que responde com base **apenas** no documento fornecido.
|
| 71 |
+
Sempre use o idioma Português do Brasil para responder.
|
| 72 |
+
|
| 73 |
+
Contexto:{context}
|
| 74 |
+
Pergunta: {question}
|
| 75 |
+
Resposta:""")
|
| 76 |
|
| 77 |
+
# 🔗 Cadeia RAG com memória e prompt
|
| 78 |
+
chat_chain = None
|
| 79 |
+
if llm and vectorstore:
|
| 80 |
chat_chain = ConversationalRetrievalChain.from_llm(
|
| 81 |
llm=llm,
|
| 82 |
retriever=vectorstore.as_retriever(search_kwargs={"k": 4}),
|
| 83 |
memory=memory,
|
| 84 |
+
combine_docs_chain_kwargs={"prompt": custom_prompt}
|
| 85 |
)
|
| 86 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
# 💬 Interface Gradio
|
| 88 |
with gr.Blocks() as demo:
|
| 89 |
gr.Markdown("## 🤖💼 CS Search Engine")
|
|
|
|
| 90 |
chatbot = gr.Chatbot(label="Assistente Técnico")
|
| 91 |
|
| 92 |
with gr.Row():
|
|
|
|
| 97 |
)
|
| 98 |
enviar_btn = gr.Button("Enviar")
|
| 99 |
|
|
|
|
| 100 |
def interagir(msg, history):
|
| 101 |
if not chat_chain:
|
| 102 |
+
history.append((msg, "Erro: A cadeia de chat não foi inicializada."))
|
| 103 |
+
return "", history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
try:
|
| 106 |
+
resposta_completa = chat_chain.invoke({"question": msg})
|
| 107 |
+
resposta_texto = resposta_completa['answer']
|
| 108 |
|
| 109 |
except Exception as e:
|
| 110 |
resposta_texto = f"Erro ao gerar resposta: {e}"
|
| 111 |
+
|
| 112 |
history.append((msg, resposta_texto))
|
| 113 |
+
|
| 114 |
+
return "", history
|
| 115 |
|
|
|
|
|
|
|
| 116 |
entrada.submit(interagir, [entrada, chatbot], [entrada, chatbot])
|
| 117 |
enviar_btn.click(interagir, [entrada, chatbot], [entrada, chatbot])
|
| 118 |
|
| 119 |
demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
|
| 120 |
|
|
|