#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Publica o KHTST v20 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_v20" 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_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 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 v20 — IPC durável: 10 correções do usuário com provas " "(cache-line 256B, CRC32 no decode Rust, bounds, read_unaligned, " "EINTR retry, magic na init, THP, BufferError atômico, pending " "clear, _PEND_MAX) + receber_frame sem perda de frames; estresse " "APROVADO (1B–1MiB, p50 21,4µs/p99 45,2µs) e Modelo→Modelo em " "TREINO REAL (2 processos, 12/12 frames, 0 descartes, ambos " "aprendem); PID-MoE (Teo 32.10), Stiefel rígido + retração polar " "(Teo 32.11), GuardaRuntime RAM (Teo 32.12); doc 32 + PLANO/" "RELATORIO/README atualizados; suíte v20 48/48, regressão " "v1–v19 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_v20 = [a for a in arq_hub if "32-v20-ipc-durabilidade" in a or a.endswith("pid_moe.py") or a.endswith("guarda_runtime.py") or a.endswith("28_teste_ipc_stress.py") or a.endswith("29_ipc_treino_modelo.py")] 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"chaves v20 presentes: {len(chaves_v20)} -> {chaves_v20}") ok = (len(estados) == 0 and len(resid) == 0 and len(chaves_v20) == 5) print("PUBLICAÇÃO v20 " + ("OK ✓" if ok else "COM PROBLEMAS ✗")) return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())