#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Publica o KHTST v23 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 v23) · LICENSE · requirements · configs/ (L=6) · src/khtst/ (PCGrad correto, RoPE com desloc, validação 5:1, checkpoint atômico, IPC com header lido — .so recompilado, dedup/NFC, filtro P9, hub com buffer, acumulação sem viés, MoA com árvore viva) · auditoria_independente/ (4 scripts hardened + 3 docs da auditoria RESOLVIDOS) · scripts/ (36 teste v23, 37 gráficos, 38 publicar) · docs/matematica/ (00–35, doc 35 NOVO com erratas nos 26/28) · tests/ (v1–v23 + conftest) · patches/ · PLANO_KHMAMBAJEPA.md · RELATORIO_KHTST.md · graficos/ (v23 incluso). EXCLUI: venv/ · __pycache__ · cache_dados · telemetria_out · cache_hub_tmp · .git · build · estados*/ · stage*/ · upload/ · 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/38_publicar_v23.py [--repo ...] """ import argparse import os import re import shutil import sys RAIZ = "/home/z/my-project/khtst" STAGE = "/home/z/my-project/khtst/stage_publicar_v23" 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", "stage_publicar_v21", "stage_publicar_v22", "stage_publicar_v23", "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) 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 v23 — auditoria independente integrada: correções válidas " "aplicadas com provas (doc 35, Teos 35.1-35.14) e claims " "refutadas documentadas (doc 35 §11). PCGrad PROJETA " "(fator=dot/n2, g=gm+(ga-fator*gm) — 0 violações I1/I2/I3 em " "100.083 pares; o antigo reescalava e violava a não-piora em " "25,3%); RoPE com OFFSET de cache (desloc absoluto propagado — " "score de decode varia com t; era constante 2,756113); tronco " "5:1 REAL (n_camadas=6, validação do campo que constrói o " "tronco; L=3 reprovado); checkpoint ATÔMICO (tmp+fsync+replace+" "fsync-dir, hash obrigatória, antigos por último); IPC lê a " "capacidade do HEADER (divergência=ValueError, fallback+Cython); " "dedup texto+entrada+saida+midia (29,5%->8,7%) + NFC; filtro P9 " "sem vazamento eval->treino (9 benchmarks pulados, hendrycks em " "train, Fable train); acumulação sem viés na retomada; hub com " "buffer + fechar(); mecanismo árvore VIVO (A-23, y+0*y_a=y bit " "a bit); erratas doc 26/28 (Sigma 1/tau diverge, T_tau=168,76, " "dH/dT=Var/T3, h^2/12 densidade contínua); auditoria HARDENED " "em auditoria_independente/ (4 scripts com assert+exit, 4/4 " "verdes); corpus real fresco 1612 registros com P9 (MATH-500 " "PULADA); A/B pareado 48 passos + grad peso_arvore vivo medido; " "suíte v23 35/35, regressão v1-v22 zero, verificar_tudo 49✓"), 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_v23 = [a for a in arq_hub if "35-auditoria-independente" in a or a.endswith("auditoria_independente/README.md") or a.endswith("scripts/36_teste_v23.py") or a.endswith("scripts/37_graficos_v23.py") or a.endswith("tests/test_khtst_v23.py") or a.endswith("tests/conftest.py") or a.endswith("graficos/v23/v23_evidencias.png") or a.endswith("auditoria_independente/verif_pcgrad_invariantes.py")] estados_locais = [a for a in arq_hub if a.startswith("cache_dados/") or a.startswith("telemetria_out/")] 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"cache_dados/telemetria vazados: {len(estados_locais)}") print(f"chaves v23 presentes: {len(chaves_v23)} -> {chaves_v23}") ok = (len(estados) == 0 and len(resid) == 0 and len(estados_locais) == 0 and len(chaves_v23) == 7) print("PUBLICAÇÃO v23 " + ("OK ✓" if ok else "COM PROBLEMAS ✗")) return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())