Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -7,41 +7,41 @@ from langchain_community.embeddings import HuggingFaceEmbeddings
|
|
7 |
from langchain_community.vectorstores import FAISS
|
8 |
from langchain_community.llms import HuggingFacePipeline
|
9 |
from langchain.chains import RetrievalQA
|
10 |
-
from transformers import AutoTokenizer,
|
11 |
import torch
|
12 |
import tempfile
|
13 |
|
14 |
# Configurações
|
15 |
EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
16 |
-
LLM_MODEL = "
|
17 |
-
DOCS_DIR = "
|
18 |
|
19 |
class RAGSystem:
|
20 |
def __init__(self):
|
21 |
# Inicializa o modelo de linguagem
|
|
|
22 |
self.tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL)
|
23 |
-
self.model =
|
24 |
LLM_MODEL,
|
25 |
-
torch_dtype=torch.float16,
|
26 |
device_map="auto",
|
27 |
-
|
28 |
)
|
29 |
|
30 |
# Configura o pipeline
|
31 |
pipe = pipeline(
|
32 |
-
"
|
33 |
model=self.model,
|
34 |
tokenizer=self.tokenizer,
|
35 |
-
max_length=
|
36 |
temperature=0.7,
|
37 |
-
top_p=0.95
|
38 |
-
repetition_penalty=1.15
|
39 |
)
|
40 |
|
41 |
# Configura o modelo LangChain
|
42 |
self.llm = HuggingFacePipeline(pipeline=pipe)
|
43 |
|
44 |
# Configura embeddings
|
|
|
45 |
self.embeddings = HuggingFaceEmbeddings(
|
46 |
model_name=EMBEDDING_MODEL,
|
47 |
model_kwargs={'device': 'cpu'}
|
@@ -72,8 +72,8 @@ class RAGSystem:
|
|
72 |
|
73 |
# Divide o texto em chunks
|
74 |
text_splitter = RecursiveCharacterTextSplitter(
|
75 |
-
chunk_size=
|
76 |
-
chunk_overlap=
|
77 |
length_function=len,
|
78 |
separators=["\n\n", "\n", ".", " ", ""]
|
79 |
)
|
@@ -108,8 +108,8 @@ class RAGSystem:
|
|
108 |
|
109 |
# Divide o texto em chunks
|
110 |
text_splitter = RecursiveCharacterTextSplitter(
|
111 |
-
chunk_size=
|
112 |
-
chunk_overlap=
|
113 |
length_function=len,
|
114 |
separators=["\n\n", "\n", ".", " ", ""]
|
115 |
)
|
@@ -151,19 +151,19 @@ class RAGSystem:
|
|
151 |
chain_type="stuff",
|
152 |
retriever=db.as_retriever(
|
153 |
search_kwargs={
|
154 |
-
"k":
|
155 |
-
"fetch_k":
|
156 |
}
|
157 |
),
|
158 |
return_source_documents=True
|
159 |
)
|
160 |
|
161 |
# Adiciona contexto sobre a fonte da resposta
|
162 |
-
prompt = f"""
|
163 |
{query}
|
164 |
|
165 |
-
Se a resposta vier da base de documentos permanente, indique isso no início
|
166 |
-
Se a resposta vier do PDF enviado
|
167 |
Se não encontrar informações suficientes, indique isso claramente."""
|
168 |
|
169 |
# Gera resposta
|
@@ -178,12 +178,13 @@ def create_demo():
|
|
178 |
rag = RAGSystem()
|
179 |
|
180 |
with gr.Blocks() as demo:
|
181 |
-
gr.Markdown("# 📚 Sistema RAG
|
182 |
gr.Markdown(f"""
|
183 |
-
###
|
184 |
-
1. Os documentos da pasta `{DOCS_DIR}` são usados como base de conhecimento
|
185 |
2. Você pode fazer upload de PDFs adicionais para consulta
|
186 |
-
3.
|
|
|
187 |
""")
|
188 |
|
189 |
with gr.Row():
|
@@ -198,7 +199,7 @@ def create_demo():
|
|
198 |
placeholder="Digite sua pergunta sobre o documento...",
|
199 |
lines=3
|
200 |
)
|
201 |
-
submit_btn = gr.Button("🔍
|
202 |
|
203 |
with gr.Column(scale=1):
|
204 |
output = gr.Textbox(
|
|
|
7 |
from langchain_community.vectorstores import FAISS
|
8 |
from langchain_community.llms import HuggingFacePipeline
|
9 |
from langchain.chains import RetrievalQA
|
10 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
11 |
import torch
|
12 |
import tempfile
|
13 |
|
14 |
# Configurações
|
15 |
EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
16 |
+
LLM_MODEL = "google/flan-t5-large" # Modelo aberto e sem necessidade de autenticação
|
17 |
+
DOCS_DIR = "documentos"
|
18 |
|
19 |
class RAGSystem:
|
20 |
def __init__(self):
|
21 |
# Inicializa o modelo de linguagem
|
22 |
+
print("Carregando modelo de linguagem...")
|
23 |
self.tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL)
|
24 |
+
self.model = AutoModelForSeq2SeqLM.from_pretrained(
|
25 |
LLM_MODEL,
|
|
|
26 |
device_map="auto",
|
27 |
+
torch_dtype=torch.float32 # T5 funciona bem com float32
|
28 |
)
|
29 |
|
30 |
# Configura o pipeline
|
31 |
pipe = pipeline(
|
32 |
+
"text2text-generation",
|
33 |
model=self.model,
|
34 |
tokenizer=self.tokenizer,
|
35 |
+
max_length=512,
|
36 |
temperature=0.7,
|
37 |
+
top_p=0.95
|
|
|
38 |
)
|
39 |
|
40 |
# Configura o modelo LangChain
|
41 |
self.llm = HuggingFacePipeline(pipeline=pipe)
|
42 |
|
43 |
# Configura embeddings
|
44 |
+
print("Configurando embeddings...")
|
45 |
self.embeddings = HuggingFaceEmbeddings(
|
46 |
model_name=EMBEDDING_MODEL,
|
47 |
model_kwargs={'device': 'cpu'}
|
|
|
72 |
|
73 |
# Divide o texto em chunks
|
74 |
text_splitter = RecursiveCharacterTextSplitter(
|
75 |
+
chunk_size=500, # Chunks menores para o T5
|
76 |
+
chunk_overlap=100,
|
77 |
length_function=len,
|
78 |
separators=["\n\n", "\n", ".", " ", ""]
|
79 |
)
|
|
|
108 |
|
109 |
# Divide o texto em chunks
|
110 |
text_splitter = RecursiveCharacterTextSplitter(
|
111 |
+
chunk_size=500,
|
112 |
+
chunk_overlap=100,
|
113 |
length_function=len,
|
114 |
separators=["\n\n", "\n", ".", " ", ""]
|
115 |
)
|
|
|
151 |
chain_type="stuff",
|
152 |
retriever=db.as_retriever(
|
153 |
search_kwargs={
|
154 |
+
"k": 4, # Aumentamos o k para ter mais contexto
|
155 |
+
"fetch_k": 6
|
156 |
}
|
157 |
),
|
158 |
return_source_documents=True
|
159 |
)
|
160 |
|
161 |
# Adiciona contexto sobre a fonte da resposta
|
162 |
+
prompt = f"""Baseado nos documentos fornecidos, responda em português à seguinte pergunta:
|
163 |
{query}
|
164 |
|
165 |
+
Se a resposta vier da base de documentos permanente, indique isso no início.
|
166 |
+
Se a resposta vier do PDF enviado, indique isso no início.
|
167 |
Se não encontrar informações suficientes, indique isso claramente."""
|
168 |
|
169 |
# Gera resposta
|
|
|
178 |
rag = RAGSystem()
|
179 |
|
180 |
with gr.Blocks() as demo:
|
181 |
+
gr.Markdown("# 📚 Sistema RAG de Consulta a Documentos")
|
182 |
gr.Markdown(f"""
|
183 |
+
### Como usar:
|
184 |
+
1. Os documentos da pasta `{DOCS_DIR}` são usados como base de conhecimento
|
185 |
2. Você pode fazer upload de PDFs adicionais para consulta
|
186 |
+
3. Digite sua pergunta e aguarde a resposta
|
187 |
+
4. As respostas são baseadas no conteúdo dos documentos
|
188 |
""")
|
189 |
|
190 |
with gr.Row():
|
|
|
199 |
placeholder="Digite sua pergunta sobre o documento...",
|
200 |
lines=3
|
201 |
)
|
202 |
+
submit_btn = gr.Button("🔍 Buscar Resposta", variant="primary")
|
203 |
|
204 |
with gr.Column(scale=1):
|
205 |
output = gr.Textbox(
|