|
| 1 | +import json |
| 2 | +from os import getenv |
| 3 | + |
| 4 | +import streamlit as st |
| 5 | +from dotenv import load_dotenv |
| 6 | +from openai import AzureOpenAI |
| 7 | + |
| 8 | +load_dotenv() |
| 9 | + |
| 10 | +with st.sidebar: |
| 11 | + azure_openai_endpoint = st.text_input( |
| 12 | + label="AZURE_OPENAI_ENDPOINT", |
| 13 | + value=getenv("AZURE_OPENAI_ENDPOINT"), |
| 14 | + key="AZURE_OPENAI_ENDPOINT", |
| 15 | + type="default", |
| 16 | + ) |
| 17 | + azure_openai_api_key = st.text_input( |
| 18 | + label="AZURE_OPENAI_API_KEY", |
| 19 | + key="AZURE_OPENAI_API_KEY", |
| 20 | + type="password", |
| 21 | + ) |
| 22 | + azure_openai_api_version = st.text_input( |
| 23 | + label="AZURE_OPENAI_API_VERSION", |
| 24 | + value=getenv("AZURE_OPENAI_API_VERSION"), |
| 25 | + key="AZURE_OPENAI_API_VERSION", |
| 26 | + type="default", |
| 27 | + ) |
| 28 | + azure_openai_dalle_model = st.text_input( |
| 29 | + label="AZURE_OPENAI_DALLE_MODEL", |
| 30 | + value=getenv("AZURE_OPENAI_DALLE_MODEL"), |
| 31 | + key="AZURE_OPENAI_DALLE_MODEL", |
| 32 | + type="default", |
| 33 | + ) |
| 34 | + "[Azure Portal](https://portal.azure.com/)" |
| 35 | + "[Azure OpenAI Studio](https://oai.azure.com/resource/overview)" |
| 36 | + "[View the source code](https://github.com/ks6088ts-labs/workshop-azure-openai/blob/main/apps/99_streamlit_examples/pages/7_Create_image.py)" |
| 37 | + |
| 38 | +st.title("Create image") |
| 39 | + |
| 40 | +if ( |
| 41 | + not azure_openai_api_key |
| 42 | + or not azure_openai_endpoint |
| 43 | + or not azure_openai_api_version |
| 44 | + or not azure_openai_dalle_model |
| 45 | +): |
| 46 | + st.warning("Please fill in the required fields at the sidebar.") |
| 47 | + st.stop() |
| 48 | + |
| 49 | +st.info("Create an image from a text description.") |
| 50 | + |
| 51 | +description = st.text_input( |
| 52 | + "Describe the image", |
| 53 | + placeholder="Please describe the content of the image", |
| 54 | +) |
| 55 | + |
| 56 | +if description: |
| 57 | + client = AzureOpenAI( |
| 58 | + api_key=azure_openai_api_key, |
| 59 | + api_version=azure_openai_api_version, |
| 60 | + azure_endpoint=azure_openai_endpoint, |
| 61 | + ) |
| 62 | + |
| 63 | + with st.spinner("Thinking..."): |
| 64 | + result = client.images.generate( |
| 65 | + model=azure_openai_dalle_model, |
| 66 | + prompt=description, |
| 67 | + n=1, |
| 68 | + ) |
| 69 | + json_response = json.loads(result.model_dump_json()) |
| 70 | + |
| 71 | + st.link_button("Show image", json_response["data"][0]["url"]) |
| 72 | + st.write(json_response) |
0 commit comments