Skip to content

Commit 2960203

Browse files
authored
Merge branch 'master' into structural-pattern-matching
2 parents 7d23cd3 + 11f745c commit 2960203

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+1476
-62
lines changed

openai-dalle/README.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
# Generate Images With DALL·E 2 and the OpenAI API
1+
# Generate Images With DALL·E and the OpenAI API
22

3-
Learn to use the OpenAI Python library to create images with DALL·E, a state-of-the-art latent diffusion model. In the associated tutorial on [generating images with DALL·E 2 and the OpenAI API](https://realpython.com/generate-images-with-dalle-openai-api/), you explore image creation and generating image variations. You learn how to interact with DALL·E using API calls and incorporate this functionality into your Python scripts.
3+
Learn to use the OpenAI Python library to create images with DALL·E, a state-of-the-art latent diffusion model. In the associated tutorial on [generating images with DALL·E and the OpenAI API](https://realpython.com/generate-images-with-dalle-openai-api/), you'll explore image creation and generating image variations. You'll learn how to interact with DALL·E using API calls and incorporate this functionality into your Python scripts.
44

55
## Setup
66

77
Create and activate a virtual environment, then install the `openai` package:
88

99
```console
1010
$ python --version
11-
Python 3.11.0
11+
Python 3.12.5
1212
$ python -m venv venv
1313
$ source venv/bin/activate
1414
(venv) $ python -m pip install openai
@@ -22,14 +22,15 @@ Follow the instructions in [the tutorial](https://realpython.com/generate-images
2222

2323
You can find the code for each of these steps in dedicated scripts:
2424

25-
- `create.py`: Create an image from a text prompt and save the image data to a file.
25+
- `create_dalle3.py`: Create an image from a text prompt using DALL·E 3 and display the URL to the image.
26+
- `create.py`: Create an image from a text prompt using DALL·E 2 and save the image data to a file.
2627
- `convert.py`: Convert a Base64-encoded PNG image delivered in a JSON response to a PNG image file.
2728
- `vary.py`: Read Base64-encoded image data and make an API request to receive variations of that image.
2829

2930
In the tutorial, you'll walk through each of these scripts and their functionality and output in more detail.
3031

3132
## Edit Images (Inpainting and Outpainting)
3233

33-
The OpenAI Image API also allows you to [edit parts of an image](https://beta.openai.com/docs/guides/images/edits) using text prompts. For this, you need to create a mask with transparent image data in the area where you want to edit the image.
34+
The OpenAI Image API also allows you to [edit parts of an image](https://platform.openai.com/docs/guides/images/edits-dall-e-2-only) using text prompts. For this, you need to create a mask with transparent image data in the area where you want to edit the image.
3435

3536
You can run `edit.py` to give this functionality a try.

openai-dalle/create.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
import json
2-
import os
32
from pathlib import Path
43

5-
import openai
4+
from openai import OpenAI
5+
6+
client = OpenAI()
67

78
PROMPT = "An eco-friendly computer from the 90s in the style of vaporwave"
89
DATA_DIR = Path.cwd() / "responses"
910

1011
DATA_DIR.mkdir(exist_ok=True)
1112

12-
openai.api_key = os.getenv("OPENAI_API_KEY")
13-
14-
response = openai.Image.create(
13+
response = client.images.generate(
14+
model="dall-e-2",
1515
prompt=PROMPT,
1616
n=1,
1717
size="256x256",
1818
response_format="b64_json",
1919
)
2020

21-
file_name = DATA_DIR / f"{PROMPT[:5]}-{response['created']}.json"
21+
file_name = DATA_DIR / f"{PROMPT[:5]}-{response.created}.json"
2222

2323
with open(file_name, mode="w", encoding="utf-8") as file:
24-
json.dump(response, file)
24+
json.dump(response.to_dict(), file)

openai-dalle/create_dalle3.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from openai import OpenAI
2+
3+
client = OpenAI()
4+
5+
PROMPT = "A vaporwave computer"
6+
7+
8+
response = client.images.generate(
9+
model="dall-e-3",
10+
prompt=PROMPT,
11+
)
12+
13+
print(response.data[0].url)
14+
print(response.data[0].revised_prompt)

openai-dalle/edit.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import json
2-
import os
32
from pathlib import Path
43

5-
import openai
4+
from openai import OpenAI
5+
6+
client = OpenAI()
67

78
SOURCE_PATH = Path.cwd() / "images" / "An ec-1667994848"
89
DESTINATION_PATH = Path.cwd() / "responses"
@@ -11,9 +12,7 @@
1112
SOURCE_PATH.mkdir(parents=True, exist_ok=True)
1213
DESTINATION_PATH.mkdir(parents=True, exist_ok=True)
1314

14-
openai.api_key = os.getenv("OPENAI_API_KEY")
15-
16-
response = openai.Image.create_edit(
15+
response = client.images.edit(
1716
image=open(SOURCE_PATH / "computer.png", mode="rb"),
1817
mask=open(SOURCE_PATH / "mask.png", mode="rb"),
1918
prompt=PROMPT,
@@ -23,8 +22,8 @@
2322
)
2423

2524
with open(
26-
DESTINATION_PATH / f"edit-{PROMPT[:5]}-{response['created']}.json",
25+
DESTINATION_PATH / f"edit-{PROMPT[:5]}-{response.created}.json",
2726
mode="w",
2827
encoding="utf-8",
2928
) as file:
30-
json.dump(response, file)
29+
json.dump(response.to_dict(), file)

openai-dalle/requirements.txt

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
1-
certifi==2022.9.24
2-
charset-normalizer==2.1.1
3-
et-xmlfile==1.1.0
4-
idna==3.4
5-
numpy==1.23.4
6-
openai==0.25.0
7-
openpyxl==3.0.10
8-
pandas==1.5.1
9-
pandas-stubs==1.2.0.62
10-
python-dateutil==2.8.2
11-
pytz==2022.6
12-
requests==2.28.1
13-
six==1.16.0
14-
tqdm==4.64.1
15-
typing_extensions==4.4.0
16-
urllib3==1.26.12
1+
annotated-types==0.7.0
2+
anyio==4.4.0
3+
certifi==2024.7.4
4+
distro==1.9.0
5+
h11==0.14.0
6+
httpcore==1.0.5
7+
httpx==0.27.0
8+
idna==3.7
9+
jiter==0.5.0
10+
openai==1.40.6
11+
pydantic==2.8.2
12+
pydantic_core==2.20.1
13+
sniffio==1.3.1
14+
tqdm==4.66.5
15+
typing_extensions==4.12.2

openai-dalle/vary.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
import json
2-
import os
32
from base64 import b64decode
43
from pathlib import Path
54

6-
import openai
5+
from openai import OpenAI
6+
7+
client = OpenAI()
78

89
DATA_DIR = Path.cwd() / "responses"
910
SOURCE_FILE = DATA_DIR / "An ec-1667994848.json"
1011

11-
openai.api_key = os.getenv("OPENAI_API_KEY")
12-
1312
with open(SOURCE_FILE, mode="r", encoding="utf-8") as json_file:
1413
saved_response = json.load(json_file)
1514
image_data = b64decode(saved_response["data"][0]["b64_json"])
1615

17-
response = openai.Image.create_variation(
16+
response = client.images.create_variation(
1817
image=image_data,
1918
n=3,
2019
size="256x256",
2120
response_format="b64_json",
2221
)
2322

24-
new_file_name = f"vary-{SOURCE_FILE.stem[:5]}-{response['created']}.json"
23+
new_file_name = f"vary-{SOURCE_FILE.stem[:5]}-{response.created}.json"
2524

2625
with open(DATA_DIR / new_file_name, mode="w", encoding="utf-8") as file:
27-
json.dump(response, file)
26+
json.dump(response.to_dict(), file)
Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
click==8.1.3
2-
Flask==2.1.2
3-
itsdangerous==2.1.2
4-
Jinja2==3.1.2
5-
MarkupSafe==2.1.1
6-
Werkzeug==2.1.2
1+
blinker==1.8.2
2+
click==8.1.7
3+
Flask==3.0.3
4+
itsdangerous==2.2.0
5+
Jinja2==3.1.4
6+
MarkupSafe==2.1.5
7+
Werkzeug==3.0.3

python-async-iterators/async_csv.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,16 @@
77
class AsyncCSVIterator:
88
def __init__(self, path):
99
self.path = path
10-
self.file_was_read = False
10+
self.reader = None
1111

1212
def __aiter__(self):
1313
return self
1414

1515
async def __anext__(self):
16-
if not self.file_was_read:
16+
if self.reader is None:
1717
async with aiofiles.open(self.path, mode="r") as file:
1818
lines = await file.readlines()
1919
self.reader = csv.reader(lines)
20-
self.file_was_read = True
2120
try:
2221
return next(self.reader)
2322
except StopIteration:

python-async-iterators/compress.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,5 @@ async def main(directory, zip_name="output.zip"):
1818
await archive.write(chunk)
1919

2020

21-
directory = Path()
21+
directory = Path.cwd()
2222
asyncio.run(main(directory))

python-class/car.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def brake(self, value):
3434
print(f"Braking to {self.speed} km/h...")
3535

3636
def __str__(self):
37-
return f"{self.make}, {self.model}, {self.color}: ({self.year})"
37+
return f"{self.make} {self.model}, {self.color} ({self.year})"
3838

3939
def __repr__(self):
4040
return (

0 commit comments

Comments
 (0)