From 9d014f68ffee50b25177dd1b3572f9c6190ce218 Mon Sep 17 00:00:00 2001 From: Jett Wang Date: Sun, 10 Dec 2023 23:05:51 +0800 Subject: [PATCH] image gen --- ...13\345\274\217\346\235\200\346\211\213.py" | 1 - ...76\345\203\217\347\224\237\346\210\220.py" | 61 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 "pages/08_\360\237\216\250\345\233\276\345\203\217\347\224\237\346\210\220.py" diff --git "a/pages/02_\360\237\222\245\346\226\271\347\250\213\345\274\217\346\235\200\346\211\213.py" "b/pages/02_\360\237\222\245\346\226\271\347\250\213\345\274\217\346\235\200\346\211\213.py" index 93de459..9fbdc53 100644 --- "a/pages/02_\360\237\222\245\346\226\271\347\250\213\345\274\217\346\235\200\346\211\213.py" +++ "b/pages/02_\360\237\222\245\346\226\271\347\250\213\345\274\217\346\235\200\346\211\213.py" @@ -12,7 +12,6 @@ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") # 设置 OpenAI API 密钥 -openai.api_key = OPENAI_API_KEY client = OpenAI() diff --git "a/pages/08_\360\237\216\250\345\233\276\345\203\217\347\224\237\346\210\220.py" "b/pages/08_\360\237\216\250\345\233\276\345\203\217\347\224\237\346\210\220.py" new file mode 100644 index 0000000..720afe6 --- /dev/null +++ "b/pages/08_\360\237\216\250\345\233\276\345\203\217\347\224\237\346\210\220.py" @@ -0,0 +1,61 @@ +import streamlit as st +from openai import OpenAI +import requests +from PIL import Image +from io import BytesIO +from dotenv import load_dotenv +import os, sys + +from libs.session import PageSessionState + +sys.path.append(os.path.abspath('..')) +load_dotenv() + +page_state = PageSessionState("image_generator") + +page_state.initn_attr("result_imgs", None) + +client = OpenAI() + + +def generate_image(prompt, quality, size, style): + try: + response = client.images.generate(model="dall-e-3", + prompt=prompt, + size=size, + quality=quality, + style=style, + n=1) + return [d.url for d in response.data] + except Exception as e: + st.error(f"Error generating image: {e}") + return None + + +# Streamlit 应用布局 +st.sidebar.markdown("# 🎨 图像生成器") + +# 用户输入 +user_prompt = st.text_area('输入图像生成器的提示:', '一只看书的狗', height=40, key="image_generator_prompt") +c1, c2, c3 = st.columns(3) +quality = c1.selectbox('清晰度', ['hd', 'standard']) +size = c2.selectbox('尺寸', ['1024x1024', '1792x1024', '1024x1792']) +style = c3.selectbox('风格', ['natural', 'vivid']) + +# 生成按钮 +if st.button('Generate Image'): + with st.spinner('Generating image...'): + image_data = generate_image(user_prompt, quality, size, style) + imgs = [] + if image_data: + for image_url in image_data: + # 获取图像并显示 + response = requests.get(image_url) + img = Image.open(BytesIO(response.content)) + imgs.append(img) + page_state.result_imgs = imgs + + +if page_state.result_imgs is not None: + for img in page_state.result_imgs: + st.image(img, caption='', use_column_width=True)