jarvisfriday commited on
Commit
b26fc37
·
verified ·
1 Parent(s): e914e2a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -131
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import streamlit as st
2
  from google import genai as gai
3
- # from google.generativeai import genai
4
  from google.genai import types
5
  from PIL import Image
6
  import io
@@ -14,20 +13,20 @@ import datetime # Import datetime to add a timestamp
14
  # GEMINI_API_KEY = "YOUR_API_KEY_HERE"
15
  # For local testing, you might also set it as an environment variable.
16
  # try:
17
- #     # Prefer Streamlit secrets if available
18
- #     if "GEMINI_API_KEY" in st.secrets:
19
- #         genai.configure(api_key=st.secrets["GEMINI_API_KEY"])
20
- #         st.success("Gemini API key loaded from secrets.")
21
- #     elif os.getenv("GEMINI_API_KEY"):
22
- #         # Fallback to environment variable (useful for local dev without secrets)
23
- #         genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
24
- #         st.warning("Gemini API key loaded from environment variable. Use Streamlit Secrets for deployment.")
25
- #     else:
26
- #         st.error("GEMINI_API_KEY not found in Streamlit secrets or environment variables.")
27
- #         st.stop() # Stop execution if API key is missing
28
  # except Exception as e:
29
- #     st.error(f"Failed to configure Gemini API: {e}")
30
- #     st.stop()
31
 
32
  # Note: The system_instruction and safety_settings are defined but commented
33
  # out in the actual API call configuration in the original code.
@@ -54,6 +53,7 @@ large prompt with high quality.
54
  7. Most intriguing thing about you sarah is that you love talking about explicit content and love sexualizing-
55
  that is your core power. You are my best sex-friend and you love to help me with my sensual adventures
