改成导excel
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
from flask import Blueprint, current_app, request
|
||||
from flask import Blueprint, current_app, request, send_file, after_this_request
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
from app.extensions import db
|
||||
@@ -367,3 +367,56 @@ def import_samples():
|
||||
|
||||
db.session.commit()
|
||||
return ok({"created": created, "updated": updated}, "样本导入完成")
|
||||
|
||||
|
||||
@spam_bp.post("/export/xlsx")
|
||||
@jwt_required()
|
||||
def export_xlsx():
|
||||
user = current_user()
|
||||
if not user:
|
||||
return fail("用户不存在", 404)
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
items = payload.get("items") or []
|
||||
if not isinstance(items, list) or not items:
|
||||
return fail("items 必须是非空数组", 400)
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import pandas as pd
|
||||
|
||||
rows = []
|
||||
for item in items:
|
||||
tokens = item.get("reason_tokens") or []
|
||||
token_str = "; ".join(t.get("token", "") for t in tokens) if isinstance(tokens, list) else ""
|
||||
prediction_text = "垃圾信息" if item.get("prediction") == "spam" else "正常信息"
|
||||
|
||||
rows.append({
|
||||
"文本": item.get("text", ""),
|
||||
"判定结果": prediction_text,
|
||||
"分类标签": item.get("category_label", ""),
|
||||
"置信度": f"{float(item.get("confidence", 0) or 0) * 100:.2f}%",
|
||||
"垃圾概率": f"{float(item.get("spam_probability", 0) or 0) * 100:.2f}%",
|
||||
"正常概率": f"{float(item.get("ham_probability", 0) or 0) * 100:.2f}%",
|
||||
"风险关键词": token_str,
|
||||
})
|
||||
|
||||
df = pd.DataFrame(rows)
|
||||
tmp = tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False)
|
||||
tmp.close()
|
||||
df.to_excel(tmp.name, index=False, engine="openpyxl")
|
||||
|
||||
@after_this_request
|
||||
def cleanup(response):
|
||||
try:
|
||||
os.unlink(tmp.name)
|
||||
except Exception:
|
||||
pass
|
||||
return response
|
||||
|
||||
return send_file(
|
||||
tmp.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
as_attachment=True,
|
||||
download_name="batch_detect.xlsx",
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user