Spaces:
Build error
Build error
update
Browse files
train.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# =================== CÓDIGO FINAL COM
|
| 2 |
|
| 3 |
import os
|
| 4 |
import glob
|
|
@@ -7,25 +7,25 @@ import csv
|
|
| 7 |
import numpy as np
|
| 8 |
from tqdm.auto import tqdm
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 10 |
-
import zipfile
|
|
|
|
| 11 |
|
| 12 |
# --- CONFIGURAÇÕES ---
|
| 13 |
# Diretório onde o Dockerfile clonou os dados do seu Space
|
| 14 |
DATA_DIR = "/app/dados"
|
| 15 |
-
# Diretório para onde os
|
| 16 |
EXTRACT_DIR = "/app/dados_extraidos"
|
| 17 |
# ---------------------
|
| 18 |
|
| 19 |
def setup_data():
|
| 20 |
-
"""Procura por
|
| 21 |
-
print("Procurando por
|
| 22 |
os.makedirs(EXTRACT_DIR, exist_ok=True)
|
| 23 |
-
|
| 24 |
zip_files_found = glob.glob(DATA_DIR + "/**/*.zip", recursive=True)
|
| 25 |
-
|
| 26 |
if not zip_files_found:
|
| 27 |
-
print("Nenhum
|
| 28 |
-
# Se não houver zips, usamos o diretório de dados original
|
| 29 |
return DATA_DIR
|
| 30 |
|
| 31 |
for zip_filepath in zip_files_found:
|
|
@@ -33,22 +33,42 @@ def setup_data():
|
|
| 33 |
try:
|
| 34 |
with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
|
| 35 |
zip_ref.extractall(EXTRACT_DIR)
|
| 36 |
-
print(f"✅
|
| 37 |
except Exception as e:
|
| 38 |
print(f"⚠️ Falha ao descompactar '{zip_filepath}': {e}")
|
| 39 |
-
|
| 40 |
-
# Retorna o diretório onde os arquivos foram extraídos
|
| 41 |
return EXTRACT_DIR
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def serialize_item_to_text(item_dict):
|
| 44 |
-
"""Converte um dicionário
|
| 45 |
parts = []
|
|
|
|
|
|
|
|
|
|
| 46 |
for key, value in item_dict.items():
|
| 47 |
if isinstance(value, dict):
|
| 48 |
nested_text = serialize_item_to_text(value)
|
| 49 |
parts.append(f"{key} ({nested_text})")
|
| 50 |
elif isinstance(value, list):
|
| 51 |
-
list_str = ', '.join([
|
| 52 |
parts.append(f"{key}: [{list_str}]")
|
| 53 |
else:
|
| 54 |
parts.append(f"{key}: {value}")
|
|
@@ -56,21 +76,20 @@ def serialize_item_to_text(item_dict):
|
|
| 56 |
|
| 57 |
def main():
|
| 58 |
"""Função principal para carregar dados e gerar embeddings."""
|
| 59 |
-
# Descompacta os dados e obtém o diretório com os arquivos processáveis
|
| 60 |
process_dir = setup_data()
|
| 61 |
-
|
| 62 |
-
csv.field_size_limit(10_000_000)
|
| 63 |
|
| 64 |
-
#
|
| 65 |
all_files = glob.glob(process_dir + "/**/*.json", recursive=True) + \
|
| 66 |
-
glob.glob(process_dir + "/**/*.csv", recursive=True)
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
print(f"\n🔎 Encontrados {len(all_files)} arquivos para processar após descompactação.")
|
| 69 |
-
|
| 70 |
if not all_files:
|
| 71 |
-
print("⚠️ Nenhum
|
| 72 |
return
|
| 73 |
-
|
| 74 |
documents = []
|
| 75 |
for filepath in all_files:
|
| 76 |
try:
|
|
@@ -85,41 +104,16 @@ def main():
|
|
| 85 |
with open(filepath, 'r', encoding='utf-8') as f:
|
| 86 |
reader = csv.DictReader(f)
|
| 87 |
for row in reader: documents.append(serialize_item_to_text(row))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
except Exception as e:
|
| 89 |
-
print(f"⚠️ Erro ao processar o
|
| 90 |
|
| 91 |
-
print(f"\nProcessamento de
|
| 92 |
-
|
| 93 |
-
if not documents:
|
| 94 |
-
print("Nenhum documento foi lido com sucesso. Encerrando.")
|
| 95 |
-
return
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
print("Carregando modelo avançado: intfloat/e5-mistral-7b-instruct")
|
| 101 |
-
model = SentenceTransformer(
|
| 102 |
-
'intfloat/e5-mistral-7b-instruct',
|
| 103 |
-
cache_folder=cache_path,
|
| 104 |
-
trust_remote_code=True
|
| 105 |
-
)
|
| 106 |
-
|
| 107 |
-
batch_size = 64
|
| 108 |
-
output_filename = 'meus_embeddings_finais.npy'
|
| 109 |
-
|
| 110 |
-
if os.path.exists(output_filename):
|
| 111 |
-
os.remove(output_filename)
|
| 112 |
-
|
| 113 |
-
print(f"🚀 Iniciando geração de embeddings (lotes de {batch_size}).")
|
| 114 |
-
for i in tqdm(range(0, len(documents), batch_size)):
|
| 115 |
-
batch = documents[i:i+batch_size]
|
| 116 |
-
batch_embeddings = model.encode(batch, show_progress_bar=False)
|
| 117 |
-
with open(output_filename, 'ab') as f_out:
|
| 118 |
-
np.save(f_out, batch_embeddings)
|
| 119 |
-
|
| 120 |
-
print(f"✅ Processo finalizado! Embeddings salvos em '{output_filename}'.")
|
| 121 |
-
|
| 122 |
-
if __name__ == "__main__":
|
| 123 |
-
main()
|
| 124 |
-
|
| 125 |
-
# =================================================================================
|
|
|
|
| 1 |
+
# =================== CÓDIGO FINAL COM SUPORTE PARA XML ===================
|
| 2 |
|
| 3 |
import os
|
| 4 |
import glob
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
from tqdm.auto import tqdm
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 10 |
+
import zipfile # Módulo para lidar com ficheiros .zip
|
| 11 |
+
import xml.etree.ElementTree as ET # Módulo para processar XML
|
| 12 |
|
| 13 |
# --- CONFIGURAÇÕES ---
|
| 14 |
# Diretório onde o Dockerfile clonou os dados do seu Space
|
| 15 |
DATA_DIR = "/app/dados"
|
| 16 |
+
# Diretório para onde os ficheiros serão extraídos
|
| 17 |
EXTRACT_DIR = "/app/dados_extraidos"
|
| 18 |
# ---------------------
|
| 19 |
|
| 20 |
def setup_data():
|
| 21 |
+
"""Procura por ficheiros .zip no diretório de dados e os descompacta."""
|
| 22 |
+
print("Procurando por ficheiros .zip para descompactar...")
|
| 23 |
os.makedirs(EXTRACT_DIR, exist_ok=True)
|
| 24 |
+
|
| 25 |
zip_files_found = glob.glob(DATA_DIR + "/**/*.zip", recursive=True)
|
| 26 |
+
|
| 27 |
if not zip_files_found:
|
| 28 |
+
print("Nenhum ficheiro .zip encontrado. Assumindo que os ficheiros já estão extraídos.")
|
|
|
|
| 29 |
return DATA_DIR
|
| 30 |
|
| 31 |
for zip_filepath in zip_files_found:
|
|
|
|
| 33 |
try:
|
| 34 |
with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
|
| 35 |
zip_ref.extractall(EXTRACT_DIR)
|
| 36 |
+
print(f"✅ Ficheiro '{os.path.basename(zip_filepath)}' descompactado com sucesso.")
|
| 37 |
except Exception as e:
|
| 38 |
print(f"⚠️ Falha ao descompactar '{zip_filepath}': {e}")
|
| 39 |
+
|
|
|
|
| 40 |
return EXTRACT_DIR
|
| 41 |
|
| 42 |
+
def xml_to_dict(element):
|
| 43 |
+
"""Função recursiva para converter um elemento XML num dicionário."""
|
| 44 |
+
# Se o elemento tem filhos, processa-os
|
| 45 |
+
if len(element) > 0:
|
| 46 |
+
d = {}
|
| 47 |
+
for child in element:
|
| 48 |
+
child_dict = xml_to_dict(child)
|
| 49 |
+
# Se a tag já existe, transforma num array
|
| 50 |
+
if child.tag in d:
|
| 51 |
+
if not isinstance(d[child.tag], list):
|
| 52 |
+
d[child.tag] = [d[child.tag]]
|
| 53 |
+
d[child.tag].append(child_dict)
|
| 54 |
+
else:
|
| 55 |
+
d[child.tag] = child_dict
|
| 56 |
+
return d
|
| 57 |
+
# Se não tem filhos, retorna o texto do elemento
|
| 58 |
+
return element.text
|
| 59 |
+
|
| 60 |
def serialize_item_to_text(item_dict):
|
| 61 |
+
"""Converte um dicionário (de JSON, CSV ou XML) numa string de texto."""
|
| 62 |
parts = []
|
| 63 |
+
if not isinstance(item_dict, dict):
|
| 64 |
+
return str(item_dict)
|
| 65 |
+
|
| 66 |
for key, value in item_dict.items():
|
| 67 |
if isinstance(value, dict):
|
| 68 |
nested_text = serialize_item_to_text(value)
|
| 69 |
parts.append(f"{key} ({nested_text})")
|
| 70 |
elif isinstance(value, list):
|
| 71 |
+
list_str = ', '.join([serialize_item_to_text(i) for i in value])
|
| 72 |
parts.append(f"{key}: [{list_str}]")
|
| 73 |
else:
|
| 74 |
parts.append(f"{key}: {value}")
|
|
|
|
| 76 |
|
| 77 |
def main():
|
| 78 |
"""Função principal para carregar dados e gerar embeddings."""
|
|
|
|
| 79 |
process_dir = setup_data()
|
| 80 |
+
csv.field_size_limit(100_000_000)
|
|
|
|
| 81 |
|
| 82 |
+
# Adiciona .xml à pesquisa de ficheiros
|
| 83 |
all_files = glob.glob(process_dir + "/**/*.json", recursive=True) + \
|
| 84 |
+
glob.glob(process_dir + "/**/*.csv", recursive=True) + \
|
| 85 |
+
glob.glob(process_dir + "/**/*.xml", recursive=True)
|
| 86 |
+
|
| 87 |
+
print(f"\n🔎 Encontrados {len(all_files)} ficheiros (JSON, CSV, XML) para processar.")
|
| 88 |
|
|
|
|
|
|
|
| 89 |
if not all_files:
|
| 90 |
+
print("⚠️ Nenhum ficheiro de dados encontrado. Verifique o conteúdo do seu repositório/zip.")
|
| 91 |
return
|
| 92 |
+
|
| 93 |
documents = []
|
| 94 |
for filepath in all_files:
|
| 95 |
try:
|
|
|
|
| 104 |
with open(filepath, 'r', encoding='utf-8') as f:
|
| 105 |
reader = csv.DictReader(f)
|
| 106 |
for row in reader: documents.append(serialize_item_to_text(row))
|
| 107 |
+
# --- LÓGICA PARA PROCESSAR XML ---
|
| 108 |
+
elif filepath.endswith('.xml'):
|
| 109 |
+
tree = ET.parse(filepath)
|
| 110 |
+
root = tree.getroot()
|
| 111 |
+
xml_dict = {root.tag: xml_to_dict(root)}
|
| 112 |
+
documents.append(serialize_item_to_text(xml_dict))
|
| 113 |
except Exception as e:
|
| 114 |
+
print(f"⚠️ Erro ao processar o ficheiro {filepath}: {e}")
|
| 115 |
|
| 116 |
+
print(f"\nProcessamento de ficheiros concluído! {len(documents)} documentos foram criados.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
if not documents:
|
| 119 |
+
print("Nenhum documento foi lido com sucesso. Enc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|