├── LICENSE
├── README.md
├── dalle2_python.py
├── output
├── if running late for class was an animal, digital art_0.png
└── if running late for class was an animal, digital art_1.png
└── requirements.txt
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Alexander
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
📸 dalle2_python 🏞
2 |
3 |
4 | Generating stunning images from the command line.
5 |
6 |
7 | This is a simple working example on how to integrate the DALLE2 API into your own Python project and create amazing images directly from the command line.
8 |
9 | ## How it works
10 | Reads a string from the command line in natural language and creates an input prompt which is then fed to OpenAIs DALLE2. The response contains urls to the generated images. The images are downloaded and stored in an output folder.
11 | To generate your own images you need to get access to the DALLE2 API (https://openai.com/dall-e-2/).
12 |
13 | ## Installation
14 | ```bash
15 | git clone https://github.com/alxschwrz/dalle2_python.git
16 | cd dalle2_python
17 | pip3 install -r requirements.txt
18 | ```
19 |
20 | ## Run example
21 | ```
22 | python3 dalle2_python.py
23 | What image should dalle create: if running late for class was an animal, digital art
24 | Generated image stored in: ./output/if running late for class was an animal, digital art_0.png
25 | Generated image stored in: ./output/if running late for class was an animal, digital art_1.png
26 | ```
27 | Now check the output folder:
28 |
29 |
30 |
31 |
32 |
33 | Enjoy!
34 |
--------------------------------------------------------------------------------
/dalle2_python.py:
--------------------------------------------------------------------------------
1 | import os
2 | import configparser
3 | import sys
4 | import webbrowser
5 | import urllib.request
6 | import openai
7 |
8 |
9 | class Dalle:
10 | def __init__(self, img_sz="512", n_images=2):
11 | self._api_keys_location = "./config"
12 | self._generated_image_location = "./output"
13 | self._stream = True
14 | self._img_sz = img_sz
15 | self._n_images = n_images
16 | self._image_urls = []
17 | self._input_prompt = None
18 | self._response = None
19 | self.initialize_openai_api()
20 |
21 | def create_template_ini_file(self):
22 | """
23 | If the ini file does not exist create it and add the organization_id and
24 | secret_key
25 | """
26 | if not os.path.isfile(self._api_keys_location):
27 | with open(self._api_keys_location, 'w') as f:
28 | f.write('[openai]\n')
29 | f.write('organization_id=\n')
30 | f.write('secret_key=\n')
31 |
32 | print('OpenAI API config file created at {}'.format(self._api_keys_location))
33 | print('Please edit it and add your organization ID and secret key')
34 | print('If you do not yet have an organization ID and secret key, you\n'
35 | 'need to register for OpenAI Codex: \n'
36 | 'https://openai.com/blog/openai-codex/')
37 | sys.exit(1)
38 |
39 |
40 | def initialize_openai_api(self):
41 | """
42 | Initialize the OpenAI API
43 | """
44 | # Check if file at API_KEYS_LOCATION exists
45 | self.create_template_ini_file()
46 | config = configparser.ConfigParser()
47 | config.read(self._api_keys_location)
48 |
49 | openai.organization_id = config['openai']['organization_id'].strip('"').strip("'")
50 | openai.api_key = config['openai']['secret_key'].strip('"').strip("'")
51 | del config
52 |
53 | def read_from_command_line(self):
54 | self._input_prompt = input("What image should dalle create: ")
55 |
56 | def generate_image_from_prompt(self):
57 | self._response = openai.Image.create(
58 | prompt=self._input_prompt,
59 | n=self._n_images,
60 | size=f"{self._img_sz}x{self._img_sz}",
61 | )
62 |
63 | def get_urls_from_response(self):
64 | for i in range(self._n_images):
65 | self._image_urls.append(self._response['data'][i]['url'])
66 |
67 | def open_urls_in_browser(self, image_urls=None):
68 | if image_urls is None:
69 | image_urls = self._image_urls
70 | for url in image_urls:
71 | webbrowser.open(url)
72 |
73 | def save_urls_as_image(self):
74 | if not os.path.isdir(self._generated_image_location):
75 | os.mkdir(self._generated_image_location)
76 | for idx, image_url in enumerate(self._image_urls):
77 | file_name = f"{self._generated_image_location}/{self._input_prompt}_{idx}.png"
78 | urllib.request.urlretrieve(image_url, file_name)
79 | print(f"Generated image stored in: {file_name}")
80 |
81 | def generate_and_save_images(self):
82 | self.read_from_command_line()
83 | self.generate_image_from_prompt()
84 | self.get_urls_from_response()
85 | self.save_urls_as_image()
86 |
87 | commandLineDalle = Dalle()
88 | commandLineDalle.generate_and_save_images()
89 | commandLineDalle.open_urls_in_browser()
--------------------------------------------------------------------------------
/output/if running late for class was an animal, digital art_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alxschwrz/dalle2_python/494b62625043911218b5ad107b26dd83e72a7526/output/if running late for class was an animal, digital art_0.png
--------------------------------------------------------------------------------
/output/if running late for class was an animal, digital art_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alxschwrz/dalle2_python/494b62625043911218b5ad107b26dd83e72a7526/output/if running late for class was an animal, digital art_1.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | openai
--------------------------------------------------------------------------------