examples/t2i.py
1.7 KB · 50 lines · python Raw
1 #!/usr/bin/env python3
2 """Send request.t2i.json to a MiniMax-H3-Image server and write the PNG.
3
4 python3 t2i.py [--url http://127.0.0.1:30000] [--prompt FILE] [--size WxH] [--out t2i.png]
5
6 --prompt and --size replace the prompt and the size in the request.
7
8 Uses only the Python standard library.
9 """
10
11 import argparse
12 import base64
13 import json
14 import urllib.request
15 from pathlib import Path
16
17 # absolute(), not resolve(): in the Hugging Face cache this file is a symlink into blobs/.
18 HERE = Path(__file__).absolute().parent
19
20
21 def main() -> None:
22 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
23 parser.add_argument("--url", default="http://127.0.0.1:30000", help="server base URL")
24 parser.add_argument("--request", type=Path, default=HERE / "request.t2i.json", help="JSON request body")
25 parser.add_argument("--prompt", type=Path, help="prompt file; replaces the prompt in the request")
26 parser.add_argument("--size", help="WIDTHxHEIGHT; replaces the size in the request")
27 parser.add_argument("--out", default="t2i.png")
28 args = parser.parse_args()
29
30 body = json.loads(args.request.read_text())
31 if args.prompt:
32 body["prompt"] = args.prompt.read_text()
33 if args.size:
34 body["size"] = args.size
35
36 request = urllib.request.Request(
37 f"{args.url.rstrip('/')}/v1/images/generations",
38 data=json.dumps(body).encode(),
39 headers={"Content-Type": "application/json"},
40 )
41 with urllib.request.urlopen(request, timeout=1800) as response:
42 payload = json.load(response)
43 with open(args.out, "wb") as image:
44 image.write(base64.b64decode(payload["data"][0]["b64_json"]))
45 print(f"wrote {args.out}")
46
47
48 if __name__ == "__main__":
49 main()
50