Spaces:
Sleeping
Sleeping
aplicaçao chatbot
Browse files- .gitattributes +1 -0
- BitDogLab_info_v2.pdf +3 -0
- Dockerfile +27 -0
- app.py +123 -0
- corretor.py +58 -0
- requirements.txt +21 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
BitDogLab_info_v2.pdf filter=lfs diff=lfs merge=lfs -text
|
BitDogLab_info_v2.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:813016ff8ba8e14d8d9743864e0a031dbb3b8d829fe96ea655ae17ce2120c835
|
| 3 |
+
size 4055561
|
Dockerfile
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Imagem base com Python
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Evita prompts interativos
|
| 5 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 6 |
+
|
| 7 |
+
# Atualiza sistema e instala dependências do chromadb (compilador C)
|
| 8 |
+
RUN apt-get update && apt-get install -y \
|
| 9 |
+
build-essential \
|
| 10 |
+
python3-dev \
|
| 11 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 12 |
+
|
| 13 |
+
# Cria diretório da aplicação
|
| 14 |
+
WORKDIR /app
|
| 15 |
+
|
| 16 |
+
# Copia os arquivos
|
| 17 |
+
COPY requirements.txt .
|
| 18 |
+
RUN pip install --upgrade pip
|
| 19 |
+
RUN pip install -r requirements.txt
|
| 20 |
+
|
| 21 |
+
COPY . .
|
| 22 |
+
|
| 23 |
+
# Expõe a porta padrão do Gradio
|
| 24 |
+
EXPOSE 7860
|
| 25 |
+
|
| 26 |
+
# Comando para iniciar a aplicação (ajuste conforme seu script)
|
| 27 |
+
CMD ["python", "app.py"]
|
app.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from typing import List
|
| 4 |
+
from llama_index.core import SimpleDirectoryReader, StorageContext, VectorStoreIndex
|
| 5 |
+
from llama_index.core.node_parser import SentenceSplitter
|
| 6 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 7 |
+
from llama_index.vector_stores.chroma import ChromaVectorStore
|
| 8 |
+
from llama_index.llms.groq import Groq
|
| 9 |
+
from llama_index.core.memory import ChatSummaryMemoryBuffer
|
| 10 |
+
import chromadb
|
| 11 |
+
from tempfile import TemporaryDirectory
|
| 12 |
+
from PyPDF2 import PdfReader
|
| 13 |
+
from corretor import corrigir_texto # <<< Correção importada aqui
|
| 14 |
+
|
| 15 |
+
# Wrapper de embedding compatível com ChromaDB
|
| 16 |
+
class ChromaEmbeddingWrapper:
|
| 17 |
+
def __init__(self, model_name: str):
|
| 18 |
+
self.model = HuggingFaceEmbedding(model_name=model_name)
|
| 19 |
+
|
| 20 |
+
def __call__(self, input: List[str]) -> List[List[float]]:
|
| 21 |
+
return self.model.embed_documents(input)
|
| 22 |
+
|
| 23 |
+
# Inicializa modelos de embedding
|
| 24 |
+
embed_model = HuggingFaceEmbedding(model_name='intfloat/multilingual-e5-large')
|
| 25 |
+
embed_model_chroma = ChromaEmbeddingWrapper(model_name='intfloat/multilingual-e5-large')
|
| 26 |
+
|
| 27 |
+
# Inicializa ChromaDB
|
| 28 |
+
chroma_client = chromadb.PersistentClient(path='./chroma_db')
|
| 29 |
+
collection_name = 'documentos_bitdoglab'
|
| 30 |
+
chroma_collection = chroma_client.get_or_create_collection(
|
| 31 |
+
name=collection_name,
|
| 32 |
+
embedding_function=embed_model_chroma
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
|
| 36 |
+
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
| 37 |
+
|
| 38 |
+
# Inicializa LLM da Groq
|
| 39 |
+
Groq_api = os.environ.get("GROQ_API_KEY")
|
| 40 |
+
llms = Groq(model='llama3-70b-8192', api_key=Groq_api or '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')
|
| 41 |
+
|
| 42 |
+
# Estados globais
|
| 43 |
+
document_index = None
|
| 44 |
+
chat_engine = None
|
| 45 |
+
|
| 46 |
+
# Carregamento único do PDF
|
| 47 |
+
def carregar_pdf_inicial():
|
| 48 |
+
global document_index, chat_engine
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
with TemporaryDirectory() as tmpdir:
|
| 52 |
+
pdf_path = "BitDogLab_info_v2.pdf"
|
| 53 |
+
text = ""
|
| 54 |
+
reader = PdfReader(pdf_path)
|
| 55 |
+
for page in reader.pages:
|
| 56 |
+
text += page.extract_text() or ""
|
| 57 |
+
|
| 58 |
+
with open(os.path.join(tmpdir, "temp.txt"), "w", encoding="utf-8") as f:
|
| 59 |
+
f.write(text)
|
| 60 |
+
|
| 61 |
+
documentos = SimpleDirectoryReader(input_dir=tmpdir)
|
| 62 |
+
docs = documentos.load_data()
|
| 63 |
+
|
| 64 |
+
node_parser = SentenceSplitter(chunk_size=1200,chunk_overlap=150)
|
| 65 |
+
nodes = node_parser.get_nodes_from_documents(docs, show_progress=True)
|
| 66 |
+
|
| 67 |
+
document_index = VectorStoreIndex(nodes, storage_context=storage_context, embed_model=embed_model)
|
| 68 |
+
|
| 69 |
+
memory = ChatSummaryMemoryBuffer(llm=llms, token_limit=256)
|
| 70 |
+
|
| 71 |
+
chat_engine = document_index.as_chat_engine(
|
| 72 |
+
chat_mode='context',
|
| 73 |
+
llm=llms,
|
| 74 |
+
memory=memory,
|
| 75 |
+
system_prompt='''Você é especialista na placa BitDog Lab e sua função é ajudar os usuários nas dúvidas e informações sobre a placa e como criar códigos.'''
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
print("PDF carregado com sucesso.")
|
| 79 |
+
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"Erro ao carregar PDF: {e}")
|
| 82 |
+
|
| 83 |
+
# Função de chat com correção de texto
|
| 84 |
+
def converse_com_bot(message, chat_history):
|
| 85 |
+
global chat_engine
|
| 86 |
+
|
| 87 |
+
if chat_engine is None:
|
| 88 |
+
return "Erro: o bot ainda não está pronto.", chat_history
|
| 89 |
+
|
| 90 |
+
response = chat_engine.chat(message)
|
| 91 |
+
resposta_corrigida = corrigir_texto(response.response) # <<< Aplica correção
|
| 92 |
+
|
| 93 |
+
if chat_history is None:
|
| 94 |
+
chat_history = []
|
| 95 |
+
|
| 96 |
+
chat_history.append({"role": "user", "content": message})
|
| 97 |
+
chat_history.append({"role": "assistant", "content": resposta_corrigida})
|
| 98 |
+
|
| 99 |
+
return "", chat_history
|
| 100 |
+
|
| 101 |
+
# Resetar conversa
|
| 102 |
+
def resetar_chat():
|
| 103 |
+
global chat_engine
|
| 104 |
+
if chat_engine:
|
| 105 |
+
chat_engine.reset()
|
| 106 |
+
return []
|
| 107 |
+
|
| 108 |
+
# Carregar PDF na inicialização
|
| 109 |
+
carregar_pdf_inicial()
|
| 110 |
+
|
| 111 |
+
# Interface Gradio
|
| 112 |
+
with gr.Blocks() as app:
|
| 113 |
+
gr.Markdown("# 🤖 Chatbot BitDog Lab - Seu assistente para esclarecer dúvidas")
|
| 114 |
+
|
| 115 |
+
chatbot = gr.Chatbot(label="Conversa", type="messages")
|
| 116 |
+
msg = gr.Textbox(label='Digite a sua mensagem')
|
| 117 |
+
limpar = gr.Button('Limpar')
|
| 118 |
+
|
| 119 |
+
msg.submit(converse_com_bot, [msg, chatbot], [msg, chatbot])
|
| 120 |
+
limpar.click(resetar_chat, None, chatbot, queue=False)
|
| 121 |
+
|
| 122 |
+
#app.launch()
|
| 123 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|
corretor.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# corretor.py
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
import unicodedata
|
| 5 |
+
|
| 6 |
+
# Dicionário com erros comuns
|
| 7 |
+
erros_comuns = {
|
| 8 |
+
"repexções": "repetições",
|
| 9 |
+
"repeções": "repetições",
|
| 10 |
+
"repitições": "repetições",
|
| 11 |
+
"repeçoes": "repetições",
|
| 12 |
+
"repiticões": "repetições",
|
| 13 |
+
"algorítmo": "algoritmo",
|
| 14 |
+
"algorimo": "algoritmo",
|
| 15 |
+
"negeção": "negação",
|
| 16 |
+
"conjunsão": "conjunção",
|
| 17 |
+
"disjunsão": "disjunção",
|
| 18 |
+
"logíca": "lógica",
|
| 19 |
+
"logica": "lógica",
|
| 20 |
+
"computácional": "computacional",
|
| 21 |
+
"computácionais": "computacionais",
|
| 22 |
+
"Repexções": "Repetições",
|
| 23 |
+
"algorítimo": "algoritmo",
|
| 24 |
+
"inteligëncia": "inteligência",
|
| 25 |
+
"inteligêcia": "inteligência",
|
| 26 |
+
"proçesso": "processo",
|
| 27 |
+
"conhecimento prévio": "conhecimento pré-existente",
|
| 28 |
+
"machine learn": "machine learning",
|
| 29 |
+
"aprendizagem de maquina": "aprendizado de máquina",
|
| 30 |
+
"treinamemto": "treinamento",
|
| 31 |
+
"resposta esperda": "resposta esperada",
|
| 32 |
+
"parâmetors": "parâmetros",
|
| 33 |
+
"varíavel": "variável",
|
| 34 |
+
"entrada e sáida": "entrada e saída",
|
| 35 |
+
"expecificação": "especificação",
|
| 36 |
+
"funcionalidae": "funcionalidade",
|
| 37 |
+
"platafoma": "plataforma",
|
| 38 |
+
"dadoos": "dados",
|
| 39 |
+
"códigoo": "código",
|
| 40 |
+
"apredizado": "aprendizado",
|
| 41 |
+
"funcinamento": "funcionamento",
|
| 42 |
+
"reconhencimento": "reconhecimento",
|
| 43 |
+
"desempenhho": "desempenho",
|
| 44 |
+
"classificaçao": "classificação",
|
| 45 |
+
"interpetar": "interpretar",
|
| 46 |
+
"devem ser treinados com base nos dados": "devem ser treinados com base em dados",
|
| 47 |
+
"idenxicar": "identificar",
|
| 48 |
+
"inicialixado": "inicializado",
|
| 49 |
+
"funxão": "função",
|
| 50 |
+
"operaçõx": "operações",
|
| 51 |
+
"bitdog lab": "BitDog Lab",
|
| 52 |
+
"Bitdog Lab": "BitDog Lab",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
def corrigir_texto(texto: str) -> str:
|
| 56 |
+
for erro, correcao in erros_comuns.items():
|
| 57 |
+
texto = re.sub(rf"\b{erro}\b", correcao, texto, flags=re.IGNORECASE)
|
| 58 |
+
return texto
|
requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Criar o arquivo requirements no Space do Hugging Face e colar as bibliotecas
|
| 2 |
+
# Biblioteca base do LlamaIndex
|
| 3 |
+
llama-index
|
| 4 |
+
|
| 5 |
+
# Integração com embeddings do Hugging Face
|
| 6 |
+
llama-index-embeddings-huggingface
|
| 7 |
+
|
| 8 |
+
# Integração com Chroma como vetor store
|
| 9 |
+
llama-index-vector-stores-chroma
|
| 10 |
+
|
| 11 |
+
# LLM Groq (LLaMA 3)
|
| 12 |
+
llama-index-llms-groq
|
| 13 |
+
|
| 14 |
+
# Banco vetorial local
|
| 15 |
+
chromadb
|
| 16 |
+
|
| 17 |
+
# Interface gráfica
|
| 18 |
+
gradio
|
| 19 |
+
|
| 20 |
+
# Manipulação de PDFs
|
| 21 |
+
PyPDF2
|