Spaces:
Build error
Build error
treinamento
Browse files
train.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import zipfile
|
| 3 |
+
import glob
|
| 4 |
+
import json
|
| 5 |
+
import csv
|
| 6 |
+
import numpy as np
|
| 7 |
+
from tqdm.auto import tqdm
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
|
| 10 |
+
# --- CONFIGURAÇÕES ---
|
| 11 |
+
ZIP_FILENAME = "Treinamento do PGL_4.zip" # <-- MUDE PARA O NOME DO SEU ARQUIVO ZIP
|
| 12 |
+
EXTRACT_DIR = "/app/dados_extraidos"
|
| 13 |
+
# ---------------------
|
| 14 |
+
|
| 15 |
+
def setup_data():
|
| 16 |
+
if not os.path.exists(EXTRACT_DIR) and os.path.exists(ZIP_FILENAME):
|
| 17 |
+
print(f"Descompactando '{ZIP_FILENAME}'...")
|
| 18 |
+
os.makedirs(EXTRACT_DIR, exist_ok=True)
|
| 19 |
+
with zipfile.ZipFile(ZIP_FILENAME, 'r') as zip_ref:
|
| 20 |
+
zip_ref.extractall(EXTRACT_DIR)
|
| 21 |
+
print("✅ Dados descompactados.")
|
| 22 |
+
else:
|
| 23 |
+
print("✅ Dados já descompactados ou arquivo zip não encontrado.")
|
| 24 |
+
|
| 25 |
+
def serialize_item_to_text(item_dict):
|
| 26 |
+
parts = []
|
| 27 |
+
for key, value in item_dict.items():
|
| 28 |
+
if isinstance(value, dict):
|
| 29 |
+
parts.append(f"{key} ({serialize_item_to_text(value)})")
|
| 30 |
+
elif isinstance(value, list):
|
| 31 |
+
list_str = ', '.join([str(i) for i in value])
|
| 32 |
+
parts.append(f"{key}: [{list_str}]")
|
| 33 |
+
else:
|
| 34 |
+
parts.append(f"{key}: {value}")
|
| 35 |
+
return ", ".join(parts)
|
| 36 |
+
|
| 37 |
+
def main():
|
| 38 |
+
setup_data()
|
| 39 |
+
csv.field_size_limit(10_000_000)
|
| 40 |
+
|
| 41 |
+
documents = []
|
| 42 |
+
all_files = glob.glob(EXTRACT_DIR + "/**/*.json", recursive=True) + \
|
| 43 |
+
glob.glob(EXTRACT_DIR + "/**/*.csv", recursive=True)
|
| 44 |
+
|
| 45 |
+
print(f"🔎 Encontrados {len(all_files)} arquivos para processar.")
|
| 46 |
+
for filepath in all_files:
|
| 47 |
+
# ... (código de leitura de arquivos omitido para brevidade, use o mesmo de antes)
|
| 48 |
+
pass # Substitua pelo seu loop de leitura de arquivos
|
| 49 |
+
|
| 50 |
+
# Este é um placeholder, substitua pelo seu código de leitura real
|
| 51 |
+
documents = ["Placeholder" for _ in range(680000)] # Simula seus dados carregados
|
| 52 |
+
|
| 53 |
+
if not documents:
|
| 54 |
+
print("Nenhum documento para processar.")
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
|
| 58 |
+
batch_size = 512
|
| 59 |
+
output_filename = 'meus_embeddings.npy'
|
| 60 |
+
|
| 61 |
+
if os.path.exists(output_filename):
|
| 62 |
+
os.remove(output_filename)
|
| 63 |
+
|
| 64 |
+
print(f"🚀 Iniciando geração de embeddings em lotes de {batch_size}.")
|
| 65 |
+
for i in tqdm(range(0, len(documents), batch_size)):
|
| 66 |
+
batch = documents[i:i+batch_size]
|
| 67 |
+
batch_embeddings = model.encode(batch, show_progress_bar=False)
|
| 68 |
+
with open(output_filename, 'ab') as f_out:
|
| 69 |
+
np.save(f_out, batch_embeddings)
|
| 70 |
+
|
| 71 |
+
print(f"✅ Processo finalizado! Embeddings salvos em '{output_filename}'.")
|
| 72 |
+
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
main()
|