"""Use distinct local roles to repair input and produce a verifiable report."""
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import csv
from html import escape
import json
from pathlib import Path
import sqlite3
import sys
from contextlib import closing
from lab_tools import run_exercise
def read_sales(path):
with path.open(encoding="utf-8", newline="") as file:
reader = csv.DictReader(file)
if reader.fieldnames != ["region", "cents"]:
raise ValueError("Expected region,cents")
rows = []
for row in reader:
if None in row or not row["region"] or row["cents"] is None:
raise ValueError(f"Malformed row ending on line {reader.line_num}")
cents = int(row["cents"])
if cents < 0:
raise ValueError("This exercise expects nonnegative sales")
rows.append((row["region"], cents))
return rows
def python_totals(rows):
totals = Counter()
for name, value in rows:
totals[name] += value
return dict(totals)
def sql_totals(rows):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("CREATE TABLE sales(region TEXT, cents INTEGER)")
db.executemany("INSERT INTO sales VALUES (?,?)", rows)
return dict(db.execute("SELECT region, SUM(cents) FROM sales GROUP BY region"))
def render_chart(path, totals):
bars = []
for index, (region, value) in enumerate(sorted(totals.items())):
y = 78 + index * 45
name = escape(region, quote=True)
bars.append(f'<text x="28" y="{y+16}">{name}</text>'
f'<rect x="140" y="{y}" width="{value}" height="22" fill="#176d93"/>'
f'<text x="{154+value}" y="{y+16}">{value}</text>')
svg = ('<svg xmlns="http://www.w3.org/2000/svg" width="720" height="180" viewBox="0 0 720 180">'
'<rect width="720" height="180" fill="#f1f7fb"/>'
'<g font-family="Segoe UI, sans-serif" font-size="17" fill="#173655">'
'<text x="28" y="41" font-size="24">Regional sales (cents)</text>'
+ ''.join(bars) + '</g></svg>')
path.write_text(svg, encoding="utf-8")
def exercise(checks, workspace, chart_output=None):
expect = checks.expect
good = workspace / "sales.csv"
good.write_text("region,cents\nEast,130\nWest,250\nEast,170\n", encoding="utf-8")
candidates = [workspace / "draft.csv", good]
trace = ["coordinate", "design"]
for candidate in candidates:
try:
rows = read_sales(candidate)
break
except FileNotFoundError:
trace.append("read_missing")
else:
raise FileNotFoundError("No allowed file present")
trace.append("read_sales")
with ThreadPoolExecutor(max_workers=2) as pool:
primary = pool.submit(python_totals, rows)
independent = pool.submit(sql_totals, rows)
totals = primary.result()
checked = independent.result()
trace.extend(("aggregate", "check"))
expect("intro_adjust", [path.name for path in candidates], "Try listed files, then adjust after FileNotFoundError",
["coordinate", "design", "read_missing", "read_sales"], trace[:4])
expect("intro_files", "sales.csv", "Parse the real local UTF-8 CSV", 3, len(rows))
errors = []
malformed = workspace / "malformed.csv"
for line in ("East,130,extra", "East", ",130", "East,no-number"):
malformed.write_text("region,cents\n" + line + "\n", encoding="utf-8")
try:
read_sales(malformed)
except ValueError:
errors.append(line)
expect("intro_bad_rows", "extra column, missing amount, empty region, noninteger amount",
"Reject malformed CSV records before aggregation",
["East,130,extra", "East", ",130", "East,no-number"], errors)
expect("intro_sql", rows, "Compare independent Python and SQLite aggregates",
[{"East": 300, "West": 250}] * 2, [totals, checked])
if totals != checked:
raise ValueError("Independent check disagrees")
report = workspace / "report.json"
report.write_text(json.dumps(totals, sort_keys=True), encoding="utf-8")
render_chart(workspace / "sales-chart.svg", totals)
if chart_output is not None:
chart_output.write_bytes((workspace / "sales-chart.svg").read_bytes())
trace.append("deliver")
expect("intro_handoffs", "missing draft, valid sales and independent check",
"Pass data through coordination, design, execution, validation and file delivery",
["coordinate", "design", "read_missing", "read_sales", "aggregate", "check", "deliver"], trace)
expect("intro_state", "report.json", "Read the persisted report bytes back", totals,
json.loads(report.read_text(encoding="utf-8")))
expect("intro_chart", "sales-chart.svg", "Read the generated SVG bars and their values",
[True, True], ["width=\"300\"" in (workspace / "sales-chart.svg").read_text(encoding="utf-8"),
"width=\"250\"" in (workspace / "sales-chart.svg").read_text(encoding="utf-8")])
if __name__ == "__main__":
if len(sys.argv) == 1:
run_exercise(exercise)
elif len(sys.argv) == 3 and sys.argv[1] == "--chart-output":
run_exercise(lambda checks, workspace: exercise(checks, workspace, Path(sys.argv[2])))
else:
raise SystemExit("usage: introduction.py [--chart-output SVG]")
本例需在 CPython 3.12 标准库,独立临时文件和 SQLite,本机显式规则决策 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12 标准库,独立临时文件和 SQLite,本机显式规则决策
入口文件:projects/ai-agent-foundations/introduction.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
introduction.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12 标准库,独立临时文件和 SQLite,本机显式规则决策。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a3082.zip