"""Verify code-assistant and office-workflow tasks with owned local fixtures."""
from html import escape
from pathlib import Path
import sys
import json
from statistics import mean
from lab_tools import run_exercise
WEIGHTS = {"inspection": 20, "repair": 50, "documentation": 30}
def weighted_score(record):
result = 0
for key, weight in WEIGHTS.items():
value = record.get(key, 0)
if type(value) is not int:
raise TypeError(f"{key} must be an integer")
result += value * weight
return min(100, max(0, result / 100))
def average_minutes(values):
return mean(values) if values else None
def summarize_tasks(records):
return {record["name"]: average_minutes(record["minutes"]) for record in records}
def lesson_page(records):
title = "用 Python 处理维修时长"
result = json.dumps(summarize_tasks(records), ensure_ascii=False)
code = "average_minutes([12, 18])"
return (
'<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
f"<title>{title}</title><h1>{title}</h1>"
"<p>空清单返回 None,保留未记录状态。</p>"
f"<pre><code>{escape(code)}</code></pre><output>{escape(result)}</output></html>"
)
def meeting_actions(notes):
items = []
for line in notes.splitlines():
if line.startswith("行动|"):
_, task, owner, deadline = line.split("|")
items.append(dict(task=task, owner=owner or None, deadline=deadline or None))
return items
def extract_topics(notes, limit):
return [line.removeprefix("要点|") for line in notes.splitlines() if line.startswith("要点|")][:limit]
def exercise(checks, workspace, export=None):
expect = checks.expect
tasks = [{"name": "机房", "minutes": [12, 18]}, {"name": "楼道", "minutes": []}]
page = lesson_page(tasks)
path = workspace / "lesson.html"
path.write_bytes(page.encode("utf8"))
if export is not None:
(export / "lesson.html").write_bytes(path.read_bytes())
expect("ai_tools_lesson", tasks, "Render a self-contained HTML tutorial from the actual Python function",
["<!doctype html>", "average_minutes([12, 18])", {"机房": 15, "楼道": None}],
[path.read_text(encoding="utf8")[:15], "average_minutes([12, 18])" if "<code>average_minutes([12, 18])</code>" in page else None,
summarize_tasks(tasks)])
expect("ai_tools_explain", [[4, 10], [0], []], "Trace regular, zero and empty inputs to the current return values",
[7, 0, None], [average_minutes(values) for values in ([4, 10], [0], [])])
def old_average(values):
return sum(values) / len(values)
try:
old_average([])
except ZeroDivisionError as exc:
observed_error = type(exc).__name__
else:
observed_error = None
expect("ai_tools_debug", [], "Reproduce division by zero and retest the empty-input branch",
["ZeroDivisionError", None, 0], [observed_error, average_minutes([]), average_minutes([0])])
before = {}
for task in tasks:
values = task["minutes"]
before[task["name"]] = sum(values) / len(values) if values else None
original = json.dumps(tasks, ensure_ascii=False)
after = summarize_tasks(tasks)
expect("ai_tools_refactor", tasks, "Compare loop and dictionary implementations and check that inputs are untouched",
[before, True], [after, json.dumps(tasks, ensure_ascii=False) == original])
scores = [{"inspection": 70, "repair": 90, "documentation": 80}, {"repair": 80}, {}, {"repair": 250}, {"repair": -25}]
expect("ai_tools_weighted", scores, "Apply explicit weights, fill absent fields and clamp to the documented range",
[83, 40, 0, 100, 0], [weighted_score(value) for value in scores])
try:
weighted_score({"repair": True})
except TypeError as exc:
invalid = str(exc)
else:
invalid = None
expect("ai_tools_weighted_invalid", {"repair": True}, "Reject a Boolean rather than treating it as a score",
"repair must be an integer", invalid)
notes = "议题|停机安排\n行动|确认电源|林|周三\n行动|更新公告||周二"
expect("ai_tools_meeting", notes, "Extract actual action, owner and deadline fields while preserving a missing owner",
[{"task": "确认电源", "owner": "林", "deadline": "周三"}, {"task": "更新公告", "owner": None, "deadline": "周二"}],
meeting_actions(notes))
paragraphs = "标题|维修\n要点|备件\n要点|排班\n要点|进场\n要点|断电\n要点|验收\n要点|归档"
expect("ai_tools_summary", paragraphs, "Select the first five explicitly marked topics",
["备件", "排班", "进场", "断电", "验收"], extract_topics(paragraphs, 5))
words = {"停机": "服务暂停", "立刻": "立即", "周三": "周三"}
raw = ["周三", "停机", "立刻", "联系值班台"]
expect("ai_tools_rewrite", raw, "Apply owned editorial substitutions while keeping the day and channel",
["周三", "服务暂停", "立即", "联系值班台"], [words.get(word, word) for word in raw])
angles = ("对象", "时段", "地点", "通知", "恢复", "依赖", "替代", "风险", "记录", "反馈")
expect("ai_tools_brainstorm", "维修计划", "Build ten distinct prompt angles and validate the request count",
[10, 10, "维修计划 · 反馈"],
[len(angles), len(set(angles)), f"维修计划 · {angles[-1]}"])
glossary = {"值班台": "duty desk", "维修": "maintenance"}
fields = ["值班台", "维修", "桥北区"]
expect("ai_tools_translate", fields, "Use a fixed glossary and flag a proper name for human confirmation",
["duty desk", "maintenance", "[待确认] 桥北区"],
[glossary.get(word, f"[待确认] {word}") for word in fields])
if __name__ == "__main__":
destination = Path(sys.argv[2]) if len(sys.argv) == 3 and sys.argv[1] == "--export" else None
run_exercise(lambda checks, root: exercise(checks, root, destination))
本例需在 Python 3.12.14,Whisper 20250625 多语言 tiny,PyTorch 2.10.0 CPU,FFmpeg 7.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Python 3.12.14,Whisper 20250625 多语言 tiny,PyTorch 2.10.0 CPU,FFmpeg 7.1。
入口文件:projects/ai-tools/tools_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
tools_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Python 3.12.14,Whisper 20250625 多语言 tiny,PyTorch 2.10.0 CPU,FFmpeg 7.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a27.zip