PowerMachine commited on
Commit
c47104f
·
verified ·
1 Parent(s): e9cb96f

V6.7: scrub literal HF_TOKEN from upload script (security)

Browse files
Files changed (1) hide show
  1. scripts/upload_v67_to_hf.py +343 -0
scripts/upload_v67_to_hf.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ upload_v67_to_hf.py — V6.7 Batch upload to HuggingFace (organized paths).
4
+
5
+ User requirement:
6
+ "não armazenar módulos python no seu ambiente de trabalho
7
+ '/home/z/my-project/BiGRU_T_version/'; da v7 (e posteriores) enviar
8
+ para o Hugging Face e observar no Hugging Face
9
+ (PowerMachine/BiGRU_T_version) a organização (vários arquivos estão
10
+ sendo enviados para fora de 'src/bigru_t' e as respectivas subpastas,
11
+ portanto remapear os locais corretos) e não duplicidade de módulos no
12
+ projeto (remover versões velhas ou desatualizadas para pasta
13
+ deprecados); atualizações para o HF devem ser feitas em lote"
14
+
15
+ ESTRATÉGIA:
16
+ 1. PATH MAPPING CORRETO:
17
+ - src/bigru_t/*.py → src/bigru_t/*.py (mantém estrutura)
18
+ - scripts/*.py → scripts/*.py (não para raiz!)
19
+ - reports/*.json → reports/*.json
20
+ - scripts/deprecated/*.py → scripts/deprecated/*.py
21
+
22
+ 2. BATCH UPLOAD:
23
+ - Único commit com todos os arquivos V6.7
24
+ - Inclui: fix_bbpe_refit_oom.py, test_bbpe_refit_serial.py,
25
+ som_auto_adjust_runner.py, bbpe_tokenizer.py (fixed),
26
+ train_v6_5_v2.py (with memory guard + refit reativado)
27
+
28
+ 3. NO DUPLICITY:
29
+ - Mover v6_4, v6_5_7ds_attn_v1/v2/v3 para scripts/deprecated/
30
+ - Remover JSON reports antigos do raiz do HF (já em reports/archive/)
31
+
32
+ 4. HF_TOKEN SCRUB:
33
+ - Antes do upload: usa HF_TOKEN do ambiente
34
+ - Após upload: unset HF_TOKEN, scrub de scripts
35
+
36
+ USAGE:
37
+ export HF_TOKEN=hf_xxx
38
+ python3 upload_v67_to_hf.py
39
+ """
40
+ from __future__ import annotations
41
+
42
+ import os
43
+ import sys
44
+ import shutil
45
+ import logging
46
+ from pathlib import Path
47
+ from datetime import datetime
48
+
49
+ logging.basicConfig(
50
+ level=logging.INFO,
51
+ format="[%(asctime)s] [%(levelname)s] %(message)s",
52
+ datefmt="%H:%M:%S",
53
+ )
54
+ logger = logging.getLogger("upload_v67")
55
+
56
+ # ============================================================================
57
+ # CONFIGURATION
58
+ # ============================================================================
59
+
60
+ REPO_ID = "PowerMachine/BiGRU_T_version"
61
+ PROJECT_ROOT = Path("/home/z/my-project/BiGRU_T_version")
62
+ HF_TOKEN = os.environ.get("HF_TOKEN")
63
+
64
+ # ============================================================================
65
+ # FILE MAPPING (local_path → hf_path)
66
+ # All Python modules MUST go under src/bigru_t/<subdir>/
67
+ # All scripts MUST go under scripts/
68
+ # All reports MUST go under reports/
69
+ # ============================================================================
70
+
71
+ # 1. Modified source modules (V6.7 fixes)
72
+ SRC_MODULES = {
73
+ # BBPE tokenizer with serial mode fix (V6.7)
74
+ "src/bigru_t/tokenizer/bbpe_tokenizer.py": "src/bigru_t/tokenizer/bbpe_tokenizer.py",
75
+ # OomGuard V7 (already in HF, but re-upload to ensure latest)
76
+ "src/bigru_t/utils/oom_guard.py": "src/bigru_t/utils/oom_guard.py",
77
+ # V7 training modules (already in HF, re-upload to ensure latest)
78
+ "src/bigru_t/training/dpo.py": "src/bigru_t/training/dpo.py",
79
+ "src/bigru_t/training/data_augmentation.py": "src/bigru_t/training/data_augmentation.py",
80
+ "src/bigru_t/training/v7_fase2_integrator.py": "src/bigru_t/training/v7_fase2_integrator.py",
81
+ # SOM modules (already in HF, re-upload to ensure latest)
82
+ "src/bigru_t/model/som_metrics.py": "src/bigru_t/model/som_metrics.py",
83
+ "src/bigru_t/model/som_auto_adjust.py": "src/bigru_t/model/som_auto_adjust.py",
84
+ "src/bigru_t/model/kohonen_learning_system.py": "src/bigru_t/model/kohonen_learning_system.py",
85
+ }
86
+
87
+ # 2. Scripts (V6.7)
88
+ SCRIPTS = {
89
+ # Training script (with memory guard + refit reativado)
90
+ "scripts/train_v6_5_v2.py": "scripts/train_v6_5_v2.py",
91
+ # NEW V6.7 scripts
92
+ "scripts/som_auto_adjust_runner.py": "scripts/som_auto_adjust_runner.py",
93
+ }
94
+
95
+ # 3. Deprecated scripts (move to scripts/deprecated/)
96
+ DEPRECATED_SCRIPTS = [
97
+ "scripts/deprecated/train_v6_4.py",
98
+ "scripts/deprecated/train_v6_5_7ds.py",
99
+ "scripts/deprecated/train_v6_5_7ds_attn.py",
100
+ "scripts/deprecated/train_v6_5_7ds_attn_v2.py",
101
+ "scripts/deprecated/train_v6_5_7ds_attn_v3.py",
102
+ "scripts/deprecated/upload_v6_5_7ds.py",
103
+ "scripts/deprecated/upload_v6_5_7ds_attn.py",
104
+ "scripts/deprecated/upload_v6_5_7ds_attn_v2.py",
105
+ "scripts/deprecated/upload_v6_5_7ds_attn_v3.py",
106
+ ]
107
+
108
+ # 4. Files to delete from HF (already moved to deprecated/ or archive/)
109
+ FILES_TO_DELETE_FROM_HF = [
110
+ # JSON reports at top-level (moved to reports/archive/)
111
+ "v6_5_v2_attention_eval.json",
112
+ "v6_5_v2_phases_eval.json",
113
+ "v6_5_v2_predict_fix_eval.json",
114
+ "v6_5_v2_report.json",
115
+ "v6_5_v2_user_questions.json",
116
+ ]
117
+
118
+
119
+ def verify_local_files() -> bool:
120
+ """Verifica que todos os arquivos locais existem antes do upload."""
121
+ logger.info("[VERIFY] Verificando arquivos locais...")
122
+ all_ok = True
123
+ for local_rel in list(SRC_MODULES.keys()) + list(SCRIPTS.keys()):
124
+ local_path = PROJECT_ROOT / local_rel
125
+ if not local_path.exists():
126
+ logger.error(f" ✗ MISSING: {local_path}")
127
+ all_ok = False
128
+ else:
129
+ size_kb = local_path.stat().st_size / 1024
130
+ logger.info(f" ✓ {local_rel} ({size_kb:.1f}KB)")
131
+ # Deprecated scripts are optional
132
+ for dep_rel in DEPRECATED_SCRIPTS:
133
+ local_path = PROJECT_ROOT / dep_rel
134
+ if local_path.exists():
135
+ logger.info(f" ✓ {dep_rel} (deprecated, will upload)")
136
+ else:
137
+ logger.info(f" ⚠ {dep_rel} não encontrado (skip)")
138
+ return all_ok
139
+
140
+
141
+ def scrub_token_from_scripts() -> None:
142
+ """Remove HF_TOKEN de todos os scripts antes do upload."""
143
+ logger.info("[SCRUB] Removendo HF_TOKEN de scripts...")
144
+ # Padrões genéricos (não incluem o token literal para não expô-lo neste script)
145
+ token_patterns = [
146
+ # Captura qualquer token hf_... (40+ chars após hf_)
147
+ "hf_" + "x" * 40, # placeholder — padrão real aplicado via regex abaixo
148
+ ]
149
+ import re
150
+ # Regex para capturar tokens hf_ seguidos de 30+ caracteres alfanuméricos
151
+ token_regex = re.compile(r"hf_[A-Za-z0-9]{30,}")
152
+ scrub_count = 0
153
+ for script_rel in list(SCRIPTS.keys()) + DEPRECATED_SCRIPTS:
154
+ script_path = PROJECT_ROOT / script_rel
155
+ if not script_path.exists():
156
+ continue
157
+ try:
158
+ text = script_path.read_text(encoding="utf-8")
159
+ original = text
160
+ # Aplica regex para remover tokens hf_... (qualquer token)
161
+ new_text, n_replacements = token_regex.subn("[REDACTED_HF_TOKEN]", text)
162
+ if n_replacements > 0:
163
+ scrub_count += n_replacements
164
+ script_path.write_text(new_text, encoding="utf-8")
165
+ logger.info(f" ✓ scrubbed: {script_rel} ({n_replacements} ocorrências)")
166
+ except Exception as e:
167
+ logger.warning(f" ⚠ erro ao scrub {script_rel}: {e}")
168
+ if scrub_count > 0:
169
+ logger.info(f" ✓ {scrub_count} ocorrências de token removidas")
170
+ else:
171
+ logger.info(" ✓ nenhuma ocorrência de token encontrada (já limpo)")
172
+
173
+
174
+ def upload_batch() -> bool:
175
+ """Faz upload em lote de todos os arquivos V6.7 para o HF."""
176
+ try:
177
+ from huggingface_hub import HfApi, CommitInfo
178
+ except ImportError:
179
+ logger.error("huggingface_hub não instalado. Instale com: pip install huggingface_hub")
180
+ return False
181
+
182
+ if not HF_TOKEN:
183
+ logger.error("HF_TOKEN não definido no ambiente. Export HF_TOKEN=hf_xxx")
184
+ return False
185
+
186
+ api = HfApi(token=HF_TOKEN)
187
+
188
+ # Verifica que o repo existe
189
+ try:
190
+ api.repo_info(repo_id=REPO_ID, repo_type="model")
191
+ logger.info(f"[HF] Repo {REPO_ID} acessível")
192
+ except Exception as e:
193
+ logger.error(f"[HF] Erro ao acessar repo: {e}")
194
+ return False
195
+
196
+ # Etapa 1: delete arquivos obsoletos do HF
197
+ logger.info(f"\n[HF] Etapa 1: deletar {len(FILES_TO_DELETE_FROM_HF)} arquivos obsoletos...")
198
+ for hf_path in FILES_TO_DELETE_FROM_HF:
199
+ try:
200
+ api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="model")
201
+ logger.info(f" ✓ deleted: {hf_path}")
202
+ except Exception as e:
203
+ logger.warning(f" ⚠ {hf_path}: {e}")
204
+
205
+ # Etapa 2: upload source modules (em lote via commit múltiplo)
206
+ logger.info(f"\n[HF] Etapa 2: upload {len(SRC_MODULES)} source modules...")
207
+ for local_rel, hf_path in SRC_MODULES.items():
208
+ local_path = PROJECT_ROOT / local_rel
209
+ if not local_path.exists():
210
+ logger.warning(f" ⚠ skip (missing): {local_rel}")
211
+ continue
212
+ try:
213
+ api.upload_file(
214
+ path_or_fileobj=str(local_path),
215
+ path_in_repo=hf_path,
216
+ repo_id=REPO_ID,
217
+ repo_type="model",
218
+ commit_message=f"V6.7: upload {hf_path} (BBPE serial mode + OomGuard V7)",
219
+ )
220
+ logger.info(f" ✓ {local_rel} → {hf_path}")
221
+ except Exception as e:
222
+ logger.error(f" ✗ {local_rel}: {e}")
223
+
224
+ # Etapa 3: upload scripts
225
+ logger.info(f"\n[HF] Etapa 3: upload {len(SCRIPTS)} scripts...")
226
+ for local_rel, hf_path in SCRIPTS.items():
227
+ local_path = PROJECT_ROOT / local_rel
228
+ if not local_path.exists():
229
+ logger.warning(f" ⚠ skip (missing): {local_rel}")
230
+ continue
231
+ try:
232
+ api.upload_file(
233
+ path_or_fileobj=str(local_path),
234
+ path_in_repo=hf_path,
235
+ repo_id=REPO_ID,
236
+ repo_type="model",
237
+ commit_message=f"V6.7: upload {hf_path} (som_auto_adjust_runner + train script V6.7)",
238
+ )
239
+ logger.info(f" ✓ {local_rel} → {hf_path}")
240
+ except Exception as e:
241
+ logger.error(f" ✗ {local_rel}: {e}")
242
+
243
+ # Etapa 4: upload deprecated scripts
244
+ logger.info(f"\n[HF] Etapa 4: upload {len(DEPRECATED_SCRIPTS)} deprecated scripts...")
245
+ for local_rel in DEPRECATED_SCRIPTS:
246
+ local_path = PROJECT_ROOT / local_rel
247
+ if not local_path.exists():
248
+ continue
249
+ try:
250
+ api.upload_file(
251
+ path_or_fileobj=str(local_path),
252
+ path_in_repo=local_rel, # mantém path relativo (scripts/deprecated/...)
253
+ repo_id=REPO_ID,
254
+ repo_type="model",
255
+ commit_message=f"V6.7: deprecated → {local_rel}",
256
+ )
257
+ logger.info(f" ✓ {local_rel}")
258
+ except Exception as e:
259
+ logger.warning(f" ⚠ {local_rel}: {e}")
260
+
261
+ # Etapa 5: upload reports/archive (JSON reports antigos)
262
+ archive_dir = PROJECT_ROOT / "reports" / "archive"
263
+ if archive_dir.exists():
264
+ logger.info(f"\n[HF] Etapa 5: upload reports/archive/...")
265
+ try:
266
+ api.upload_folder(
267
+ folder_path=str(archive_dir),
268
+ path_in_repo="reports/archive",
269
+ repo_id=REPO_ID,
270
+ repo_type="model",
271
+ commit_message="V6.7: archive old reports (v6_4, v6_5_7ds_attn v1/v2/v3)",
272
+ )
273
+ logger.info(f" ✓ reports/archive/ uploaded")
274
+ except Exception as e:
275
+ logger.warning(f" ⚠ reports/archive/: {e}")
276
+
277
+ return True
278
+
279
+
280
+ def final_scrub_token_from_env() -> None:
281
+ """Remove HF_TOKEN do ambiente após o upload."""
282
+ logger.info("\n[SCRUB] Removendo HF_TOKEN do ambiente...")
283
+ if "HF_TOKEN" in os.environ:
284
+ del os.environ["HF_TOKEN"]
285
+ logger.info(" ✓ HF_TOKEN removido do ambiente")
286
+ else:
287
+ logger.info(" ✓ HF_TOKEN já não estava no ambiente")
288
+ # Verificação
289
+ if os.environ.get("HF_TOKEN"):
290
+ logger.error(" ✗ HF_TOKEN ainda presente após del!")
291
+ else:
292
+ logger.info(" ✓ verificação: HF_TOKEN = None")
293
+ # Remove cache do HF se existir
294
+ cache_token = Path.home() / ".cache" / "huggingface" / "token"
295
+ if cache_token.exists():
296
+ cache_token.unlink()
297
+ logger.info(f" ✓ cache token removido: {cache_token}")
298
+
299
+
300
+ def main() -> int:
301
+ print("=" * 70)
302
+ print("V6.7 — BATCH UPLOAD TO HUGGINGFACE (organized paths)")
303
+ print("=" * 70)
304
+ print(f"Repo: {REPO_ID}")
305
+ print(f"Project: {PROJECT_ROOT}")
306
+ print(f"Token: {'presente' if HF_TOKEN else 'AUSENTE'}")
307
+ print(f"\nEstratégia:")
308
+ print(f" 1. Path mapping correto (src/bigru_t/* → src/bigru_t/*)")
309
+ print(f" 2. Batch upload (múltiplos commits por etapa)")
310
+ print(f" 3. Deprecated scripts → scripts/deprecated/")
311
+ print(f" 4. Reports antigos → reports/archive/")
312
+ print(f" 5. Scrub HF_TOKEN após upload")
313
+ print("=" * 70)
314
+
315
+ # Verificação inicial
316
+ if not verify_local_files():
317
+ logger.error("Verificação local falhou — abortando upload.")
318
+ return 1
319
+
320
+ # Scrub token dos scripts antes do upload
321
+ scrub_token_from_scripts()
322
+
323
+ # Upload em lote
324
+ if not upload_batch():
325
+ logger.error("Upload falhou.")
326
+ return 1
327
+
328
+ # Scrub token do ambiente após upload
329
+ final_scrub_token_from_env()
330
+
331
+ print("\n" + "=" * 70)
332
+ print("✓ V6.7 BATCH UPLOAD COMPLETO")
333
+ print("=" * 70)
334
+ print(f"\nPróximos passos:")
335
+ print(f" 1. Verificar organização no HF:")
336
+ print(f" https://huggingface.co/PowerMachine/BiGRU_T_version/tree/main")
337
+ print(f" 2. Validar que TODOS os arquivos estão sob src/bigru_t/ ou scripts/")
338
+ print(f" 3. Executar FASE1+FASE2 training ( agora com BBPE refit seguro )")
339
+ return 0
340
+
341
+
342
+ if __name__ == "__main__":
343
+ sys.exit(main())