"""Validate image bytes, vision request structure and analysis report routing."""
import base64
from io import BytesIO
import json
from pathlib import Path
from httpx2 import Client, MockTransport, Response
from openai import OpenAI
from PIL import Image, ImageDraw, UnidentifiedImageError, __version__ as pillow_version
from lab_tools import run_exercise
MIMES = {"PNG":"image/png","JPEG":"image/jpeg","WEBP":"image/webp","GIF":"image/gif"}
TASKS = {
"classify":"从图表、界面、商品、文档中选一个类别。",
"describe":"描述图中的可见对象、颜色和位置。",
"ocr":"提取可见文字。模糊处保留为未知。",
"chart":"描述柱形图的类型、坐标和数值。无法辨认时标为未知。",
"ui":"检查界面的布局、按钮和可读性。",
"product":"根据图片整理外观。材料与规格未知时留空。",
}
FIXTURES = {
"chart":{"classify":"图表","describe":"三个蓝柱","ocr":"STOCK 7","chart":"三柱依次为 20、40、60 像素。"},
"ui":{"classify":"界面","describe":"两栏筛选界面","ocr":"FILTER","ui":"确认筛选按钮是否有文字。"},
"product":{"classify":"商品","describe":"橙色容器","ocr":"","product":"容器外观为橙色,材质未知。"},
"document":{"classify":"文档","describe":"两行清单","ocr":"BIN 7"},
}
CATEGORIES = {"图表":"chart","界面":"ui","商品":"product","文档":None}
BAR_COLOR = (26,90,165)
def image_input(path, *, byte_limit=200_000, pixel_limit=80_000):
with path.open("rb") as stream:
raw = stream.read(byte_limit + 1)
if len(raw) > byte_limit:
raise ValueError("byte_limit")
with Image.open(BytesIO(raw)) as image:
if image.format not in MIMES or image.width * image.height > pixel_limit:
raise ValueError("format_or_size")
if getattr(image, "n_frames", 1) != 1:
raise ValueError("animated_input")
mime = MIMES[image.format]
image.verify()
return "data:" + mime + ";base64," + base64.b64encode(raw).decode("ascii")
def create_samples(root):
for label, suffix in (("chart","png"),("ui","jpeg"),("product","png"),("document","png")):
image = Image.new("RGB",(240,120),"white")
draw = ImageDraw.Draw(image)
if label == "chart":
draw.text((8,8),"STOCK 7",fill="black")
for x,height in zip((50,110,170),(20,40,60),strict=True):
draw.rectangle((x-8,100-height,x+8,99),fill=BAR_COLOR)
elif label == "ui":
draw.rectangle((8,10,65,110),outline="black")
draw.rectangle((72,10,220,110),outline="black")
draw.text((15,24),"FILTER",fill="black")
elif label == "product":
draw.rounded_rectangle((58,25,177,100),radius=10,fill=(240,148,58))
else:
draw.text((8,15),"BIN 7",fill="black")
draw.line((8,35,230,35),fill="black")
image.save(root/f"{label}.{suffix}")
def analyze(client, path, out_dir):
uri = image_input(path)
def query(task):
reply = client.chat.completions.create(model="lab-vision",max_completion_tokens=150,
messages=[{"role":"user","content":[{"type":"text","text":TASKS[task]},
{"type":"image_url","image_url":{"url":uri}}]}])
content = reply.choices[0].message.content if reply.choices else None
if content is None:
raise ValueError("missing_text")
return content
category = query("classify")
if category not in CATEGORIES:
raise ValueError("unexpected_category")
description = query("describe")
extracted = query("ocr")
specialist = CATEGORIES[category]
details = query(specialist) if specialist else None
data = dict(file=path.name,category=category,description=description,extracted_text=extracted,
specialist=specialist,details=details)
with (out_dir/f"{path.stem}.json").open("x",encoding="utf8") as output:
json.dump(data,output,ensure_ascii=False,indent=2)
with (out_dir/f"{path.stem}.txt").open("x",encoding="utf8") as output:
output.write("\n".join(f"{key}: {value}" for key,value in data.items()) + "\n")
return data
def exercise(checks, workspace):
expect = checks.expect
create_samples(workspace)
samples = {path.read_bytes():path for path in workspace.iterdir()}
chart = workspace/"chart.png"
with Image.open(chart) as image:
heights = [sum(image.getpixel((x,y)) == BAR_COLOR for y in range(30,100)) for x in (50,110,170)]
expect("multi_intro_chart_pixels","three local sample bars","Measure actual bar pixels separately from any fixed vision output",
[20,40,60],heights)
bad = workspace/"broken.png"
bad.write_bytes(b"not image data")
rejected = []
for path, limit in ((workspace/"missing.png",200_000),(bad,200_000),(chart,8)):
try:
image_input(path,byte_limit=limit)
except (FileNotFoundError,UnidentifiedImageError) as error:
rejected.append(type(error).__name__)
except ValueError as error:
rejected.append(str(error))
expect("multi_intro_media_input",["missing","broken","oversize"],"Reject invalid media before building a request",
["FileNotFoundError","UnidentifiedImageError","byte_limit"],rejected)
sent = []
names = {prompt:kind for kind,prompt in TASKS.items()}
bad_category = False
def fixture(request):
assert request.url.host == "api.openai.com" and request.url.path == "/v1/chat/completions"
assert request.headers["Authorization"] == "Bearer fixture-key"
body = json.loads(request.content)
assert body["max_completion_tokens"] == 150
text, image = body["messages"][0]["content"]
assert text["type"] == "text" and image["type"] == "image_url"
header, encoded = image["image_url"]["url"].split(",",1)
raw = base64.b64decode(encoded,validate=True)
source = samples[raw]
mime = "image/jpeg" if source.suffix == ".jpeg" else "image/png"
assert header == f"data:{mime};base64"
task = names[text["text"]]
sent.append([source.stem, task, mime])
content = "未知类别" if bad_category else FIXTURES[source.stem][task]
return Response(200,json={"id":"fixture","object":"chat.completion","created":1,"model":"lab-vision",
"choices":[{"index":0,"message":{"role":"assistant","content":content},"finish_reason":"stop"}]})
reports = workspace/"reports"
reports.mkdir()
with OpenAI(api_key="fixture-key",base_url="https://api.openai.com/v1",max_retries=0,
http_client=Client(transport=MockTransport(fixture),trust_env=False)) as client:
results = [analyze(client,path,reports) for path in sorted(samples.values())]
expect("multi_intro_reports",["chart","document","product","ui"],
"Execute distinct vision report routes and reread JSON and text from disk",
[["图表","chart","STOCK 7"],["文档",None,"BIN 7"],["商品","product",""],["界面","ui","FILTER"]],
[[row["category"],row["specialist"],row["extracted_text"]] for row in results])
for row in results:
stem = Path(row["file"]).stem
assert json.loads((reports/f"{stem}.json").read_bytes()) == row
assert row["description"] in (reports/f"{stem}.txt").read_text(encoding="utf8")
expect("multi_intro_sdk_routes",["PNG","JPEG"],"Inspect the actual serialized image bytes, task names and request count",
[["classify","describe","ocr","chart"],["classify","describe","ocr"],["classify","describe","ocr","product"],
["classify","describe","ocr","ui"],["image/jpeg","image/png"],15],
[[item[1] for item in sent if item[0]==label] for label in ("chart","document","product","ui")]
+ [sorted({item[2] for item in sent}),len(sent)])
bad_category = True
try:
analyze(client,chart,reports)
except ValueError as error:
failure = str(error)
else:
failure = "accepted"
expect("multi_intro_classification_error","unknown label","Reject an unexpected fixed label before writing a report",
"unexpected_category",failure)
expect("multi_intro_pillow","runtime","Read image library version","13.0.0",pillow_version)
if __name__ == "__main__":
run_exercise(exercise)
本例需在 CPython 3.12.14,Pillow 13.0.0、FFmpeg 7.1、eSpeak NG 与 PocketSphinx 5.0.4。CPython 3.12.14,Pillow 13.0.0、OpenAI SDK 3.46.0、httpx2 2.16.0,内存固定回包。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14,Pillow 13.0.0、FFmpeg 7.1、eSpeak NG 与 PocketSphinx 5.0.4。CPython 3.12.14,Pillow 13.0.0、OpenAI SDK 3.46.0、httpx2 2.16.0,内存固定回包。
入口文件:projects/ai-multimodal-intro/vision_report.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
vision_report.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14,Pillow 13.0.0、FFmpeg 7.1、eSpeak NG 与 PocketSphinx 5.0.4。CPython 3.12.14,Pillow 13.0.0、OpenAI SDK 3.46.0、httpx2 2.16.0,内存固定回包。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a18.zip