Spaces:
Runtime error
Runtime error
Download app.py from ppw2004/NLP_coursework_llm: direct link, hf CLI and curl.
- Browser
- Download file 2.03 kB
-
https://huggingface.co/spaces/ppw2004/NLP_coursework_llm/resolve/main/app.py
- Command line
-
hf download hf://spaces/ppw2004/NLP_coursework_llm/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ppw2004/NLP_coursework_llm/resolve/main/app.py
2.03 kB
| import os | |
| # 【修改1】设置 HF 镜像,防止下载分词器超时 | |
| os.environ["HF_ENDPOINT"] = "https://hf-mirror.com" | |
| import gradio as gr | |
| import torch | |
| from transformers import BertTokenizer, BertForSequenceClassification | |
| import torch.nn.functional as F | |
| # 1. 配置路径 | |
| # 注意:这里需要改为你运行main.py后生成的模型文件夹路径 | |
| # 如果你是在本地运行,可能是 "./experiments" 或者具体的checkpoint文件夹 | |
| model_path = "./experiments" | |
| base_model_name = "bert-base-uncased" | |
| # 2. 加载模型和分词器 | |
| # 加载分词器 (通常使用基础模型的tokenizer) | |
| tokenizer = BertTokenizer.from_pretrained(base_model_name) | |
| # 加载你微调后的模型 | |
| # 注意:确保你的模型文件夹里有 config.json 和 pytorch_model.bin | |
| model = BertForSequenceClassification.from_pretrained(model_path, num_labels=2) | |
| model.eval() # 切换到评估模式 | |
| # 3. 定义预测函数 | |
| def predict(text): | |
| # 数据预处理 | |
| inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512) | |
| # 模型推理 | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| logits = outputs.logits | |
| # 获取概率 (Softmax) | |
| probabilities = F.softmax(logits, dim=1) | |
| # 构建返回结果 (假设是二分类:0-Real, 1-Fake,根据你的实际标签调整) | |
| # labels 需要和你训练时的标签对应 | |
| labels = ["Real News", "Fake News"] | |
| # Gradio 需要返回一个 {label: probability} 的字典 | |
| return {labels[i]: float(probabilities[0][i]) for i in range(len(labels))} | |
| # 4. 创建 Gradio 界面 | |
| iface = gr.Interface( | |
| fn=predict, | |
| inputs=gr.Textbox(lines=2, placeholder="请输入一段新闻文本..."), | |
| outputs=gr.Label(num_top_classes=2), | |
| title="虚假新闻检测 Demo", | |
| description="输入新闻文本,模型将判断其真伪。", | |
| examples=[["这里可以填入一些测试用的示例文本"]] | |
| ) | |
| # 5. 启动应用 | |
| if __name__ == "__main__": | |
| iface.launch(share=True) |