mrj-crom commited on
Commit
fd84774
·
verified ·
1 Parent(s): 38a5ce0

sync: rag/indexar_conhecimento.py

Browse files
Files changed (1) hide show
  1. rag/indexar_conhecimento.py +95 -0
rag/indexar_conhecimento.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import re
4
+ import math
5
+ from collections import defaultdict, Counter
6
+
7
+ DIR_DOCS = "/home/j/Área de trabalho/crompressor-ia/docs"
8
+ ARQUIVO_INDEX = "/home/j/Área de trabalho/crompressor-ia/rag/cromdb_rag_index.json"
9
+ CHUNK_SIZE = 500
10
+ OVERLAP = 100
11
+
12
+ def tokenizar(texto):
13
+ """Tokenização simples: minúsculas e apenas alfanuméricos."""
14
+ return re.findall(r'\b\w+\b', texto.lower())
15
+
16
+ def ler_documentos():
17
+ textos = []
18
+ # Inclui o README principal
19
+ readme = "/home/j/Área de trabalho/crompressor-ia/README.md"
20
+ if os.path.exists(readme):
21
+ with open(readme, 'r', encoding='utf-8') as f:
22
+ textos.append(("README.md", f.read()))
23
+
24
+ # Inclui docs/
25
+ if os.path.exists(DIR_DOCS):
26
+ for raiz, _, arquivos in os.walk(DIR_DOCS):
27
+ for arq in arquivos:
28
+ if arq.endswith(".md") or arq.endswith(".txt"):
29
+ caminho = os.path.join(raiz, arq)
30
+ with open(caminho, 'r', encoding='utf-8') as f:
31
+ textos.append((arq, f.read()))
32
+ return textos
33
+
34
+ def gerar_chunks(textos):
35
+ chunks = []
36
+ chunk_id = 0
37
+ for titulo, conteudo in textos:
38
+ """Divide o documento em pedaços (Chunks) para BM25/TF-IDF"""
39
+ pos = 0
40
+ while pos < len(conteudo):
41
+ pedaço = conteudo[pos:pos+CHUNK_SIZE]
42
+ chunks.append({
43
+ "id": chunk_id,
44
+ "fonte": titulo,
45
+ "texto": pedaço
46
+ })
47
+ chunk_id += 1
48
+ pos += (CHUNK_SIZE - OVERLAP)
49
+ return chunks
50
+
51
+ def indexar_bm25(chunks):
52
+ print(f"Indexando {len(chunks)} fragmentos de conhecimento...")
53
+
54
+ # Calcular N (total de documentos/chunks)
55
+ N = len(chunks)
56
+
57
+ # Document frequency: quantos chunks contém o termo X
58
+ df = Counter()
59
+
60
+ # Frequência de termo em cada chunk
61
+ tf = []
62
+ lista_comprimentos = []
63
+
64
+ for c in chunks:
65
+ tokens = tokenizar(c["texto"])
66
+ freq_termo = Counter(tokens)
67
+ tf.append(freq_termo)
68
+ for termo in freq_termo.keys():
69
+ df[termo] += 1
70
+ lista_comprimentos.append(len(tokens))
71
+
72
+ avgdl = sum(lista_comprimentos) / N if N > 0 else 1
73
+
74
+ # Salvar estrutura
75
+ index_db = {
76
+ "N": N,
77
+ "avgdl": avgdl,
78
+ "df": dict(df),
79
+ "chunks": chunks,
80
+ "tf": [dict(t) for t in tf],
81
+ "comprimentos": lista_comprimentos
82
+ }
83
+
84
+ with open(ARQUIVO_INDEX, 'w', encoding='utf-8') as f:
85
+ json.dump(index_db, f, ensure_ascii=False)
86
+
87
+ print(f"✅ Indexação concluída e salva em {ARQUIVO_INDEX} (Motor BM25 Nativo)")
88
+
89
+ if __name__ == "__main__":
90
+ docs = ler_documentos()
91
+ if not docs:
92
+ print("Nenhum documento encontrado.")
93
+ else:
94
+ ck = gerar_chunks(docs)
95
+ indexar_bm25(ck)