File size: 10,275 Bytes
6852d71
6f1dbe9
7f29224
9224061
4fa0927
31fe207
 
e49e7e7
4fa0927
5c408af
e49e7e7
6852d71
6f1dbe9
6852d71
4fa0927
 
6f1dbe9
b576e4e
4fa0927
e49e7e7
 
 
5c408af
e49e7e7
 
6f1dbe9
e49e7e7
6852d71
e49e7e7
5c408af
e49e7e7
 
5c408af
e49e7e7
5c408af
6852d71
 
e49e7e7
 
6852d71
 
 
9224061
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f1dbe9
5c408af
9224061
 
 
 
 
6f1dbe9
9224061
 
 
 
 
e49e7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
5c408af
 
e49e7e7
 
 
 
 
 
9224061
 
 
 
e49e7e7
 
 
 
 
 
6f1dbe9
 
e49e7e7
6f1dbe9
6852d71
6f1dbe9
e49e7e7
6f1dbe9
 
 
 
9224061
 
 
6f1dbe9
9224061
 
 
6f1dbe9
e49e7e7
6f1dbe9
e49e7e7
 
 
 
6f1dbe9
e49e7e7
 
 
 
6f1dbe9
5c408af
9224061
 
5c408af
 
9224061
 
 
6f1dbe9
 
 
 
e49e7e7
 
6f1dbe9
 
4fa0927
e49e7e7
 
6852d71
6f1dbe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e49e7e7
6f1dbe9
 
 
 
 
 
 
 
 
 
e49e7e7
6f1dbe9
 
 
 
 
 
 
 
 
 
 
 
6852d71
6f1dbe9
e49e7e7
 
 
6f1dbe9
 
 
 
 
 
6852d71
 
6f1dbe9
 
 
 
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import os
from typing import Optional, Tuple
import gradio as gr
from langchain_community.document_loaders import PyPDFLoader, DirectoryLoader
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, AutoModelForSeq2SeqLM, pipeline
import torch
import tempfile
import time

# Configurações
EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
LLM_MODEL = "google/flan-t5-large"
DOCS_DIR = "documents"

class RAGSystem:
    def __init__(self):
        self.tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL)
        self.model = AutoModelForSeq2SeqLM.from_pretrained(
            LLM_MODEL,
            device_map="auto",
            torch_dtype=torch.float32
        )
        
        pipe = pipeline(
            "text2text-generation",
            model=self.model,
            tokenizer=self.tokenizer,
            max_length=512,
            temperature=0.7,
            top_p=0.95
        )
        
        self.llm = HuggingFacePipeline(pipeline=pipe)
        self.embeddings = HuggingFaceEmbeddings(
            model_name=EMBEDDING_MODEL,
            model_kwargs={'device': 'cpu'}
        )
        self.base_db = self.load_base_knowledge()

    def load_base_knowledge(self) -> Optional[FAISS]:
        try:
            if not os.path.exists(DOCS_DIR):
                os.makedirs(DOCS_DIR)
                return None

            loader = DirectoryLoader(
                DOCS_DIR,
                glob="**/*.pdf",
                loader_cls=PyPDFLoader
            )
            documents = loader.load()
            
            if not documents:
                return None
            
            text_splitter = RecursiveCharacterTextSplitter(
                chunk_size=500,
                chunk_overlap=100,
                length_function=len,
                separators=["\n\n", "\n", ".", " ", ""]
            )
            texts = text_splitter.split_documents(documents)
            
            return FAISS.from_documents(texts, self.embeddings)
            
        except Exception as e:
            print(f"Erro ao carregar base de conhecimento: {str(e)}")
            return None

    def process_pdf(self, file_content: bytes) -> Optional[FAISS]:
        try:
            with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
                tmp_file.write(file_content)
                tmp_path = tmp_file.name

            loader = PyPDFLoader(tmp_path)
            documents = loader.load()
            os.unlink(tmp_path)
            
            if not documents:
                return None
            
            text_splitter = RecursiveCharacterTextSplitter(
                chunk_size=500,
                chunk_overlap=100,
                length_function=len,
                separators=["\n\n", "\n", ".", " ", ""]
            )
            texts = text_splitter.split_documents(documents)
            
            db = FAISS.from_documents(texts, self.embeddings)
            
            if self.base_db is not None:
                db.merge_from(self.base_db)
            
            return db
            
        except Exception as e:
            print(f"Erro ao processar PDF: {str(e)}")
            return None

    def generate_response(self, file_obj, query: str, progress=gr.Progress()) -> Tuple[str, str, str]:
        """Retorna (resposta, status, tempo_decorrido)"""
        if not query.strip():
            return "Por favor, insira uma pergunta.", "⚠️ Aguardando pergunta", "0s"
        
        start_time = time.time()
        try:
            progress(0, desc="Iniciando processamento...")
            
            # Processa documento
            progress(0.2, desc="Processando documento...")
            if file_obj is not None:
                db = self.process_pdf(file_obj)
                if db is None:
                    return "Não foi possível processar o PDF.", "❌ Erro no processamento", "0s"
            elif self.base_db is not None:
                db = self.base_db
            else:
                return "Nenhuma base de conhecimento disponível.", "❌ Sem documentos", "0s"
            
            progress(0.4, desc="Buscando informações relevantes...")
            qa_chain = RetrievalQA.from_chain_type(
                llm=self.llm,
                chain_type="stuff",
                retriever=db.as_retriever(
                    search_kwargs={"k": 4, "fetch_k": 6}
                ),
                return_source_documents=True
            )
            
            progress(0.6, desc="Gerando resposta...")
            prompt = f"""Baseado nos documentos fornecidos, responda em português à seguinte pergunta:
            {query}
            
            Se a resposta vier da base de documentos permanente, indique isso no início.
            Se a resposta vier do PDF enviado, indique isso no início.
            Se não encontrar informações suficientes, indique isso claramente."""
            
            result = qa_chain({"query": prompt})
            elapsed_time = f"{time.time() - start_time:.1f}s"
            
            progress(1.0, desc="Concluído!")
            return result["result"], "✅ Sucesso", elapsed_time
            
        except Exception as e:
            elapsed_time = f"{time.time() - start_time:.1f}s"
            return f"Erro ao gerar resposta: {str(e)}", "❌ Erro", elapsed_time

