File size: 3,537 Bytes
bfc3f0d
ad60afc
0115514
efb4cac
bfc3f0d
255cc2c
 
 
efb4cac
c393df3
 
efb4cac
255cc2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c393df3
 
 
 
 
bfc3f0d
255cc2c
 
 
 
 
 
 
 
0520cb9
c393df3
efb4cac
0520cb9
efb4cac
 
0115514
255cc2c
c393df3
efb4cac
 
255cc2c
c393df3
efb4cac
 
 
 
255cc2c
c393df3
bfc3f0d
 
0115514
bfc3f0d
 
255cc2c
bfc3f0d
 
 
0115514
bfc3f0d
c393df3
bfc3f0d
 
efb4cac
255cc2c
c393df3
0115514
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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()