Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,89 +1,164 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
| 3 |
from PIL import Image
|
| 4 |
-
|
| 5 |
-
import
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
| 11 |
|
| 12 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
try:
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# Text-to-image generation
|
| 34 |
-
contents.append({"parts": [{"text": prompt}]})
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
elif part.text:
|
| 50 |
-
return f"Text response: {part.text}"
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
-
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
css
|
| 59 |
-
.
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
with gr.
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
with gr.Row():
|
| 70 |
-
with gr.Column(
|
| 71 |
-
image_input = gr.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
prompt_input = gr.Textbox(
|
| 73 |
-
|
| 74 |
-
placeholder="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
)
|
| 76 |
-
generate_button = gr.Button("Generate", variant="primary")
|
| 77 |
-
|
| 78 |
-
with gr.Column(scale=1):
|
| 79 |
-
output_image = gr.Image(label="Generated Image", type="pil")
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
fn=process_image,
|
| 84 |
inputs=[image_input, prompt_input],
|
| 85 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
from PIL import Image
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import google.generativeai as genai
|
| 6 |
+
|
| 7 |
+
# Hardcode the Gemini API key
|
| 8 |
+
GEMINI_API_KEY = "AIzaSyDL5Rilo7ptJpUOZdY6wy8PJYUcVcnDADs"
|
| 9 |
|
| 10 |
+
def configure_api_key():
|
| 11 |
+
"""Configure the Gemini API key."""
|
| 12 |
+
if not GEMINI_API_KEY:
|
| 13 |
+
raise gr.Error("Gemini API key is not set.")
|
| 14 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 15 |
|
| 16 |
+
def generate(text, images, model="gemini-2.5-flash"):
|
| 17 |
+
"""Generate content using the Gemini model."""
|
| 18 |
+
configure_api_key()
|
| 19 |
+
|
| 20 |
+
# Convert images to Gemini-compatible format
|
| 21 |
+
contents = []
|
| 22 |
+
for img in images:
|
| 23 |
+
if img.mode == "RGBA":
|
| 24 |
+
img = img.convert("RGB")
|
| 25 |
+
contents.append(img)
|
| 26 |
+
contents.append(text)
|
| 27 |
+
|
| 28 |
try:
|
| 29 |
+
response = genai.GenerativeModel(model).generate_content(contents)
|
| 30 |
+
|
| 31 |
+
text_response = ""
|
| 32 |
+
image_path = None
|
| 33 |
+
|
| 34 |
+
for part in response.candidates[0].content.parts:
|
| 35 |
+
if hasattr(part, 'text') and part.text:
|
| 36 |
+
text_response += part.text + "\n"
|
| 37 |
+
elif hasattr(part, 'inline_data') and part.inline_data:
|
| 38 |
+
# Save generated image to a temporary file
|
| 39 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
| 40 |
+
image_path = tmp.name
|
| 41 |
+
generated_image = Image.open(BytesIO(part.inline_data.data))
|
| 42 |
+
generated_image.save(image_path)
|
| 43 |
+
print(f"Generated image saved to: {image_path} with prompt: {text}")
|
| 44 |
+
|
| 45 |
+
return image_path, text_response
|
| 46 |
+
except Exception as e:
|
| 47 |
+
raise gr.Error(f"Error generating content: {str(e)}")
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
def load_uploaded_images(uploaded_files):
|
| 50 |
+
"""Load and display uploaded images immediately."""
|
| 51 |
+
uploaded_images = []
|
| 52 |
+
if uploaded_files:
|
| 53 |
+
for file in uploaded_files:
|
| 54 |
+
if file.name.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
|
| 55 |
+
img = Image.open(file.name)
|
| 56 |
+
uploaded_images.append(img)
|
| 57 |
+
return uploaded_images
|
| 58 |
|
| 59 |
+
def process_image_and_prompt(uploaded_files, prompt):
|
| 60 |
+
"""Process uploaded images and prompt to generate output."""
|
| 61 |
+
try:
|
| 62 |
+
if not uploaded_files:
|
| 63 |
+
raise gr.Error("Please upload at least one image.")
|
| 64 |
+
if not prompt:
|
| 65 |
+
raise gr.Error("Please provide a prompt.")
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
# Load images
|
| 68 |
+
images = load_uploaded_images(uploaded_files)
|
| 69 |
+
|
| 70 |
+
# Generate content
|
| 71 |
+
image_path, text_response = generate(
|
| 72 |
+
text=prompt,
|
| 73 |
+
images=images
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Prepare outputs
|
| 77 |
+
output_images = [Image.open(image_path)] if image_path else None
|
| 78 |
+
return images, output_images, text_response
|
| 79 |
except Exception as e:
|
| 80 |
+
raise gr.Error(f"Error: {str(e)}")
|
| 81 |
|
| 82 |
+
# Gradio interface
|
| 83 |
+
with gr.Blocks(css="style.css") as demo:
|
| 84 |
+
gr.HTML("""
|
| 85 |
+
<div class="header-container">
|
| 86 |
+
<div>
|
| 87 |
+
<img src="https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png" alt="Gemini logo">
|
| 88 |
+
</div>
|
| 89 |
+
<div>
|
| 90 |
+
<h1>Gemini for Image Editing</h1>
|
| 91 |
+
<p>Powered by <a href="https://gradio.app/">Gradio</a>β‘οΈ |
|
| 92 |
+
<a href="https://huggingface.co/spaces">Duplicate this Space</a> |
|
| 93 |
+
<a href="https://aistudio.google.com/apikey">Learn about Gemini API</a></p>
|
| 94 |
+
</div>
|
| 95 |
+
</div>
|
| 96 |
+
""")
|
| 97 |
+
|
| 98 |
+
with gr.Accordion("β οΈ API Configuration β οΈ", open=False):
|
| 99 |
+
gr.Markdown("""
|
| 100 |
+
- **Note:** The Gemini API is pre-configured for this Space.
|
| 101 |
+
- **Issue:** β Sometimes the model returns text instead of an image.
|
| 102 |
+
### π§ Steps to Address:
|
| 103 |
+
1. **π οΈ Duplicate the Space**
|
| 104 |
+
- Create a copy on Hugging Face Spaces for modifications.
|
| 105 |
+
2. **π API Key Info**
|
| 106 |
+
- The API key is already set up for this demo. For custom deployments, get your own key from Google AI Studio.
|
| 107 |
+
""")
|
| 108 |
|
| 109 |
+
with gr.Accordion("π Usage Instructions", open=False):
|
| 110 |
+
gr.Markdown("""
|
| 111 |
+
### π Usage
|
| 112 |
+
- Upload an image and enter a prompt to generate outputs.
|
| 113 |
+
- If text is returned instead of an image, it will appear in the text output.
|
| 114 |
+
- Supported formats: PNG, JPG, JPEG, WEBP
|
| 115 |
+
- β **Do not use NSFW images!**
|
| 116 |
+
""")
|
| 117 |
|
| 118 |
with gr.Row():
|
| 119 |
+
with gr.Column():
|
| 120 |
+
image_input = gr.File(
|
| 121 |
+
file_types=["image"],
|
| 122 |
+
file_count="multiple",
|
| 123 |
+
label="Upload Images"
|
| 124 |
+
)
|
| 125 |
prompt_input = gr.Textbox(
|
| 126 |
+
lines=2,
|
| 127 |
+
placeholder="Enter prompt here...",
|
| 128 |
+
label="Prompt"
|
| 129 |
+
)
|
| 130 |
+
submit_btn = gr.Button("Generate")
|
| 131 |
+
|
| 132 |
+
with gr.Column():
|
| 133 |
+
uploaded_gallery = gr.Gallery(label="Uploaded Images")
|
| 134 |
+
output_gallery = gr.Gallery(label="Generated Outputs")
|
| 135 |
+
output_text = gr.Textbox(
|
| 136 |
+
label="Gemini Output",
|
| 137 |
+
placeholder="Text response will appear here if no image is generated."
|
| 138 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
+
submit_btn.click(
|
| 141 |
+
fn=process_image_and_prompt,
|
|
|
|
| 142 |
inputs=[image_input, prompt_input],
|
| 143 |
+
outputs=[uploaded_gallery, output_gallery, output_text]
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
image_input.upload(
|
| 147 |
+
fn=load_uploaded_images,
|
| 148 |
+
inputs=[image_input],
|
| 149 |
+
outputs=[uploaded_gallery]
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
gr.Markdown("## Try these examples")
|
| 153 |
+
examples = [
|
| 154 |
+
["data/1.webp", "change text to 'HUGGINGFACE'"],
|
| 155 |
+
["data/2.webp", "remove the spoon from hand only"],
|
| 156 |
+
["data/3.webp", "change text to 'AI POWERED'"],
|
| 157 |
+
["data/1.jpg", "add futuristic style to background"],
|
| 158 |
+
]
|
| 159 |
+
gr.Examples(
|
| 160 |
+
examples=examples,
|
| 161 |
+
inputs=[image_input, prompt_input]
|
| 162 |
)
|
| 163 |
|
| 164 |
+
demo.launch()
|
|
|