Spaces:
Building
Building
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from PIL import Image
|
3 |
+
import google.generativeai as genai
|
4 |
+
import io
|
5 |
+
import os
|
6 |
+
|
7 |
+
# Configure Google Gemini API (replace with your actual API key)
|
8 |
+
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
|
9 |
+
if not GOOGLE_API_KEY:
|
10 |
+
st.error("Please set the GOOGLE_API_KEY environment variable.")
|
11 |
+
st.stop()
|
12 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
13 |
+
|
14 |
+
# Function to generate the modified image
|
15 |
+
def generate_modified_image(uploaded_image, background_description):
|
16 |
+
try:
|
17 |
+
model = genai.GenerativeModel('gemini-pro-vision')
|
18 |
+
|
19 |
+
image_parts = [
|
20 |
+
{"mime_type": uploaded_image.type, "data": uploaded_image.getvalue()}
|
21 |
+
]
|
22 |
+
|
23 |
+
prompt_parts = [
|
24 |
+
"You are an AI that can modify the background of an image based on a text description.",
|
25 |
+
"Here is the image:",
|
26 |
+
image_parts,
|
27 |
+
f"Modify the background of this image to: '{background_description}'. Be creative and make the new background look realistic and integrated with the foreground.",
|
28 |
+
"Output only the modified image."
|
29 |
+
]
|
30 |
+
|
31 |
+
response = model.generate_content(prompt_parts, stream=False)
|
32 |
+
response.resolve()
|
33 |
+
|
34 |
+
if response and hasattr(response, 'parts') and len(response.parts) > 0:
|
35 |
+
image_bytes = response.parts[-1].data['image/png'] # Assuming the output is PNG
|
36 |
+
return Image.open(io.BytesIO(image_bytes))
|
37 |
+
else:
|
38 |
+
st.error("Failed to generate the modified image.")
|
39 |
+
return None
|
40 |
+
|
41 |
+
except Exception as e:
|
42 |
+
st.error(f"An error occurred: {e}")
|
43 |
+
return None
|
44 |
+
|
45 |
+
# Streamlit web app
|
46 |
+
st.title("Image Background Modifier")
|
47 |
+
|
48 |
+
uploaded_file = st.file_uploader("Upload an image...", type=["png", "jpg", "jpeg"])
|
49 |
+
background_text = st.text_area("Describe the desired background:", "")
|
50 |
+
|
51 |
+
if uploaded_file is not None and background_text:
|
52 |
+
if st.button("Modify Background"):
|
53 |
+
with st.spinner("Generating modified image..."):
|
54 |
+
modified_image = generate_modified_image(uploaded_file, background_text)
|
55 |
+
|
56 |
+
if modified_image:
|
57 |
+
st.image(modified_image, caption="Modified Image", use_column_width=True)
|
58 |
+
else:
|
59 |
+
st.info("Please upload an image and describe the desired background.")
|