feat: 申报赛道推荐助手首版 v1.0.1(match-guide-track-default)
All checks were successful
技能自动化发布 / release (push) Successful in 6s
All checks were successful
技能自动化发布 / release (push) Successful in 6s
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
|
||||
349
scripts/service/match_service.py
Normal file
349
scripts/service/match_service.py
Normal file
@@ -0,0 +1,349 @@
|
||||
"""赛道匹配内核(唯一业务内核)。
|
||||
|
||||
匹配算法(对齐《核心建设内容:各部门"Skill"深度需求规格书》科研处 Skill 001):
|
||||
H1/H2 硬门槛过滤(职称 / SCI 一区)→ 剔除并说明原因
|
||||
S1 标签覆盖率 = 教师标签 ∩ 赛道标签 / 赛道标签数
|
||||
S2 优先方向命中(每命中 +0.15,封顶 0.3)
|
||||
S3 综合得分 = 0.7×覆盖率 + 优先命中(百分数展示)
|
||||
T1 分层:≥80 强烈推荐;50~80 可尝试;<50 不建议
|
||||
T2 Top 3 排序输出
|
||||
E1 画像完整性:无研究标签 → 不匹配,提示补录
|
||||
|
||||
全部得分确定性计算、理由可追溯到具体标签;推荐仅供参考,不构成申报决定。
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
TIER_STRONG = "强烈推荐"
|
||||
TIER_TRY = "可尝试"
|
||||
TIER_NOT = "不建议"
|
||||
|
||||
_TIER_RANK = {TIER_NOT: 0, TIER_TRY: 1, TIER_STRONG: 2}
|
||||
|
||||
# 职称档位:数值越大越高职称;门槛 min_title 使用"X及以上"档位
|
||||
_TITLE_RANK = {
|
||||
"助教": 0,
|
||||
"讲师": 1,
|
||||
"助理研究员": 1,
|
||||
"博士后": 1,
|
||||
"副高及以上": 2,
|
||||
"副教授": 2,
|
||||
"副研究员": 2,
|
||||
"高级实验师": 2,
|
||||
"正高及以上": 3,
|
||||
"教授": 3,
|
||||
"研究员": 3,
|
||||
}
|
||||
|
||||
_STRONG_THRESHOLD = 80
|
||||
_TRY_THRESHOLD = 50
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _split_tags(raw: Any) -> list[str]:
|
||||
"""把逗号/分号/顿号分隔的标签文本拆成去空格列表。"""
|
||||
if not raw:
|
||||
return []
|
||||
import re
|
||||
|
||||
return [t for t in (s.strip() for s in re.split(r"[,,;;、\n]", str(raw))) if t]
|
||||
|
||||
|
||||
def _title_rank(title: str) -> Optional[int]:
|
||||
if not title:
|
||||
return None
|
||||
return _TITLE_RANK.get(str(title).strip())
|
||||
|
||||
|
||||
def _min_title_rank(min_title: str) -> Optional[int]:
|
||||
text = str(min_title or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
if text in _TITLE_RANK:
|
||||
return _TITLE_RANK[text]
|
||||
if text.endswith("及以上"):
|
||||
return _TITLE_RANK.get(text[:-3])
|
||||
return None
|
||||
|
||||
|
||||
def _norm_teacher(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""归一化教师画像键(兼容 camelCase / snake_case / 常见中文键)。"""
|
||||
aliases = {
|
||||
"teacherName": ("teacher_name", "姓名", "教师姓名"),
|
||||
"department": ("department", "学院", "所属学院"),
|
||||
"title": ("title", "职称"),
|
||||
"researchTags": ("research_tags", "研究标签", "标签"),
|
||||
"recentPapers": ("recent_papers", "近3年论文", "论文"),
|
||||
"projectHistory": ("project_history", "项目经历", "项目"),
|
||||
"sciQ1Count": ("sci_q1_count", "sci一区", "sci一区篇数"),
|
||||
"corePaperCount": ("core_paper_count", "核心论文", "核心论文篇数"),
|
||||
}
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in raw.items():
|
||||
out.setdefault(str(key), value)
|
||||
for canonical, names in aliases.items():
|
||||
if str(key) in names or _camel(str(key)) == canonical:
|
||||
out.setdefault(canonical, value)
|
||||
return out
|
||||
|
||||
|
||||
def _norm_track(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
aliases = {
|
||||
"year": ("year", "年度", "指南年度"),
|
||||
"agency": ("agency", "学部", "归口"),
|
||||
"programName": ("program_name", "项目类型"),
|
||||
"trackName": ("track_name", "赛道名称", "赛道"),
|
||||
"trackTags": ("track_tags", "需求标签"),
|
||||
"priorityKeywords": ("priority_keywords", "优先方向", "优先资助方向"),
|
||||
"minTitle": ("min_title", "职称门槛"),
|
||||
"minSciQ1": ("min_sci_q1", "sci一区门槛"),
|
||||
"quota": ("quota", "拟资助数"),
|
||||
"sourceDoc": ("source_doc", "指南来源"),
|
||||
}
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in raw.items():
|
||||
out.setdefault(str(key), value)
|
||||
for canonical, names in aliases.items():
|
||||
if str(key) in names or _camel(str(key)) == canonical:
|
||||
out.setdefault(canonical, value)
|
||||
return out
|
||||
|
||||
|
||||
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 _to_int(value: Any) -> Optional[int]:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(float(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def match_teacher(teacher: dict[str, Any], tracks: list[dict[str, Any]], season: str) -> dict[str, Any]:
|
||||
"""对单个教师执行硬门槛过滤 + 标签匹配,返回分层结果(不落库)。"""
|
||||
teacher = _norm_teacher(teacher)
|
||||
tracks = [_norm_track(t) for t in tracks]
|
||||
teacher_name = str(teacher.get("teacherName") or "").strip() or "未命名教师"
|
||||
teacher_tags = _split_tags(teacher.get("researchTags"))
|
||||
papers_text = str(teacher.get("recentPapers") or "")
|
||||
projects_text = str(teacher.get("projectHistory") or "")
|
||||
sci_q1 = _to_int(teacher.get("sciQ1Count")) or 0
|
||||
title_rank = _title_rank(str(teacher.get("title") or ""))
|
||||
|
||||
if not teacher_tags and not papers_text:
|
||||
raise ValueError(f"教师 {teacher_name} 画像不完整:请至少填写研究标签或论文标题(E1)")
|
||||
|
||||
eligible: list[dict[str, Any]] = []
|
||||
excluded: list[dict[str, Any]] = []
|
||||
for track in tracks:
|
||||
track_name = str(track.get("trackName") or "").strip()
|
||||
program = str(track.get("programName") or "").strip()
|
||||
label = f"{program}·{track_name}" if program else track_name
|
||||
|
||||
min_title = str(track.get("minTitle") or "").strip()
|
||||
required_rank = _min_title_rank(min_title)
|
||||
if required_rank is not None and (title_rank is None or title_rank < required_rank):
|
||||
excluded.append({"track": label, "reason": f"职称门槛:要求{min_title},现为{teacher.get('title') or '未填写'}(H1)"})
|
||||
continue
|
||||
|
||||
min_sci = _to_int(track.get("minSciQ1")) or 0
|
||||
if min_sci > 0 and sci_q1 < min_sci:
|
||||
excluded.append({"track": label, "reason": f"SCI一区门槛:要求 {min_sci} 篇,现有 {sci_q1} 篇(H2)"})
|
||||
continue
|
||||
|
||||
track_tags = _split_tags(track.get("trackTags"))
|
||||
if not track_tags:
|
||||
excluded.append({"track": label, "reason": "赛道未配置需求标签,无法匹配(数据待补)"})
|
||||
continue
|
||||
|
||||
matched_tags = [t for t in track_tags if t in teacher_tags]
|
||||
coverage = round(len(matched_tags) / len(track_tags), 4)
|
||||
|
||||
priority_hits = []
|
||||
haystack = ",".join(teacher_tags) + ";" + papers_text + ";" + projects_text
|
||||
for keyword in _split_tags(track.get("priorityKeywords")):
|
||||
if keyword and keyword in haystack:
|
||||
priority_hits.append(keyword)
|
||||
|
||||
score = round(0.7 * coverage + min(len(priority_hits) * 0.15, 0.3), 4)
|
||||
match_pct = int(round(score * 100))
|
||||
|
||||
reasons = []
|
||||
if matched_tags:
|
||||
reasons.append(f"命中需求标签:{'、'.join(matched_tags)}(覆盖 {len(matched_tags)}/{len(track_tags)})")
|
||||
if priority_hits:
|
||||
reasons.append(f"优先资助方向命中:{'、'.join(priority_hits)}")
|
||||
if min_sci > 0:
|
||||
reasons.append(f"SCI一区余量:现有 {sci_q1} 篇 / 要求 {min_sci} 篇")
|
||||
if not reasons:
|
||||
reasons.append("与赛道方向存在部分相关性")
|
||||
|
||||
if match_pct >= _STRONG_THRESHOLD:
|
||||
tier = TIER_STRONG
|
||||
elif match_pct >= _TRY_THRESHOLD:
|
||||
tier = TIER_TRY
|
||||
else:
|
||||
tier = TIER_NOT
|
||||
if tier == TIER_TRY:
|
||||
reasons.append("建议补充与赛道直接相关的成果说明后再申报")
|
||||
|
||||
eligible.append(
|
||||
{
|
||||
"track": label,
|
||||
"track_name": track_name,
|
||||
"program_name": program,
|
||||
"agency": str(track.get("agency") or ""),
|
||||
"match_pct": match_pct,
|
||||
"tier": tier,
|
||||
"matched_tags": matched_tags,
|
||||
"coverage": coverage,
|
||||
"priority_hits": priority_hits,
|
||||
"reasons": reasons,
|
||||
}
|
||||
)
|
||||
|
||||
eligible.sort(key=lambda x: (-x["match_pct"], x["track"]))
|
||||
tiers: dict[str, list[dict[str, Any]]] = {TIER_STRONG: [], TIER_TRY: [], TIER_NOT: []}
|
||||
for entry in eligible:
|
||||
tiers[entry["tier"]].append(entry)
|
||||
top3 = eligible[:3]
|
||||
|
||||
return {
|
||||
"teacher_name": teacher_name,
|
||||
"department": str(teacher.get("department") or ""),
|
||||
"title": str(teacher.get("title") or ""),
|
||||
"season": str(season),
|
||||
"eligible_count": len(eligible),
|
||||
"excluded": excluded,
|
||||
"top3": top3,
|
||||
"tiers": {k: v for k, v in tiers.items() if v},
|
||||
}
|
||||
|
||||
|
||||
def _write_report(result: dict[str, Any], batch_no: str) -> str:
|
||||
from service.report_service import write_report_for_kernel
|
||||
|
||||
return write_report_for_kernel(result=result, batch_no=batch_no)
|
||||
|
||||
|
||||
def run_match(teachers_raw: list[dict[str, Any]], tracks: list[dict[str, Any]], season: str, *, batch_no: str = "") -> dict[str, Any]:
|
||||
"""匹配内核:逐教师匹配 → 写库 → 生成建议书(多人时另出汇总页)。"""
|
||||
from service.report_service import build_batch_brief
|
||||
|
||||
log = _log()
|
||||
init_db()
|
||||
if not teachers_raw:
|
||||
raise ValueError("没有可匹配的教师画像")
|
||||
if not tracks:
|
||||
raise ValueError("指南赛道库为空:请先录入当年指南赛道(add-track / import-tracks)")
|
||||
|
||||
batch_no = batch_no or now_unix().to_bytes(5, "big").hex() + uuid.uuid4().hex[:6]
|
||||
if log:
|
||||
log.info("match_kernel_start batch_no=%s teachers=%s tracks=%s season=%s stage=kernel", batch_no, len(teachers_raw), len(tracks), season)
|
||||
|
||||
results = []
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for teacher_raw in teachers_raw:
|
||||
result = match_teacher(teacher_raw, tracks, season)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO match_reports
|
||||
(batch_no, teacher_name, department, season, top_json, tiers_json, eligible_count, excluded_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_no,
|
||||
result["teacher_name"],
|
||||
result["department"],
|
||||
result["season"],
|
||||
json.dumps(result["top3"], ensure_ascii=False),
|
||||
json.dumps(result["tiers"], ensure_ascii=False),
|
||||
result["eligible_count"],
|
||||
json.dumps(result["excluded"], ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
report_id = int(cur.lastrowid)
|
||||
result["report_id"] = report_id
|
||||
result["batch_no"] = batch_no
|
||||
report_file = _write_report(result, batch_no)
|
||||
cur.execute("UPDATE match_reports SET report_file = ? WHERE id = ?", (report_file, report_id))
|
||||
result["report_file"] = report_file
|
||||
results.append(result)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
brief_file = build_batch_brief(batch_no=batch_no, results=results, season=season)
|
||||
tier_counts: dict[str, int] = {}
|
||||
for result in results:
|
||||
for tier, entries in result["tiers"].items():
|
||||
tier_counts[tier] = tier_counts.get(tier, 0) + len(entries)
|
||||
|
||||
payload = {
|
||||
"ok": True,
|
||||
"batch_no": batch_no,
|
||||
"season": season,
|
||||
"count": len(results),
|
||||
"tier_counts": tier_counts,
|
||||
"brief_file": brief_file,
|
||||
"disclaimer": "推荐仅供参考,申报决策请结合个人规划与学院统筹。",
|
||||
"reports": results,
|
||||
}
|
||||
if log:
|
||||
log.info("match_kernel_done batch_no=%s count=%s stage=kernel", batch_no, len(results))
|
||||
return payload
|
||||
|
||||
|
||||
def load_tracks(year: Optional[int] = None) -> list[dict[str, Any]]:
|
||||
"""读取赛道库(缺省全部年度;可按年度筛选)。"""
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if year:
|
||||
cur.execute("SELECT * FROM guide_tracks WHERE year = ? ORDER BY id", (year,))
|
||||
else:
|
||||
cur.execute("SELECT * FROM guide_tracks ORDER BY year DESC, 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 load_teachers(teacher_name: str = "") -> list[dict[str, Any]]:
|
||||
"""读取教师画像(可按姓名精确筛选)。"""
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if teacher_name:
|
||||
cur.execute("SELECT * FROM teacher_profiles WHERE teacher_name = ?", (teacher_name,))
|
||||
else:
|
||||
cur.execute("SELECT * FROM teacher_profiles ORDER BY id")
|
||||
columns = [d[0] for d in cur.description]
|
||||
rows = [dict(zip(columns, row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
return rows
|
||||
272
scripts/service/profile_service.py
Normal file
272
scripts/service/profile_service.py
Normal file
@@ -0,0 +1,272 @@
|
||||
"""教师画像 / 指南赛道 / 推荐报告 的维护与查询。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from service.match_service import _norm_teacher, _norm_track, _to_int
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.timeutil import now_unix
|
||||
|
||||
_TEACHER_TEXT_FIELDS = ("teacher_name", "department", "title", "research_tags", "recent_papers", "project_history")
|
||||
_TEACHER_INT_FIELDS = ("sci_q1_count", "core_paper_count")
|
||||
_TRACK_TEXT_FIELDS = ("agency", "program_name", "track_name", "track_tags", "priority_keywords", "min_title", "source_doc")
|
||||
_TRACK_INT_FIELDS = ("year", "min_sci_q1", "quota")
|
||||
|
||||
_KNOWN_MIN_TITLES = ("讲师及以上", "副高及以上", "正高及以上")
|
||||
|
||||
|
||||
def _log():
|
||||
try:
|
||||
return get_skill_logger()
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _snake(name: str) -> str:
|
||||
return "".join("_" + ch.lower() if ch.isupper() else ch for ch in str(name)).lstrip("_")
|
||||
|
||||
|
||||
def upsert_teacher(fields: dict[str, Any]) -> dict[str, Any]:
|
||||
"""按姓名幂等写入教师画像;未提供字段不覆盖。"""
|
||||
teacher_name = str(fields.get("teacher_name") or "").strip()
|
||||
if not teacher_name:
|
||||
raise ValueError("教师姓名(teacher_name)不能为空")
|
||||
values: dict[str, Any] = {"teacher_name": teacher_name}
|
||||
for key in _TEACHER_TEXT_FIELDS:
|
||||
if key != "teacher_name" and fields.get(key) not in (None, ""):
|
||||
values[key] = str(fields[key]).strip()
|
||||
for key in _TEACHER_INT_FIELDS:
|
||||
if fields.get(key) not in (None, ""):
|
||||
number = _to_int(fields[key])
|
||||
if number is None or number < 0:
|
||||
raise ValueError(f"字段 {key} 必须是非负整数:{fields[key]}")
|
||||
values[key] = number
|
||||
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT id FROM teacher_profiles WHERE teacher_name = ?", (teacher_name,))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
teacher_id = int(row[0])
|
||||
set_clause = ", ".join(f"{k} = ?" for k in values if k != "teacher_name")
|
||||
cur.execute(
|
||||
f"UPDATE teacher_profiles SET {set_clause}, updated_at = ? WHERE id = ?",
|
||||
[values[k] for k in values if k != "teacher_name"] + [now_unix(), teacher_id],
|
||||
)
|
||||
action = "updated"
|
||||
else:
|
||||
columns = ", ".join(values.keys())
|
||||
placeholders = ", ".join("?" for _ in values)
|
||||
cur.execute(
|
||||
f"INSERT INTO teacher_profiles ({columns}, created_at, updated_at) VALUES ({placeholders}, ?, ?)",
|
||||
list(values.values()) + [now_unix(), now_unix()],
|
||||
)
|
||||
teacher_id = int(cur.lastrowid)
|
||||
action = "created"
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("teacher_upserted teacher=%s action=%s stage=profile", teacher_name, action)
|
||||
return {"ok": True, "teacher_name": teacher_name, "id": teacher_id, "action": action}
|
||||
|
||||
|
||||
def upsert_track(fields: dict[str, Any]) -> dict[str, Any]:
|
||||
"""按(年度+学部+项目类型+赛道名)幂等写入指南赛道。"""
|
||||
year = _to_int(fields.get("year"))
|
||||
track_name = str(fields.get("track_name") or "").strip()
|
||||
if year is None or year < 2020 or year > 2100:
|
||||
raise ValueError(f"指南年度无效:{fields.get('year')}")
|
||||
if not track_name:
|
||||
raise ValueError("赛道名称(track_name)不能为空")
|
||||
if fields.get("min_title") and str(fields["min_title"]).strip() not in _KNOWN_MIN_TITLES:
|
||||
raise ValueError(f"职称门槛只接受 {'、'.join(_KNOWN_MIN_TITLES)}:{fields['min_title']}")
|
||||
values: dict[str, Any] = {"year": year, "track_name": track_name}
|
||||
for key in _TRACK_TEXT_FIELDS:
|
||||
if key not in ("track_name",) and fields.get(key) not in (None, ""):
|
||||
values[key] = str(fields[key]).strip()
|
||||
for key in ("min_sci_q1", "quota"):
|
||||
if fields.get(key) not in (None, ""):
|
||||
number = _to_int(fields[key])
|
||||
if number is None or number < 0:
|
||||
raise ValueError(f"字段 {key} 必须是非负整数:{fields[key]}")
|
||||
values[key] = number
|
||||
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT id FROM guide_tracks WHERE year = ? AND COALESCE(agency,'') = ? AND COALESCE(program_name,'') = ? AND track_name = ?",
|
||||
(year, values.get("agency", ""), values.get("program_name", ""), track_name),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
track_id = int(row[0])
|
||||
set_clause = ", ".join(f"{k} = ?" for k in values if k != "track_name")
|
||||
cur.execute(
|
||||
f"UPDATE guide_tracks SET {set_clause}, updated_at = ? WHERE id = ?",
|
||||
[values[k] for k in values if k != "track_name"] + [now_unix(), track_id],
|
||||
)
|
||||
action = "updated"
|
||||
else:
|
||||
columns = ", ".join(values.keys())
|
||||
placeholders = ", ".join("?" for _ in values)
|
||||
cur.execute(
|
||||
f"INSERT INTO guide_tracks ({columns}, created_at, updated_at) VALUES ({placeholders}, ?, ?)",
|
||||
list(values.values()) + [now_unix(), now_unix()],
|
||||
)
|
||||
track_id = int(cur.lastrowid)
|
||||
action = "created"
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
log = _log()
|
||||
if log:
|
||||
log.info("track_upserted year=%s track=%s action=%s stage=track", year, track_name, action)
|
||||
return {"ok": True, "year": year, "track_name": track_name, "id": track_id, "action": action}
|
||||
|
||||
|
||||
def _import_generic(rows: Any, upsert, label: str) -> dict[str, Any]:
|
||||
if not isinstance(rows, list) or not rows:
|
||||
raise ValueError(f"导入内容应为非空 JSON 数组({label})")
|
||||
if len(rows) > 500:
|
||||
raise ValueError(f"单次导入条数过多({len(rows)}),上限 500 条")
|
||||
results = []
|
||||
for idx, raw in enumerate(rows):
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError(f"第 {idx + 1} 条不是 JSON 对象")
|
||||
results.append(upsert(raw))
|
||||
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 import_teachers(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""批量导入教师画像。"""
|
||||
return _import_generic(rows, lambda row: upsert_teacher({_snake(k): v for k, v in _norm_teacher(row).items()}), "教师画像")
|
||||
|
||||
|
||||
def import_tracks(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""批量导入指南赛道。"""
|
||||
return _import_generic(rows, lambda row: upsert_track({_snake(k): v for k, v in _norm_track(row).items()}), "指南赛道")
|
||||
|
||||
|
||||
def list_teachers(department: str = "") -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if department:
|
||||
cur.execute("SELECT * FROM teacher_profiles WHERE department LIKE ? ORDER BY id", (f"%{department}%",))
|
||||
else:
|
||||
cur.execute("SELECT * FROM teacher_profiles ORDER BY 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_tracks(year: Optional[int] = None) -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if year:
|
||||
cur.execute("SELECT * FROM guide_tracks WHERE year = ? ORDER BY id", (year,))
|
||||
else:
|
||||
cur.execute("SELECT * FROM guide_tracks ORDER BY year DESC, 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_reports(limit: int = 20, tier: str = "") -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
limit = max(1, min(int(limit), 200))
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if tier:
|
||||
cur.execute(
|
||||
"SELECT id, batch_no, season, teacher_name, department, eligible_count, top_json, report_file, created_at FROM match_reports WHERE top_json LIKE ? ORDER BY id DESC LIMIT ?",
|
||||
(f"%{tier}%", limit),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"SELECT id, batch_no, season, teacher_name, department, eligible_count, top_json, report_file, created_at FROM match_reports 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_report(report_id: int) -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM match_reports WHERE id = ?", (report_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"推荐报告不存在:{report_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
report = dict(zip(columns, row))
|
||||
finally:
|
||||
conn.close()
|
||||
for key in ("top_json", "tiers_json", "excluded_json"):
|
||||
try:
|
||||
report[key] = json.loads(report.get(key) or "[]")
|
||||
except (TypeError, ValueError):
|
||||
report[key] = []
|
||||
return report
|
||||
|
||||
|
||||
def stats() -> dict[str, Any]:
|
||||
init_db()
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT COUNT(*) FROM teacher_profiles")
|
||||
teacher_total = int(cur.fetchone()[0])
|
||||
cur.execute("SELECT year, COUNT(*) FROM guide_tracks GROUP BY year ORDER BY year DESC")
|
||||
tracks_by_year = {str(r[0]): int(r[1]) for r in cur.fetchall()}
|
||||
cur.execute("SELECT COUNT(*) FROM match_reports")
|
||||
report_total = int(cur.fetchone()[0])
|
||||
cur.execute(
|
||||
"SELECT teacher_name, season, top_json FROM match_reports ORDER BY id DESC LIMIT 50"
|
||||
)
|
||||
strong = []
|
||||
for teacher_name, season, top_json in cur.fetchall():
|
||||
try:
|
||||
top = json.loads(top_json or "[]")
|
||||
except (TypeError, ValueError):
|
||||
top = []
|
||||
if top and top[0].get("tier") == "强烈推荐":
|
||||
strong.append({"teacher_name": teacher_name, "season": season, "top_track": top[0]["track"], "match_pct": top[0]["match_pct"]})
|
||||
strong = strong[:5]
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"ok": True,
|
||||
"teacher_total": teacher_total,
|
||||
"tracks_by_year": tracks_by_year,
|
||||
"report_total": report_total,
|
||||
"strong_top": strong,
|
||||
}
|
||||
185
scripts/service/report_service.py
Normal file
185
scripts/service/report_service.py
Normal file
@@ -0,0 +1,185 @@
|
||||
"""《申报策略建议书》HTML 组装。
|
||||
|
||||
- 每位教师一份 `report-{report_id}.html`(Top 3 卡片 + 完整分层清单 + 剔除原因)
|
||||
- 批量匹配另生成汇总页 `brief-{batch_no}.html`(各教师 Top 1 一览)
|
||||
写入 `{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
|
||||
|
||||
_TEMPLATE_REL = "assets/html/match-report.html"
|
||||
|
||||
_TIER_BADGE = {"强烈推荐": "tier-strong", "可尝试": "tier-try", "不建议": "tier-not"}
|
||||
|
||||
|
||||
def _esc(value: Any) -> str:
|
||||
return html_escape(str(value if value is not None else "—"))
|
||||
|
||||
|
||||
def html_escape(text: str) -> str:
|
||||
import html
|
||||
|
||||
return html.escape(text, quote=True)
|
||||
|
||||
|
||||
def _pct(value: Any) -> str:
|
||||
try:
|
||||
return f"{int(value)}%"
|
||||
except (TypeError, ValueError):
|
||||
return "—"
|
||||
|
||||
|
||||
def _top_cards(top3: list[dict[str, Any]]) -> str:
|
||||
if not top3:
|
||||
return '<p class="muted">没有可推荐的赛道:请检查画像完整性或指南赛道库。</p>'
|
||||
medals = ["🥇", "🥈", "🥉"]
|
||||
cards = []
|
||||
for idx, entry in enumerate(top3):
|
||||
badge = _TIER_BADGE.get(str(entry.get("tier")), "tier-not")
|
||||
reasons = "".join(f"<li>{_esc(r)}</li>" for r in entry.get("reasons") or [])
|
||||
cards.append(
|
||||
f'<div class="card-item">'
|
||||
f'<div class="card-head"><span class="medal">{medals[idx] if idx < 3 else "·"}</span>'
|
||||
f'<strong>{_esc(entry.get("track"))}</strong>'
|
||||
f'<span class="tag {badge}">{_esc(entry.get("tier"))} · {_pct(entry.get("match_pct"))}</span></div>'
|
||||
f'<ol class="reasons">{reasons}</ol>'
|
||||
f"</div>"
|
||||
)
|
||||
return "".join(cards)
|
||||
|
||||
|
||||
def _tier_table(tiers: dict[str, list[dict[str, Any]]]) -> str:
|
||||
rows = []
|
||||
order = ["强烈推荐", "可尝试", "不建议"]
|
||||
for tier in order:
|
||||
for entry in tiers.get(tier) or []:
|
||||
badge = _TIER_BADGE.get(tier, "tier-not")
|
||||
rows.append(
|
||||
"<tr>"
|
||||
f'<td class="nowrap"><span class="tag {badge}">{_esc(tier)}</span></td>'
|
||||
f'<td>{_esc(entry.get("track"))}</td>'
|
||||
f'<td class="nowrap">{_pct(entry.get("match_pct"))}</td>'
|
||||
f'<td class="muted">{_esc("、".join(entry.get("matched_tags") or []))}</td>'
|
||||
"</tr>"
|
||||
)
|
||||
if not rows:
|
||||
return '<tr><td colspan="4" class="muted">无</td></tr>'
|
||||
return "".join(rows)
|
||||
|
||||
|
||||
def _excluded_table(excluded: list[dict[str, Any]]) -> str:
|
||||
if not excluded:
|
||||
return ""
|
||||
rows = "".join(f"<tr><td>{_esc(e.get('track'))}</td><td class='muted'>{_esc(e.get('reason'))}</td></tr>" for e in excluded)
|
||||
return f'<div class="section"><h2>被硬门槛剔除的赛道</h2><table><tr><th>赛道</th><th>原因</th></tr>{rows}</table></div>'
|
||||
|
||||
|
||||
def build_match_html(result: dict[str, Any], batch_no: str = "") -> str:
|
||||
body = f"""
|
||||
<div class="verdict-line">
|
||||
<span class="tag tier-info">{_esc(result.get("teacher_name"))}</span>
|
||||
<span class="muted">{_esc(result.get("department") or "")} · 指南年度 {_esc(result.get("season"))} · 可匹配赛道 {_esc(result.get("eligible_count"))} 个 · 批次 {_esc(batch_no or result.get("batch_no"))}</span>
|
||||
</div>
|
||||
<div class="section"><h2>Top 3 最匹配赛道</h2>{_top_cards(result.get("top3") or [])}</div>
|
||||
<div class="section"><h2>完整分层清单</h2>
|
||||
<table><tr><th>分层</th><th>赛道</th><th>匹配度</th><th>命中标签</th></tr>{_tier_table(result.get("tiers") or {})}</table>
|
||||
</div>
|
||||
{_excluded_table(result.get("excluded") or [])}
|
||||
<footer>推荐由标签匹配算法生成、仅供参考;申报决策请结合个人规划与学院统筹,以当年度正式指南为准。</footer>
|
||||
"""
|
||||
template = load_html_template(_TEMPLATE_REL)
|
||||
return render_html_placeholders(
|
||||
template,
|
||||
{
|
||||
"TITLE": f"申报策略建议书 · {result.get('teacher_name') or ''}",
|
||||
"GENERATED_AT": str(result.get("season") or ""),
|
||||
"BODY": body,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def write_report_for_kernel(*, result: dict[str, Any], batch_no: str) -> str:
|
||||
html_text = build_match_html(result, batch_no)
|
||||
log = get_skill_logger()
|
||||
path = write_html_page(f"report-{result['report_id']}.html", html_text)
|
||||
log.info("match_report_written report_id=%s path=%s stage=report", result["report_id"], path)
|
||||
return path
|
||||
|
||||
|
||||
def build_report_for_report_id(report_id: int) -> str:
|
||||
"""按报告 id 从库中取数并重写 HTML(重建入口用)。"""
|
||||
from db.connection import get_conn
|
||||
|
||||
log = get_skill_logger()
|
||||
log.info("report_render_start report_id=%s stage=render", report_id)
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT * FROM match_reports WHERE id = ?", (report_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"推荐报告不存在:{report_id}")
|
||||
columns = [d[0] for d in cur.description]
|
||||
record = dict(zip(columns, row))
|
||||
finally:
|
||||
conn.close()
|
||||
result = dict(record)
|
||||
for key in ("top_json", "tiers_json", "excluded_json"):
|
||||
target = key[:-5] if key.endswith("_json") else key
|
||||
try:
|
||||
result[target] = json.loads(record.get(key) or "[]")
|
||||
except (TypeError, ValueError):
|
||||
result[target] = []
|
||||
result["top3"] = result.get("top") or []
|
||||
html_text = build_match_html(result)
|
||||
path = write_html_page(f"report-{report_id}.html", html_text)
|
||||
log.info("report_render_done report_id=%s path=%s stage=render", report_id, path)
|
||||
return path
|
||||
|
||||
|
||||
def build_batch_brief(*, batch_no: str, results: list[dict[str, Any]], season: str) -> str:
|
||||
"""批量匹配汇总页:各教师 Top 1 一览。"""
|
||||
log = get_skill_logger()
|
||||
rows = []
|
||||
for result in results:
|
||||
top3 = result.get("top3") or []
|
||||
if top3:
|
||||
first = top3[0]
|
||||
badge = _TIER_BADGE.get(str(first.get("tier")), "tier-not")
|
||||
rows.append(
|
||||
"<tr>"
|
||||
f"<td>{_esc(result.get('teacher_name'))}</td>"
|
||||
f"<td class='muted'>{_esc(result.get('department'))}</td>"
|
||||
f"<td><span class='tag {badge}'>{_esc(first.get('tier'))}</span></td>"
|
||||
f"<td>{_esc(first.get('track'))}</td>"
|
||||
f"<td class='nowrap'>{_pct(first.get('match_pct'))}</td>"
|
||||
"</tr>"
|
||||
)
|
||||
else:
|
||||
rows.append(f"<tr><td>{_esc(result.get('teacher_name'))}</td><td colspan='4' class='muted'>无可推荐赛道(画像待补全)</td></tr>")
|
||||
if not rows:
|
||||
rows.append('<tr><td colspan="5" class="muted">本期无匹配结果。</td></tr>')
|
||||
|
||||
body = f"""
|
||||
<div class="verdict-line">
|
||||
<span class="muted">指南年度 {_esc(season)} · 教师 {_esc(len(results))} 人 · 批次 {_esc(batch_no)}</span>
|
||||
</div>
|
||||
<div class="section"><h2>各教师 Top 1 赛道一览</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": str(season), "BODY": body},
|
||||
)
|
||||
path = write_html_page(f"brief-{batch_no}.html", page)
|
||||
log.info("match_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', '')}"
|
||||
)
|
||||
686
scripts/service/task_service.py
Normal file
686
scripts/service/task_service.py
Normal file
@@ -0,0 +1,686 @@
|
||||
"""任务编排层:job_context / emit / finish、鉴权与错误转换。
|
||||
|
||||
领域业务在 ``service/match_service.py``(匹配内核)、
|
||||
``service/profile_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 这是模板演示入口,请使用 match 命令执行申报赛道匹配。")
|
||||
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 os
|
||||
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 ("teachers", "tracks", "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_add_teacher(
|
||||
*,
|
||||
name: str,
|
||||
department: str = "",
|
||||
title: str = "",
|
||||
tags: str = "",
|
||||
papers: str = "",
|
||||
projects: str = "",
|
||||
sci_q1: Optional[int] = None,
|
||||
core_papers: Optional[int] = None,
|
||||
) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.profile_service import upsert_teacher
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=add_teacher teacher=%s stage=profile", name)
|
||||
emit("开始写入教师画像", skill=SKILL_SLUG, stage="profile")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=add_teacher stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
log.error("add_teacher_denied stage=auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
fields: dict[str, Any] = {"teacher_name": name}
|
||||
for key, value in (("department", department), ("title", title), ("research_tags", tags), ("recent_papers", papers), ("project_history", projects)):
|
||||
if value:
|
||||
fields[key] = value
|
||||
if sci_q1 is not None:
|
||||
fields["sci_q1_count"] = sci_q1
|
||||
if core_papers is not None:
|
||||
fields["core_paper_count"] = core_papers
|
||||
payload = upsert_teacher(fields)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"教师 {name} 画像已{('更新' if payload['action'] == 'updated' else '录入')}", skill=SKILL_SLUG, stage="profile")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=add_teacher error_code=TEACHER_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="TEACHER_INVALID", stage="profile")
|
||||
print(f"ERROR:TEACHER_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=add_teacher stage=profile")
|
||||
finish(status="failed", message="画像写入异常,详见统一日志", skill=SKILL_SLUG, stage="profile")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_import_teachers(teachers_json: str) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.profile_service import import_teachers
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=import_teachers stage=profile")
|
||||
emit("开始批量导入教师画像", skill=SKILL_SLUG, stage="profile")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=import_teachers 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(teachers_json, "--teachers-json")
|
||||
payload = import_teachers(rows)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"导入完成:新增 {payload['created']},更新 {payload['updated']}", skill=SKILL_SLUG, stage="profile")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=import_teachers error_code=TEACHER_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="TEACHER_INVALID", stage="profile")
|
||||
print(f"ERROR:TEACHER_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=import_teachers stage=profile")
|
||||
finish(status="failed", message="画像导入异常,详见统一日志", skill=SKILL_SLUG, stage="profile")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_import_tracks(tracks_json: str) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.profile_service import import_tracks
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=import_tracks stage=track")
|
||||
emit("开始批量导入指南赛道", skill=SKILL_SLUG, stage="track")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=import_tracks 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(tracks_json, "--tracks-json")
|
||||
payload = import_tracks(rows)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"导入完成:新增 {payload['created']},更新 {payload['updated']}", skill=SKILL_SLUG, stage="track")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=import_tracks error_code=TRACK_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="TRACK_INVALID", stage="track")
|
||||
print(f"ERROR:TRACK_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=import_tracks stage=track")
|
||||
finish(status="failed", message="赛道导入异常,详见统一日志", skill=SKILL_SLUG, stage="track")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_add_track(
|
||||
*,
|
||||
year: int,
|
||||
track_name: str,
|
||||
program: str = "",
|
||||
agency: str = "",
|
||||
tags: str = "",
|
||||
priority: str = "",
|
||||
min_title: str = "",
|
||||
min_sci_q1: Optional[int] = None,
|
||||
quota: Optional[int] = None,
|
||||
source: str = "",
|
||||
) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.profile_service import upsert_track
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=add_track year=%s track=%s stage=track", year, track_name)
|
||||
emit("开始写入指南赛道", skill=SKILL_SLUG, stage="track")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=add_track stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
fields: dict[str, Any] = {"year": year, "track_name": track_name}
|
||||
for key, value in (("agency", agency), ("program_name", program), ("track_tags", tags), ("priority_keywords", priority), ("min_title", min_title), ("source_doc", source)):
|
||||
if value:
|
||||
fields[key] = value
|
||||
if min_sci_q1 is not None:
|
||||
fields["min_sci_q1"] = min_sci_q1
|
||||
if quota is not None:
|
||||
fields["quota"] = quota
|
||||
payload = upsert_track(fields)
|
||||
_print_json(payload)
|
||||
finish(status="success", message=f"赛道 {track_name} 已{('更新' if payload['action'] == 'updated' else '录入')}", skill=SKILL_SLUG, stage="track")
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=add_track error_code=TRACK_INVALID detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="TRACK_INVALID", stage="track")
|
||||
print(f"ERROR:TRACK_INVALID {exc}")
|
||||
return 1
|
||||
except JobStopped:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=add_track stage=track")
|
||||
finish(status="failed", message="赛道写入异常,详见统一日志", skill=SKILL_SLUG, stage="track")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_list_teachers(department: str = "") -> int:
|
||||
log = _get_task_logger()
|
||||
from service.profile_service import list_teachers
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_teachers department=%s", department)
|
||||
try:
|
||||
teachers = list_teachers(department=department)
|
||||
_print_json({"ok": True, "count": len(teachers), "teachers": teachers})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_teachers")
|
||||
print("ERROR:QUERY_FAILED 教师画像查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_list_tracks(year: Optional[int] = None) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.profile_service import list_tracks
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_tracks year=%s", year)
|
||||
try:
|
||||
tracks = list_tracks(year=year)
|
||||
_print_json({"ok": True, "count": len(tracks), "tracks": tracks})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_tracks")
|
||||
print("ERROR:QUERY_FAILED 赛道查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 匹配主命令
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def cmd_match(*, teacher: str = "", year: Optional[int] = None) -> int:
|
||||
"""申报赛道匹配(同步):缺省匹配全部教师;可指定教师与指南年度。"""
|
||||
log = _get_task_logger()
|
||||
from service.match_service import load_teachers, load_tracks, run_match
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=match teacher=%s year=%s stage=match", teacher, year)
|
||||
emit("开始申报赛道匹配", skill=SKILL_SLUG, stage="match")
|
||||
try:
|
||||
ok, reason = check_entitlement(SKILL_SLUG)
|
||||
if not ok:
|
||||
log.warning("entitlement_failed task_type=match stage=auth")
|
||||
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED", stage="auth")
|
||||
print(f"ERROR:ENTITLEMENT_DENIED {reason}")
|
||||
return 1
|
||||
|
||||
teachers = load_teachers(teacher_name=teacher)
|
||||
tracks = load_tracks(year=year)
|
||||
if not teachers:
|
||||
message = "没有可匹配的教师画像:请先录入教师(add-teacher / import-teachers)"
|
||||
log.warning("task_failed task_type=match error_code=TEACHER_NOT_FOUND stage=match")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="TEACHER_NOT_FOUND", stage="match")
|
||||
print(f"ERROR:TEACHER_NOT_FOUND {message}")
|
||||
return 1
|
||||
if not tracks:
|
||||
message = "指南赛道库为空:请先录入赛道(add-track / import-tracks)"
|
||||
log.warning("task_failed task_type=match error_code=TRACK_EMPTY stage=match")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="TRACK_EMPTY", stage="match")
|
||||
print(f"ERROR:TRACK_EMPTY {message}")
|
||||
return 1
|
||||
|
||||
season = str(year or tracks[0].get("year") or "")
|
||||
result = run_match(teachers, tracks, season)
|
||||
payload = {k: v for k, v in result.items() if k != "reports"}
|
||||
payload["reports_brief"] = [
|
||||
{
|
||||
"report_id": r["report_id"],
|
||||
"teacher_name": r["teacher_name"],
|
||||
"tier": (r["top3"][0]["tier"] if r["top3"] else "无可推荐"),
|
||||
"top_track": (r["top3"][0]["track"] if r["top3"] else ""),
|
||||
"match_pct": (r["top3"][0]["match_pct"] if r["top3"] else None),
|
||||
"report_file": r["report_file"],
|
||||
}
|
||||
for r in result["reports"]
|
||||
]
|
||||
_print_json(payload)
|
||||
finish(
|
||||
status="success",
|
||||
message=f"匹配完成 {result['count']} 名教师,建议书已生成",
|
||||
skill=SKILL_SLUG,
|
||||
stage="match",
|
||||
batch_no=result["batch_no"],
|
||||
)
|
||||
return 0
|
||||
except JobStopped:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=match error_code=PROFILE_INCOMPLETE detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="PROFILE_INCOMPLETE", stage="match")
|
||||
print(f"ERROR:PROFILE_INCOMPLETE {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=match stage=match")
|
||||
emit("匹配失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="match")
|
||||
finish(status="failed", message="匹配执行异常,详见统一日志", skill=SKILL_SLUG, stage="match")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_match_batch_input() -> int:
|
||||
"""批量匹配(async Action 入口):匹配 input/ 目录中的教师画像 JSON 与库内赛道。"""
|
||||
log = _get_task_logger()
|
||||
from service.match_service import load_tracks, run_match
|
||||
from util.runtime_paths import get_input_dir
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=match_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=match_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=match_batch error_code=TEACHER_NOT_FOUND stage=batch")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="TEACHER_NOT_FOUND", stage="batch")
|
||||
print(f"ERROR:TEACHER_NOT_FOUND {message}")
|
||||
return 1
|
||||
|
||||
teachers = []
|
||||
for path in files:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
payload = json.load(f)
|
||||
if isinstance(payload, dict):
|
||||
payload = payload.get("teachers") or [payload]
|
||||
teachers.extend(payload)
|
||||
|
||||
tracks = load_tracks()
|
||||
if not tracks:
|
||||
message = "指南赛道库为空:请先录入赛道(add-track / import-tracks)"
|
||||
log.warning("task_failed task_type=match_batch error_code=TRACK_EMPTY stage=batch")
|
||||
finish(status="failed", message=message, skill=SKILL_SLUG, error_code="TRACK_EMPTY", stage="batch")
|
||||
print(f"ERROR:TRACK_EMPTY {message}")
|
||||
return 1
|
||||
|
||||
season = str(tracks[0].get("year") or "")
|
||||
result = run_match(teachers, tracks, season)
|
||||
for index, report in enumerate(result["reports"], start=1):
|
||||
top = (report.get("top3") or [{}])[0]
|
||||
emit(
|
||||
f"[{index}/{len(result['reports'])}] {report['teacher_name']}:"
|
||||
f"{(top.get('tier') or '无可推荐')}{(' · ' + top.get('track', '')) if top.get('track') else ''}",
|
||||
skill=SKILL_SLUG,
|
||||
stage="batch",
|
||||
)
|
||||
_print_json(
|
||||
{
|
||||
"ok": True,
|
||||
"batch_no": result["batch_no"],
|
||||
"count": result["count"],
|
||||
"tier_counts": result["tier_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=match_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_reports(limit: int = 20) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.profile_service import list_reports
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=list_reports limit=%s", limit)
|
||||
try:
|
||||
reports = list_reports(limit=limit)
|
||||
_print_json({"ok": True, "count": len(reports), "reports": reports})
|
||||
return 0
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=list_reports")
|
||||
print("ERROR:QUERY_FAILED 推荐报告查询异常,详见统一日志")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_show_report(report_id: int) -> int:
|
||||
log = _get_task_logger()
|
||||
from service.profile_service import get_report
|
||||
|
||||
with job_context(skill=SKILL_SLUG):
|
||||
log.info("task_start task_type=show_report report_id=%s", report_id)
|
||||
try:
|
||||
report = get_report(int(report_id))
|
||||
_print_json({"ok": True, "report": report})
|
||||
return 0
|
||||
except ValueError as exc:
|
||||
log.warning("task_failed task_type=show_report error_code=REPORT_NOT_FOUND detail=%s", exc)
|
||||
print(f"ERROR:REPORT_NOT_FOUND {exc}")
|
||||
return 1
|
||||
except Exception:
|
||||
log.exception("task_failed task_type=show_report")
|
||||
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_report_id
|
||||
from service.profile_service import list_reports
|
||||
|
||||
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 = [r["id"] for r in list_reports(limit=10)]
|
||||
if not targets:
|
||||
log.warning("task_failed task_type=render_html error_code=REPORT_NOT_FOUND stage=render")
|
||||
finish(status="failed", message="暂无可重建的推荐报告", skill=SKILL_SLUG, error_code="REPORT_NOT_FOUND", stage="render")
|
||||
print("ERROR:REPORT_NOT_FOUND 暂无可重建的推荐报告")
|
||||
return 1
|
||||
written = [{"report_id": rid, "path": build_report_for_report_id(rid)} for rid 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=REPORT_NOT_FOUND detail=%s", exc)
|
||||
finish(status="failed", message=str(exc), skill=SKILL_SLUG, error_code="REPORT_NOT_FOUND", stage="render")
|
||||
print(f"ERROR:REPORT_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.profile_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
|
||||
Reference in New Issue
Block a user