Seperti yang sudah dibahas pada modul sebelumnya, url yang disediakan tidak permananent, expired dalam 1 jam. Oleh karena itu kita perlu menyimpan image kedalam local storage.
Ada dua pendekatan untuk menyimpan image, pada modul ini kita akan membahas pendekatan pertama, menggunakan http request.
import openai
from dotenv import dotenv_values
import os
import requests
config = dotenv_values(".env")
openai.api_key = config["OPENAI_KEY"]
image_dir_name = "img"
image_directory = os.path.join(os.curdir, image_dir_name)
if not os.path.isdir(image_directory):
os.mkdir(image_directory)
prompt = "a surrealist dream-like oil painting by Salvador Dalí of a cat playing checkers"
response = openai.Image.create(
prompt = prompt,
size= "512x512",
n=1
)
image_url = (response["data"][0]["url"])
image_file_path = os.path.join(image_directory, "cat.png")
image_content = requests.get(image_url).content
with open(image_file_path, "wb") as image_file:
image_file.write(image_content)
Code diatas akan menyimpan image dengan nama cat.png kedalam direktori img.
Jika Anda ingin menampilkannya dalam Jupyter Notebook (tutorial menggunakan Jupyter Notebook). Gunakan code dibawah:
from IPython.display import Image Image(filename=image_file_path)
Anda juga dapat membuat fungsi dari kode diatas untuk menyimpan image:
def save_image(url, image_name):
image_dir_name = "img"
image_directory = os.path.join(os.curdir, image_dir_name)
if not os.path.isdir(image_directory):
os.mkdir(image_directory)
image_file_path = os.path.join(image_directory, image_name)
image_content = requests.get(image_url).content
with open(image_file_path, "wb") as image_file:
image_file.write(image_content)
Jika Anda menggunakan parameter n > 1, Anda cukup melakukan loop seperti berikut: Contohnya menggunakan nama file fox-01, fox-02 dan seterusnya.
for idx, img in enumerate(response["data"]):
save_image(img["url"], f"fox-{idx}.png")
Pada modul berikutnya kita akan membahas pendekatan kedua.