蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行摘要、数据查询和客服转接

PYTHONPython 3.12.14,SQLite 内存库,formulas 1.3.4、XlsxWriter 3.3.1、openpyxl 3.1.5。固定虚构输入。workflows.py
workflows.py207 行
"""Work through owned writing, data, learning, design, and support examples."""
import csv
from dataclasses import dataclass
from io import StringIO
import re
import sqlite3

from lab_tools import run_exercise


EVENT = {"before": "周四", "after": "周二 14:30", "room": "B204",
         "talk": "4 分钟", "deadline": "周五 12:00"}
CSV_TEXT = 'week,zone,minutes\n1,北区,4\n2,北区,8\n2,"南区,库房",7\n3,北区,\n'
FACTS = (
    ("设备清点", "林", "周二", "A1"),
    ("确认停机", "顾", "周三", "A2"),
    ("准备公告", "", "", "A3"),
    ("核对恢复", "陈", "周五", "A4"),
)
DOCS = {
    "FAQ-01": ("public", "v3", ("试用", "试听"), "可预约一次 20 分钟体验。"),
    "FAQ-02": ("public", "v2", ("时段", "几点"), "周三 14:00–16:00 开放。"),
    "KB-09": ("internal", "v1", ("维修密钥",), "内部合成演练记录。"),
}


def meeting_notice(event):
    return {"subject": "演练评审时间调整",
            "message": f"{event['before']}的评审改至{event['after']},地点仍为 {event['room']}。"
                       f"请准备 {event['talk']} 汇报。无法出席请在{event['deadline']}前联系协调员。",
            "reply": "请确认是否参加。"}


def read_metrics(text):
    rows = csv.DictReader(StringIO(text, newline=""))
    if rows.fieldnames != ["week", "zone", "minutes"]:
        raise ValueError("unexpected CSV header")
    return [(int(row["week"]), row["zone"], int(row["minutes"]) if row["minutes"] else None) for row in rows]


def average(records):
    known = [value for _, _, value in records if value is not None]
    return sum(known) / len(known) if known else None


def brief(notes, max_chars):
    selected = []
    used = 0
    for source, line in notes:
        if not line:
            continue
        addition = len(line) + bool(selected)
        if used + addition > max_chars:
            break
        selected.append([source, line])
        used += addition
    return selected


def meeting_rows():
    return [dict(task=task, owner=owner or None, due=due or None, evidence=evidence)
            for task, owner, due, evidence in FACTS]


def faq(query, dissatisfied=False):
    if not dissatisfied:
        for key, (visibility, revision, terms, text) in DOCS.items():
            if visibility == "public" and any(term in query for term in terms):
                return ["answer", text, f"{key}@{revision}"]
    return ["human_review", "请联系值班人员核对。", None]


@dataclass(frozen=True)
class DraftTask:
    audience: str
    sections: tuple
    checks: tuple

    def outline(self):
        return {"audience": self.audience, "sections": list(self.sections), "checks": list(self.checks)}


