Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,13 +1,7 @@
|
|
1 |
-
import json
|
2 |
import os
|
3 |
-
import time
|
4 |
-
import uuid
|
5 |
import tempfile
|
6 |
-
from PIL import Image
|
7 |
import gradio as gr
|
8 |
-
import base64
|
9 |
-
import mimetypes
|
10 |
-
|
11 |
from google import genai
|
12 |
from google.genai import types
|
13 |
|
@@ -17,7 +11,6 @@ def save_binary_file(file_name, data):
|
|
17 |
|
18 |
def generate(text, file_name, api_key, model="gemini-2.0-flash-exp"):
|
19 |
client = genai.Client(api_key=(api_key.strip() if api_key and api_key.strip() != "" else os.environ.get("GEMINI_API_KEY")))
|
20 |
-
|
21 |
files = [client.files.upload(file=file_name)]
|
22 |
|
23 |
contents = [
|
@@ -48,7 +41,6 @@ def generate(text, file_name, api_key, model="gemini-2.0-flash-exp"):
|
|
48 |
candidate = chunk.candidates[0].content.parts[0]
|
49 |
if candidate.inline_data:
|
50 |
save_binary_file(temp_path, candidate.inline_data.data)
|
51 |
-
print(f"Arquivo de tipo {candidate.inline_data.mime_type} salvo em: {temp_path} com prompt: {text}")
|
52 |
image_path = temp_path
|
53 |
break
|
54 |
else:
|
@@ -60,11 +52,11 @@ def generate(text, file_name, api_key, model="gemini-2.0-flash-exp"):
|
|
60 |
def process_image_and_prompt(composite_pil, prompt, gemini_api_key):
|
61 |
try:
|
62 |
if not composite_pil:
|
63 |
-
raise gr.Error("
|
64 |
if not prompt:
|
65 |
-
raise gr.Error("
|
66 |
if not gemini_api_key and not os.environ.get("GEMINI_API_KEY"):
|
67 |
-
raise gr.Error("
|
68 |
|
69 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
70 |
composite_path = tmp.name
|
@@ -76,94 +68,62 @@ def process_image_and_prompt(composite_pil, prompt, gemini_api_key):
|
|
76 |
result_img = Image.open(image_path)
|
77 |
if result_img.mode == "RGBA":
|
78 |
result_img = result_img.convert("RGB")
|
79 |
-
return
|
80 |
else:
|
81 |
return None, text_response
|
82 |
except Exception as e:
|
83 |
-
raise gr.Error(f"Erro
|
84 |
|
85 |
-
# Interface
|
86 |
-
with gr.Blocks(css="style.css", title="Gemini
|
87 |
gr.HTML(
|
88 |
"""
|
89 |
-
<div class="header
|
90 |
-
<
|
91 |
-
|
92 |
-
</
|
93 |
-
<div class="header-text">
|
94 |
-
<h1>✨ Gemini para Edição de Imagens ✨</h1>
|
95 |
-
<p>Desenvolvido com <a href="https://gradio.app/">Gradio</a> ⚡️ |
|
96 |
-
<a href="https://huggingface.co/spaces/ameerazam08/Gemini-Image-Edit?duplicate=true">Duplique este Repositório</a> |
|
97 |
-
<a href="https://aistudio.google.com/apikey">Obtenha uma Chave API</a> |
|
98 |
-
Siga-me no LinkedIn: <a href="https://www.linkedin.com/in/dheiver-santos/">dheiver-santos</a></p>
|
99 |
-
</div>
|
100 |
</div>
|
101 |
"""
|
102 |
)
|
103 |
|
104 |
-
with gr.
|
105 |
-
with gr.
|
|
|
|
|
|
|
106 |
with gr.Row():
|
107 |
-
|
108 |
-
|
109 |
-
image_input = gr.Image(type="pil", label="Carregar Imagem (PNG)", image_mode="RGBA", elem_classes="upload-box")
|
110 |
-
gemini_api_key = gr.Textbox(lines=1, placeholder="Insira a Chave API Gemini", label="Chave API Gemini",
|
111 |
-
elem_classes="api-key-input", type="password")
|
112 |
-
prompt_input = gr.Textbox(lines=3, placeholder="Digite seu prompt aqui...", label="Prompt de Edição",
|
113 |
-
elem_classes="prompt-input")
|
114 |
-
with gr.Row():
|
115 |
-
submit_btn = gr.Button("Gerar Imagem", variant="primary", elem_classes="generate-btn")
|
116 |
-
clear_btn = gr.Button("Limpar", variant="secondary")
|
117 |
-
|
118 |
-
with gr.Column(scale=2, min_width=400):
|
119 |
-
gr.Markdown("### 📷 Resultado")
|
120 |
-
output_gallery = gr.Gallery(label="Imagem Gerada", elem_classes="output-gallery", preview=True)
|
121 |
-
output_text = gr.Textbox(label="Saída de Texto (se aplicável)", placeholder="Se nenhuma imagem for gerada, o texto aparecerá aqui.",
|
122 |
-
elem_classes="output-text", interactive=False)
|
123 |
|
124 |
-
with gr.
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
- Insira um prompt em inglês descrevendo a edição desejada.
|
144 |
-
- Clique em "Gerar Imagem" para processar.
|
145 |
-
- Veja o resultado na galeria ou texto abaixo.
|
146 |
-
- **Dica:** Use prompts claros como "add lipstick on lips" ou "remove the spoon".
|
147 |
-
- ❌ **Não use imagens NSFW!**
|
148 |
-
""")
|
149 |
-
|
150 |
-
gr.Markdown("### 🎨 Exemplos Práticos", elem_classes="gr-examples-header")
|
151 |
examples = [
|
152 |
["data/1.webp", "change text to 'AMEER'", ""],
|
153 |
["data/2.webp", "remove the spoon from hand only", ""],
|
154 |
["data/3.webp", "change text to 'Make it'", ""],
|
155 |
-
["data/1.jpg", "add joker style only on face", ""],
|
156 |
-
["data/1777043.jpg", "add joker style only on face", ""],
|
157 |
-
["data/2807615.jpg", "add lipstick on lip only", ""],
|
158 |
-
["data/76860.jpg", "add lipstick on lip only", ""],
|
159 |
-
["data/2807615.jpg", "make it happy looking face only", ""],
|
160 |
]
|
161 |
-
gr.Examples(examples=examples, inputs=[image_input, prompt_input, gemini_api_key], outputs=[
|
162 |
-
fn=process_image_and_prompt, cache_examples=False
|
163 |
|
164 |
# Eventos
|
165 |
-
submit_btn.click(fn=process_image_and_prompt, inputs=[image_input, prompt_input, gemini_api_key],
|
166 |
-
|
167 |
-
clear_btn.click(fn=lambda: (None, "", "", None, ""), inputs=[], outputs=[image_input, prompt_input, gemini_api_key, output_gallery, output_text])
|
168 |
|
169 |
demo.queue(max_size=50).launch()
|
|
|
|
|
1 |
import os
|
|
|
|
|
2 |
import tempfile
|
3 |
+
from PIL import Image
|
4 |
import gradio as gr
|
|
|
|
|
|
|
5 |
from google import genai
|
6 |
from google.genai import types
|
7 |
|
|
|
11 |
|
12 |
def generate(text, file_name, api_key, model="gemini-2.0-flash-exp"):
|
13 |
client = genai.Client(api_key=(api_key.strip() if api_key and api_key.strip() != "" else os.environ.get("GEMINI_API_KEY")))
|
|
|
14 |
files = [client.files.upload(file=file_name)]
|
15 |
|
16 |
contents = [
|
|
|
41 |
candidate = chunk.candidates[0].content.parts[0]
|
42 |
if candidate.inline_data:
|
43 |
save_binary_file(temp_path, candidate.inline_data.data)
|
|
|
44 |
image_path = temp_path
|
45 |
break
|
46 |
else:
|
|
|
52 |
def process_image_and_prompt(composite_pil, prompt, gemini_api_key):
|
53 |
try:
|
54 |
if not composite_pil:
|
55 |
+
raise gr.Error("Carregue uma imagem primeiro.", duration=5)
|
56 |
if not prompt:
|
57 |
+
raise gr.Error("Digite um prompt antes de gerar.", duration=5)
|
58 |
if not gemini_api_key and not os.environ.get("GEMINI_API_KEY"):
|
59 |
+
raise gr.Error("Insira uma chave API Gemini ou configure a variável GEMINI_API_KEY.", duration=10)
|
60 |
|
61 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
62 |
composite_path = tmp.name
|
|
|
68 |
result_img = Image.open(image_path)
|
69 |
if result_img.mode == "RGBA":
|
70 |
result_img = result_img.convert("RGB")
|
71 |
+
return result_img, ""
|
72 |
else:
|
73 |
return None, text_response
|
74 |
except Exception as e:
|
75 |
+
raise gr.Error(f"Erro: {e}", duration=5)
|
76 |
|
77 |
+
# Interface Moderna
|
78 |
+
with gr.Blocks(css="style.css", theme=gr.themes.Soft(), title="Gemini Image Editor") as demo:
|
79 |
gr.HTML(
|
80 |
"""
|
81 |
+
<div class="header">
|
82 |
+
<img src="https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png" alt="Logo" class="logo">
|
83 |
+
<h1>Gemini Image Editor</h1>
|
84 |
+
<p class="subtitle">Edite imagens com IA de forma simples e poderosa</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
</div>
|
86 |
"""
|
87 |
)
|
88 |
|
89 |
+
with gr.Row(elem_classes="main-container"):
|
90 |
+
with gr.Column(scale=1, elem_classes="input-section"):
|
91 |
+
image_input = gr.Image(type="pil", label="Carregar Imagem (PNG)", elem_classes="image-upload")
|
92 |
+
prompt_input = gr.Textbox(placeholder="Digite o prompt (ex: 'add a hat')", label="Prompt", elem_classes="prompt-box")
|
93 |
+
gemini_api_key = gr.Textbox(placeholder="Chave API Gemini", label="API Key", type="password", elem_classes="api-key-box")
|
94 |
with gr.Row():
|
95 |
+
submit_btn = gr.Button("Gerar", variant="primary", elem_classes="submit-btn")
|
96 |
+
clear_btn = gr.Button("Limpar", variant="secondary", elem_classes="clear-btn")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
+
with gr.Column(scale=2, elem_classes="output-section"):
|
99 |
+
output_image = gr.Image(label="Resultado", elem_classes="output-image")
|
100 |
+
output_text = gr.Textbox(label="Mensagem", placeholder="Resultados de texto aparecem aqui", interactive=False, elem_classes="output-text")
|
101 |
+
|
102 |
+
with gr.Accordion("ℹ️ Como Usar e Configurar", open=False, elem_classes="info-accordion"):
|
103 |
+
gr.Markdown("""
|
104 |
+
### Como Usar
|
105 |
+
1. Faça upload de uma imagem PNG.
|
106 |
+
2. Digite um prompt em inglês (ex: "remove the background").
|
107 |
+
3. Insira sua chave API Gemini ou configure a variável `GEMINI_API_KEY`.
|
108 |
+
4. Clique em "Gerar" e veja o resultado!
|
109 |
+
|
110 |
+
### Configuração
|
111 |
+
- Obtenha sua chave API em <a href="https://aistudio.google.com/apikey">Google AI Studio</a>.
|
112 |
+
- Duplique este projeto em <a href="https://huggingface.co/spaces/ameerazam08/Gemini-Image-Edit?duplicate=true">Hugging Face</a>.
|
113 |
+
- Contato: <a href="https://www.linkedin.com/in/dheiver-santos/">Dheiver Santos</a>.
|
114 |
+
""")
|
115 |
+
|
116 |
+
gr.Markdown("### Exemplos", elem_classes="examples-header")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
examples = [
|
118 |
["data/1.webp", "change text to 'AMEER'", ""],
|
119 |
["data/2.webp", "remove the spoon from hand only", ""],
|
120 |
["data/3.webp", "change text to 'Make it'", ""],
|
|
|
|
|
|
|
|
|
|
|
121 |
]
|
122 |
+
gr.Examples(examples=examples, inputs=[image_input, prompt_input, gemini_api_key], outputs=[output_image, output_text],
|
123 |
+
fn=process_image_and_prompt, cache_examples=False)
|
124 |
|
125 |
# Eventos
|
126 |
+
submit_btn.click(fn=process_image_and_prompt, inputs=[image_input, prompt_input, gemini_api_key], outputs=[output_image, output_text])
|
127 |
+
clear_btn.click(fn=lambda: (None, "", "", None, ""), inputs=[], outputs=[image_input, prompt_input, gemini_api_key, output_image, output_text])
|
|
|
128 |
|
129 |
demo.queue(max_size=50).launch()
|