Spaces:
Sleeping
Sleeping
| from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, ServiceContext | |
| from llama_index.llms.openai import OpenAI | |
| from huggingface_hub import snapshot_download | |
| import gradio as gr | |
| import os | |
| import yaml | |
| import json | |
| # 🔑 Configure sua API da OpenAI (adicione no Hugging Face em Settings > Secrets) | |
| os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") | |
| # 🔥 Função para extrair conteúdo de YAML, JSON, TXT e MD | |
| def extrair_conteudo_dos_arquivos(pasta): | |
| texto_final = "" | |
| for root, dirs, files in os.walk(pasta): | |
| for file in files: | |
| caminho_arquivo = os.path.join(root, file) | |
| try: | |
| if file.endswith(('.yml', '.yaml')): | |
| with open(caminho_arquivo, 'r', encoding='utf-8') as f: | |
| data = yaml.safe_load(f) | |
| texto = yaml.dump(data, allow_unicode=True) | |
| texto_final += f"\n\n### Arquivo: {file}\n{texto}" | |
| elif file.endswith('.json'): | |
| with open(caminho_arquivo, 'r', encoding='utf-8') as f: | |
| data = json.load(f) | |
| texto = json.dumps(data, indent=2, ensure_ascii=False) | |
| texto_final += f"\n\n### Arquivo: {file}\n{texto}" | |
| elif file.endswith(('.md', '.txt')): | |
| with open(caminho_arquivo, 'r', encoding='utf-8') as f: | |
| texto = f.read() | |
| texto_final += f"\n\n### Arquivo: {file}\n{texto}" | |
| else: | |
| continue | |
| except Exception as e: | |
| print(f"Erro ao ler {file}: {e}") | |
| return texto_final | |
| # 🔧 Função para gerar o arquivo documentacao.txt | |
| def gerar_arquivo_documentacao(pasta_origem, arquivo_destino="documentacao.txt"): | |
| texto = extrair_conteudo_dos_arquivos(pasta_origem) | |
| if texto.strip() == "": | |
| print("⚠️ Nenhum conteúdo encontrado nos arquivos!") | |
| else: | |
| with open(arquivo_destino, 'w', encoding='utf-8') as f: | |
| f.write(texto) | |
| print(f"✅ Arquivo {arquivo_destino} gerado com sucesso.") | |
| # 📥 Baixar a documentação do Hugging Face Dataset | |
| docs_dir = snapshot_download( | |
| repo_id="Jeice/n8n-docs-v2", | |
| repo_type="dataset" | |
| ) | |
| # 🔨 Gerar o arquivo de documentação consolidado | |
| gerar_arquivo_documentacao(docs_dir) | |
| # 📚 Carregar o documento gerado | |
| documents = SimpleDirectoryReader(input_files=["documentacao.txt"]).load_data() | |
| # 🔎 Criar o índice vetorial | |
| service_context = ServiceContext.from_defaults( | |
| llm=OpenAI(model="gpt-3.5-turbo") | |
| ) | |
| index = VectorStoreIndex.from_documents(documents, service_context=service_context) | |
| # 🚀 Criar engine de consulta | |
| query_engine = index.as_query_engine() | |
| # 💬 Função do chatbot | |
| def chatbot(input_text): | |
| response = query_engine.query(input_text) | |
| return str(response) | |
| # 🎨 Interface Gradio — Bonita e Funcional | |
| interface = gr.Interface( | |
| fn=chatbot, | |
| inputs=gr.Textbox(lines=2, placeholder="Digite sua pergunta sobre o n8n..."), | |
| outputs="text", | |
| title="🤖 Bot de Dúvidas sobre o n8n", | |
| description="Este agente responde dúvidas sobre o n8n, baseado na documentação oficial que você subiu.", | |
| examples=[ | |
| ["Como criar um workflow no n8n?"], | |
| ["Para que serve o node HTTP Request?"], | |
| ["Quais são os nodes para integração com Google Sheets?"], | |
| ], | |
| theme="default", | |
| allow_flagging="never" | |
| ) | |
| # 🚀 Executar | |
| interface.launch() | |