thliang01 commited on
Commit
1553ebb
·
unverified ·
1 Parent(s): 23df3d9

Add app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -2
app.py CHANGED
@@ -1,4 +1,71 @@
1
  import streamlit as st
 
 
 
2
 
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
+ import base64
4
+ import os
5
 
6
+ st.title("OpenAI GPT-Image-1 Text-to-Image Demo")
7
+
8
+ prompt = st.text_area("Please enter image description (prompt)")
9
+ api_key = os.environ.get("OPENAI_API_KEY")
10
+ if api_key:
11
+ st.info("OPENAI_API_KEY environment variable detected, will use automatically.")
12
+ else:
13
+ api_key = st.text_input("Please enter OpenAI API Key", type="password")
14
+
15
+ uploaded_image = st.file_uploader(
16
+ "(Optional) Upload an image to edit", type=["png", "jpg", "jpeg", "webp"]
17
+ )
18
+
19
+ if st.button("Generate Image") and prompt and api_key:
20
+ if uploaded_image:
21
+ # Call image edit API
22
+ headers = {"Authorization": f"Bearer {api_key}"}
23
+ files = {
24
+ "image": (uploaded_image.name, uploaded_image, uploaded_image.type),
25
+ }
26
+ data = {
27
+ "prompt": prompt,
28
+ "model": "gpt-image-1",
29
+ "size": "1024x1024",
30
+ }
31
+ with st.spinner("Image editing in progress..."):
32
+ response = requests.post(
33
+ "https://api.openai.com/v1/images/edits",
34
+ headers=headers,
35
+ files=files,
36
+ data=data,
37
+ )
38
+ if response.status_code == 200:
39
+ img_b64 = response.json()["data"][0]["b64_json"]
40
+ img_bytes = base64.b64decode(img_b64)
41
+ col1, col2 = st.columns(2)
42
+ with col1:
43
+ st.image(uploaded_image, caption="Original Image", use_column_width=True)
44
+ with col2:
45
+ st.image(img_bytes, caption="Edited Image", use_column_width=True)
46
+ else:
47
+ st.error(f"API Error: {response.text}")
48
+ else:
49
+ # Call image generation API
50
+ headers = {
51
+ "Authorization": f"Bearer {api_key}",
52
+ "Content-Type": "application/json",
53
+ }
54
+ payload = {
55
+ "prompt": prompt,
56
+ "model": "gpt-image-1",
57
+ "output_format": "png",
58
+ "size": "1024x1024",
59
+ }
60
+ with st.spinner("Image generation in progress..."):
61
+ response = requests.post(
62
+ "https://api.openai.com/v1/images/generations",
63
+ headers=headers,
64
+ json=payload,
65
+ )
66
+ if response.status_code == 200:
67
+ img_b64 = response.json()["data"][0]["b64_json"]
68
+ img_bytes = base64.b64decode(img_b64)
69
+ st.image(img_bytes, caption="Generated Image", use_column_width=True)
70
+ else:
71
+ st.error(f"API Error: {response.text}")