AnonyAuthor commited on
Commit
c94bb17
·
verified ·
1 Parent(s): 9597739

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import hf_hub_download
3
+ import pickle
4
+ import os
5
+
6
+ # 1) 下载并加载模型(pickle 文件)
7
+ def load_pickled_object(repo_id: str, filename: str):
8
+ # 如果已经下载过就不重复下载
9
+ cache_dir = os.path.join(".cache", repo_id.replace("/", "_"))
10
+ os.makedirs(cache_dir, exist_ok=True)
11
+ local_path = hf_hub_download(
12
+ repo_id=repo_id,
13
+ filename=filename,
14
+ cache_dir=cache_dir,
15
+ force_download=False # 如果本地已有就不重新下
16
+ )
17
+ # 反序列化
18
+ with open(local_path, "rb") as f:
19
+ obj = pickle.load(f)
20
+ return obj
21
+
22
+ # 在 Space 启动时就加载一次
23
+ # 请替换成你自己的 repo id 和 pickle 文件名
24
+ MODEL_REPO = "szk2024/test"
25
+ MODEL_FILE = "evil_model.pkl"
26
+
27
+ try:
28
+ model = load_pickled_object(MODEL_REPO, MODEL_FILE)
29
+ except Exception as e:
30
+ # 如果出错可以打印日志
31
+ print("❌ 模型加载失败:", e)
32
+ model = None
33
+
34
+ # 2) 定义预测函数(根据你的 pickle 对象改写)
35
+ def predict(text: str):
36
+ if model is None:
37
+ return "模型加载失败,请检查日志"
38
+ # 假设你的 pickle 对象有一个 predict 方法
39
+ try:
40
+ res = model.predict([text])
41
+ return str(res)
42
+ except Exception as e:
43
+ return f"预测失败:{e}"
44
+
45
+ # 3) 用 Gradio 搭个简单的文本接口
46
+ iface = gr.Interface(
47
+ fn=predict,
48
+ inputs=gr.Textbox(lines=2, placeholder="在此输入内容…"),
49
+ outputs="text",
50
+ title="Pickle 模型调用示例",
51
+ description="从 Hugging Face Hub 下载 pickle 并反序列化后预测"
52
+ )
53
+
54
+ if __name__ == "__main__":
55
+ iface.launch(server_name="0.0.0.0", server_port=7860)