def exercise(checks, workspace):
    expect = checks.expect
    outline = DraftTask("首次参与值班的开发者", ("手工交接遗漏", "记录格式", "验证脚本", "下次实践"),
                        ("每段对应独立工单", "末段给出下一步")).outline()
    expect("use_outline", outline["audience"], "Assemble the audience, argument order and verifiable closing step",
           ["手工交接遗漏", "记录格式", "验证脚本", "下次实践"], outline["sections"])
    rough = "请大家务必一定要在周二14:30到 B204 进行实际评审。"
    polished = rough.replace("请大家务必一定要", "请").replace("进行实际评审", "参加评审")
    expect("use_polish", rough, "Remove redundant phrasing while preserving time and location",
           ["请在周二14:30到 B204 参加评审。", ["14:30", "B204"]],
           [polished, re.findall(r"\d{2}:\d{2}|B\d+", polished)])
    time, room = EVENT["after"], EVENT["room"]
    tags = ("管理汇报", "新手说明", "社交短句", "正式邮件")
    variants = [f"变更记录\\n时间 {time}\\n地点 {room}", f"第一次来?{time}到 {room} 找值班同事。",
                f"{time},{room} 见!", f"各位同事:\\n请于{time}到 {room}。\\n值班组"]
    social_formats = ("直接提醒", "问答", "准备清单", "现场信息", "倒计时")
    social = [f"{kind}|{time}到 {room} 参加公开演练。" for kind in social_formats]
    expect("use_social_copy", social_formats, "Create five bounded copy variants from the same approved facts",
           [5, True, True], [len(set(social)), all(len(x) <= 100 for x in social),
                            all(time in x and room in x for x in social)])
    expect("use_style", list(tags), "Make four distinct format variants with the same source facts",
           [4, True, True], [len(set(variants)), all(EVENT["after"] in x for x in variants),
                            all(EVENT["room"] in x for x in variants)])
    notice = meeting_notice(EVENT)
    expect("use_email_template", EVENT, "Assemble the subject, body and required reply",
           ["演练评审时间调整", "请确认是否参加。"], [notice["subject"], notice["reply"]])
    expect("use_email_change", EVENT, "Check the previous time, revised time, room, duration and reply deadline",
           list(EVENT.values()), [value for value in EVENT.values() if value in notice["message"]])
    blog = DraftTask("刚开始接值班任务的人", ("小故障引入", "检查数据", "定位空值", "核对改动", "行动建议"),
                     ("有独立例子", "不编造数据")).outline()
    expect("use_blog_outline", blog["audience"], "Build an ordered blog outline with three distinct practice sections",
           ["检查数据", "定位空值", "核对改动"], blog["sections"][1:-1])
    intro = (
        "早班开始时,值班表显示北区本周比上周慢了一倍。接班的人没有先改系统,而是打开原始表,"
        "把每周行数、空值和计时单位记在纸上。第一周的四分钟和第二周的八分钟都能对应工单,"
        "第三周却只登记了区域,处理时长还空着。把空白写成零,曲线就会突然下坠,让没有结单的任务看起来已经完成。"
        "于是她先写了一个只读脚本,让程序保留空值,按地区核对结果,再打印原记录供同事复查。"
        "下面的练习从这张小表开始,用可观察的测试分别核对解析、查询和改动前后的行为。"
    )
    expect("use_blog_intro", "面向接班的开发者,约 200–300 字", "Check size and retain the declared evidence in the drafted opening",
           [True, True, True], [200 <= len(intro) <= 300, "四分钟" in intro, "还空着" in intro])
    technical = "先读工单。处理 NULL,切勿混同零值。"
    revised = technical.replace("。处理 NULL,切勿混同零值。", ",再处理缺失值。保留空白,避免与真实零混淆。")
    expect("use_blog_revision", technical, "Check plain-language replacement and transition",
           [False, True, True], ["NULL" in revised, "再" in revised, "零" in revised])

    metrics = read_metrics(CSV_TEXT)
    expect("use_csv_parse", CSV_TEXT, "Read CSV with quotes, Unicode and an empty field",
           [[2, "南区,库房", 7], [3, "北区", None]], [list(row) for row in metrics[-2:]])
    try:
        read_metrics("week,place,minutes\n1,北区,4\n")
    except ValueError as exc:
        message = str(exc)
    else:
        message = None
    expect("use_debug", "mistyped CSV header", "Reproduce a malformed header and check the fixed header with a missing cell",
           ["unexpected CSV header", None], [message, metrics[-1][2]])
    before = sum(value for _, _, value in metrics[:3]) / 3
    expect("use_refactor", "four rows, one unknown", "Compare independent mean with the missing-aware implementation",
           [round(before, 5), None], [round(average(metrics), 5), average(metrics[-1:])])
    conn = sqlite3.connect(":memory:")
    try:
        conn.execute("CREATE TABLE metrics(week INTEGER, zone TEXT, minutes INTEGER)")
        conn.executemany("INSERT INTO metrics VALUES(?,?,?)", metrics)
        query = "SELECT week, SUM(minutes) FROM metrics WHERE zone=? GROUP BY week ORDER BY week"
        result = [list(row) for row in conn.execute(query, ("北区",))]
        empty = list(conn.execute(query, ("未登记区域",)))
    finally:
        conn.close()
    expect("use_sql", "北区", "Execute the actual parameterized grouped query and its no-result branch",
           [[[1, 4], [2, 8], [3, None]], []], [result, empty])
    expect("use_data_chart", result, "Report known change separately from a missing period and choose trend and comparison views",
           [4, [3], ["时间折线图", "分区条形图"]],
           [result[1][1] - result[0][1], [week for week, value in result if value is None],
            ["时间折线图", "分区条形图"] if result == sorted(result) else []])

    notes = [("A1", "已完成设备清点。"), ("A2", "停机时间尚未确认。"), ("A3", "公告仍待起草。"), ("A4", "计划周五核对恢复。")]
    other = [("B1", "道路演练已改期。"), ("B2", "接驳方案待定。")]
    expect("use_summary_runtime", [notes, other], "Actually extract from distinct inputs and enforce a character budget",
           [[["A1", "已完成设备清点。"], ["A2", "停机时间尚未确认。"]], [["B1", "道路演练已改期。"]], []],
           [brief(notes, 18), brief(other, 8), brief(notes, 1)])
    pending = [item["evidence"] for item in meeting_rows() if item["owner"] is None or item["due"] is None]
    expect("use_summary_contract", ["A1", "A2", "A3", "A4"], "Preserve evidence IDs and unresolved fields in structured output",
           [["A1", "A2", "A3", "A4"], ["A3"]], [[item["evidence"] for item in meeting_rows()], pending])
    expect("use_meeting", [list(row) for row in FACTS], "Read responsible person, deadline, and unknown values separately",
           [{"task": "设备清点", "owner": "林", "due": "周二", "evidence": "A1"},
            {"task": "准备公告", "owner": None, "due": None, "evidence": "A3"}],
           [meeting_rows()[0], meeting_rows()[2]])

    plan = [("读入", "自行指出缺少的列"), ("过滤", "解释空值为何保留"),
            ("汇总", "手算一条分组结果"), ("复查", "比较两种实现")]
    expect("use_learning", "四周,每周两小时,初学 CSV", "Build four goals with diagnostic questions and a completion task",
           [4, "复查", "比较两种实现"], [len(plan), plan[-1][0], plan[-1][1]])
    labeled = [(0, "未恢复"), (10, "已恢复")]
    sample = 6
    label = min(labeled, key=lambda item: abs(sample - item[0]))[1]
    programmed = "已恢复" if sample >= 8 else "未恢复"
    expect("use_concept", [labeled, sample, 8], "Run a nearest-neighbor decision and compare it with a manually coded cutoff",
           ["已恢复", "未恢复"], [label, programmed])
    groups = {
        "常规": ("通知", "清单", "演示", "图解", "值班", "反馈", "复盘", "自测", "检索", "归档"),
        "发散": ("把地图做成折页", "用颜色讲时序", "用声音提示状态", "设计匿名任务挑战", "交换两组场景"),
        "混搭": ("图解+导航", "清单+角色卡", "复盘+接龙"),
    }
    expect("use_brainstorm", list(groups), "Check the three categories, counts and distinct ideas",
           [[10, 5, 3], 18], [[len(items) for items in groups.values()], len({item for items in groups.values() for item in items})])
    layout = {"purpose": "值班交接页", "regions": ["导航", "开场", "三个任务", "联系"],
              "initial": "浅蓝", "revision": "深蓝", "avoid": "自动播放"}
    expect("use_design", layout, "Check layout handoff, original and revised theme and excluded behavior",
           [4, "深蓝", "自动播放"], [len(layout["regions"]), layout["revision"], layout["avoid"]])
    story = {"cast": ("巡检员", "实习生", "档案员"), "beats": ("找到旧单", "核对矛盾", "重建记录", "交接"),
             "endings": ("公开更正", "遗失证据", "留待下一班"), "conflict": "快速恢复与记录完整性"}
    expect("use_story", "维修记录谜题", "Validate cast, four beats, a conflict and three alternate endings",
           [3, 4, 3, True], [len(story["cast"]), len(story["beats"]), len(story["endings"]), bool(story["conflict"])])
    expect("use_faq", ["试听", "几点开放", "维修密钥", "地址", "不满意"],
           "Retrieve only visible and versioned records, with an explicit handoff",
           [["answer", "可预约一次 20 分钟体验。", "FAQ-01@v3"], ["answer", "周三 14:00–16:00 开放。", "FAQ-02@v2"],
            ["human_review", "请联系值班人员核对。", None], ["human_review", "请联系值班人员核对。", None],
            ["human_review", "请联系值班人员核对。", None]],
           [faq("想试听"), faq("几点开放"), faq("维修密钥"), faq("地址在哪"), faq("想试听", dissatisfied=True)])


if __name__ == "__main__":
    run_exercise(exercise)
本例需在 Python 3.12.14,SQLite 内存库,formulas 1.3.4、XlsxWriter 3.3.1、openpyxl 3.1.5。固定虚构输入。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12.14,SQLite 内存库,formulas 1.3.4、XlsxWriter 3.3.1、openpyxl 3.1.5。固定虚构输入。

入口文件:projects/ai-use-cases/workflows.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 workflows.py,或下载右侧课程工程包。
  2. 确认本地已准备 Python 3.12.14,SQLite 内存库,formulas 1.3.4、XlsxWriter 3.3.1、openpyxl 3.1.5。固定虚构输入。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI(人工智能)

课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip

下载课程关联工程包:AI(人工智能)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a29.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习