import os, sys, pandas as pd, numpy as np, torch, gradio as gr from pytorch_tabnet.pretraining import TabNetPretrainer from huggingface_hub import HfApi REPO_ID = os.getenv("SPACE_ID") or os.getenv("HF_SPACE_ID") # 两种写法都兼容 MODEL_DIR = "tabnet_ae" ZIP_PATH = f"{MODEL_DIR}/tabnet.zip" DEVICE = "cpu" def train_if_needed(): if os.path.exists(ZIP_PATH): print("✅ Found existing model, skip training.", flush=True) return # ---------- 训练 ---------- print("🚀 No model found – training …", flush=True) df = pd.read_csv( "https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv" ) X = df["Temp"].values.reshape(-1, 1).astype("float32") model = TabNetPretrainer(device_name="cpu", n_d=8, n_a=8, n_steps=3) model.fit(X, max_epochs=1, batch_size=1024) os.makedirs(MODEL_DIR, exist_ok=True) model.save_model(f"{MODEL_DIR}/tabnet") # 会生成 tabnet.zip print("🏁 Training done & model saved.", flush=True) # ---------- 可选上传 ---------- HF_TOKEN = os.getenv("HF_TOKEN") if HF_TOKEN and REPO_ID: try: print("📤 Uploading weights to Hub …", flush=True) HfApi().upload_folder( repo_id=REPO_ID, folder_path=MODEL_DIR, path_in_repo=MODEL_DIR, repo_type="space", # ← 关键:避免 RepositoryNotFound token=HF_TOKEN, ) print("✅ Upload complete.", flush=True) except Exception as e: print(f"⚠️ Upload failed (ignored): {e}", flush=True) train_if_needed() # ---------- 加载 ---------- tabnet = TabNetPretrainer() tabnet.load_model(ZIP_PATH) print("🎉 Model loaded, launching Gradio.", flush=True) # ---------- Gradio ---------- def detect(csv_file): df = pd.read_csv(csv_file.name) X = df.select_dtypes("number").values.astype("float32") preds, recon = tabnet.predict(X) err = np.mean((X - recon) ** 2, axis=1) df["anomaly"] = err > np.quantile(err, 0.995) return df.head(50) demo = gr.Interface( fn=detect, inputs=gr.File(label="Upload CSV"), outputs=gr.DataFrame(), title="🩺 TabNet Anomaly Detection (CPU, auto-train on first run)" ) if __name__ == "__main__": demo.launch()