examples/api_generate.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Generate the same image with the MiniMax API, as a reference for the local result. |
| 3 | |
| 4 | export MINIMAX_API_BASE=https://api.minimax.cn # CN; Global: https://api.minimax.io |
| 5 | export MINIMAX_API_KEY=<API key> |
| 6 | python3 api_generate.py t2i # POST /v1/images/generations with instruction.t2i.txt |
| 7 | python3 api_generate.py edit # POST /v1/images/edits with instruction.edit.txt and reference1.png |
| 8 | |
| 9 | The API applies the same prompt enhancement internally. Writes the image (api_<task>.png) and |
| 10 | the prompt the API used (api_<task>_revised_prompt.txt). Uses only the Python standard library. |
| 11 | """ |
| 12 | |
| 13 | import argparse |
| 14 | import base64 |
| 15 | import json |
| 16 | from pathlib import Path |
| 17 | |
| 18 | from context_ir import HERE, add_task_arguments, post, request_body |
| 19 | |
| 20 | |
| 21 | def main() -> None: |
| 22 | parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 23 | add_task_arguments(parser) |
| 24 | args = parser.parse_args() |
| 25 | |
| 26 | instruction = args.instruction or HERE / f"instruction.{args.task}.txt" |
| 27 | body = request_body(args.task, instruction, args.image, args.size) |
| 28 | body.update({"n": 1, "response_format": "b64_json", "output_format": "png"}) |
| 29 | path = "/v1/images/generations" if args.task == "t2i" else "/v1/images/edits" |
| 30 | result = post(path, body) |
| 31 | item = result["data"][0] |
| 32 | if "error" in item: |
| 33 | raise RuntimeError(f"image failed: {item['error']} (request_id {result.get('request_id')})") |
| 34 | Path(f"api_{args.task}.png").write_bytes(base64.b64decode(item["b64_json"])) |
| 35 | Path(f"api_{args.task}_revised_prompt.txt").write_text(item["revised_prompt"]) |
| 36 | print(json.dumps({"request_id": result.get("request_id"), "size": item.get("size"), "usage": result.get("usage")})) |
| 37 | |
| 38 | |
| 39 | if __name__ == "__main__": |
| 40 | main() |
| 41 | |