def create_demo():
    rag = RAGSystem()
    
    with gr.Blocks(theme=gr.themes.Soft()) as demo:
        with gr.Column(elem_id="container"):
            # Cabeçalho
            gr.Markdown(
                """
                # 🤖 Assistente de Documentos Inteligente
                
                Este sistema usa tecnologia RAG (Retrieval-Augmented Generation) para responder perguntas sobre seus documentos.
                """
            )
            
            # Área principal
            with gr.Row():
                # Coluna de entrada
                with gr.Column():
                    with gr.Group():
                        gr.Markdown("### 📄 Documentos")
                        file_input = gr.File(
                            label="Upload de PDF (opcional)",
                            type="binary",
                            file_types=[".pdf"],
                            height=100,
                        )
                        info = gr.Markdown(
                            f"""
                            ℹ️ Além do upload, o sistema também consulta a pasta `{DOCS_DIR}`
                            """
                        )
                    
                    with gr.Group():
                        gr.Markdown("### ❓ Sua Pergunta")
                        query_input = gr.Textbox(
                            placeholder="Digite sua pergunta aqui...",
                            lines=3,
                            max_lines=6,
                            show_label=False,
                        )
                    
                    with gr.Row():
                        clear_btn = gr.Button("🗑️ Limpar", variant="secondary")
                        submit_btn = gr.Button("🔍 Enviar Pergunta", variant="primary")
                
                # Coluna de saída
                with gr.Column():
                    with gr.Group():
                        gr.Markdown("### 📝 Resposta")
                        with gr.Row():
                            status_output = gr.Textbox(
                                label="Status",
                                value="⏳ Aguardando...",
                                interactive=False,
                                show_label=False,
                            )
                            time_output = gr.Textbox(
                                label="Tempo",
                                value="0s",
                                interactive=False,
                                show_label=False,
                            )
                        
                        response_output = gr.Textbox(
                            label="Resposta",
                            placeholder="A resposta aparecerá aqui...",
                            interactive=False,
                            lines=12,
                            show_label=False,
                        )
            
            # Exemplos
            with gr.Accordion("📚 Exemplos de Perguntas", open=False):
                gr.Examples(
                    examples=[
                        [None, "Qual é o tema principal dos documentos?"],
                        [None, "Pode resumir os pontos principais?"],
                        [None, "Quais são as principais conclusões?"],
                        [None, "Explique o contexto deste documento."],
                    ],
                    inputs=[file_input, query_input],
                )
            
            # Rodapé
            gr.Markdown(
                """
                ---
                ### 🔧 Sobre o Sistema
                * Usa modelo T5 para geração de respostas
                * Processamento de documentos com tecnologia RAG
                * Suporte a múltiplos documentos PDF
                * Respostas baseadas apenas no conteúdo dos documentos
                """
            )
        
        # Eventos
        submit_btn.click(
            fn=rag.generate_response,
            inputs=[file_input, query_input],
            outputs=[response_output, status_output, time_output],
        )
        
        clear_btn.click(
            lambda: (None, "", "⏳ Aguardando...", "0s"),
            outputs=[file_input, query_input, status_output, time_output],
        )
        
        # Limpa a resposta quando a pergunta muda
        query_input.change(
            lambda: ("", "⏳ Aguardando...", "0s"),
            outputs=[response_output, status_output, time_output],
        )
    
    return demo

if __name__ == "__main__":
    demo = create_demo()
    demo.launch()