Finish-him commited on
Commit
0c65912
·
verified ·
1 Parent(s): f4cd3d5

Update train.py

Browse files
Files changed (1) hide show
  1. train.py +53 -55
train.py CHANGED
@@ -1,5 +1,3 @@
1
- # =================== CÓDIGO FINAL COM SUPORTE PARA XML ===================
2
-
3
  import os
4
  import glob
5
  import json
@@ -7,62 +5,42 @@ import csv
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:
32
- print(f"Descompactando '{zip_filepath}' para '{EXTRACT_DIR}'...")
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)
@@ -75,23 +53,19 @@ def serialize_item_to_text(item_dict):
75
  return ", ".join(parts)
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:
96
  if filepath.endswith('.json'):
97
  with open(filepath, 'r', encoding='utf-8') as f:
@@ -104,16 +78,40 @@ def main():
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. Encerrando.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import glob
3
  import json
 
5
  import numpy as np
6
  from tqdm.auto import tqdm
7
  from sentence_transformers import SentenceTransformer
8
+ import zipfile
9
+ import xml.etree.ElementTree as ET
10
 
 
 
11
  DATA_DIR = "/app/dados"
 
12
  EXTRACT_DIR = "/app/dados_extraidos"
 
13
 
14
  def setup_data():
 
 
15
  os.makedirs(EXTRACT_DIR, exist_ok=True)
16
+ zip_files = glob.glob(DATA_DIR + "/**/*.zip", recursive=True)
17
+ if not zip_files:
18
+ print("Nenhum arquivo .zip encontrado, usando o diretório de dados principal.")
 
 
19
  return DATA_DIR
20
+ for zip_path in zip_files:
21
+ print(f"Descompactando {zip_path}...")
22
+ with zipfile.ZipFile(zip_path, 'r') as zf:
23
+ zf.extractall(EXTRACT_DIR)
 
 
 
 
 
 
24
  return EXTRACT_DIR
25
 
26
  def xml_to_dict(element):
27
+ d = {}
28
+ for child in element:
29
+ child_dict = xml_to_dict(child)
30
+ if child.tag in d:
31
+ if not isinstance(d[child.tag], list):
32
+ d[child.tag] = [d[child.tag]]
33
+ d[child.tag].append(child_dict)
34
+ else:
35
+ d[child.tag] = child_dict
36
+ if not d:
37
+ return element.text
38
+ return d
 
 
 
 
39
 
40
  def serialize_item_to_text(item_dict):
 
41
  parts = []
42
  if not isinstance(item_dict, dict):
43
  return str(item_dict)
 
44
  for key, value in item_dict.items():
45
  if isinstance(value, dict):
46
  nested_text = serialize_item_to_text(value)
 
53
  return ", ".join(parts)
54
 
55
  def main():
 
56
  process_dir = setup_data()
57
+ csv.field_size_limit(10_000_000)
58
 
 
59
  all_files = glob.glob(process_dir + "/**/*.json", recursive=True) + \
60
  glob.glob(process_dir + "/**/*.csv", recursive=True) + \
61
  glob.glob(process_dir + "/**/*.xml", recursive=True)
62
+ print(f"\n🔎 Encontrados {len(all_files)} arquivos (JSON, CSV, XML) para processar.")
 
63
 
64
  if not all_files:
 
65
  return
66
 
67
  documents = []
68
+ for filepath in tqdm(all_files, desc="Processando arquivos"):
69
  try:
70
  if filepath.endswith('.json'):
71
  with open(filepath, 'r', encoding='utf-8') as f:
 
78
  with open(filepath, 'r', encoding='utf-8') as f:
79
  reader = csv.DictReader(f)
80
  for row in reader: documents.append(serialize_item_to_text(row))
 
81
  elif filepath.endswith('.xml'):
82
  tree = ET.parse(filepath)
83
  root = tree.getroot()
84
  xml_dict = {root.tag: xml_to_dict(root)}
85
  documents.append(serialize_item_to_text(xml_dict))
86
  except Exception as e:
87
+ print(f"⚠️ Erro ao processar o arquivo {filepath}: {e}")
 
 
88
 
89
+ print(f"\nProcessamento de arquivos concluído! {len(documents)} documentos foram criados.")
90
  if not documents:
91
+ return
92
+
93
+ cache_path = os.environ.get('SENTENCE_TRANSFORMERS_HOME', '/app/cache/torch')
94
+
95
+ print("Carregando modelo de alta performance: intfloat/multilingual-e5-large")
96
+ model = SentenceTransformer(
97
+ 'intfloat/multilingual-e5-large',
98
+ cache_folder=cache_path
99
+ )
100
+
101
+ batch_size = 128
102
+ output_filename = 'meus_embeddings_e5_large.npy'
103
+
104
+ if os.path.exists(output_filename):
105
+ os.remove(output_filename)
106
+
107
+ print(f"🚀 Iniciando geração de embeddings (lotes de {batch_size}).")
108
+ for i in tqdm(range(0, len(documents), batch_size), desc="Gerando Embeddings"):
109
+ batch = documents[i:i + batch_size]
110
+ batch_embeddings = model.encode(batch, show_progress_bar=False)
111
+ with open(output_filename, 'ab') as f_out:
112
+ np.save(f_out, batch_embeddings)
113
+
114
+ print(f"✅ Processo finalizado! Embeddings salvos em '{output_filename}'.")
115
+
116
+ if __name__ == "__main__":
117
+ main()