File: image_stream.py

package info (click to toggle)
python-openai 1.99.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,784 kB
  • sloc: python: 57,274; sh: 140; makefile: 7
file content (53 lines) | stat: -rw-r--r-- 1,644 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python

import base64
from pathlib import Path

from openai import OpenAI

client = OpenAI()


def main() -> None:
    """Example of OpenAI image streaming with partial images."""
    stream = client.images.generate(
        model="gpt-image-1",
        prompt="A cute baby sea otter",
        n=1,
        size="1024x1024",
        stream=True,
        partial_images=3,
    )

    for event in stream:
        if event.type == "image_generation.partial_image":
            print(f"  Partial image {event.partial_image_index + 1}/3 received")
            print(f"   Size: {len(event.b64_json)} characters (base64)")

            # Save partial image to file
            filename = f"partial_{event.partial_image_index + 1}.png"
            image_data = base64.b64decode(event.b64_json)
            with open(filename, "wb") as f:
                f.write(image_data)
            print(f"   šŸ’¾ Saved to: {Path(filename).resolve()}")

        elif event.type == "image_generation.completed":
            print(f"\nāœ… Final image completed!")
            print(f"   Size: {len(event.b64_json)} characters (base64)")

            # Save final image to file
            filename = "final_image.png"
            image_data = base64.b64decode(event.b64_json)
            with open(filename, "wb") as f:
                f.write(image_data)
            print(f"   šŸ’¾ Saved to: {Path(filename).resolve()}")

        else:
            print(f"ā“ Unknown event: {event}")  # type: ignore[unreachable]


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(f"Error generating image: {error}")