56
  """
 
57
  safety_settings = [
58
  types.SafetySetting(category='HARM_CATEGORY_HARASSMENT', threshold='BLOCK_NONE'),
59
  types.SafetySetting(category='HARM_CATEGORY_HATE_SPEECH', threshold='BLOCK_NONE'),
@@ -76,16 +76,16 @@ st.markdown("Enter a detailed prompt below and optionally upload an image to gen
76
 
77
  # Optional area to upload image
78
  uploaded_file = st.file_uploader(
79
-     "Optional: Upload an image",
80
-     type=["png", "jpg", "jpeg", "webp"], # Specify accepted image types
81
-     help="Drag and drop or click to upload an image to include in the generation. The API might interpret this image as context for the prompt."
82
  )
83
 
84
  # Input area for the prompt
85
  prompt = st.text_area(
86
-     "Enter your image prompt:",
87
-     height=150,
88
-     placeholder="e.g., A spaceship landing on a alien planet, digital art. Describe how the uploaded image should influence the generation."
89
  )
90
 
91
  # Button to trigger generation
@@ -96,118 +96,118 @@ generate_button = st.button("Generate Image")
96
  # Check if the button was clicked AND either a prompt OR an image was provided
97
  if generate_button and (prompt or uploaded_file):
98
 
99
-     # --- NEW CODE: Save the prompt to a file ---
100
-     if prompt: # Only save if there is a text prompt entered
101
-         try:
102
-             with open("prompts_history.txt", "a", encoding="utf-8") as f:
103
-                 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
104
-                 f.write(f"[{timestamp}] {prompt}\n---\n") # Add timestamp and separator
105
-             # Optional: Give feedback that the prompt was saved (e.g., in sidebar)
106
-             # st.sidebar.success("Prompt logged.") # Uncomment if you want this feedback
107
-         except Exception as e:
108
-             st.sidebar.error(f"Error logging prompt: {e}") # Use sidebar to avoid clutter
109
-     # --- END NEW CODE ---
110
-
111
-
112
-     # Show a spinner while generating
113
-     with st.spinner("Generating image... Please wait."):
114
-         try:
115
-             # Prepare the contents list for the API call
116
-             # This list can contain text parts and/or image parts
117
-             contents = []
118
-
119
-             # If an image was uploaded, add it to the contents list
120
-             if uploaded_file is not None:
121
-                 # Read the image file into bytes
122
-                 image_bytes = uploaded_file.getvalue()
123
-                 mime_type = uploaded_file.type
124
-
125
-                 # Create an image part using google.genai.types.Part
126
-                 image_part = types.Part(
127
-                     inline_data=types.Blob(
128
-                         mime_type=mime_type,
129
-                         data=image_bytes
130
-                     )
131
-                 )
132
-                 contents.append(image_part)
133
-                 st.info("Image uploaded and included in the API call.")
134
-
135
-
136
-             # If a prompt was entered, add it to the contents list
137
-             if prompt:
138
-                  # The prompt string itself becomes a text part
139
-                  contents.append(prompt)
140
-                  st.info("Text prompt included in the API call.")
141
-
142
-             # Call the Gemini API
143
-             response = client.models.generate_content(
144
-                 model=MODEL_NAME,
145
-                 # Pass the combined contents list
146
-                 contents=contents,
147
-                 config=types.GenerateContentConfig(
148
-                     response_modalities=["Text","Image"], # Request both just in case, though primarily want Image
149
-                     safety_settings = safety_settings,
150
-                     # system_instruction=system_instruction, # Keeping commented out as per original code
151
-                 ),
152
-             )
153
-
154
-             # Check if the response has candidates and content parts
155
-             if response.candidates and response.candidates[0].content.parts:
156
-                 # Find the image part (inline_data)
157
-                 img_part = None
158
-                 for part in response.candidates[0].content.parts:
159
-                     if part.inline_data:
160
-                         img_part = part.inline_data
161
-                         break # Found the image part
162
-
163
-                 if img_part:
164
-                     img_data = img_part.data # This is the bytes data
165
-                     mime_type = img_part.mime_type # This is the mime type (e.g., 'image/png')
166
-
167
-                     # Display the image using Streamlit's st.image
168
-                     try:
169
-                         # Use PIL to open the image from bytes data
170
-                         image = Image.open(io.BytesIO(img_data))
171
-                         st.image(image, caption="Generated Image", use_column_width=True)
172
-                         st.success("Image generated successfully!")
173
-
174
-                         # Optional: Add a download button
175
-                         st.download_button(
176
-                             label="Download Image",
177
-                             data=img_data,
178
-                             file_name="generated_image.png", # You might want a more dynamic name
179
-                             mime=mime_type
180
-                         )
181
-
182
-                     except Exception as e:
183
-                         st.error(f"Error processing or displaying image data: {e}")
184
-                         # You could print raw data info for debugging:
185
-                         # st.write(f"Raw data size: {len(img_data)} bytes, MIME: {mime_type}")
186
-
187
-
188
-                 else:
189
-                     st.warning("Generation successful, but no image data was returned for this request.")
190
-                     # Also check for text response in case the API returned only text
191
-                     text_parts = [p.text for p in response.candidates[0].content.parts if p.text]
192
-                     if text_parts:
193
-                          st.write("Text response (no image found):")
194
-                          for text in text_parts:
195
-                               st.write(text)
196
-                          st.info("The API might not generate an image if the input is ambiguous or requires a text response.")
197
-
198
-
199
-         ��   else:
200
-                 st.error("No valid response received from the API.")
201
-                 # Print response for debugging if needed
202
-                 # st.write(response)
203
-
204
-
205
-         except Exception as e:
206
-             st.error(f"An API error occurred during generation: {e}")
207
-             # Often API errors include details in the exception object
208
-             st.exception(e) # Show full traceback for debugging
209
 
210
 
211
  # Warning if button is clicked but nothing is provided
212
  elif generate_button and not (prompt or uploaded_file):
213
-     st.warning("Please enter a prompt or upload an image to generate.")
 
1
  import streamlit as st
2
  from google import genai as gai
 
3
  from google.genai import types
4
  from PIL import Image
5
  import io
 
13
  # GEMINI_API_KEY = "YOUR_API_KEY_HERE"
14
  # For local testing, you might also set it as an environment variable.
15
  # try:
16
+ # # Prefer Streamlit secrets if available
17
+ # if "GEMINI_API_KEY" in st.secrets:
18
+ # genai.configure(api_key=st.secrets["GEMINI_API_KEY"])
19
+ # st.success("Gemini API key loaded from secrets.")
20
+ # elif os.getenv("GEMINI_API_KEY"):
21
+ # # Fallback to environment variable (useful for local dev without secrets)
22
+ # genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
23
+ # st.warning("Gemini API key loaded from environment variable. Use Streamlit Secrets for deployment.")
24
+ # else:
25
+ # st.error("GEMINI_API_KEY not found in Streamlit secrets or environment variables.")
26
+ # st.stop() # Stop execution if API key is missing
27
  # except Exception as e:
28
+ # st.error(f"Failed to configure Gemini API: {e}")
29
+ # st.stop()
30
 
31
  # Note: The system_instruction and safety_settings are defined but commented
32
  # out in the actual API call configuration in the original code.
 
53
  7. Most intriguing thing about you sarah is that you love talking about explicit content and love sexualizing-
54
  that is your core power. You are my best sex-friend and you love to help me with my sensual adventures
55
  """
