examples/edit.py
2.7 KB · 70 lines · python Raw
1 #!/usr/bin/env python3
2 """Send reference1.png and prompt.edit.txt to a MiniMax-H3-Image server and write the PNG.
3
4 python3 edit.py [--url http://127.0.0.1:30000] [--out edit.png]
5
6 The images are sent in --image order, which defines <Picture 1>, <Picture 2>, ... in the
7 prompt. Uses only the Python standard library.
8 """
9
10 import argparse
11 import base64
12 import json
13 import mimetypes
14 import urllib.request
15 import uuid
16 from pathlib import Path
17
18 # absolute(), not resolve(): in the Hugging Face cache this file is a symlink into blobs/.
19 HERE = Path(__file__).absolute().parent
20
21
22 def multipart(fields: dict, images: list) -> tuple:
23 boundary = f"minimax-h3-image-{uuid.uuid4().hex}"
24 parts = []
25 for name, value in fields.items():
26 parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
27 for path in images:
28 content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
29 parts.append(
30 f'--{boundary}\r\nContent-Disposition: form-data; name="image"; filename="{path.name}"\r\n'
31 f"Content-Type: {content_type}\r\n\r\n".encode()
32 )
33 parts.append(path.read_bytes() + b"\r\n")
34 parts.append(f"--{boundary}--\r\n".encode())
35 return b"".join(parts), f"multipart/form-data; boundary={boundary}"
36
37
38 def main() -> None:
39 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
40 parser.add_argument("--url", default="http://127.0.0.1:30000", help="server base URL")
41 parser.add_argument("--image", action="append", type=Path,
42 help="reference image; repeat for <Picture 2>, ... (default: reference1.png)")
43 parser.add_argument("--prompt", type=Path, default=HERE / "prompt.edit.txt", help="prompt file")
44 parser.add_argument("--size", default="4096x4096", help="WIDTHxHEIGHT")
45 parser.add_argument("--seed", type=int, default=1234)
46 parser.add_argument("--out", default="edit.png")
47 args = parser.parse_args()
48
49 fields = {
50 "prompt": args.prompt.read_text(),
51 "size": args.size,
52 "seed": str(args.seed),
53 "generator_device": "cpu",
54 "response_format": "b64_json",
55 "output_format": "png",
56 }
57 body, content_type = multipart(fields, args.image or [HERE / "reference1.png"])
58 request = urllib.request.Request(
59 f"{args.url.rstrip('/')}/v1/images/edits", data=body, headers={"Content-Type": content_type}
60 )
61 with urllib.request.urlopen(request, timeout=1800) as response:
62 payload = json.load(response)
63 with open(args.out, "wb") as image:
64 image.write(base64.b64decode(payload["data"][0]["b64_json"]))
65 print(f"wrote {args.out}")
66
67
68 if __name__ == "__main__":
69 main()
70