Files
aigc-home/docs/hel-892/batch181-parameter-plan/acquire.py
T

182 lines
6.6 KiB
Python

"""Bounded eight-file exact-commit preparation; no target connections."""
import base64
import datetime
import hashlib
import json
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
DOC = Path(__file__).resolve().parent
REPO = "https://github.com/Comfy-Org/ComfyUI"
COMMIT = "8010b48d2c1be986613f8e8c761527d205bd756f"
API = "https://api.github.com/repos/Comfy-Org/ComfyUI"
PATHS = (
"nodes.py",
"comfy_extras/nodes_canny.py",
"comfy_extras/nodes_images.py",
"server.py",
"comfy_api/latest/__init__.py",
"comfy_api/latest/_io_public.py",
"comfy_api/latest/_io.py",
"comfy_api/internal/__init__.py",
)
def sha(data):
return hashlib.sha256(data).hexdigest()
def utc():
return datetime.datetime.now(datetime.timezone.utc).isoformat()
def write(name, data):
with (DOC / name).open("xb") as stream:
stream.write(data)
def save(name, value):
write(name, (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode())
def request(key, suffix):
url = API + suffix
cap = 524288
receipt = dict(key=key, url=url, response_cap=cap, started_at_utc=utc())
req = urllib.request.Request(url, headers={"User-Agent": "HEL-892-static-audit"})
try:
try:
response = urllib.request.urlopen(req, timeout=30)
except urllib.error.HTTPError as exc:
response = exc
with response:
raw = response.read(cap + 1)
receipt.update(
status=response.status, headers=dict(response.headers), final_url=response.url
)
write("network/" + key + ".body", raw)
receipt.update(bytes=len(raw), sha256=sha(raw), cap_exceeded=len(raw) > cap)
assert len(raw) <= cap, "HTTP response exceeds cap; bounded prefix preserved"
assert receipt["status"] == 200, "HTTP failure; raw response preserved"
result = json.loads(raw)
except Exception as exc:
receipt["error"] = type(exc).__name__ + ": " + str(exc)
raise
finally:
receipt["completed_at_utc"] = utc()
save("network/" + key + ".json", receipt)
return result, receipt
def main():
(DOC / "network").mkdir()
(DOC / "source-text").mkdir()
old = ROOT / "docs/hel-892/batch180-exact-engine"
commit = json.loads((old / "network/commit.body").read_bytes())
root = json.loads((old / "network/root-tree.body").read_bytes())
snapshot_path = "docs/hel-892/batch179-target-snapshots/incoming/ssh-snapshot.stdout.json"
snapshot_bytes = (ROOT / snapshot_path).read_bytes()
core = json.loads(snapshot_bytes)["installations"][0]["core"]
assert core["head"] == COMMIT == commit["sha"]
assert core["tree"] == commit["tree"]["sha"] == root["sha"]
reused = []
for name in (
"network/commit.body",
"network/commit.json",
"network/root-tree.body",
"network/root-tree.json",
"identity-4.json",
"source-text/LICENSE.txt",
):
path = old / name
reused.append(
dict(
file=str(path.relative_to(ROOT)),
bytes=path.stat().st_size,
sha256=sha(path.read_bytes()),
retrieval_time="original180 record; not new acquisition",
)
)
save("metadata-license-reuse.json", reused)
trees = {"": root}
outcomes = []
for index, path in enumerate(PATHS):
try:
parent, _, filename = path.rpartition("/")
current = ""
for part in parent.split("/") if parent else ():
entries = {x["path"]: x for x in trees[current]["tree"]}
entry = entries[part]
current = (current + "/" + part).strip("/")
if current not in trees:
tree, _ = request(
"tree-" + current.replace("/", "__"), "/git/trees/" + entry["sha"]
)
assert tree["sha"] == entry["sha"] and not tree["truncated"]
trees[current] = tree
entry = next(x for x in trees[parent]["tree"] if x["path"] == filename)
key = "text-" + str(index)
item, receipt = request(key, "/contents/" + path + "?ref=" + COMMIT)
assert item["path"] == path and item["type"] == "file" and item["encoding"] == "base64"
assert item["sha"] == entry["sha"] and item["size"] == entry["size"]
assert item["size"] <= 262144, "decoded text exceeds whitelist limit; not accepted"
data = base64.b64decode(item["content"])
assert len(data) == item["size"]
blob = hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest()
assert blob == item["sha"]
data.decode("utf-8")
row = dict(
repo=REPO,
commit=COMMIT,
tree=core["tree"],
path=path,
git_blob_sha1=blob,
bytes=len(data),
sha256=sha(data),
request_key=key,
retrieved_at_utc=receipt["completed_at_utc"],
state="accepted",
file="source-text/" + path.replace("/", "__") + ".txt",
current_process_loaded="unknown",
)
if index < 3:
original = next(x for x in core["files"] if x["relative_path"] == path)
for field in ("bytes", "sha256", "git_blob_sha1"):
assert row[field] == original[field], (
path,
field,
"historical snapshot mismatch",
)
row.update(
snapshot=original,
snapshot_file=snapshot_path,
snapshot_sha256=sha(snapshot_bytes),
historical_installation_bytes=True,
)
else:
row.update(
historical_installation_bytes=False,
scope="canonical declaration/interface text only; target SDK bytes not sampled",
)
write(row["file"], data)
except Exception as error:
row = dict(
path=path,
repo=REPO,
commit=COMMIT,
state="gap",
error=type(error).__name__ + ": " + str(error),
expanded=False,
)
save("identity-" + str(index) + ".json", row)
outcomes.append(row)
print(path, row["state"], row.get("bytes"), row.get("error", ""))
save("identities.json", outcomes)
if __name__ == "__main__":
main()