Download scripts/chat_rag.py from aionaion/chatdoc: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/spaces/aionaion/chatdoc/resolve/main/scripts/chat_rag.py
- Command line
-
hf download hf://spaces/aionaion/chatdoc/scripts/chat_rag.py
-
curl -L -o chat_rag.py https://huggingface.co/spaces/aionaion/chatdoc/resolve/main/scripts/chat_rag.py
11.1 kB
| #!/usr/bin/env python3 | |
| """ | |
| Chat interativo local para testar o RAG | |
| """ | |
| import sys | |
| import time | |
| from pathlib import Path | |
| from typing import List, Dict, Any | |
| import argparse | |
| import logging | |
| import warnings | |
| # Feedback visual imediato | |
| print("⏳ Carregando bibliotecas e configurações...", end="", flush=True) | |
| start_time = time.time() | |
| # Adiciona o diretório raiz do projeto ao path | |
| sys.path.append(str(Path(__file__).parent.parent)) | |
| from app.services.document_processor import DocumentProcessor | |
| from app.services.vector_store import VectorStoreManager | |
| from app.services.rag_service import RAGService | |
| from app.core.config import settings | |
| print(f" Concluído em {time.time() - start_time:.2f}s", flush=True) | |
| # --- Configuração de Logging --- | |
| # 1. Filtrar warnings para uma interface mais limpa | |
| warnings.filterwarnings("ignore") | |
| # 2. Obter o logger raiz | |
| root_logger = logging.getLogger() | |
| # 3. Limpar handlers existentes para evitar duplicação ou saídas indesejadas | |
| if root_logger.hasHandlers(): | |
| root_logger.handlers.clear() | |
| # 4. Configurar o logging para salvar em arquivo | |
| log_file_path = Path(__file__).parent.parent / "chat_rag.log" | |
| logging.basicConfig( | |
| level=logging.INFO, # Captura logs de nível INFO e acima | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| filename=str(log_file_path), | |
| filemode='a' # 'a' para adicionar (append) ao log existente | |
| ) | |
| # 5. Silenciar loggers muito "barulhentos" de bibliotecas de terceiros | |
| logging.getLogger("chromadb.telemetry.product.posthog").setLevel(logging.CRITICAL) | |
| logging.getLogger("sentence_transformers").setLevel(logging.WARNING) | |
| # Logger específico para este script (opcional, já que o raiz está configurado) | |
| logger = logging.getLogger(__name__) | |
| class RAGChat: | |
| def __init__(self): | |
| """Inicializa os serviços do RAG""" | |
| print("🚀 Inicializando serviços RAG (pode levar alguns segundos)...", flush=True) | |
| logger.info("--- NOVA SESSÃO INICIADA ---") | |
| # Inicializar serviços | |
| self.processor = DocumentProcessor() | |
| self.vector_store = VectorStoreManager() | |
| self.rag_service = RAGService() | |
| # Identificar LLM em uso | |
| llm_name = "Nenhuma (Modo Simples)" | |
| if self.rag_service.llm: | |
| try: | |
| if hasattr(self.rag_service.llm, 'model_name'): | |
| llm_name = f"{self.rag_service.llm.__class__.__name__} ({self.rag_service.llm.model_name})" | |
| elif hasattr(self.rag_service.llm, 'model'): | |
| llm_name = f"{self.rag_service.llm.__class__.__name__} ({self.rag_service.llm.model})" | |
| else: | |
| llm_name = self.rag_service.llm.__class__.__name__ | |
| except: | |
| llm_name = "LLM Desconhecida" | |
| print(f"✅ RAG Chat pronto! [LLM: {llm_name}]", flush=True) | |
| logger.info(f"RAG Chat inicializado com sucesso. LLM: {llm_name}") | |
| def ingest_documents(self, directory: str = None): | |
| """Ingere documentos da pasta especificada""" | |
| if directory is None: | |
| directory = settings.documents_directory_raw | |
| docs_path = Path(directory) | |
| if not docs_path.exists(): | |
| print(f"❌ Diretório não encontrado: {directory}", flush=True) | |
| logger.error(f"Diretório de ingestão não encontrado: {directory}") | |
| return | |
| print(f"📂 Processando documentos de: {directory}", flush=True) | |
| logger.info(f"Iniciando processamento de documentos de: {directory}") | |
| # Processar documentos | |
| documents = self.processor.process_directory(docs_path) | |
| if documents: | |
| self.vector_store.add_documents(documents) | |
| print(f"✅ {len(documents)} chunks processados e adicionados ao banco vetorial", flush=True) | |
| logger.info(f"{len(documents)} chunks adicionados ao banco vetorial.") | |
| stats = self.vector_store.get_collection_stats() | |
| print(f"📊 Estatísticas do banco: {stats.get('total_documents', 0)} documentos", flush=True) | |
| logger.info(f"Estatísticas do banco: {stats}") | |
| else: | |
| print("⚠️ Nenhum documento processado", flush=True) | |
| logger.warning("Nenhum documento encontrado para processar.") | |
| print(f" Extensões suportadas: {', '.join(settings.supported_extensions)}", flush=True) | |
| def ask_question(self, question: str, show_sources: bool = True): | |
| """Faz uma pergunta ao sistema RAG""" | |
| print(f"\n❓ Pergunta: {question}", flush=True) | |
| logger.info(f"Recebida pergunta: {question}") | |
| print("-" * 50, flush=True) | |
| try: | |
| result = self.rag_service.query(question) | |
| logger.info(f"Resposta gerada: {result['answer']}") | |
| print(f"🤖 Resposta: {result['answer']}", flush=True) | |
| if show_sources and result['sources']: | |
| print(f"\n📚 Fontes ({len(result['sources'])} encontradas):", flush=True) | |
| for i, source in enumerate(result['sources'], 1): | |
| filename = Path(source['filename']).name | |
| chunk_id = source.get('chunk', '?') | |
| print(f" {i}. {filename} (chunk {chunk_id})", flush=True) | |
| logger.info(f"Fontes encontradas: {[s['source'] for s in result['sources']]}") | |
| return result | |
| except Exception as e: | |
| print(f"❌ Erro: {e}", flush=True) | |
| logger.exception(f"Erro ao processar a pergunta: {question}") | |
| return None | |
| def search_documents(self, query: str, limit: int = 5): | |
| """Busca documentos sem gerar resposta""" | |
| print(f"\n🔍 Buscando: '{query}'", flush=True) | |
| logger.info(f"Buscando por documentos com o termo: '{query}'") | |
| results = self.rag_service.search_documents(query, k=limit) | |
| if results: | |
| print(f"📄 Encontrados {len(results)} documentos:", flush=True) | |
| for i, result in enumerate(results, 1): | |
| print(f"\n {i}. {result['filename']} (score: {result['score']:.3f})", flush=True) | |
| print(" " + "-" * 40, flush=True) | |
| print(f" {result['content']}", flush=True) | |
| print(" " + "-" * 40, flush=True) | |
| logger.info(f"Encontrados {len(results)} documentos para a busca.") | |
| else: | |
| print("⚠️ Nenhum documento encontrado", flush=True) | |
| logger.warning("Nenhum documento encontrado para a busca.") | |
| return results | |
| def show_stats(self): | |
| """Mostra estatísticas do sistema""" | |
| stats = self.vector_store.get_collection_stats() | |
| indexed_docs = self.vector_store.list_indexed_documents() | |
| print("\n📊 ESTATÍSTICAS DO SISTEMA", flush=True) | |
| print("=" * 30, flush=True) | |
| print(f"• Modelo de embeddings: {settings.embeddings_model}", flush=True) | |
| print(f"• Total de chunks no banco: {stats.get('total_documents', 0)}", flush=True) | |
| print(f"• Pasta do Chroma: {settings.chroma_persist_directory}", flush=True) | |
| if indexed_docs: | |
| print(f"\n📚 Documentos Indexados ({len(indexed_docs)}):", flush=True) | |
| for doc_name in indexed_docs: | |
| print(f" • {doc_name}", flush=True) | |
| else: | |
| print("\n📚 Nenhum documento indexado.", flush=True) | |
| logger.info(f"Exibindo estatísticas: {stats}") | |
| def interactive_chat(self): | |
| """Modo chat interativo""" | |
| print("\n" + "=" * 60, flush=True) | |
| print("💬 CHAT RAG INTERATIVO", flush=True) | |
| print("=" * 60, flush=True) | |
| print("Comandos:", flush=True) | |
| print(" /help - Mostra esta ajuda", flush=True) | |
| print(" /stats - Mostra estatísticas", flush=True) | |
| print(" /search - Busca documentos", flush=True) | |
| print(" /ingest - Reingere documentos", flush=True) | |
| print(" /quit - Sair", flush=True) | |
| print("=" * 60, flush=True) | |
| while True: | |
| try: | |
| user_input = input("\n💭 Você: ").strip() | |
| if not user_input: | |
| continue | |
| if user_input.lower() == '/quit': | |
| print("👋 Até logo!", flush=True) | |
| logger.info("Saindo do chat interativo.") | |
| break | |
| elif user_input.lower() == '/help': | |
| print("📋 Comandos disponíveis:", flush=True) | |
| print(" /help - Mostra ajuda", flush=True) | |
| print(" /stats - Estatísticas do sistema", flush=True) | |
| print(" /search - Busca documentos (ex: /search senha)", flush=True) | |
| print(" /ingest - Reingere documentos", flush=True) | |
| print(" /quit - Sair", flush=True) | |
| print(" Qualquer outra coisa será tratada como pergunta", flush=True) | |
| elif user_input.lower() == '/stats': | |
| self.show_stats() | |
| elif user_input.lower().startswith('/search'): | |
| query = user_input[8:].strip() | |
| if query: | |
| self.search_documents(query) | |
| else: | |
| print("⚠️ Uso: /search <termo de busca>", flush=True) | |
| elif user_input.lower() == '/ingest': | |
| self.ingest_documents() | |
| else: | |
| self.ask_question(user_input) | |
| except KeyboardInterrupt: | |
| print("\n\n👋 Interrompido pelo usuário", flush=True) | |
| logger.warning("Chat interrompido pelo usuário (KeyboardInterrupt).") | |
| break | |
| except Exception as e: | |
| print(f"❌ Erro inesperado: {e}", flush=True) | |
| logger.exception("Erro inesperado no loop do chat.") | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Chat RAG Local") | |
| parser.add_argument("--question", "-q", help="Pergunta única") | |
| parser.add_argument("--search", "-s", help="Busca por documentos") | |
| parser.add_argument("--ingest", "-i", action="store_true", help="Ingerir documentos") | |
| parser.add_argument("--stats", action="store_true", help="Mostrar estatísticas") | |
| parser.add_argument("--interactive", action="store_true", help="Modo interativo") | |
| args = parser.parse_args() | |
| chat = RAGChat() | |
| if args.ingest: | |
| chat.ingest_documents() | |
| if args.stats: | |
| chat.show_stats() | |
| if args.search: | |
| chat.search_documents(args.search) | |
| if args.question: | |
| chat.ask_question(args.question) | |
| if args.interactive or not any([args.question, args.search, args.ingest, args.stats]): | |
| chat.interactive_chat() | |
| if __name__ == "__main__": | |
| main() | |