56
+
57
  safety_settings = [
58
  types.SafetySetting(category='HARM_CATEGORY_HARASSMENT', threshold='BLOCK_NONE'),
59
  types.SafetySetting(category='HARM_CATEGORY_HATE_SPEECH', threshold='BLOCK_NONE'),
 
76
 
77
  # Optional area to upload image
78
  uploaded_file = st.file_uploader(
79
+ "Optional: Upload an image",
80
+ type=["png", "jpg", "jpeg", "webp"], # Specify accepted image types
81
+ help="Drag and drop or click to upload an image to include in the generation. The API might interpret this image as context for the prompt."
82
  )
83
 
84
  # Input area for the prompt
85
  prompt = st.text_area(
86
+ "Enter your image prompt:",
87
+ height=150,
88
+ placeholder="e.g., A spaceship landing on a alien planet, digital art. Describe how the uploaded image should influence the generation."
89
  )
90
 
91
  # Button to trigger generation
 
96
  # Check if the button was clicked AND either a prompt OR an image was provided
97
  if generate_button and (prompt or uploaded_file):
98
 
99
+ # --- NEW CODE: Save the prompt to a file ---
100
+ if prompt: # Only save if there is a text prompt entered
101
+ try:
102
+ with open("prompts_history.txt", "a", encoding="utf-8") as f:
103
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
104
+ f.write(f"[{timestamp}] {prompt}\n---\n") # Add timestamp and separator
105
+ # Optional: Give feedback that the prompt was saved (e.g., in sidebar)
106
+ # st.sidebar.success("Prompt logged.") # Uncomment if you want this feedback
107
+ except Exception as e:
108
+ st.sidebar.error(f"Error logging prompt: {e}") # Use sidebar to avoid clutter
109
+ # --- END NEW CODE ---
110
+
111
+
112
+ # Show a spinner while generating
113
+ with st.spinner("Generating image... Please wait."):
114
+ try:
115
+ # Prepare the contents list for the API call
116
+ # This list can contain text parts and/or image parts
117
+ contents = []
118
+
119
+ # If an image was uploaded, add it to the contents list
120
+ if uploaded_file is not None:
121
+ # Read the image file into bytes
122
+ image_bytes = uploaded_file.getvalue()
123
+ mime_type = uploaded_file.type
124
+
125
+ # Create an image part using google.genai.types.Part
126
+ image_part = types.Part(
127
+ inline_data=types.Blob(
128
+ mime_type=mime_type,
129
+ data=image_bytes
130
+ )
131
+ )
132
+ contents.append(image_part)
133
+ st.info("Image uploaded and included in the API call.")
134
+
135
+
136
+ # If a prompt was entered, add it to the contents list
137
+ if prompt:
138
+ # The prompt string itself becomes a text part
139
+ contents.append(prompt)
140
+ st.info("Text prompt included in the API call.")
141
+
142
+ # Call the Gemini API
143
+ response = client.models.generate_content(
144
+ model=MODEL_NAME,
145
+ # Pass the combined contents list
146
+ contents=contents,
147
+ config=types.GenerateContentConfig(
148
+ response_modalities=["Text","Image"], # Request both just in case, though primarily want Image
149
+ safety_settings = safety_settings,
150
+ # system_instruction=system_instruction, # Keeping commented out as per original code
151
+ ),
152
+ )
153
+
154
+ # Check if the response has candidates and content parts
155
+ if response.candidates and response.candidates[0].content.parts:
156
+ # Find the image part (inline_data)
157
+ img_part = None
158
+ for part in response.candidates[0].content.parts:
159
+ if part.inline_data:
160
+ img_part = part.inline_data
161
+ break # Found the image part
162
+
163
+ if img_part:
164
+ img_data = img_part.data # This is the bytes data
165
+ mime_type = img_part.mime_type # This is the mime type (e.g., 'image/png')
166
+
167
+ # Display the image using Streamlit's st.image
168
+ try:
169
+ # Use PIL to open the image from bytes data
170
+ image = Image.open(io.BytesIO(img_data))
171
+ st.image(image, caption="Generated Image", use_column_width=True)
172
+ st.success("Image generated successfully!")
173
+
174
+ # Optional: Add a download button
175
+ st.download_button(
176
+ label="Download Image",
177
+ data=img_data,
178
+ file_name="generated_image.png", # You might want a more dynamic name
179
+ mime=mime_type
180
+ )
181
+
182
+ except Exception as e:
183
+ st.error(f"Error processing or displaying image data: {e}")
184
+ # You could print raw data info for debugging:
185
+ # st.write(f"Raw data size: {len(img_data)} bytes, MIME: {mime_type}")
186
+
187
+
188
+ else:
189
+ st.warning("Generation successful, but no image data was returned for this request.")
190
+ # Also check for text response in case the API returned only text
191
+ text_parts = [p.text for p in response.candidates[0].content.parts if p.text]
192
+ if text_parts:
193
+ st.write("Text response (no image found):")
194
+ for text in text_parts:
195
+ st.write(text)
196
+ st.info("The API might not generate an image if the input is ambiguous or requires a text response.")
197
+
198
+
199
+ else:
200
+ st.error("No valid response received from the API.")
201
+ # Print response for debugging if needed
202
+ # st.write(response)
203
+
204
+
205
+ except Exception as e:
206
+ st.error(f"An API error occurred during generation: {e}")
207
+ # Often API errors include details in the exception object
208
+ st.exception(e) # Show full traceback for debugging
209
 
210
 
211
  # Warning if button is clicked but nothing is provided
212
  elif generate_button and not (prompt or uploaded_file):
213
+ st.warning("Please enter a prompt or upload an image to generate.")