feat: 职称评审核验助手首版 v1.0.1(verify-promotion-metric-default)
All checks were successful
技能自动化发布 / release (push) Successful in 7s
All checks were successful
技能自动化发布 / release (push) Successful in 7s
This commit is contained in:
46
scripts/service/entitlement_service.py
Normal file
46
scripts/service/entitlement_service.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""在线鉴权(可选模板)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
import requests
|
||||
from jiangchang_skill_core import config
|
||||
|
||||
|
||||
def check_entitlement(skill_slug: str) -> Tuple[bool, str]:
|
||||
auth_base = (config.get("JIANGCHANG_AUTH_BASE_URL") or "").strip().rstrip("/")
|
||||
if not auth_base:
|
||||
return True, ""
|
||||
user_id = (config.get("JIANGCHANG_USER_ID") or "").strip()
|
||||
if not user_id:
|
||||
return False, "鉴权失败:缺少用户身份(JIANGCHANG_USER_ID)"
|
||||
|
||||
auth_api_key = (config.get("JIANGCHANG_AUTH_API_KEY") or "").strip()
|
||||
timeout = int((config.get("JIANGCHANG_AUTH_TIMEOUT_SECONDS") or "5").strip())
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if auth_api_key:
|
||||
headers["Authorization"] = f"Bearer {auth_api_key}"
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"skill_slug": skill_slug,
|
||||
"trace_id": (config.get("JIANGCHANG_TRACE_ID") or "").strip(),
|
||||
"context": {"entry": "main.py"},
|
||||
}
|
||||
try:
|
||||
res = requests.post(f"{auth_base}/api/entitlements/check", json=payload, headers=headers, timeout=timeout)
|
||||
except requests.RequestException as exc:
|
||||
return False, f"鉴权请求失败:{exc}"
|
||||
if res.status_code != 200:
|
||||
return False, f"鉴权服务异常:HTTP {res.status_code}"
|
||||
try:
|
||||
body = res.json()
|
||||
except ValueError:
|
||||
return False, "鉴权服务异常:返回非 JSON"
|
||||
code = body.get("code")
|
||||
data = body.get("data") or {}
|
||||
if code != 200:
|
||||
return False, str(body.get("msg") or "鉴权失败")
|
||||
if not data.get("allow", False):
|
||||
return False, str(data.get("reason") or "未购买或已过期")
|
||||
return True, ""
|
||||
78
scripts/service/html_page_service.py
Normal file
78
scripts/service/html_page_service.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""技能 HTML 报告页:写入 `{skill_data}/html/*.html`(宿主扫描预览)。
|
||||
|
||||
契约要点(权威说明见 `references/ACTIONS.md`「HTML 页面报告」):
|
||||
|
||||
- 目录:仅一层 `html/*.html`(非递归)
|
||||
- 重新生成 Action id 必须为 `render-html`(宿主硬编码)
|
||||
- 页面布局底线见 `references/ACTIONS.md`「宿主预览布局」;模板壳 `assets/html/example-report.html`
|
||||
- 成功后建议 `steps: refreshCatalog` 以重扫侧栏
|
||||
- 本模块只提供路径/模板/原子写;业务 KPI/表格由各技能自行填充
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import Mapping
|
||||
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.runtime_paths import get_html_dir, get_skill_root
|
||||
|
||||
# Host Data Management looks up this exact Skill Action id for「重新生成」.
|
||||
HOST_HTML_RENDER_ACTION_ID = "render-html"
|
||||
|
||||
_UNSAFE_NAME = re.compile(r"[\\/]|^\.\.|\.\.$")
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def assert_html_filename(filename: str) -> str:
|
||||
name = (filename or "").strip()
|
||||
if not name.lower().endswith(".html"):
|
||||
raise ValueError(f"html filename must end with .html: {filename!r}")
|
||||
if _UNSAFE_NAME.search(name) or "/" in name or "\\" in name:
|
||||
raise ValueError(f"html filename must be a basename only: {filename!r}")
|
||||
if len(name) > 200:
|
||||
raise ValueError(f"html filename too long: {filename!r}")
|
||||
return name
|
||||
|
||||
|
||||
def html_page_path(filename: str, *, create_dir: bool = True) -> str:
|
||||
return os.path.join(get_html_dir(create=create_dir), assert_html_filename(filename))
|
||||
|
||||
|
||||
def load_html_template(relative_under_skill_root: str) -> str:
|
||||
"""Load UTF-8 template from skill root (e.g. ``assets/html/example-report.html``)."""
|
||||
rel = (relative_under_skill_root or "").strip().replace("\\", "/")
|
||||
if not rel or rel.startswith("/") or ".." in rel.split("/"):
|
||||
raise ValueError(f"invalid template path: {relative_under_skill_root!r}")
|
||||
path = os.path.join(get_skill_root(), *rel.split("/"))
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def render_html_placeholders(template: str, mapping: Mapping[str, str]) -> str:
|
||||
"""Replace ``{{KEY}}`` tokens. Unknown keys are left as-is."""
|
||||
page = template
|
||||
for key, value in mapping.items():
|
||||
page = page.replace("{{" + str(key) + "}}", str(value))
|
||||
return page
|
||||
|
||||
|
||||
def write_html_page(filename: str, html: str) -> str:
|
||||
"""Atomically write UTF-8 HTML under ``html/``. Returns absolute path."""
|
||||
dest = html_page_path(filename, create_dir=True)
|
||||
tmp = dest + ".tmp"
|
||||
text = html if isinstance(html, str) else str(html)
|
||||
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, dest)
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("html_page_written path=%s bytes=%s", dest, len(text.encode("utf-8")))
|
||||
return dest
|
||||
184
scripts/service/report_service.py
Normal file
184
scripts/service/report_service.py
Normal file
@@ -0,0 +1,184 @@
|
||||
"""《核验报告》HTML 组装。
|
||||
|
||||
- 每案例一份 `report-{case_id}.html`(三色结论 + 达标矩阵 + 补充材料清单)
|
||||
- 批量核验另生成汇总页 `brief-{batch_no}.html`
|
||||
写入 `{skill_data}/html/`,宿主数据管理侧栏可预览;重建走固定 Action id `render-html`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from service.html_page_service import load_html_template, render_html_placeholders, write_html_page
|
||||
from util.logging_config import get_skill_logger
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
_TEMPLATE_REL = "assets/html/verify-report.html"
|
||||
|
||||
_VERDICT_BADGE = {"安全": "tier-strong", "边缘": "tier-try", "硬伤": "tier-strong"}
|
||||
_COLOR_BADGE = {"green": "tier-strong", "yellow": "tier-try", "red": "tag-red", "gray": "tier-not"}
|
||||
_COLOR_MARK = {"green": "🟢 达标", "yellow": "🟡 边缘", "red": "🔴 硬伤", "gray": "⚪ 待核"}
|
||||
|
||||
|
||||
def _esc(value: Any) -> str:
|
||||
import html
|
||||
|
||||
return html.escape(str(value if value is not None else "—"), quote=True)
|
||||
|
||||
|
||||
def _verdict_badge(verdict: str) -> str:
|
||||
return {"安全": "tier-strong", "边缘": "tier-try", "硬伤": "tag-red"}.get(verdict, "tier-not")
|
||||
|
||||
|
||||
def _matrix_rows(matrix: list[dict[str, Any]]) -> str:
|
||||
rows = []
|
||||
for item in matrix:
|
||||
color = str(item.get("color") or "gray")
|
||||
badge = _COLOR_BADGE.get(color, "tier-not")
|
||||
required = item.get("required")
|
||||
required_text = "—" if required is None else f"{required:g}"
|
||||
margin = item.get("margin")
|
||||
margin_text = "—" if margin is None else f"{margin * 100:.1f}%"
|
||||
rows.append(
|
||||
"<tr>"
|
||||
f"<td>{_esc(item.get('metric'))}</td>"
|
||||
f"<td class='nowrap'>{_esc(required_text)}</td>"
|
||||
f"<td class='nowrap'>{_esc(item.get('actual'))}</td>"
|
||||
f"<td class='nowrap'>{_esc(margin_text)}</td>"
|
||||
f"<td class='nowrap'><span class='tag {badge}'>{_COLOR_MARK.get(color, color)}</span></td>"
|
||||
f"<td class='muted'>{_esc(item.get('basis'))}</td>"
|
||||
"</tr>"
|
||||
)
|
||||
if not rows:
|
||||
rows.append('<tr><td colspan="6" class="muted">无</td></tr>')
|
||||
return "".join(rows)
|
||||
|
||||
|
||||
def _advice_list(matrix: list[dict[str, Any]]) -> str:
|
||||
advices = [item.get("advice") for item in matrix if item.get("advice")]
|
||||
if not advices:
|
||||
return '<p class="muted">无补充事项。</p>'
|
||||
items = "".join(f"<li>{_esc(a)}</li>" for a in advices)
|
||||
return f"<ol class='reasons'>{items}</ol>"
|
||||
|
||||
|
||||
def build_verify_html(result: dict[str, Any], batch_no: str = "") -> str:
|
||||
verdict = str(result.get("verdict") or "")
|
||||
mark = {"安全": "🟢 安全", "边缘": "🟡 边缘", "硬伤": "🔴 硬伤"}.get(verdict, verdict)
|
||||
body = f"""
|
||||
<div class="verdict-line">
|
||||
<span class="tag {_verdict_badge(verdict)}">{mark}</span>
|
||||
<span class="muted">{_esc(result.get("department") or "")} · 申报 {_esc(result.get("apply_rank") or "—")} · 批次 {_esc(batch_no or result.get("batch_no"))}</span>
|
||||
</div>
|
||||
<p class="para">{_esc(result.get("summary"))}</p>
|
||||
<div class="section"><h2>硬指标达标矩阵</h2>
|
||||
<table>
|
||||
<tr><th>指标</th><th>最低要求</th><th>实有</th><th>余量</th><th>判定</th><th>依据</th></tr>
|
||||
{_matrix_rows(result.get("matrix") or [])}
|
||||
</table>
|
||||
</div>
|
||||
<div class="section"><h2>补充材料清单</h2>{_advice_list(result.get("matrix") or [])}</div>
|
||||
<footer>核验仅针对硬指标形式审查,不构成评审结论;门槛以人事处最新文件为准,是否通过评审由评委会决定。</footer>
|
||||
"""
|
||||
template = load_html_template(_TEMPLATE_REL)
|
||||
return render_html_placeholders(
|
||||
template,
|
||||
{
|
||||
"TITLE": f"职称申报核验报告 · {result.get('teacher_name') or ''}",
|
||||
"GENERATED_AT": "",
|
||||
"BODY": body,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def write_report_for_kernel(*, result: dict[str, Any], batch_no: str) -> str:
|
||||
html_text = build_verify_html(result, batch_no)
|
||||
log = _log()
|
||||
path = write_html_page(f"report-{result['case_id']}.html", html_text)
|
||||
if log:
|
||||
log.info("verify_report_written case_id=%s path=%s stage=report", result["case_id"], path)
|
||||
return path
|
||||
|
||||
|
||||
def build_report_for_case_id(case_id: int) -> str:
|
||||
"""按案例 id 从库中取数并重写 HTML(重建入口用)。"""
|
||||
from db.connection import get_conn
|
||||
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("report_render_start case_id=%s stage=render", case_id)
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM verify_cases WHERE id = ?", (case_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"核验案例不存在:{case_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
record = dict(zip(columns, row))
|
||||
finally:
|
||||
conn.close()
|
||||
result = dict(record)
|
||||
try:
|
||||
result["matrix"] = json.loads(record.get("matrix_json") or "[]")
|
||||
except (TypeError, ValueError):
|
||||
result["matrix"] = []
|
||||
html_text = build_verify_html(result)
|
||||
path = write_html_page(f"report-{case_id}.html", html_text)
|
||||
log.info("report_render_done case_id=%s path=%s stage=render", case_id, path)
|
||||
return path
|
||||
|
||||
|
||||
def build_batch_brief(*, batch_no: str, results: list[dict[str, Any]]) -> str:
|
||||
rows = []
|
||||
for result in results:
|
||||
verdict = str(result.get("verdict") or "")
|
||||
badge = _verdict_badge(verdict)
|
||||
red_items = [m for m in result.get("matrix") or [] if m.get("color") == "red"]
|
||||
red_text = "、".join(str(m.get("metric")) for m in red_items) if red_items else "—"
|
||||
rows.append(
|
||||
"<tr>"
|
||||
f"<td>{_esc(result.get('teacher_name'))}</td>"
|
||||
f"<td class='muted'>{_esc(result.get('department'))}</td>"
|
||||
f"<td class='nowrap'>{_esc(result.get('apply_rank'))}</td>"
|
||||
f"<td class='nowrap'><span class='tag {badge}'>{_esc(verdict)}</span></td>"
|
||||
f"<td class='muted'>{_esc(red_text)}</td>"
|
||||
"</tr>"
|
||||
)
|
||||
if not rows:
|
||||
rows.append('<tr><td colspan="5" class="muted">本期无核验结果。</td></tr>')
|
||||
|
||||
counts: dict[str, int] = {}
|
||||
for result in results:
|
||||
counts[str(result.get("verdict"))] = counts.get(str(result.get("verdict")), 0) + 1
|
||||
chips = " ".join(
|
||||
f"<span class='tag {_verdict_badge(v)}'>{_esc(v)} × {n}</span>" for v, n in sorted(counts.items())
|
||||
)
|
||||
|
||||
body = f"""
|
||||
<div class="verdict-line">
|
||||
{chips or '<span class="muted">无</span>'}
|
||||
<span class="muted">批次 {_esc(batch_no)} · 案例 {_esc(len(results))} 个</span>
|
||||
</div>
|
||||
<div class="section"><h2>核验结论一览</h2>
|
||||
<table><tr><th>教师</th><th>学院</th><th>申报级别</th><th>结论</th><th>硬伤项</th></tr>{''.join(rows)}</table>
|
||||
</div>
|
||||
<footer>汇总由批量核验自动生成,供师资科排序复核;核验不构成评审结论。</footer>
|
||||
"""
|
||||
template = load_html_template(_TEMPLATE_REL)
|
||||
page = render_html_placeholders(
|
||||
template,
|
||||
{"TITLE": "职称核验汇总", "GENERATED_AT": "", "BODY": body},
|
||||
)
|
||||
path = write_html_page(f"brief-{batch_no}.html", page)
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("verify_brief_written batch_no=%s path=%s stage=report", batch_no, path)
|
||||
return path
|
||||
57
scripts/service/sibling_bridge.py
Normal file
57
scripts/service/sibling_bridge.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""兄弟技能 CLI 调用工具。
|
||||
|
||||
通过子进程调用同级其他 skill 的 main.py,并解析 JSON 输出。
|
||||
具体调用哪些兄弟技能,由复制后的业务 skill 在 service 层按需决定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from util.logging_config import subprocess_env_with_trace
|
||||
from util.runtime_paths import get_skills_root
|
||||
|
||||
|
||||
def call_sibling_json(skill_slug: str, args: List[str]) -> Optional[Dict[str, Any]]:
|
||||
"""通用兄弟技能调用器。
|
||||
|
||||
Args:
|
||||
skill_slug: 兄弟技能的 slug(即同级目录名)。
|
||||
args: 传给 main.py 的命令行参数列表。
|
||||
|
||||
Returns:
|
||||
若兄弟技能输出可解析的 JSON 对象则返回 dict;否则返回 None。
|
||||
"""
|
||||
script_path = os.path.join(get_skills_root(), skill_slug, "scripts", "main.py")
|
||||
if not os.path.isfile(script_path):
|
||||
return None
|
||||
proc = subprocess.run(
|
||||
[sys.executable, script_path, *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
env=subprocess_env_with_trace(),
|
||||
)
|
||||
raw = (proc.stdout or "").strip()
|
||||
if not raw or raw.startswith("ERROR"):
|
||||
return None
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def get_sibling_main_path(skill_slug: str) -> str:
|
||||
"""获取兄弟技能的 main.py 绝对路径。
|
||||
|
||||
使用示例(在 task_service.py 中):
|
||||
from service.sibling_bridge import get_sibling_main_path, call_sibling_json
|
||||
result = call_sibling_json("account-manager", ["list", "--limit", "10"])
|
||||
"""
|
||||
return os.path.join(get_skills_root(), skill_slug, "scripts", "main.py")
|
||||
84
scripts/service/task_run_support.py
Normal file
84
scripts/service/task_run_support.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""任务运行辅助:录屏信息组装与 CLI 输出(通用模板,无业务逻辑)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
def build_video_info(
|
||||
video_summary: dict[str, Any],
|
||||
compose_context_before: Optional[dict[str, Any]] = None,
|
||||
compose_context_after: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""将 RpaVideoSession.summary() 转为 finish() / CLI 可用的 video 块。"""
|
||||
return {
|
||||
"enabled": video_summary.get("enabled", False),
|
||||
"path": video_summary.get("path"),
|
||||
"capture_path": video_summary.get("capture_path"),
|
||||
"record_log_path": video_summary.get("record_log_path"),
|
||||
"warnings": list(video_summary.get("warnings") or []),
|
||||
"voiceover_path": video_summary.get("voiceover_path"),
|
||||
"music_path": video_summary.get("music_path"),
|
||||
"audio_warnings": list(video_summary.get("audio_warnings") or []),
|
||||
"compose_context": {
|
||||
**(compose_context_before or {}),
|
||||
"after_compose": compose_context_after or {},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def merge_video_into_result_summary(
|
||||
payload: dict[str, Any],
|
||||
video_info: Optional[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""把 video artifact 字段写入 finish() 结果对象(video / video_path 等)。"""
|
||||
if not video_info:
|
||||
return payload
|
||||
payload = dict(payload)
|
||||
payload["video"] = video_info
|
||||
payload["video_path"] = video_info.get("path")
|
||||
payload["raw_video"] = video_info.get("capture_path")
|
||||
payload["video_log"] = video_info.get("record_log_path")
|
||||
payload["video_warnings"] = list(video_info.get("warnings") or [])
|
||||
payload["voiceover_path"] = video_info.get("voiceover_path")
|
||||
payload["music_path"] = video_info.get("music_path")
|
||||
payload["audio_warnings"] = list(video_info.get("audio_warnings") or [])
|
||||
return payload
|
||||
|
||||
|
||||
def _print_video_summary(video_block: Optional[dict[str, Any]]) -> None:
|
||||
"""任务完成后在 CLI 打印录屏路径、日志与诊断信息。"""
|
||||
if not isinstance(video_block, dict) or not video_block.get("enabled"):
|
||||
return
|
||||
record_log = video_block.get("record_log_path")
|
||||
if record_log:
|
||||
print(f"录屏日志:{record_log}")
|
||||
path = video_block.get("path")
|
||||
if path:
|
||||
print(f"录屏路径:{path}")
|
||||
else:
|
||||
print("录屏路径:未生成")
|
||||
warnings = video_block.get("warnings") or []
|
||||
if warnings:
|
||||
print(f"视频诊断:{'; '.join(str(w) for w in warnings)}")
|
||||
capture = video_block.get("capture_path")
|
||||
if capture:
|
||||
print(f"原始录屏路径:{capture}")
|
||||
voiceover = video_block.get("voiceover_path")
|
||||
if voiceover:
|
||||
print(f"旁白路径:{voiceover}")
|
||||
music = video_block.get("music_path")
|
||||
if music:
|
||||
print(f"背景音乐:{music}")
|
||||
audio_warnings = video_block.get("audio_warnings") or []
|
||||
if audio_warnings:
|
||||
print(f"音频诊断:{'; '.join(str(w) for w in audio_warnings)}")
|
||||
compose_ctx = video_block.get("compose_context")
|
||||
if isinstance(compose_ctx, dict):
|
||||
print(
|
||||
"视频合成上下文:"
|
||||
f"media_assets_root={compose_ctx.get('media_assets_root', '')}; "
|
||||
f"ffmpeg_path={compose_ctx.get('ffmpeg_path', '')}; "
|
||||
f"background_music_issue={compose_ctx.get('background_music_issue') or ''}; "
|
||||
f"background_music_sample_path={compose_ctx.get('background_music_sample_path', '')}"
|
||||
)
|
||||
570
scripts/service/task_service.py
Normal file
570
scripts/service/task_service.py
Normal file
@@ -0,0 +1,570 @@
|
||||
"""任务编排层:job_context / emit / finish、鉴权与错误转换。
|
||||
|
||||
领域业务在 ``service/verify_service.py``(核验内核)、
|
||||
``service/threshold_service.py``(门槛/案例/统计)、
|
||||
``service/report_service.py``(HTML 简报),由本模块调用;
|
||||
多入口(CLI / Action / 对话 / cron)复用同一内核,禁止按入口分叉业务。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from jiangchang_skill_core import collect_runtime_diagnostics, config, format_runtime_health_lines
|
||||
from jiangchang_skill_core.activity import JobStopped, emit, finish, job_context
|
||||
|
||||
from jiangchang_skill_core.rpa.video_session import RpaVideoSession
|
||||
from service.entitlement_service import check_entitlement
|
||||
from service.task_run_support import (
|
||||
_print_video_summary,
|
||||
build_video_info,
|
||||
merge_video_into_result_summary,
|
||||
)
|
||||
from util.constants import LOG_LOGGER_NAME, PLATFORM_KIT_MIN_VERSION, SKILL_SLUG, SKILL_VERSION
|
||||
from util.logging_config import get_skill_logger, setup_skill_logging
|
||||
from util.runtime_paths import get_db_path, get_skill_root
|
||||
from db.connection import init_db
|
||||
|
||||
|
||||
def _get_task_logger():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
setup_skill_logging(SKILL_SLUG, LOG_LOGGER_NAME)
|
||||
return get_skill_logger()
|
||||
|
||||
|
||||
def _print_json(payload: dict[str, Any]) -> None:
|
||||
print(json.dumps(payload, ensure_ascii=False))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 模板演示入口(保留:满足 POLICY-RPA-003 录屏集成与 CLI run 契约;不承载本技能业务)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def _run_template_demo(target: Optional[str], input_id: Optional[str]) -> tuple[int, dict[str, Any]]:
|
||||
"""最小 RpaVideoSession 示范:不启动浏览器、不执行业务,仅演示录屏包裹范式。"""
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
data_dir = get_skill_root()
|
||||
|
||||
async with RpaVideoSession(
|
||||
skill_slug=SKILL_SLUG,
|
||||
skill_data_dir=data_dir,
|
||||
batch_id=batch_id,
|
||||
title="开始执行示例任务",
|
||||
closing_title="示例任务执行完成",
|
||||
) as video:
|
||||
video.add_step("准备执行示例任务")
|
||||
if target:
|
||||
video.add_step(f"接收目标参数:{target}")
|
||||
if input_id:
|
||||
video.add_step(f"接收输入标识:{input_id}")
|
||||
video.add_step("示例任务执行完成")
|
||||
|
||||
video_summary = video.summary()
|
||||
video_info = build_video_info(video_summary, {}, {})
|
||||
return 1, video_info
|
||||
|
||||
|
||||
def cmd_run(target: Optional[str] = None, input_id: Optional[str] = None) -> int:
|
||||
"""模板演示入口:本技能主能力请使用 broadcast 等业务命令。"""
|
||||
log = _get_task_logger()
|
||||
task_type = "demo"
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info(
|
||||
"task_start task_type=%s target_id=%s input_id=%s stage=run",
|
||||
task_type,
|
||||
target,
|
||||
input_id,
|
||||
)
|
||||
emit("开始处理任务", skill=SKILL_SLUG, stage="run")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning(
|
||||
"entitlement_failed task_type=%s stage=auth error_code=ENTITLEMENT_DENIED",
|
||||
task_type,
|
||||
)
|
||||
emit("鉴权失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="auth")
|
||||
finish(
|
||||
status="failed",
|
||||
message=reason,
|
||||
skill=SKILL_SLUG,
|
||||
error_code="ENTITLEMENT_DENIED",
|
||||
stage="auth",
|
||||
)
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
log.info("entitlement_ok task_type=%s stage=auth", task_type)
|
||||
log.info("rpa_start stage=demo_prepare task_type=%s", task_type)
|
||||
log.info("task_run_demo_start target_id=%s input_id=%s stage=demo_prepare", target, input_id)
|
||||
rc, video_info = asyncio.run(_run_template_demo(target, input_id))
|
||||
log.info("rpa_done stage=demo_prepare status=ok")
|
||||
log.info(
|
||||
"task_run_demo_done target_id=%s input_id=%s stage=demo_finish status=failed",
|
||||
target,
|
||||
input_id,
|
||||
)
|
||||
_print_video_summary(video_info)
|
||||
|
||||
summary_payload = merge_video_into_result_summary(
|
||||
{
|
||||
"template_demo": True,
|
||||
"target": target,
|
||||
"input_id": input_id,
|
||||
},
|
||||
video_info,
|
||||
)
|
||||
|
||||
log.warning(
|
||||
"task_failed task_type=%s stage=demo_finish error_code=TEMPLATE_STUB",
|
||||
task_type,
|
||||
)
|
||||
finish(
|
||||
status="failed",
|
||||
message="模板演示入口未承载本技能业务",
|
||||
skill=SKILL_SLUG,
|
||||
error_code="TEMPLATE_STUB",
|
||||
**summary_payload,
|
||||
)
|
||||
print("ERROR:TEMPLATE_STUB 这是模板演示入口,请使用 verify-metric 命令执行职称硬指标核验。")
|
||||
return rc
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception(
|
||||
"task_failed task_type=%s target_id=%s input_id=%s",
|
||||
task_type,
|
||||
target,
|
||||
input_id,
|
||||
)
|
||||
emit("任务失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="run")
|
||||
finish(
|
||||
status="failed",
|
||||
message="任务执行异常,详见统一日志",
|
||||
skill=SKILL_SLUG,
|
||||
stage="run",
|
||||
)
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 基础命令
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_config_path() -> int:
|
||||
example_path = os.path.join(get_skill_root(), ".env.example")
|
||||
env_path = config.get_env_file_path() or ""
|
||||
_print_json(
|
||||
{
|
||||
"skill": SKILL_SLUG,
|
||||
"env_path": env_path,
|
||||
"example_path": os.path.abspath(example_path),
|
||||
}
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_health() -> int:
|
||||
runtime = collect_runtime_diagnostics(
|
||||
skill_slug=SKILL_SLUG,
|
||||
platform_kit_min_version=PLATFORM_KIT_MIN_VERSION,
|
||||
skill_root=get_skill_root(),
|
||||
)
|
||||
example_path = os.path.join(get_skill_root(), ".env.example")
|
||||
env_path = config.get_env_file_path() or ""
|
||||
env_exists = bool(env_path and os.path.isfile(env_path))
|
||||
|
||||
health_status = "failed" if runtime.has_fatal_issues else "ok"
|
||||
lines = [
|
||||
f"{SKILL_SLUG} health: {health_status}",
|
||||
*format_runtime_health_lines(runtime),
|
||||
f"env_path: {env_path}",
|
||||
f"env_exists: {env_exists}",
|
||||
f"example_path: {os.path.abspath(example_path)}",
|
||||
]
|
||||
for line in lines:
|
||||
print(line)
|
||||
return 1 if runtime.has_fatal_issues else 0
|
||||
|
||||
|
||||
def cmd_version() -> int:
|
||||
_print_json({"version": SKILL_VERSION, "skill": SKILL_SLUG})
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_init_db() -> int:
|
||||
"""幂等创建/迁移本地 SQLite 与数据管理元数据(宿主 install/upgrade 可调用)。"""
|
||||
log = _get_task_logger()
|
||||
try:
|
||||
init_db()
|
||||
except Exception as exc: # noqa: BLE001 — CLI 边界,统一成可机读失败
|
||||
print(
|
||||
json.dumps(
|
||||
{"ok": False, "skill": SKILL_SLUG, "error": str(exc)},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 1
|
||||
_print_json({"ok": True, "skill": SKILL_SLUG, "db_path": get_db_path()})
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 门槛库维护
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _parse_json_arg(raw: str, label: str) -> list[dict[str, Any]]:
|
||||
import sys
|
||||
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
raise ValueError(f"缺少导入 JSON({label})")
|
||||
if text == "-":
|
||||
text = sys.stdin.read().strip()
|
||||
elif text.startswith(("[", "{")):
|
||||
pass
|
||||
elif os.path.isfile(text):
|
||||
with open(text, encoding="utf-8") as f:
|
||||
text = f.read().strip()
|
||||
else:
|
||||
raise ValueError(f"{label} 不是有效文件路径或 JSON:{text[:80]}")
|
||||
try:
|
||||
payload = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"导入 JSON 解析失败:{exc}") from exc
|
||||
if isinstance(payload, dict):
|
||||
for key in ("thresholds", "cases", "items"):
|
||||
if isinstance(payload.get(key), list):
|
||||
payload = payload[key]
|
||||
break
|
||||
else:
|
||||
payload = [payload]
|
||||
if not isinstance(payload, list):
|
||||
raise ValueError(f"{label} 应为对象数组")
|
||||
return payload
|
||||
|
||||
|
||||
def cmd_set_threshold(
|
||||
*,
|
||||
rank: str,
|
||||
metric_key: str,
|
||||
metric_name: str = "",
|
||||
min_value: float,
|
||||
unit: str = "",
|
||||
basis_doc: str = "",
|
||||
clause: str = "",
|
||||
) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.threshold_service import upsert_threshold
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=set_threshold rank=%s metric=%s stage=threshold", rank, metric_key)
|
||||
emit("开始更新评审门槛", skill=SKILL_SLUG, stage="threshold")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=set_threshold stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
payload = upsert_threshold({
|
||||
"rank": rank,
|
||||
"metric_key": metric_key,
|
||||
"metric_name": metric_name,
|
||||
"min_value": float(min_value),
|
||||
"unit": unit,
|
||||
"basis_doc": basis_doc,
|
||||
"clause": clause,
|
||||
})
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"门槛已更新:{rank}/{metric_key}", skill=SKILL_SLUG, stage="threshold")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=set_threshold error_code=THRESHOLD_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="THRESHOLD_INVALID", stage="threshold")
|
||||
print(f"ERROR:THRESHOLD_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=set_threshold stage=threshold")
|
||||
finish(status="failed", message="门槛更新异常,详见统一日志", skill=SKILL_SLUG, stage="threshold")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_import_thresholds(thresholds_json: str) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.threshold_service import import_thresholds
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=import_thresholds stage=threshold")
|
||||
emit("开始批量导入门槛", skill=SKILL_SLUG, stage="threshold")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=import_thresholds stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
rows = _parse_json_arg(thresholds_json, "--thresholds-json")
|
||||
payload = import_thresholds(rows)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"导入完成:新增 {payload['created']},更新 {payload['updated']}", skill=SKILL_SLUG, stage="threshold")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=import_thresholds error_code=THRESHOLD_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="THRESHOLD_INVALID", stage="threshold")
|
||||
print(f"ERROR:THRESHOLD_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=import_thresholds stage=threshold")
|
||||
finish(status="failed", message="门槛导入异常,详见统一日志", skill=SKILL_SLUG, stage="threshold")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_view_thresholds(rank: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.threshold_service import list_thresholds
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=view_thresholds rank=%s", rank)
|
||||
try:
|
||||
thresholds = list_thresholds(rank=rank)
|
||||
_print_json({"ok": True, "count": len(thresholds), "thresholds": thresholds})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=view_thresholds")
|
||||
print("ERROR:QUERY_FAILED 门槛查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 核验主命令
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_verify_metric(
|
||||
*,
|
||||
teacher_name: str,
|
||||
apply_rank: str,
|
||||
metrics_json: str,
|
||||
department: str = "",
|
||||
) -> int:
|
||||
"""职称硬指标核验(主命令,同步)。"""
|
||||
log = _get_task_logger()
|
||||
from service.verify_service import run_verify
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=verify_metric teacher=%s rank=%s stage=verify", teacher_name, apply_rank)
|
||||
emit("开始职称硬指标核验", skill=SKILL_SLUG, stage="verify")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=verify_metric stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
metrics = _parse_json_arg(metrics_json, "--metrics-json")
|
||||
if not metrics:
|
||||
raise ValueError("申报指标 JSON 为空")
|
||||
case = metrics[0] if len(metrics) == 1 else dict(metrics[0])
|
||||
if teacher_name:
|
||||
case.setdefault("teacherName", teacher_name)
|
||||
if department:
|
||||
case.setdefault("department", department)
|
||||
case.setdefault("applyRank", apply_rank)
|
||||
|
||||
result = run_verify([case])
|
||||
brief = result["reports"][0]
|
||||
_print_json({
|
||||
"ok": True,
|
||||
"batch_no": result["batch_no"],
|
||||
"case_id": brief["case_id"],
|
||||
"teacher_name": brief["teacher_name"],
|
||||
"verdict": brief["verdict"],
|
||||
"summary": brief["summary"],
|
||||
"matrix": brief["matrix"],
|
||||
"report_file": brief["report_file"],
|
||||
"disclaimer": result["disclaimer"],
|
||||
})
|
||||
finish(
|
||||
status="success",
|
||||
message=f"核验完成:{brief['teacher_name']} 结论 {brief['verdict']}",
|
||||
skill=SKILL_SLUG,
|
||||
stage="verify",
|
||||
batch_no=result["batch_no"],
|
||||
)
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=verify_metric error_code=METRIC_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="METRIC_INVALID", stage="verify")
|
||||
print(f"ERROR:METRIC_INVALID {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=verify_metric stage=verify")
|
||||
emit("核验失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="verify")
|
||||
finish(status="failed", message="核验执行异常,详见统一日志", skill=SKILL_SLUG, stage="verify")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_verify_batch_input() -> int:
|
||||
"""批量核验(async Action 入口):核验 input/ 目录中的申报案例 JSON。"""
|
||||
log = _get_task_logger()
|
||||
from service.verify_service import run_verify
|
||||
from util.runtime_paths import get_input_dir
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=verify_batch stage=batch")
|
||||
emit("开始批量核验", skill=SKILL_SLUG, stage="batch")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=verify_batch stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
input_dir = get_input_dir()
|
||||
files = sorted(
|
||||
os.path.join(input_dir, name)
|
||||
for name in os.listdir(input_dir)
|
||||
if name.lower().endswith(".json")
|
||||
)
|
||||
if not files:
|
||||
message = f"input 目录没有申报案例 JSON:{input_dir}"
|
||||
log.warning("task_failed task_type=verify_batch error_code=METRIC_INVALID stage=batch")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="METRIC_INVALID", stage="batch")
|
||||
print(f"ERROR:METRIC_INVALID {message}")
|
||||
return 1
|
||||
|
||||
cases = []
|
||||
for path in files:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
payload = json.load(f)
|
||||
if isinstance(payload, dict):
|
||||
payload = payload.get("cases") or [payload]
|
||||
cases.extend(payload)
|
||||
|
||||
result = run_verify(cases)
|
||||
for index, brief in enumerate(result["reports"], start=1):
|
||||
emit(
|
||||
f"[{index}/{len(result['reports'])}] {brief['teacher_name']}:{brief['verdict']}",
|
||||
skill=SKILL_SLUG,
|
||||
stage="batch",
|
||||
)
|
||||
_print_json({
|
||||
"ok": True,
|
||||
"batch_no": result["batch_no"],
|
||||
"count": result["count"],
|
||||
"verdict_counts": result["verdict_counts"],
|
||||
"brief_file": result["brief_file"],
|
||||
})
|
||||
finish(status="success", message=f"批量核验完成 {result['count']} 个案例", skill=SKILL_SLUG, stage="batch", batch_no=result["batch_no"])
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=verify_batch stage=batch")
|
||||
emit("批量核验失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="batch")
|
||||
finish(status="failed", message="批量核验执行异常,详见统一日志", skill=SKILL_SLUG, stage="batch")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 案例与统计
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_list_cases(limit: int = 20, verdict: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.threshold_service import list_cases
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_cases limit=%s verdict=%s", limit, verdict)
|
||||
try:
|
||||
cases = list_cases(limit=limit, verdict=verdict)
|
||||
_print_json({"ok": True, "count": len(cases), "cases": cases})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_cases")
|
||||
print("ERROR:QUERY_FAILED 核验案例查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_show_case(case_id: int) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.threshold_service import get_case
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=show_case case_id=%s", case_id)
|
||||
try:
|
||||
case = get_case(int(case_id))
|
||||
_print_json({"ok": True, "case": case})
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=show_case error_code=CASE_NOT_FOUND detail=%s", exc)
|
||||
print(f"ERROR:CASE_NOT_FOUND {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=show_case")
|
||||
print("ERROR:QUERY_FAILED 核验案例查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_render_html(report_id: Optional[int] = None) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.report_service import build_report_for_case_id
|
||||
from service.threshold_service import list_cases
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=render_html report_id=%s stage=render", report_id)
|
||||
try:
|
||||
if report_id:
|
||||
targets = [int(report_id)]
|
||||
else:
|
||||
targets = [c["id"] for c in list_cases(limit=10)]
|
||||
if not targets:
|
||||
log.warning("task_failed task_type=render_html error_code=CASE_NOT_FOUND stage=render")
|
||||
finish(status="failed", message="暂无可重建的核验案例", skill=SKILL_SLUG, error_code="CASE_NOT_FOUND", stage="render")
|
||||
print("ERROR:CASE_NOT_FOUND 暂无可重建的核验案例")
|
||||
return 1
|
||||
written = [{"case_id": cid, "path": build_report_for_case_id(cid)} for cid in targets]
|
||||
_print_json({"ok": True, "count": len(written), "reports": written})
|
||||
finish(status="success", message=f"已重建 {len(written)} 份核验报告", skill=SKILL_SLUG, stage="render")
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=render_html error_code=CASE_NOT_FOUND detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="CASE_NOT_FOUND", stage="render")
|
||||
print(f"ERROR:CASE_NOT_FOUND {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=render_html stage=render")
|
||||
finish(status="failed", message="报告重建异常,详见统一日志", skill=SKILL_SLUG, stage="render")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_stats() -> int:
|
||||
log = _get_task_logger()
|
||||
from service.threshold_service import stats
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=stats")
|
||||
try:
|
||||
_print_json(stats())
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=stats")
|
||||
print("ERROR:QUERY_FAILED 统计查询异常,详见统一日志")
|
||||
return 1
|
||||
188
scripts/service/threshold_service.py
Normal file
188
scripts/service/threshold_service.py
Normal file
@@ -0,0 +1,188 @@
|
||||
"""评审门槛库 / 核验案例 的维护与查询。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from service.verify_service import _METRIC_ALIASES, _snake, norm_metrics
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.timeutil import now_unix
|
||||
|
||||
_KNOWN_RANKS = ("副教授", "教授")
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def upsert_threshold(fields: dict[str, Any]) -> dict[str, Any]:
|
||||
"""按(级别+指标键)幂等写入门槛。"""
|
||||
normalized = norm_metrics({str(k): v for k, v in fields.items()})
|
||||
rank = str(normalized.get("rank") or fields.get("rank") or "").strip()
|
||||
metric_key = str(normalized.get("metricKey") or fields.get("metric_key") or fields.get("metricKey") or "").strip()
|
||||
metric_name = str(normalized.get("metricName") or fields.get("metric_name") or "").strip()
|
||||
rank = rank if rank in _KNOWN_RANKS else (str(fields.get("rank") or "").strip() or rank)
|
||||
if rank not in _KNOWN_RANKS:
|
||||
raise ValueError(f"申报级别只接受 {'、'.join(_KNOWN_RANKS)}:{rank}")
|
||||
if not metric_key:
|
||||
raise ValueError("指标键(metric_key)不能为空")
|
||||
min_value = fields.get("min_value", fields.get("minValue"))
|
||||
try:
|
||||
min_value = float(min_value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f"最低要求必须为数字:{min_value}") from exc
|
||||
if min_value < 0:
|
||||
raise ValueError(f"最低要求必须非负:{min_value}")
|
||||
|
||||
metric_name = metric_name or str(_METRIC_ALIASES.get(metric_key, (metric_key,))[0])
|
||||
values = {
|
||||
"rank": rank,
|
||||
"metric_key": metric_key,
|
||||
"metric_name": metric_name,
|
||||
"min_value": min_value,
|
||||
"unit": str(fields.get("unit") or "").strip(),
|
||||
"basis_doc": str(fields.get("basis_doc") or fields.get("basisDoc") or "").strip(),
|
||||
"clause": str(fields.get("clause") or "").strip(),
|
||||
}
|
||||
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM threshold_rules WHERE rank = ? AND metric_key = ?", (rank, metric_key))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
threshold_id = int(row[0])
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE threshold_rules
|
||||
SET metric_name = ?, min_value = ?, unit = ?, basis_doc = ?, clause = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(values["metric_name"], values["min_value"], values["unit"], values["basis_doc"], values["clause"], now_unix(), threshold_id),
|
||||
)
|
||||
action = "updated"
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO threshold_rules
|
||||
(rank, metric_key, metric_name, min_value, unit, basis_doc, clause, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(values["rank"], values["metric_key"], values["metric_name"], values["min_value"], values["unit"], values["basis_doc"], values["clause"], now_unix(), now_unix()),
|
||||
)
|
||||
threshold_id = int(cur.lastrowid)
|
||||
action = "created"
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("threshold_upserted rank=%s metric=%s action=%s stage=threshold", rank, metric_key, action)
|
||||
return {"ok": True, "rank": rank, "metric_key": metric_key, "id": threshold_id, "action": action}
|
||||
|
||||
|
||||
def import_thresholds(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
if not isinstance(rows, list) or not rows:
|
||||
raise ValueError("导入内容应为非空 JSON 数组(门槛)")
|
||||
if len(rows) > 200:
|
||||
raise ValueError(f"单次导入条数过多({len(rows)}),上限 200 条")
|
||||
results = [upsert_threshold(row) for row in rows]
|
||||
return {
|
||||
"ok": True,
|
||||
"count": len(results),
|
||||
"created": sum(1 for r in results if r["action"] == "created"),
|
||||
"updated": sum(1 for r in results if r["action"] == "updated"),
|
||||
"items": results,
|
||||
}
|
||||
|
||||
|
||||
def list_thresholds(rank: str = "") -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if rank:
|
||||
cur.execute("SELECT * FROM threshold_rules WHERE rank = ? ORDER BY id", (rank,))
|
||||
else:
|
||||
cur.execute("SELECT * FROM threshold_rules ORDER BY rank, id")
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
|
||||
|
||||
def list_cases(limit: int = 20, verdict: str = "") -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
limit = max(1, min(int(limit), 200))
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if verdict:
|
||||
cur.execute(
|
||||
"SELECT id, batch_no, teacher_name, department, apply_rank, verdict, report_file, created_at FROM verify_cases WHERE verdict = ? ORDER BY id DESC LIMIT ?",
|
||||
(verdict, limit),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"SELECT id, batch_no, teacher_name, department, apply_rank, verdict, report_file, created_at FROM verify_cases ORDER BY id DESC LIMIT ?",
|
||||
(limit,),
|
||||
)
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
|
||||
|
||||
def get_case(case_id: int) -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM verify_cases WHERE id = ?", (case_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"核验案例不存在:{case_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
case = dict(zip(columns, row))
|
||||
finally:
|
||||
conn.close()
|
||||
for key in ("matrix_json", "metrics_json"):
|
||||
try:
|
||||
case[key[:-5]] = json.loads(case.get(key) or "[]")
|
||||
except (TypeError, ValueError):
|
||||
case[key[:-5]] = [] if key == "matrix_json" else {}
|
||||
return case
|
||||
|
||||
|
||||
def stats() -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT verdict, COUNT(*) FROM verify_cases GROUP BY verdict")
|
||||
by_verdict = {str(r[0]): int(r[1]) for r in cur.fetchall()}
|
||||
cur.execute("SELECT COUNT(*) FROM threshold_rules")
|
||||
threshold_total = int(cur.fetchone()[0])
|
||||
cur.execute("SELECT COUNT(*) FROM verify_cases")
|
||||
case_total = int(cur.fetchone()[0])
|
||||
cur.execute(
|
||||
"SELECT teacher_name, department, apply_rank FROM verify_cases WHERE verdict = '硬伤' ORDER BY id DESC LIMIT 5"
|
||||
)
|
||||
red_cases = [{"teacher_name": r[0], "department": r[1], "apply_rank": r[2]} for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"ok": True,
|
||||
"case_total": case_total,
|
||||
"by_verdict": by_verdict,
|
||||
"threshold_total": threshold_total,
|
||||
"red_cases": red_cases,
|
||||
}
|
||||
288
scripts/service/verify_service.py
Normal file
288
scripts/service/verify_service.py
Normal file
@@ -0,0 +1,288 @@
|
||||
"""职称硬指标核验内核(唯一业务内核)。
|
||||
|
||||
核验规则(对齐《核心建设内容:各部门"Skill"深度需求规格书》人事处 Skill 001):
|
||||
R1 逐项比对:实有 < 最低要求 → 红(硬伤,附依据条款)
|
||||
R2 边缘识别:达标但余量 < 10% → 黄(建议补充说明或再积累)
|
||||
R3 安全判定:全部已核项 ≥ 要求 × 1.10 → 绿
|
||||
R4 数据待核:指标缺失 → 灰(不判不达标,提示补材料)
|
||||
R5 综合结论:任一红 → 硬伤(暂缓提交);有黄/灰 → 边缘(建议补充);全绿 → 安全
|
||||
R6 基础条件:学历/任现职年限与门槛同口径比对
|
||||
V1 门槛库完备性:指标无对应门槛 → 请人事处补充配置
|
||||
|
||||
核验仅针对硬指标形式审查,不构成评审结论。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.timeutil import now_unix
|
||||
|
||||
VERDICT_SAFE = "安全"
|
||||
VERDICT_BORDER = "边缘"
|
||||
VERDICT_RED = "硬伤"
|
||||
|
||||
_COLOR_PASS = "green"
|
||||
_COLOR_BORDER = "yellow"
|
||||
_COLOR_RED = "red"
|
||||
_COLOR_PENDING = "gray"
|
||||
|
||||
_SAFE_MARGIN = 0.10
|
||||
|
||||
_METRIC_ALIASES = {
|
||||
"teacherName": ("teacher_name", "姓名", "教师姓名"),
|
||||
"department": ("department", "学院", "所属学院"),
|
||||
"applyRank": ("apply_rank", "申报级别", "申报职称"),
|
||||
"presidingProvincial": ("presiding_provincial", "主持省部级项目", "省部级项目"),
|
||||
"corePapers": ("core_papers", "核心期刊论文", "核心论文"),
|
||||
"teachingHours": ("teaching_hours", "年均教学工作量", "教学工作量"),
|
||||
"currentTitleYears": ("current_title_years", "任现职年限", "现职称年限"),
|
||||
"monographs": ("monographs", "专著/教材", "专著"),
|
||||
"awards": ("awards", "教学/科研获奖", "获奖"),
|
||||
"degree": ("degree", "学历学位", "学历"),
|
||||
}
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _camel(name: str) -> str:
|
||||
parts = str(name).split("_")
|
||||
if len(parts) <= 1:
|
||||
return str(name)
|
||||
head, *rest = parts
|
||||
return head + "".join(p[:1].upper() + p[1:] for p in rest if p)
|
||||
|
||||
|
||||
def _snake(name: str) -> str:
|
||||
return "".join("_" + ch.lower() if ch.isupper() else ch for ch in str(name)).lstrip("_")
|
||||
|
||||
|
||||
def norm_metrics(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""归一化申报指标键(兼容 camelCase / snake_case / 中文键,canonical 同时提供两种形式)。"""
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in raw.items():
|
||||
out.setdefault(str(key), value)
|
||||
for canonical, names in _METRIC_ALIASES.items():
|
||||
if str(key) in names or _camel(str(key)) == canonical:
|
||||
out.setdefault(canonical, value)
|
||||
out.setdefault(_snake(canonical), value)
|
||||
return out
|
||||
|
||||
|
||||
def _to_float(value: Any) -> Optional[float]:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def load_thresholds(rank: str) -> dict[str, dict[str, Any]]:
|
||||
"""读取某级别的门槛(metric_key → 门槛行)。"""
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT metric_key, metric_name, min_value, unit, basis_doc, clause FROM threshold_rules WHERE rank = ?",
|
||||
(rank,),
|
||||
)
|
||||
thresholds = {}
|
||||
for metric_key, metric_name, min_value, unit, basis_doc, clause in cur.fetchall():
|
||||
thresholds[str(metric_key)] = {
|
||||
"metric_name": metric_name,
|
||||
"min_value": float(min_value),
|
||||
"unit": unit or "",
|
||||
"basis_doc": basis_doc or "",
|
||||
"clause": clause or "",
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
return thresholds
|
||||
|
||||
|
||||
def verify_metrics(metrics_raw: dict[str, Any], thresholds: dict[str, dict[str, Any]]) -> dict[str, Any]:
|
||||
"""对单个申报案例执行矩阵计算(纯计算,不落库)。"""
|
||||
metrics = norm_metrics(metrics_raw)
|
||||
teacher_name = str(metrics.get("teacherName") or "").strip() or "未命名申报人"
|
||||
apply_rank = str(metrics.get("applyRank") or "").strip()
|
||||
|
||||
matrix: list[dict[str, Any]] = []
|
||||
has_red = False
|
||||
has_yellow_or_gray = False
|
||||
|
||||
for metric_key, threshold in thresholds.items():
|
||||
actual_raw = metrics.get(metric_key)
|
||||
required = float(threshold["min_value"])
|
||||
unit = threshold["unit"]
|
||||
basis = threshold["basis_doc"] + (threshold["clause"] or "")
|
||||
display_actual = metrics.get(metric_key)
|
||||
|
||||
actual = _to_float(actual_raw)
|
||||
if actual is None:
|
||||
has_yellow_or_gray = True
|
||||
matrix.append({
|
||||
"metric": threshold["metric_name"],
|
||||
"metric_key": metric_key,
|
||||
"required": required,
|
||||
"actual": display_actual,
|
||||
"margin": None,
|
||||
"color": _COLOR_PENDING,
|
||||
"basis": basis,
|
||||
"advice": f"数据待核:请补充{threshold['metric_name']}证明材料后重新核验(R4)。",
|
||||
})
|
||||
continue
|
||||
|
||||
margin = round((actual - required) / required, 4) if required > 0 else None
|
||||
if actual < required:
|
||||
has_red = True
|
||||
advice = f"硬伤:{threshold['metric_name']}实有 {actual:g} {unit},未达最低要求 {required:g} {unit},须补足后方可提交"
|
||||
color = _COLOR_RED
|
||||
elif margin is not None and margin < _SAFE_MARGIN:
|
||||
has_yellow_or_gray = True
|
||||
advice = f"边缘项:仅超线 {margin * 100:.1f}%,建议补充说明或继续积累(R2)"
|
||||
color = _COLOR_BORDER
|
||||
else:
|
||||
advice = ""
|
||||
color = _COLOR_PASS
|
||||
matrix.append({
|
||||
"metric": threshold["metric_name"],
|
||||
"metric_key": metric_key,
|
||||
"required": required,
|
||||
"actual": actual,
|
||||
"margin": margin,
|
||||
"color": color,
|
||||
"basis": basis,
|
||||
"advice": f"{advice}(依据:{basis})" if advice else "",
|
||||
})
|
||||
|
||||
# V1:申报指标中存在但门槛库未配置的键(排除标识字段与其别名形式)
|
||||
identity_keys = {"teacher_name", "teacherName", "department", "apply_rank", "applyRank"}
|
||||
known_keys = set(thresholds.keys()) | set(_METRIC_ALIASES.keys())
|
||||
unconfigured = []
|
||||
for key in metrics:
|
||||
if key in identity_keys or key in known_keys:
|
||||
continue
|
||||
if _snake(key) in known_keys or _camel(key) in known_keys:
|
||||
continue
|
||||
if metrics.get(key) in (None, ""):
|
||||
continue
|
||||
if any(key in names for names in _METRIC_ALIASES.values()):
|
||||
continue
|
||||
unconfigured.append(str(key))
|
||||
for key in unconfigured:
|
||||
has_yellow_or_gray = True
|
||||
matrix.append({
|
||||
"metric": str(_METRIC_ALIASES.get(key, (key,))[0]) if key in _METRIC_ALIASES else key,
|
||||
"metric_key": key,
|
||||
"required": None,
|
||||
"actual": metrics.get(key),
|
||||
"margin": None,
|
||||
"color": _COLOR_PENDING,
|
||||
"basis": "",
|
||||
"advice": "门槛库未配置该指标的最低要求,请人事处补充(V1)。",
|
||||
})
|
||||
|
||||
if has_red:
|
||||
verdict = VERDICT_RED
|
||||
summary = "存在不达门槛的硬伤项,暂缓提交;请按矩阵补足材料后重新核验。"
|
||||
elif has_yellow_or_gray:
|
||||
verdict = VERDICT_BORDER
|
||||
summary = "无硬伤,但存在边缘项或待核数据,建议补充说明后提交。"
|
||||
else:
|
||||
verdict = VERDICT_SAFE
|
||||
summary = "全部硬指标超标准 10% 以上,形式审查通过。"
|
||||
|
||||
return {
|
||||
"teacher_name": teacher_name,
|
||||
"department": str(metrics.get("department") or ""),
|
||||
"apply_rank": apply_rank,
|
||||
"verdict": verdict,
|
||||
"summary": summary,
|
||||
"matrix": matrix,
|
||||
}
|
||||
|
||||
|
||||
def run_verify(cases: list[dict[str, Any]], *, batch_no: str = "") -> dict[str, Any]:
|
||||
"""核验内核:逐案例矩阵计算 → 写库 → 生成《核验报告》。"""
|
||||
from service.report_service import write_report_for_kernel, build_batch_brief
|
||||
|
||||
log = _log()
|
||||
init_db()
|
||||
if not cases:
|
||||
raise ValueError("没有可核验的申报案例")
|
||||
if len(cases) > 200:
|
||||
raise ValueError(f"单批核验案例数过多({len(cases)}),上限 200 个")
|
||||
|
||||
batch_no = batch_no or now_unix().to_bytes(5, "big").hex() + uuid.uuid4().hex[:6]
|
||||
if log:
|
||||
log.info("verify_kernel_start batch_no=%s count=%s stage=kernel", batch_no, len(cases))
|
||||
|
||||
results = []
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for case in cases:
|
||||
if not isinstance(case, dict):
|
||||
raise ValueError("申报案例必须是 JSON 对象")
|
||||
result = verify_metrics(case, load_thresholds(str(case.get("applyRank") or case.get("apply_rank") or "").strip()))
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO verify_cases
|
||||
(batch_no, teacher_name, department, apply_rank, metrics_json, verdict, matrix_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_no,
|
||||
result["teacher_name"],
|
||||
result["department"],
|
||||
result["apply_rank"],
|
||||
json.dumps(case, ensure_ascii=False),
|
||||
result["verdict"],
|
||||
json.dumps(result["matrix"], ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
case_id = int(cur.lastrowid)
|
||||
result["case_id"] = case_id
|
||||
result["batch_no"] = batch_no
|
||||
report_file = write_report_for_kernel(result=result, batch_no=batch_no)
|
||||
cur.execute("UPDATE verify_cases SET report_file = ? WHERE id = ?", (report_file, case_id))
|
||||
result["report_file"] = report_file
|
||||
results.append(result)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
verdict_counts: dict[str, int] = {}
|
||||
for result in results:
|
||||
verdict_counts[result["verdict"]] = verdict_counts.get(result["verdict"], 0) + 1
|
||||
brief_file = build_batch_brief(batch_no=batch_no, results=results)
|
||||
|
||||
payload = {
|
||||
"ok": True,
|
||||
"batch_no": batch_no,
|
||||
"count": len(results),
|
||||
"verdict_counts": verdict_counts,
|
||||
"brief_file": brief_file,
|
||||
"disclaimer": "核验仅针对硬指标形式审查,不构成评审结论;门槛以人事处最新文件为准。",
|
||||
"reports": results,
|
||||
}
|
||||
if log:
|
||||
log.info(
|
||||
"verify_kernel_done batch_no=%s count=%s red=%s yellow=%s green=%s stage=kernel",
|
||||
batch_no,
|
||||
len(results),
|
||||
verdict_counts.get(VERDICT_RED, 0),
|
||||
verdict_counts.get(VERDICT_BORDER, 0),
|
||||
verdict_counts.get(VERDICT_SAFE, 0),
|
||||
)
|
||||
return payload
|
||||
Reference in New Issue
Block a user