ProfessorLeVesseur commited on
Commit
9acdb45
1 Parent(s): 017f64f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -29
app.py CHANGED
@@ -10,14 +10,14 @@ import requests
10
  # load_dotenv()
11
 
12
  # Streamlit page setup
13
- st.set_page_config(page_title="Pixel Generator", layout="centered", initial_sidebar_state="collapsed")
14
 
15
  #Add the image with a specified width
16
  image_width = 300 # Set the desired width in pixels
17
  st.image('MTSS.ai_Logo.png', width=image_width)
18
 
19
  st.header('PromptCanvas™ | Images')
20
- st.subheader('Image Builder')
21
 
22
  # Retrieve the OpenAI API Key from secrets
23
  openai.api_key = st.secrets["openai_api_key"]
@@ -30,47 +30,182 @@ openai.api_key = st.secrets["openai_api_key"]
30
  # Set the OpenAI API key
31
  # openai.api_key = openai_api_key
32
 
33
- def generate_images(prompt): #def generate_images(image_description, num_images):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  response = openai.images.generate(
35
  model="dall-e-3",
36
- prompt = prompt,
37
  size="1024x1024",
38
  quality="standard",
39
- n = 1,
40
  )
41
  image_url = response.data[0].url
42
  return image_url
43
 
44
- # prompt = st.text_area("Enter a description for the image you want to generate")
45
-
46
- # #create a button
47
- # if st.button("Generate Images"):
48
- # with st.spinner("Analyzing the image ..."):
49
- # generate_image=generate_images(prompt) #generate_image=generate_images(prompt, num_of_images)
50
- # st.image(generate_image)
51
-
52
- # Use a unique key for the text area to avoid conflicts with other session_state usages
53
- image_description_prompt = st.text_area("Enter a description for the image you want to generate", key="image_description")
54
 
55
- if st.button("Generate Images"):
56
- with st.spinner("Analyzing the image ..."):
57
- # Generate the image and store its URL in session_state
58
- st.session_state['generated_image_url'] = generate_images(image_description_prompt)
 
 
 
59
 
60
- # Check if the 'generated_image_url' key exists in session_state and display the image and download button
61
- if 'generated_image_url' in st.session_state and st.session_state['generated_image_url']:
62
  st.image(st.session_state['generated_image_url'], caption="Generated Image")
63
-
64
- # Fetch the image from the URL to enable downloading
65
  response = requests.get(st.session_state['generated_image_url'])
66
  if response.status_code == 200:
67
- img_bytes = BytesIO(response.content)
68
  st.download_button(
69
  label="Download Image",
70
- data=img_bytes,
71
- file_name="generated_image.png",
72
- mime="image/png",
73
- type="primary"
74
  )
