Download scripts/67_publicar_v070.py from PowerMachine/khtst-rust: direct link, hf CLI and curl.
- Browser
- Download file 7.46 kB
-
https://huggingface.co/PowerMachine/khtst-rust/resolve/main/scripts/67_publicar_v070.py
- Command line
-
hf download hf://PowerMachine/khtst-rust/scripts/67_publicar_v070.py
-
curl -L -o 67_publicar_v070.py https://huggingface.co/PowerMachine/khtst-rust/resolve/main/scripts/67_publicar_v070.py
7.46 kB
| #!/usr/bin/env python3 | |
| """67_publicar_v070.py — Publicação da v0.7.0 no HF (UM ÚNICO upload_folder | |
| organizado — o HF bloqueia envios parciais em sequência e em curto espaço | |
| de tempo; uma única operação atômica evita o bloqueio). | |
| Fases: | |
| 1. inventário da conta + APAGAMENTO de estados de treino remanescentes; | |
| 2. varredura local do VALOR do token (nenhum arquivo pode contê-lo); | |
| 3. UM ÚNICO upload_folder (sem estados — checkpoints regeneráveis via | |
| scripts 61/56); | |
| 4. verificação pós-upload (0 estados, módulos-chave presentes, contagem); | |
| 5. varredura REMOTA do valor do token (baixa e inspeciona os arquivos). | |
| Token: EXCLUSIVAMENTE via variável de ambiente HF_TOKEN (nunca em arquivo). | |
| """ | |
| import os, sys, tempfile | |
| ARQUIVOS_EXCLUIR_DIRS = {"target", ".cargo", "__pycache__", ".git", ".venv", | |
| "skills", "externos"} | |
| ARQUIVOS_EXCLUIR_NOME = {"shard_treino.jsonl", "shard_validacao.jsonl", | |
| "bpe.json", "rustup-init.sh"} | |
| SUFIXOS_ESTADO = (".pt", ".pth", ".ckpt", ".safetensors", ".bin", ".npz", | |
| ".msgpack") | |
| NOMES_ESTADO = {"gerador_conceitos.json", "tokenizador_conceitos.json", | |
| "gerador_aritmetica.json"} | |
| def coletar(pasta): | |
| arquivos = {} | |
| for raiz, dirs, fs in os.walk(pasta): | |
| dirs[:] = [d for d in dirs if d not in ARQUIVOS_EXCLUIR_DIRS] | |
| for f in fs: | |
| if f in ARQUIVOS_EXCLUIR_NOME or f in NOMES_ESTADO: | |
| continue | |
| if f.endswith(SUFIXOS_ESTADO): | |
| continue | |
| if f.endswith(".so") or f in (".gitignore", "Cargo.lock.ori"): | |
| continue | |
| if f.startswith("hf_") or f.startswith("intros_"): | |
| continue # scripts de análise externa (não fazem parte) | |
| caminho = os.path.join(raiz, f) | |
| rel = os.path.relpath(caminho, pasta) | |
| arquivos[rel] = caminho | |
| return arquivos | |
| def varre_token_em_arquivos(token, pares): | |
| tb = token.encode() | |
| achados = [] | |
| for rel, p in pares.items(): | |
| try: | |
| with open(p, "rb") as f: | |
| if tb in f.read(): | |
| achados.append(rel) | |
| except OSError: | |
| pass | |
| return achados | |
| def main(): | |
| from huggingface_hub import HfApi | |
| token = os.environ.get("HF_TOKEN") | |
| if not token: | |
| print("ERRO: HF_TOKEN ausente"); sys.exit(1) | |
| api = HfApi(token=token) | |
| repo = "PowerMachine/khtst-rust" | |
| # ---------------- 1) inventário da conta + apaga estados ---------------- | |
| print("=== 1) inventário da conta HF (procura estados de treino) ===") | |
| repos = list(api.list_models(author="PowerMachine")) | |
| print(f"repos: {len(repos)}") | |
| total_removidos = 0 | |
| for r in repos: | |
| try: | |
| files = api.list_repo_files(repo_id=r.id, repo_type="model") | |
| except Exception as e: | |
| print(f" {r.id}: erro ao listar ({e})"); continue | |
| estados = [f for f in files | |
| if f.endswith(SUFIXOS_ESTADO) | |
| or f.split("/")[-1] in NOMES_ESTADO | |
| or (".meta.json" in f and "checkpoint" in f)] | |
| if estados: | |
| print(f" {r.id}: APAGANDO {len(estados)} estados") | |
| for f in estados: | |
| api.delete_file(path_in_repo=f, repo_id=r.id, repo_type="model") | |
| total_removidos += len(estados) | |
| else: | |
| print(f" {r.id}: {len(files)} arquivos, 0 estados") | |
| print(f"estados removidos no total: {total_removidos}") | |
| # ---------------- 2) varredura local do token ---------------- | |
| pasta = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| arquivos = coletar(pasta) | |
| print(f"\n=== 2) varredura local: {len(arquivos)} arquivos ===") | |
| achados = varre_token_em_arquivos(token, arquivos) | |
| if achados: | |
| print(f"ERRO: valor do token encontrado em: {achados}"); sys.exit(1) | |
| print("varredura de token local: limpa") | |
| import subprocess | |
| home = os.path.expanduser("~") | |
| try: | |
| saida = subprocess.run( | |
| ["grep", "-rl", token, home, "--include=*.py", "--include=*.json", | |
| "--include=*.md", "--include=*.sh", "--include=*.toml"], | |
| capture_output=True, text=True, timeout=120) | |
| if saida.stdout.strip(): | |
| print(f"ERRO: token no home: {saida.stdout.strip()}"); sys.exit(1) | |
| except Exception: | |
| pass | |
| print("varredura do home: limpa") | |
| # ---------------- 3) UM ÚNICO upload_folder ---------------- | |
| # FILTRO por ignore_patterns (glob) — NUNCA passar ignore_patterns=None: | |
| # o upload_folder subiria a pasta INTEIRA (target/, estados, .so — | |
| # lição v0.7.0: o primeiro envio subiu 1 971 arquivos e precisou de | |
| # delete_folder de recuperação). | |
| ignores = ( | |
| [f"{d}/**" for d in ARQUIVOS_EXCLUIR_DIRS] | |
| + [f"{d}" for d in ARQUIVOS_EXCLUIR_DIRS] | |
| + list(ARQUIVOS_EXCLUIR_NOME) + list(NOMES_ESTADO) | |
| + list(SUFIXOS_ESTADO) | |
| + ["*.so", ".gitignore", "hf_*.py", "hf_*.json", "intros_*.json"] | |
| ) | |
| print(f"\n=== 3) upload_folder ÚNICO ({len(arquivos)} arquivos) ===") | |
| api.upload_folder( | |
| repo_id=repo, repo_type="model", folder_path=pasta, | |
| ignore_patterns=ignores, commit_message="v0.7.0: FNH gate de punição + " | |
| "árvore de pesos indexada (arestas duplas) + quebra-cabeça do " | |
| "Pensamento + NLP/NLG + decodificador especulativo + auto-ajuste SOM " | |
| "limitado + correções v070-1/2/3 — 73/73 gates, 84/84 cargo, " | |
| "provas r-28..r-32", | |
| ) | |
| print("upload concluído") | |
| # ---------------- 4) verificação pós-upload ---------------- | |
| print("\n=== 4) verificação pós-upload ===") | |
| files = api.list_repo_files(repo_id=repo, repo_type="model") | |
| estados = [f for f in files if f.endswith(SUFIXOS_ESTADO) | |
| or f.split("/")[-1] in NOMES_ESTADO] | |
| assert not estados, f"estados publicados: {estados}" | |
| chaves = ["src/fnh.rs", "src/arvore_pesos.rs", "src/nlp.rs", "src/nlg.rs", | |
| "src/pensamento.rs", "scripts/61_treino_v070.py", | |
| "scripts/66_suite_v070.py", | |
| "docs/memorias/r-28-analise-repos-design-v070.md", | |
| "docs/memorias/r-32-resultados-v070.md", | |
| "resultados/suite_v070_final.json"] | |
| faltando = [c for c in chaves if c not in files] | |
| assert not faltando, f"faltando: {faltando}" | |
| print(f"repo: {len(files)} arquivos | 0 estados | módulos-chave OK") | |
| # ---------------- 5) varredura REMOTA do token ---------------- | |
| print("\n=== 5) varredura REMOTA do valor do token ===") | |
| with tempfile.TemporaryDirectory() as tmp: | |
| achados_remotos = [] | |
| for f in files: | |
| if f.endswith((".py", ".rs", ".md", ".json", ".toml", ".sh", ".cfg", | |
| ".txt", ".jsonl")): | |
| try: | |
| p = api.hf_hub_download(repo_id=repo, repo_type="model", | |
| filename=f, local_dir=tmp) | |
| with open(p, "rb") as fh: | |
| if token.encode() in fh.read(): | |
| achados_remotos.append(f) | |
| except Exception: | |
| pass | |
| if achados_remotos: | |
| print(f"ERRO: token remoto em: {achados_remotos}"); sys.exit(1) | |
| print("varredura remota: limpa") | |
| print("\nPUBLICAÇÃO v0.7.0 CONCLUÍDA") | |
| if __name__ == "__main__": | |
| main() | |