"""Owned offline image request construction; never sends an API request."""
import argparse,base64,copy,hashlib,json,struct,sys,zlib
from pathlib import Path
GUIDE_DATE="2026-11-23"
MIB=1024*1024
def png(width=2,height=1):
def chunk(kind,data):return struct.pack(">I",len(data))+kind+data+struct.pack(">I",zlib.crc32(kind+data)&0xffffffff)
scan=(b"\0"+b"\x20\x70\xd0"*width)*height
return b"\x89PNG\r\n\x1a\n"+chunk(b"IHDR",struct.pack(">IIBBBBB",width,height,8,2,0,0,0))+chunk(b"IDAT",zlib.compress(scan))+chunk(b"IEND",b"")
def inspect_png(data):
if data[:8]!=b"\x89PNG\r\n\x1a\n":raise ValueError("not_png")
offset=8;packed=b"";size=None;ended=False
while offset<len(data):
if offset+12>len(data):raise ValueError("truncated")
length=struct.unpack(">I",data[offset:offset+4])[0]
if length>len(data)-offset-12:raise ValueError("truncated")
kind=data[offset+4:offset+8];body=data[offset+8:offset+8+length]
if zlib.crc32(kind+body)&0xffffffff!=struct.unpack(">I",data[offset+8+length:offset+12+length])[0]:raise ValueError("crc")
if kind==b"IHDR":
width,height,depth,color,compression,filtering,interlace=struct.unpack(">IIBBBBB",body)
if size or not width or not height or depth!=8 or color!=2 or compression or filtering or interlace:raise ValueError("owned_fixture_profile_only")
size=(width,height)
if kind==b"IDAT":packed+=body
offset+=length+12
if kind==b"IEND":ended=True;break
if not ended or offset!=len(data) or size is None:raise ValueError("truncated_or_extra")
expected=size[1]*(1+size[0]*3)
if expected>10*MIB:raise ValueError("owned_decoder_budget")
decoder=zlib.decompressobj();scan=decoder.decompress(packed,expected+1)
if not decoder.eof or decoder.unconsumed_tail or len(scan)!=expected:raise ValueError("scanline")
# This teaching decoder deliberately accepts only its owned filter-0 RGB8 fixtures.
if any(scan[y*(1+size[0]*3)]!=0 for y in range(size[1])):raise ValueError("owned_fixture_profile_only")
return dict(mime="image/png",width=size[0],height=size[1],bytes=len(data),sha256=hashlib.sha256(data).hexdigest())
def image_block(*,raw=None,url=None,file_id=None,file_data=None,filename=None,detail=None):
if sum(v is not None for v in (raw,url,file_id,file_data))!=1:raise ValueError("one_image_source")
if detail not in (None,"low","high","original","auto"):raise ValueError("detail")
if file_id is not None:
if not file_id or filename is not None:raise ValueError("file_identity_fields")
if detail is not None:raise ValueError("detail_requires_image_url")
return {"type":"file","file_id":file_id}
if file_data is not None:
if detail is not None:raise ValueError("detail_requires_image_url")
return {"type":"file","file_data":file_data,**({"filename":filename} if filename is not None else {})}
if filename is not None:raise ValueError("filename_requires_file_data")
if raw is not None:
meta=inspect_png(raw);value="data:"+meta["mime"]+";base64,"+base64.b64encode(raw).decode("ascii")
else:
if not url.startswith(("https://","http://")) or len(url)>8192:raise ValueError("url_shape")
value=url
return {"type":"image_url","image_url":{"url":value,**({"detail":detail} if detail else {})}}
def content(family,block,prompt):
if family=="chat":return [{"type":"text","text":prompt},copy.deepcopy(block)]
if family=="responses":
image={"type":"input_image"}
if block["type"]=="file":
if "file_id" not in block:raise ValueError("owned_responses_file_data_not_implemented")
image["file_id"]=block["file_id"]
else:
image["image_url"]=block["image_url"]["url"]
if "detail" in block["image_url"]:image["detail"]=block["image_url"]["detail"]
return [{"type":"input_text","text":prompt},image]
if family=="messages":
if block["type"]=="file":raise ValueError("owned_messages_file_source_pending")
value=block["image_url"]["url"]
if value.startswith("data:"):
header,data=value.split(",",1);source={"type":"base64","media_type":header[5:].split(";",1)[0],"data":data}
else:source={"type":"url","url":value}
return [{"type":"text","text":prompt},{"type":"image","source":source}]
raise ValueError("family")
def wire_request(family,blocks,role="user"):
# These are message/image fragments for the guide, not a complete provider schema.
allowed={"chat":{"user","system","tool"},"messages":{"user"},"responses":{"user","developer"}}
if role not in allowed.get(family,set()):raise ValueError("owned_role_subset")
key="input" if family=="responses" else "messages"
request={"model":"deepseek-flash",key:[{"role":role,"content":copy.deepcopy(blocks)}]}
if family=="messages":request["max_tokens"]=256
return request
def wire_bytes(value):return json.dumps(value,ensure_ascii=False,separators=(",",":")).encode("utf8")
def bounds(*,count,width,height,image_bytes,request_bytes,total_bytes,has_file_id=False):
if count<1 or count>600:return "count"
if max(width,height)>(4096 if count>=15 else 8192):return "dimension"
if image_bytes>(64 if has_file_id else 32)*MIB:return "single_image"
if request_bytes>48*MIB:return "request_body"
if total_bytes>(200 if has_file_id else 64)*MIB:return "aggregate"
return "accepted_by_owned_checks"
def upload_fields(purpose,seconds=None):
if purpose not in ("user_data","text_recognition","rich_layout_recognition"):raise ValueError("purpose")
fields=[("purpose",purpose)]
if seconds is not None:
if type(seconds) is not int or not 3600<=seconds<=2592000:raise ValueError("expiry")
fields.extend([("expires_after[anchor]","created_at"),("expires_after[seconds]",str(seconds))])
return fields
def observe():
cases=[]
def add(name,input,expected,actual,operation):
if actual!=expected:raise AssertionError((name,expected,actual))
cases.append(dict(name=name,input=input,preconditions="Owned RGB8 filter-0 PNG or explicitly inert numeric boundary metadata; no account/endpoint.",
operation=operation,expected=expected,actual=actual,passed=True))
def error(fn):
try:fn()
except ValueError as e:return str(e)
raise AssertionError("expected failure")
fixture=png();meta=inspect_png(fixture)
add("actual_PNG_bytes",{"bytes":len(fixture),"sha256":meta["sha256"]},[2,1,"image/png"],[meta["width"],meta["height"],meta["mime"]],"Validate CRC, inflate and owned RGB8 scanline profile.")
broken=bytearray(fixture);broken[30]^=1
add("CRC_corruption",{"changed_offset":30},"crc",error(lambda:inspect_png(bytes(broken))),"Parse corrupted bytes without relying on a filename.")
block=image_block(raw=fixture)
encoded=block["image_url"]["url"].split(",",1)[1]
add("base64_roundtrip",{"raw_sha256":meta["sha256"]},fixture.hex(),base64.b64decode(encoded,validate=True).hex(),"Encode original bytes, decode strict base64 and compare every byte.")
add("base64_character_count",{"raw_bytes":len(fixture)},4*((len(fixture)+2)//3),len(encoded),"Compare actual base64 length with block padding formula.")
for family in ("chat","messages","responses"):
parts=content(family,block,"核对蓝色图块")
request=wire_request(family,parts);raw=wire_bytes(request);recovered=json.loads(raw)
key="input" if family=="responses" else "messages"
add(family+"_ordered_blocks",{"payload_sha256":hashlib.sha256(raw).hexdigest()},["text","image"],
["text" if x["type"] in ("text","input_text") else "image" for x in recovered[key][0]["content"]],"Serialize UTF-8 JSON and parse actual content order; no HTTP.")
add("UTF8_bytes_differ_from_characters",{"prompt":"蓝色"},True,len(wire_bytes({"text":"蓝色"}))>len(wire_bytes({"text":"蓝色"}).decode("utf8")),"Measure final UTF-8 bytes rather than character count.")
for detail in ("low","high","original","auto"):
add("detail_"+detail,{"detail":detail},detail,image_block(raw=fixture,detail=detail)["image_url"]["detail"],"Inspect independently built image_url detail field; no image scaling or token measurement.")
add("mutually_exclusive_sources",{}, "one_image_source",error(lambda:image_block(raw=fixture,url="https://example.com/i.png")),"Reject ambiguous owned builder arguments before serialization.")
add("file_id_filename_mutex",{}, "file_identity_fields",error(lambda:image_block(file_id="owned-inert-id",filename="x.png")),"Do not attach filename to file_id.")
inline=image_block(file_data=block["image_url"]["url"],filename="owned.png")
add("inline_file_fields",{},["file","owned.png"],[inline["type"],inline["filename"]],"Build file_data variant without claiming an upload exists.")
add("Responses_file_id",{},{"type":"input_image","file_id":"owned-inert-id"},content("responses",image_block(file_id="owned-inert-id"),"x")[1],"Inspect file_id field; sample identity is deliberately inert.")
for family in ("chat","responses"):
add(family+"_assistant_rejected",{},"owned_role_subset",error(lambda:wire_request(family,[],"assistant")),"Apply the explicitly implemented local role subset, not a server response.")
url="https://example.com/"+("a"*(8192-len("https://example.com/")))
add("URL_8192",{"length":8192},8192,len(image_block(url=url)["image_url"]["url"]),"Build a syntactically allowed length; no URL download or DNS.")
add("URL_8193",{"length":8193},"url_shape",error(lambda:image_block(url=url+"a")),"Check local URL length only.")
base=dict(count=1,width=2,height=1,image_bytes=len(fixture),request_bytes=len(wire_bytes(wire_request("chat",content("chat",block,"x")))),total_bytes=len(fixture))
large=inspect_png(png(8192,1))
for count,expected in [(14,"accepted_by_owned_checks"),(15,"dimension")]:
values={**base,"count":count,"width":large["width"],"height":large["height"]}
add("actual_8192px_PNG_count_"+str(count),values,expected,bounds(**values),"Read actual owned PNG dimensions and evaluate count-dependent rule; no upload.")
for label,changes,expected in [
("count_600",{"count":600},"accepted_by_owned_checks"),("count_601",{"count":601},"count"),
("body_48MiB",{"request_bytes":48*MIB},"accepted_by_owned_checks"),("body_over_48MiB",{"request_bytes":48*MIB+1},"request_body"),
("raw_32MiB",{"image_bytes":32*MIB},"accepted_by_owned_checks"),("raw_over_32MiB",{"image_bytes":32*MIB+1},"single_image"),
("file_64MiB",{"image_bytes":64*MIB,"has_file_id":True},"accepted_by_owned_checks"),
("total_200MiB",{"total_bytes":200*MIB,"has_file_id":True},"accepted_by_owned_checks"),
("total_over_200MiB",{"total_bytes":200*MIB+1,"has_file_id":True},"aggregate")]:
values={**base,**changes};add("numeric_"+label,values,expected,bounds(**values),"Evaluate explicitly inert numeric manifest metadata; no file of this size was allocated/uploaded.")
for seconds in (3600,2592000):
fields=upload_fields("user_data",seconds)
add("expiry_"+str(seconds),{"seconds":seconds},[["purpose","user_data"],["expires_after[anchor]","created_at"],["expires_after[seconds]",str(seconds)]],[list(x) for x in fields],"Construct ordered upload field plan; multipart body and upload not performed.")
add("expiry_under_minimum",{"seconds":3599},"expiry",error(lambda:upload_fields("user_data",3599)),"Reject local expiry value outside current documented range.")
add("document_purpose_before_file",{}, "rich_layout_recognition",upload_fields("rich_layout_recognition")[0][1],"Construct purpose-first field plan; no document parsing.")
path=Path(__file__).resolve();digest=hashlib.sha256(path.read_bytes()).hexdigest()
for case in cases:case["test_source"]={"path":path.name,"sha256":digest}
return dict(cases=cases,version="Python"+sys.version.split()[0],binary_sha256=hashlib.sha256(Path(sys.executable).read_bytes()).hexdigest(),
guide_snapshot=GUIDE_DATE,source_sha256=digest,fixture_sha256=meta["sha256"],owned_decoder_profile="RGB8 noninterlaced PNG with filter0 only; not a general media decoder",
scope="Owned offline encoding, JSON, field and numeric boundary observations only. Not DSH/SDK/provider execution, OCR, model accuracy, API400, upload, download, token or billing proof.",
model_requests=0,network_requests=0,source_tutorial_scripts_executed=False,real_uploads=0,real_file_deletes=0,DSH_application_executed=False)
if __name__=="__main__":
parser=argparse.ArgumentParser();parser.add_argument("--fixture-output",type=Path);args=parser.parse_args()
if args.fixture_output:args.fixture_output.write_bytes(png())
print(json.dumps(observe(),ensure_ascii=False))
本例需在 Windows、Python3.12标准库;完全离线,无第三方SDK、真实密钥或模型。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python3.12标准库;完全离线,无第三方SDK、真实密钥或模型。
入口文件:projects/deepseek-harness-modality-payload/vision_payload_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
vision_payload_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python3.12标准库;完全离线,无第三方SDK、真实密钥或模型。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a128.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a146.zip