File size: 2,349 Bytes
9420014
36ae08f
5949794
36ae08f
9420014
 
 
 
5949794
9420014
 
 
5949794
 
9420014
 
5949794
 
 
 
 
 
 
36ae08f
9420014
 
 
5949794
9420014
5949794
9420014
 
 
 
 
 
 
 
 
 
 
 
 
5949794
9420014
5949794
9420014
7347252
9420014
 
7347252
9420014
 
 
87d977d
7347252
9420014
87d977d
7347252
 
 
 
87d977d
7347252
9420014
5e096f3
9420014
36ae08f
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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()