File size: 5,572 Bytes
6852d71
e49e7e7
7f29224
31fe207
4fa0927
31fe207
 
e49e7e7
4fa0927
e49e7e7
 
6852d71
 
4fa0927
 
e49e7e7
4fa0927
e49e7e7
 
 
 
 
 
 
 
 
 
6852d71
e49e7e7
 
 
 
 
 
 
 
 
6852d71
 
e49e7e7
 
 
 
 
6852d71
 
 
e49e7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6852d71
e49e7e7
 
6852d71
e49e7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fa0927
e49e7e7
 
 
6852d71
e49e7e7
 
 
 
 
 
 
 
6852d71
e49e7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6852d71
e49e7e7
 
 
 
6852d71
 
e49e7e7
 
 
 
 
 
 
6852d71
a31ad5a
e49e7e7
7f29224
6852d71
e49e7e7
a31ad5a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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()