75
- st.success('Powered by MTSS GPT. AI can make mistakes. Consider checking important information.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
 
10
  # load_dotenv()
11
 
12
  # Streamlit page setup
13
+ st.set_page_config(page_title="PromptCanvas™", layout="centered", initial_sidebar_state="collapsed")
14
 
15
  #Add the image with a specified width
16
  image_width = 300 # Set the desired width in pixels
17
  st.image('MTSS.ai_Logo.png', width=image_width)
18
 
19
  st.header('PromptCanvas™ | Images')
20
+ st.subheader('Image Builder + Alt Text')
21
 
22
  # Retrieve the OpenAI API Key from secrets
23
  openai.api_key = st.secrets["openai_api_key"]
 
30
  # Set the OpenAI API key
31
  # openai.api_key = openai_api_key
32
 
33
+ # def generate_images(prompt): #def generate_images(image_description, num_images):
34
+ # response = openai.images.generate(
35
+ # model="dall-e-3",
36
+ # prompt = prompt,
37
+ # size="1024x1024",
38
+ # quality="standard",
39
+ # n = 1,
40
+ # )
41
+ # image_url = response.data[0].url
42
+ # return image_url
43
+
44
+ # # Use a unique key for the text area to avoid conflicts with other session_state usages
45
+ # image_description_prompt = st.text_area("Enter a description for the image you want to generate", key="image_description")
46
+
47
+ # if st.button("Generate Images"):
48
+ # with st.spinner("Analyzing the image ..."):
49
+ # # Generate the image and store its URL in session_state
50
+ # st.session_state['generated_image_url'] = generate_images(image_description_prompt)
51
+
52
+ # # Check if the 'generated_image_url' key exists in session_state and display the image and download button
53
+ # if 'generated_image_url' in st.session_state and st.session_state['generated_image_url']:
54
+ # st.image(st.session_state['generated_image_url'], caption="Generated Image")
55
+
56
+ # # Fetch the image from the URL to enable downloading
57
+ # response = requests.get(st.session_state['generated_image_url'])
58
+ # if response.status_code == 200:
59
+ # img_bytes = BytesIO(response.content)
60
+ # st.download_button(
61
+ # label="Download Image",
62
+ # data=img_bytes,
63
+ # file_name="generated_image.png",
64
+ # mime="image/png",
65
+ # type="primary"
66
+ # )
67
+ # st.success('Powered by MTSS GPT. AI can make mistakes. Consider checking important information.')
68
+
69
+ def generate_images(prompt):
70
  response = openai.images.generate(
71
  model="dall-e-3",
72
+ prompt=prompt,
73
  size="1024x1024",
74
  quality="standard",
75
+ n=1,
76
  )
77
  image_url = response.data[0].url
78
  return image_url
79
 
80
+ # Input for image description
81
+ # prompt = st.text_input("Enter a description for the image you want to generate")
82
+ prompt = st.text_area("Enter a description for the image you want to generate")
 
 
 
 
 
 
 
83
 
84
+ # Generate Image button
85
+ if st.button("Generate Image"):
86
+ generated_image_url = generate_images(prompt)
87
+ if generated_image_url:
88
+ # st.image(generated_image_url, caption="Generated Image")
89
+ # Store the generated image URL in the session state
90
+ st.session_state['generated_image_url'] = generated_image_url
91
 
92
+ # Display the generated image if it's in the session state
93
+ if 'generated_image_url' in st.session_state:
94
  st.image(st.session_state['generated_image_url'], caption="Generated Image")
95
+
96
+ # Fetch the image to download
97
  response = requests.get(st.session_state['generated_image_url'])
98
  if response.status_code == 200:
99
+ # Create a download button and provide the image content as a byte stream
100
  st.download_button(
101
  label="Download Image",
102
+ data=response.content,
103
+ file_name="generated_image.jpg",
104
+ mime="image/jpeg"
 
105
  )
106
+
107
+ # Show the following options only if an image has been generated
108
+ if 'generated_image_url' in st.session_state:
109
+
110
+ # Toggle for showing additional details input
111
+ show_details = st.toggle("Add details about the image.", value=False)
112
+
113
+ if show_details:
114
+ # Text input for additional details about the image, shown only if toggle is True
115
+ additional_details = st.text_area(
116
+ "The details could include specific information that is important to include in the alt text or reflect why the image is being used:",
117
+ disabled=not show_details
118
+ )
119
+
120
+ # Toggle for modifying the prompt for complex images
121
+ complex_image = st.toggle("Is this a complex image? ", value=False)
122
+
123
+ if complex_image:
124
+ # Text input for additional details about the image, shown only if toggle is True
125
+ complex_image_details = st.caption(
126
+ "By clicking this toggle, it will inform MTSS.ai to create a description that exceeds the 125 character limit. "
127
+ "Add the description in a placeholder behind the image and 'Description in the content placeholder' in the alt text box. "
128
+ )
129
+
130
+ # Analyze Image button
131
+ # Button to trigger the analysis
132
+ analyze_button = st.button("Analyze the Image", type="secondary")
133
+
134
+ # Optimized prompt for complex images
135
+ complex_image_prompt_text = (
136
+ "As an expert in image accessibility and alternative text, thoroughly describe the image provided. "
137
+ "Provide a brief description using not more than 500 characters that convey the essential information conveyed by the image in eight or fewer clear and concise sentences. "
138
+ "Skip phrases like 'image of' or 'picture of.' "
139
+ "Your description should form a clear, well-structured, and factual paragraph that avoids bullet points, focusing on creating a seamless narrative."
140
+ )
141
+
142
+ # Check if an image has been uploaded, if the API key is available, and if the button has been pressed
143
+ if analyze_button:
144
+
145
+ with st.spinner("Analyzing the image ..."):
146
+
147
+ # Determine which prompt to use based on the complexity of the image
148
+ if complex_image:
149
+ prompt_text = complex_image_prompt_text
150
+ else:
151
+ prompt_text = (
152
+ "As an expert in image accessibility and alternative text, succinctly describe the image provided in less than 125 characters. "
153
+ "Provide a brief description using not more than 125 characters that convey the essential information conveyed by the image in three or fewer clear and concise sentences for use as alt text. "
154
+ "Skip phrases like 'image of' or 'picture of.' "
155
+ "Your description should form a clear, well-structured, and factual paragraph that avoids bullet points and newlines, focusing on creating a seamless narrative that serves as effective alternative text for accessibility purposes."
156
+ )
157
+
158
+ if show_details and additional_details:
159
+ prompt_text += (
160
+ f"\n\nAdditional Context Provided by the User:\n{additional_details}"
161
+ )
162
+
163
+ # Create the payload for the completion request
164
+ messages = [
165
+ {
166
+ "role": "user",
167
+ "content": [
168
+ {"type": "text", "text": prompt_text},
169
+ {
170
+ "type": "image_url",
171
+ "image_url": st.session_state['generated_image_url'],
172
+ },
173
+ ],
174
+ }
175
+ ]
176
+
177
+ # Make the request to the OpenAI API
178
+ try:
179
+ # Without Stream
180
+
181
+ # response = openai.chat.completions.create(
182
+ # model="gpt-4-vision-preview", messages=messages, max_tokens=250, stream=False
183
+ # )
184
+
185
+ # Stream the response
186
+ full_response = ""
187
+ message_placeholder = st.empty()
188
+ for completion in openai.chat.completions.create(
189
+ model="gpt-4-vision-preview", messages=messages,
190
+ max_tokens=1200, stream=True
191
+ ):
192
+ # Check if there is content to display
193
+ if completion.choices[0].delta.content is not None:
194
+ full_response += completion.choices[0].delta.content
195
+ message_placeholder.markdown(full_response + "▌")
196
+ # Final update to placeholder after the stream ends
197
+ message_placeholder.markdown(full_response)
198
+
199
+ # # Display the response in a text area
200
+ # st.text_area('Response:', value=full_response, height=250, key="response_text_area")
201
+
202
+ st.success('Powered by MTSS GPT. AI can make mistakes. Consider checking important information.')
203
+ except Exception as e:
204
+ st.error(f"An error occurred: {e}")
205
+ # else:
206
+ # # Warnings for user action required
207
+ # if not st.session_state['generated_image_url'] and analyze_button:
208
+ # st.warning("Please upload an image.")
209
+
210
+
211