Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,14 +9,13 @@ from groq import Groq
|
|
| 9 |
|
| 10 |
# --- IMPORTS LANGCHAIN / RAG ---
|
| 11 |
from langchain_community.document_loaders import TextLoader
|
| 12 |
-
from langchain_community.document_loaders import PyPDFLoader
|
| 13 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 14 |
from langchain_huggingface import HuggingFaceEmbeddings # Embeddings que rodam na CPU
|
| 15 |
from langchain_community.vectorstores import FAISS
|
| 16 |
from langchain.chains import RetrievalQA
|
| 17 |
from langchain_groq import ChatGroq
|
| 18 |
-
#
|
| 19 |
-
# mas o HuggingFaceEmbeddings é local/gratuito.
|
| 20 |
|
| 21 |
# 1. Título da Página e Configuração de Layout
|
| 22 |
st.set_page_config(page_title="Iza - Assistente Groq RAG", layout="wide")
|
|
@@ -79,28 +78,32 @@ groq_llm = ChatGroq(model_name="mixtral-8x7b-32768", temperature=0.7)
|
|
| 79 |
with st.sidebar:
|
| 80 |
st.header("Opções")
|
| 81 |
|
| 82 |
-
#
|
| 83 |
if 'retriever' not in st.session_state:
|
| 84 |
st.session_state.retriever = None
|
| 85 |
st.session_state.retriever_source = None
|
| 86 |
|
| 87 |
-
uploaded_file = st.file_uploader(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
# Processamento do Arquivo
|
| 90 |
if uploaded_file:
|
| 91 |
-
# Apenas processa se o arquivo for novo
|
| 92 |
if st.session_state.retriever_source != uploaded_file.name:
|
| 93 |
|
| 94 |
-
# 1. SALVAR/LER ARQUIVO TEMPORARIAMENTE
|
| 95 |
-
bytes_data = uploaded_file.read()
|
| 96 |
-
# Cria um caminho de arquivo temporário (importa o 'os' para remover depois, se necessário)
|
| 97 |
file_path = f"./temp_file_{uploaded_file.name.replace('/', '_')}"
|
|
|
|
| 98 |
try:
|
|
|
|
|
|
|
| 99 |
with open(file_path, "wb") as f:
|
| 100 |
f.write(bytes_data)
|
| 101 |
|
| 102 |
-
# 2. CONFIGURAÇÃO RAG
|
| 103 |
-
with st.spinner(f"Processando '{uploaded_file.name}'
|
| 104 |
|
| 105 |
# Carregamento do Documento
|
| 106 |
if uploaded_file.type == 'application/pdf':
|
|
@@ -108,42 +111,42 @@ with st.sidebar:
|
|
| 108 |
elif uploaded_file.type in ['text/markdown', 'text/plain']:
|
| 109 |
loader = TextLoader(file_path)
|
| 110 |
else:
|
| 111 |
-
|
| 112 |
-
st.session_state.retriever = None
|
| 113 |
-
st.session_state.retriever_source = None
|
| 114 |
|
| 115 |
documents = loader.load()
|
| 116 |
-
|
| 117 |
-
# Fragmentação do Texto
|
| 118 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 119 |
texts = text_splitter.split_documents(documents)
|
| 120 |
|
| 121 |
# HuggingFace Embeddings (Roda na CPU)
|
| 122 |
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 123 |
-
|
| 124 |
-
# Criar o Vector Store (FAISS)
|
| 125 |
vectorstore = FAISS.from_documents(texts, embeddings)
|
| 126 |
|
| 127 |
-
#
|
| 128 |
st.session_state.retriever = vectorstore.as_retriever()
|
| 129 |
st.session_state.retriever_source = uploaded_file.name
|
| 130 |
-
st.success(f"Arquivo '{uploaded_file.name}' processado
|
| 131 |
|
| 132 |
except Exception as e:
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
st.session_state.retriever = None
|
| 135 |
st.session_state.retriever_source = None
|
| 136 |
finally:
|
| 137 |
-
#
|
| 138 |
if os.path.exists(file_path):
|
| 139 |
os.remove(file_path)
|
| 140 |
|
| 141 |
else:
|
| 142 |
-
# Se o arquivo já foi processado
|
| 143 |
-
st.
|
| 144 |
|
| 145 |
elif st.session_state.retriever_source is not None:
|
| 146 |
-
# Limpa se o
|
|
|
|
| 147 |
st.session_state.retriever = None
|
| 148 |
st.session_state.retriever_source = None
|
| 149 |
|
|
@@ -185,10 +188,10 @@ if prompt := st.chat_input("Pergunte algo sobre o documento ou faça uma pesquis
|
|
| 185 |
llm=groq_llm,
|
| 186 |
chain_type="stuff",
|
| 187 |
retriever=st.session_state.retriever,
|
| 188 |
-
return_source_documents=False
|
| 189 |
)
|
| 190 |
|
| 191 |
-
# OBS: A resposta RAG
|
| 192 |
with st.spinner("Buscando no documento e gerando resposta..."):
|
| 193 |
result = qa_chain.invoke({"query": prompt})
|
| 194 |
full_response = result['result']
|
|
|
|
| 9 |
|
| 10 |
# --- IMPORTS LANGCHAIN / RAG ---
|
| 11 |
from langchain_community.document_loaders import TextLoader
|
| 12 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 13 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 14 |
from langchain_huggingface import HuggingFaceEmbeddings # Embeddings que rodam na CPU
|
| 15 |
from langchain_community.vectorstores import FAISS
|
| 16 |
from langchain.chains import RetrievalQA
|
| 17 |
from langchain_groq import ChatGroq
|
| 18 |
+
# --------------------------
|
|
|
|
| 19 |
|
| 20 |
# 1. Título da Página e Configuração de Layout
|
| 21 |
st.set_page_config(page_title="Iza - Assistente Groq RAG", layout="wide")
|
|
|
|
| 78 |
with st.sidebar:
|
| 79 |
st.header("Opções")
|
| 80 |
|
| 81 |
+
# Inicializa variáveis de sessão para RAG
|
| 82 |
if 'retriever' not in st.session_state:
|
| 83 |
st.session_state.retriever = None
|
| 84 |
st.session_state.retriever_source = None
|
| 85 |
|
| 86 |
+
uploaded_file = st.file_uploader(
|
| 87 |
+
"Anexe um arquivo para pesquisa RAG (opcional)",
|
| 88 |
+
type=["txt", "md", "pdf"],
|
| 89 |
+
help="O arquivo será processado e a IA poderá responder perguntas sobre seu conteúdo."
|
| 90 |
+
)
|
| 91 |
|
| 92 |
+
# Lógica de Processamento do Arquivo
|
| 93 |
if uploaded_file:
|
| 94 |
+
# Apenas processa se o arquivo for novo
|
| 95 |
if st.session_state.retriever_source != uploaded_file.name:
|
| 96 |
|
|
|
|
|
|
|
|
|
|
| 97 |
file_path = f"./temp_file_{uploaded_file.name.replace('/', '_')}"
|
| 98 |
+
|
| 99 |
try:
|
| 100 |
+
# 1. SALVAR/LER ARQUIVO TEMPORARIAMENTE
|
| 101 |
+
bytes_data = uploaded_file.read()
|
| 102 |
with open(file_path, "wb") as f:
|
| 103 |
f.write(bytes_data)
|
| 104 |
|
| 105 |
+
# 2. CONFIGURAÇÃO RAG (Processo de Embedding)
|
| 106 |
+
with st.spinner(f"Processando '{uploaded_file.name}' com LangChain e HuggingFace Embeddings (CPU)..."):
|
| 107 |
|
| 108 |
# Carregamento do Documento
|
| 109 |
if uploaded_file.type == 'application/pdf':
|
|
|
|
| 111 |
elif uploaded_file.type in ['text/markdown', 'text/plain']:
|
| 112 |
loader = TextLoader(file_path)
|
| 113 |
else:
|
| 114 |
+
raise ValueError("Tipo de arquivo não suportado após o upload.")
|
|
|
|
|
|
|
| 115 |
|
| 116 |
documents = loader.load()
|
|
|
|
|
|
|
| 117 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 118 |
texts = text_splitter.split_documents(documents)
|
| 119 |
|
| 120 |
# HuggingFace Embeddings (Roda na CPU)
|
| 121 |
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
|
|
|
|
|
|
| 122 |
vectorstore = FAISS.from_documents(texts, embeddings)
|
| 123 |
|
| 124 |
+
# Armazenar na sessão
|
| 125 |
st.session_state.retriever = vectorstore.as_retriever()
|
| 126 |
st.session_state.retriever_source = uploaded_file.name
|
| 127 |
+
st.success(f"Arquivo '{uploaded_file.name}' processado! Pergunte sobre ele.")
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
+
# Tratamento de erro 403 e outros
|
| 131 |
+
if "403" in str(e):
|
| 132 |
+
st.error("Erro no upload (403 Forbidden). O servidor está rejeitando a requisição. Tente com um arquivo menor ou execute localmente.")
|
| 133 |
+
else:
|
| 134 |
+
st.error(f"Erro ao processar o arquivo com LangChain: {e}")
|
| 135 |
+
|
| 136 |
st.session_state.retriever = None
|
| 137 |
st.session_state.retriever_source = None
|
| 138 |
finally:
|
| 139 |
+
# Garante que o arquivo temporário seja removido
|
| 140 |
if os.path.exists(file_path):
|
| 141 |
os.remove(file_path)
|
| 142 |
|
| 143 |
else:
|
| 144 |
+
# Se o arquivo já foi processado
|
| 145 |
+
st.info(f"O arquivo '{st.session_state.retriever_source}' já foi processado e está ativo.")
|
| 146 |
|
| 147 |
elif st.session_state.retriever_source is not None:
|
| 148 |
+
# Limpa se o uploader foi esvaziado, mas o retriever estava ativo
|
| 149 |
+
st.warning("O arquivo processado foi removido. A IA voltará a usar pesquisa web.")
|
| 150 |
st.session_state.retriever = None
|
| 151 |
st.session_state.retriever_source = None
|
| 152 |
|
|
|
|
| 188 |
llm=groq_llm,
|
| 189 |
chain_type="stuff",
|
| 190 |
retriever=st.session_state.retriever,
|
| 191 |
+
return_source_documents=False
|
| 192 |
)
|
| 193 |
|
| 194 |
+
# OBS: A resposta RAG vem completa (sem streaming simples)
|
| 195 |
with st.spinner("Buscando no documento e gerando resposta..."):
|
| 196 |
result = qa_chain.invoke({"query": prompt})
|
| 197 |
full_response = result['result']
|