openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
examples/image_stream.py
53lines · modeblame
a85ad051stainless-app[bot]11 months ago | 1 | #!/usr/bin/env python |
| 2 | | |
| 3 | import base64 | |
| 4 | from pathlib import Path | |
| 5 | | |
| 6 | from openai import OpenAI | |
| 7 | | |
| 8 | client = OpenAI() | |
| 9 | | |
| 10 | | |
| 11 | def main() -> None: | |
| 12 | """Example of OpenAI image streaming with partial images.""" | |
| 13 | stream = client.images.generate( | |
| 14 | model="gpt-image-1", | |
| 15 | prompt="A cute baby sea otter", | |
| 16 | n=1, | |
| 17 | size="1024x1024", | |
| 18 | stream=True, | |
| 19 | partial_images=3, | |
| 20 | ) | |
| 21 | | |
| 22 | for event in stream: | |
| 23 | if event.type == "image_generation.partial_image": | |
| 24 | print(f" Partial image {event.partial_image_index + 1}/3 received") | |
| 25 | print(f" Size: {len(event.b64_json)} characters (base64)") | |
| 26 | | |
| 27 | # Save partial image to file | |
| 28 | filename = f"partial_{event.partial_image_index + 1}.png" | |
| 29 | image_data = base64.b64decode(event.b64_json) | |
| 30 | with open(filename, "wb") as f: | |
| 31 | f.write(image_data) | |
| 32 | print(f" 💾 Saved to: {Path(filename).resolve()}") | |
| 33 | | |
| 34 | elif event.type == "image_generation.completed": | |
| 35 | print(f"\n✅ Final image completed!") | |
| 36 | print(f" Size: {len(event.b64_json)} characters (base64)") | |
| 37 | | |
| 38 | # Save final image to file | |
| 39 | filename = "final_image.png" | |
| 40 | image_data = base64.b64decode(event.b64_json) | |
| 41 | with open(filename, "wb") as f: | |
| 42 | f.write(image_data) | |
| 43 | print(f" 💾 Saved to: {Path(filename).resolve()}") | |
| 44 | | |
| 45 | else: | |
| 46 | print(f"❓ Unknown event: {event}") # type: ignore[unreachable] | |
| 47 | | |
| 48 | | |
| 49 | if __name__ == "__main__": | |
| 50 | try: | |
| 51 | main() | |
| 52 | except Exception as error: | |
fd2c3f12David Meadows10 months ago | 53 | print(f"Error generating image: {error}") |