#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Publica o KHTST v21 no HuggingFace — UM ÚNICO COMMIT COMPLETO (anti-bloqueio do Hub: `upload_folder` + `delete_patterns=["*"]` substitui ATOMICAMENTE todo o conteúdo; nunca há uploads parciais em sequência curta — requisito do usuário). INCLUI: README (card v20) · LICENSE · requirements · configs/ (chaves v20) · src/khtst/ (ipc/ v20 com header 256 B + write_exact + BufferError + _PEND_MAX, nucleo/pid_moe.py + guarda_runtime.py, ortogonais.py com polar+rígido, treinador wired) · scripts/ (28 estresse, 29 modelo→modelo em treino) · docs/matematica/ (provas 00–32, doc 32 NOVO) · tests/ (v1–v20) · patches/ · PLANO_KHMAMBAJEPA.md · RELATORIO_KHTST.md · graficos. EXCLUI: venv/ · __pycache__ · cache_dados · telemetria_out · cache_hub_tmp · .git · build · estados*/ · stage*/ · qualquer `.pt/.pth/.ckpt/.safetensors/.bin` (REQUISITO: nenhum estado de treino no Hub) · qualquer arquivo com padrão de token hf_... SEGURANÇA: token EXCLUSIVAMENTE da variável de ambiente HF_TOKEN — nunca gravado em arquivo, log, repo ou remote URL. Uso: HF_TOKEN=hf_... python3 scripts/30_publicar_v20.py [--repo ...] """ import argparse import os import re import shutil import sys RAIZ = "/home/z/my-project/khtst_v20" STAGE = "/home/z/my-project/khtst_v20/stage_publicar_v21" IGNORAR_DIRS = {"__pycache__", "cache_dados", "telemetria_out", "cache_hub_tmp", ".git", "build", "venv", ".venv", "estados_local", "estados_local_teste", "estados", "stage_publicar", "stage_publicar_v17", "stage_publicar_v18", "stage_publicar_v19", "stage_publicar_v20", "hf_stage", "download", "upload", "node_modules"} IGNORAR_NOMES = {"resultados_v21.json", "resultados_v20.json"} IGNORAR_EXT = (".pt", ".pth", ".ckpt", ".safetensors", ".pyc", ".pt.tmp", ".bin") PADRAO_TOKEN = re.compile(r"hf_[A-Za-z0-9]{30,}") RESIDUOS_PROIBIDOS = ("bugwatch",) def preparar_stage() -> int: if os.path.exists(STAGE): shutil.rmtree(STAGE) n = 0 for raiz, dirs, arquivos in os.walk(RAIZ): dirs[:] = [d for d in dirs if d not in IGNORAR_DIRS] rel = os.path.relpath(raiz, RAIZ) alvo_raiz = os.path.join(STAGE, rel) if rel != "." else STAGE os.makedirs(alvo_raiz, exist_ok=True) for a in arquivos: if a.endswith(IGNORAR_EXT) or a.startswith("."): continue if a in IGNORAR_NOMES: continue if any(r in a.lower() for r in RESIDUOS_PROIBIDOS): print(f" [RESÍDUO] ignorado: {a}") continue origem = os.path.join(raiz, a) destino = os.path.join(alvo_raiz, a) shutil.copy2(origem, destino) n += 1 return n def auditar_stage() -> int: """Auditoria: 0 estados de treino, 0 tokens, 0 resíduos.""" problemas = 0 n_arq = 0 for raiz, dirs, arquivos in os.walk(STAGE): for a in arquivos: n_arq += 1 cam = os.path.join(raiz, a) if a.endswith(IGNORAR_EXT): print(f" [ESTADO] {cam}"); problemas += 1 continue try: with open(cam, "rb") as f: dados = f.read() except OSError: continue if PADRAO_TOKEN.search(dados.decode("utf-8", errors="ignore")): print(f" [TOKEN] {cam}"); problemas += 1 print(f"stage: {n_arq} arquivos | problemas: {problemas}") return problemas def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--repo", default="PowerMachine/khtst-multimodal-ptbr") args = ap.parse_args() token = os.environ.get("HF_TOKEN") if not token: print("ERRO: HF_TOKEN ausente no ambiente"); return 1 from huggingface_hub import HfApi, upload_folder api = HfApi(token=token) # v21: garantir que o Rust REMOVIDO não volta if os.path.isdir(os.path.join(RAIZ, "src", "khtst", "ipc", "rust")): print("ERRO: src/khtst/ipc/rust existe — remova antes de publicar") return 1 print("== preparando stage ==") n = preparar_stage() print(f"{n} arquivos copiados para o stage") print("== auditando stage (estados/tokens/resíduos) ==") if auditar_stage() > 0: print("ERRO: stage contém itens proibidos — abortando"); return 1 print("== commit ÚNICO no Hub (upload_folder + delete_patterns) ==") upload_folder( repo_id=args.repo, repo_type="model", folder_path=STAGE, commit_message=( "KHTST v21 — fonte única do IPC (Rust removido por DRY; layout " "com _Static_assert compile-time + auditoria import-time); " "Newton-Schulz com normalização espectral CERTIFICADA " "(min(sqrt(|A|inf)/1.2, |X|F), janela invariante 1.255 provada, " "nunca pior que v20, Teos 33.3-33.6); imagem adaptativa " "(letterbox+LANCZOS+janela saliente+upscale limitado, Teos " "33.7-33.10); hot-paths Cython (conv causal fundida com " "gradiente analítico exato, ganho 2.3-7.6x; top-k parcial do " "roteador, Teos 33.11-33.13); tabela v17 de 18 sinais FECHADA " "no treinador com 8 produtores reais (Teo 33.14); A/B/C/D " "pareado real 48 passos (ganhos 1.10-1.12x, leitura honesta); " "doc 33 + PLANO/RELATORIO/README; suíte v21 40/40, regressão " "v1-v20 zero, verificar_tudo 49✓; deprecados removidos"), delete_patterns=["*"], token=token, ) print("== auditoria pós-upload ==") info = api.repo_info(args.repo, files_metadata=False) arq_hub = [s.rfilename for s in info.siblings] estados = [a for a in arq_hub if a.endswith(IGNORAR_EXT)] resid = [a for a in arq_hub if any(r in a.lower() for r in RESIDUOS_PROIBIDOS)] chaves_v21 = [a for a in arq_hub if "33-v21-fonte-unica" in a or a.endswith("ipc/layout.py") or a.endswith("mamba3hot.pyx") or a.endswith("redimensionar.py") or a.endswith("31_teste_v21.py") or a.endswith("test_khtst_v21.py")] rust_hub = [a for a in arq_hub if "/rust/" in a or a.endswith("Cargo.toml")] print(f"arquivos no Hub: {len(arq_hub)}") print(f"estados de treino no Hub: {len(estados)} {estados[:5]}") print(f"resíduos: {len(resid)}") print(f"Rust remanescente no Hub: {len(rust_hub)} {rust_hub[:5]}") print(f"chaves v21 presentes: {len(chaves_v21)} -> {chaves_v21}") ok = (len(estados) == 0 and len(resid) == 0 and len(rust_hub) == 0 and len(chaves_v21) == 6) ok = (len(estados) == 0 and len(resid) == 0 and len(chaves_v20) == 5) print("PUBLICAÇÃO v21 " + ("OK ✓" if ok else "COM PROBLEMAS ✗")) return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())