Pada modul ini kita mulai membuat web app color generator.
Buka file app.py, lalu gunakan code berikut:
import openai, json from flask import Flask, render_template, request from dotenv import dotenv_values config = dotenv_values(".env") openai.api_key = config["OPENAI_KEY"] app = Flask(__name__, template_folder='templates' ) def get_colors(theme): prompt = f""" You are a color palette generating bot that respond to text prompts for color palettes You should generate color that fit the theme, mood, or instructions in the prompt. The palettes should be between 2 and 8 colors. Q: Convert the following verbal description of a color palette into a list of colors: The Mediterranean Sea A: ["#006699", "66CCCC", "#F0E68C", "#008000", "#F08080"] Q: Convert the following verbal description of a color palette into a list of colors: sage, nature, earth A: ["#EDF1D6", "9DC08B", "#609966", "#40513B"] Desired format: the JSON array of hexadecimal color code Q: Convert the following verbal description of a color palette into a list of colors: {theme} A: """ response = openai.Completion.create( model = "text-davinci-003", prompt = prompt, max_tokens= 100 ) colors = json.loads(response['choices'][0]['text']) return colors @app.route("/palette", methods=["POST"]) def prompt_to_palette(): query = request.form.get("query") colors = get_colors(query) return {"colors": colors} @app.route("/") def index(): return render_template("index.html") if __name__ == "__main__": app.run(debug=True)
Buat file templates/index.html. Lalu masukan html berikut. HTML, CSS dan JavaScript tidak akan dibahas karena diluar scope tutorial.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Color Palette Generator</title> <style> html, body { margin:0; } .container{ background-color: black; width: 100%; height: 100vh; display: flex; } .color { height: 100%; display: flex; justify-content: center; align-items: flex-end; cursor: pointer; transition: 0.2s opacity; } .color:active{ opacity: 0.8; } .color span { font-size: 1.5rem; margin-bottom: 2rem; color:white; text-shadow: 1px 1px black; } #form { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } #form input[type="text"] { font-size: 2rem; outline: 0; border: solid 2px white; background-color: #f2f2f2; padding: 20px; width: 400px; } .btn { background-color: #4caf50; padding: 20px; font-size: 2rem; color: white; border: solid 2px white; transition: 0.2s opacity; } .btn:hover{ opacity: 0.8; } </style> </head> <body> <div class="container"></div> <form id="form"> <input type="text" name="query"> <button class="btn">Submit</button> </form> <script> const form = document.querySelector("#form"); form.addEventListener("submit", function(e){ e.preventDefault(); const query = form.elements.query.value; fetch("/palette", { method: "POST", headers: { "Content-Type" : "Application/X-WWW-form-urlencoded" }, body: new URLSearchParams({ query: query }) }) .then((response) => response.json()) .then(data => { const colors = data.colors; const container = document.querySelector(".container"); container.innerHTML = ""; for(const color of colors){ const div = document.createElement("div"); div.classList.add("color"); div.style.backgroundColor = color; div.style.width = `calc(100%/ ${colors.length})`; div.addEventListener("click", function(){ navigator.clipboard.writeText(color); }) const span = document.createElement("span"); span.innerText = color; div.appendChild(span) container.appendChild(div); } }) }) </script> </body> </html>
Buka command prompt, lalu jalankan perintah berikut:
(env) $ flask run
Kemudian buka browser, masuk ke http://127.0.0.1:5000/
Jika web aplikasi dijalankan dengan memberikan query beautiful sunset, akan tampil kurang lebih seperti gambar berikut.

Nah, sampai disini kita sudah selesai mengimplementasikan OpenAI API kedalam web app sederhana diatas.
Anda masih bisa optimalkan Javascript, CSS serta HTML diatas. Contoh diatas masih ada kekurangan seperti tidak support responsif. Anda juga bisa lakukan code refactoring dengan memisahkan CSS dan JavaScript dari HTML. Namun hal ini bukan scope dari tutorial.