Spaces:
Running
Running
import os | |
from typing import Optional | |
import gradio as gr | |
from langchain_community.document_loaders import PyPDFLoader | |
from langchain.text_splitter import RecursiveCharacterTextSplitter | |
from langchain_community.embeddings import HuggingFaceEmbeddings | |
from langchain_community.vectorstores import FAISS | |
from langchain_community.llms import HuggingFacePipeline | |
from langchain.chains import RetrievalQA | |
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline | |
import torch | |
import tempfile | |
# Configurações | |
EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2" | |
LLM_MODEL = "mistralai/Mistral-7B-v0.1" | |
class RAGSystem: | |
def __init__(self): | |
# Inicializa o modelo de linguagem | |
self.tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL) | |
self.model = AutoModelForCausalLM.from_pretrained( | |
LLM_MODEL, | |
torch_dtype=torch.float16, | |
device_map="auto", | |
load_in_8bit=True # Usa quantização 8-bit para reduzir uso de memória | |
) | |
# Configura o pipeline | |
pipe = pipeline( | |
"text-generation", | |
model=self.model, | |
tokenizer=self.tokenizer, | |
max_length=2048, | |
temperature=0.7, | |
top_p=0.95, | |
repetition_penalty=1.15 | |
) | |
# Configura o modelo LangChain | |
self.llm = HuggingFacePipeline(pipeline=pipe) | |
# Configura embeddings | |
self.embeddings = HuggingFaceEmbeddings( | |
model_name=EMBEDDING_MODEL, | |
model_kwargs={'device': 'cpu'} | |
) | |
def process_pdf(self, file_content: bytes) -> Optional[FAISS]: | |
"""Processa o PDF e cria a base de conhecimento""" | |
try: | |
# Cria arquivo temporário | |
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file: | |
tmp_file.write(file_content) | |
tmp_path = tmp_file.name | |
# Carrega e processa o PDF | |
loader = PyPDFLoader(tmp_path) | |
documents = loader.load() | |
# Remove arquivo temporário | |
os.unlink(tmp_path) | |
if not documents: | |
return None | |
# Divide o texto em chunks | |
text_splitter = RecursiveCharacterTextSplitter( | |
chunk_size=1000, | |
chunk_overlap=200, | |
length_function=len, | |
separators=["\n\n", "\n", ".", " ", ""] | |
) | |
texts = text_splitter.split_documents(documents) | |
# Cria base de conhecimento | |
db = FAISS.from_documents(texts, self.embeddings) | |
return db | |
except Exception as e: | |
print(f"Erro ao processar PDF: {str(e)}") | |
return None | |
def generate_response(self, file_obj, query: str) -> str: | |
"""Gera resposta para a consulta""" | |
if file_obj is None: | |
return "Por favor, faça upload de um arquivo PDF." | |
if not query.strip(): | |
return "Por favor, insira uma pergunta." | |
try: | |
# Processa o PDF | |
db = self.process_pdf(file_obj) | |
if db is None: | |
return "Não foi possível processar o PDF." | |
# Configura o chain RAG | |
qa_chain = RetrievalQA.from_chain_type( | |
llm=self.llm, | |
chain_type="stuff", | |
retriever=db.as_retriever( | |
search_kwargs={ | |
"k": 3, | |
"fetch_k": 5 | |
} | |
), | |
return_source_documents=True | |
) | |
# Gera resposta | |
result = qa_chain({"query": query}) | |
return result["result"] | |
except Exception as e: | |
return f"Erro ao gerar resposta: {str(e)}" | |
# Interface Gradio | |
def create_demo(): | |
rag = RAGSystem() | |
with gr.Blocks() as demo: | |
gr.Markdown("# 📚 Sistema RAG com Mistral-7B") | |
gr.Markdown(""" | |
### Instruções: | |
1. Faça upload de um arquivo PDF | |
2. Digite sua pergunta sobre o conteúdo | |
3. Aguarde a resposta gerada pelo modelo | |
""") | |
with gr.Row(): | |
with gr.Column(scale=1): | |
file_input = gr.File( | |
label="Upload do PDF", | |
type="binary", | |
file_types=[".pdf"] | |
) | |
query_input = gr.Textbox( | |
label="Sua Pergunta", | |
placeholder="Digite sua pergunta sobre o documento...", | |
lines=3 | |
) | |
submit_btn = gr.Button("🔍 Pesquisar", variant="primary") | |
with gr.Column(scale=1): | |
output = gr.Textbox( | |
label="Resposta", | |
lines=10 | |
) | |
submit_btn.click( | |
fn=rag.generate_response, | |
inputs=[file_input, query_input], | |
outputs=output | |
) | |
gr.Examples( | |
examples=[ | |
[None, "Qual é o tema principal deste documento?"], | |
[None, "Pode fazer um resumo dos pontos principais?"], | |
[None, "Quais são as principais conclusões?"] | |
], | |
inputs=[file_input, query_input] | |
) | |
return demo | |
if __name__ == "__main__": | |
demo = create_demo() | |
demo.launch() |