leicam commited on
Commit
d133185
·
verified ·
1 Parent(s): 9ce4fe2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +309 -0
app.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import google.generativeai as genai
3
+ import os
4
+ import base64
5
+ from PIL import Image
6
+ import io
7
+
8
+ # Configurar API do Google (Nano Banana Pro = Gemini 3 Pro Image)
9
+ GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
10
+
11
+ if GOOGLE_API_KEY:
12
+ genai.configure(api_key=GOOGLE_API_KEY)
13
+
14
+ def generate_image(prompt, negative_prompt, aspect_ratio):
15
+ """
16
+ Gera imagem usando Nano Banana Pro (Gemini 3 Pro Image)
17
+ """
18
+ if not GOOGLE_API_KEY:
19
+ return None, "❌ API Key do Google não configurada. Configure GOOGLE_API_KEY no Hugging Face Spaces."
20
+
21
+ try:
22
+ # Usar o modelo Nano Banana Pro (Gemini 3 Pro Image)
23
+ model = genai.GenerativeModel('gemini-3-pro-image-preview')
24
+
25
+ # Construir prompt completo
26
+ full_prompt = prompt
27
+
28
+ if negative_prompt:
29
+ full_prompt += f"\n\nEvitar: {negative_prompt}"
30
+
31
+ # Adicionar instruções de qualidade
32
+ full_prompt += "\n\nGerar imagem fotorrealista, ultra detalhada, 8k, professional photography."
33
+
34
+ # Configuração de geração
35
+ generation_config = {
36
+ "temperature": 0.4,
37
+ "top_p": 0.95,
38
+ "top_k": 40,
39
+ }
40
+
41
+ # Gerar imagem
42
+ response = model.generate_content(
43
+ [full_prompt],
44
+ generation_config=generation_config
45
+ )
46
+
47
+ # Processar resposta
48
+ if response.parts:
49
+ for part in response.parts:
50
+ if hasattr(part, 'inline_data') and part.inline_data:
51
+ # Decodificar imagem base64
52
+ image_data = base64.b64decode(part.inline_data.data)
53
+ image = Image.open(io.BytesIO(image_data))
54
+
55
+ success_msg = f"""✅ Imagem gerada com sucesso usando Nano Banana Pro!
56
+
57
+ **Configurações:**
58
+ - Modelo: Gemini 3 Pro Image (Nano Banana Pro)
59
+ - Aspect Ratio: {aspect_ratio}
60
+ - Qualidade: Ultra-realista
61
+
62
+ **Prompt usado:** {prompt[:150]}..."""
63
+
64
+ return image, success_msg
65
+
66
+ return None, "❌ Não foi possível gerar a imagem. Tente novamente."
67
+
68
+ except Exception as e:
69
+ error_msg = str(e)
70
+ if "API_KEY" in error_msg.upper() or "quota" in error_msg.lower():
71
+ return None, f"❌ Erro de API Key ou quota excedida: {error_msg}"
72
+ elif "billing" in error_msg.lower():
73
+ return None, "❌ Você precisa ativar o faturamento no Google Cloud Console para usar Nano Banana Pro."
74
+ return None, f"❌ Erro ao gerar imagem: {error_msg}"
75
+
76
+ # Exemplos de prompts
77
+ examples = [
78
+ [
79
+ "A stunning portrait of a woman with flowing red hair, golden hour lighting, professional photography, bokeh background, 8k ultra detailed, cinematic composition, soft focus, natural skin texture",
80
+ "blurry, low quality, distorted, ugly, deformed, bad anatomy, worst quality",
81
+ "1:1 (Instagram)"
82
+ ],
83
+ [
84
+ "Futuristic cyberpunk cityscape at night, neon lights reflecting on wet streets, flying cars, blade runner style, hyper realistic, 8k resolution, dramatic lighting, rain effects, cinematic atmosphere",
85
+ "blurry, cartoonish, low detail, oversaturated, daytime",
86
+ "16:9 (Paisagem)"
87
+ ],
88
+ [
89
+ "Ancient mystical forest with rays of god light piercing through tall trees, moss-covered stones, ethereal atmosphere, photorealistic, highly detailed, nature photography, magical ambiance, fog",
90
+ "modern buildings, people, cars, low quality, artificial, urban",
91
+ "4:5 (Retrato)"
92
+ ],
93
+ [
94
+ "Modern luxury living room interior, minimalist Scandinavian design, floor-to-ceiling windows, natural lighting, architectural photography, 8k, ultra realistic, clean lines, warm tones",
95
+ "cluttered, dark, low quality, messy, old furniture, baroque style",
96
+ "16:9 (Paisagem)"
97
+ ]
98
+ ]
99
+
100
+ # Criar interface Gradio
101
+ with gr.Blocks(
102
+ theme=gr.themes.Soft(
103
+ primary_hue="green",
104
+ secondary_hue="gray",
105
+ ),
106
+ css="""
107
+ .gradio-container {
108
+ font-family: 'Inter', 'Manrope', sans-serif;
109
+ }
110
+ .title {
111
+ text-align: center;
112
+ font-size: 2.5em;
113
+ font-weight: 800;
114
+ margin-bottom: 0.3em;
115
+ background: linear-gradient(135deg, #39FF14 0%, #00CC11 100%);
116
+ -webkit-background-clip: text;
117
+ -webkit-text-fill-color: transparent;
118
+ letter-spacing: -0.02em;
119
+ }
120
+ .subtitle {
121
+ text-align: center;
122
+ font-size: 1.1em;
123
+ color: #6b7280;
124
+ margin-bottom: 2em;
125
+ }
126
+ .dot-indicator {
127
+ display: inline-block;
128
+ width: 8px;
129
+ height: 8px;
130
+ background: #39FF14;
131
+ border-radius: 50%;
132
+ margin-right: 6px;
133
+ animation: pulse 2s ease-in-out infinite;
134
+ }
135
+ @keyframes pulse {
136
+ 0%, 100% { opacity: 1; }
137
+ 50% { opacity: 0.5; }
138
+ }
139
+ """
140
+ ) as demo:
141
+
142
+ # Header
143
+ gr.HTML("""
144
+ <div style="text-align: center; margin-bottom: 30px;">
145
+ <h1 class="title">🎨 Gerador Ultra-Realista de Imagens</h1>
146
+ <p class="subtitle">
147
+ <span class="dot-indicator"></span>
148
+ Powered by Nano Banana Pro (Gemini 3 Pro Image) · Leicam Tech
149
+ </p>
150
+ </div>
151
+ """)
152
+
153
+ with gr.Row():
154
+ with gr.Column(scale=1):
155
+ gr.Markdown("## ⚙️ Configurações")
156
+
157
+ prompt = gr.Textbox(
158
+ label="📝 Descrição da Imagem (Prompt)",
159
+ placeholder="Ex: A beautiful sunset over mountains, photorealistic, 8k resolution, professional photography, golden hour lighting...",
160
+ lines=5,
161
+ info="Seja o mais detalhado possível. Descreva iluminação, cores, texturas, estilo."
162
+ )
163
+
164
+ negative_prompt = gr.Textbox(
165
+ label="🚫 Prompt Negativo (o que evitar)",
166
+ placeholder="Ex: blurry, low quality, distorted, ugly...",
167
+ value="blurry, low quality, distorted, ugly, deformed, bad anatomy, worst quality, lowres",
168
+ lines=3,
169
+ info="Liste elementos que você NÃO quer ver na imagem"
170
+ )
171
+
172
+ aspect_ratio = gr.Dropdown(
173
+ label="📐 Formato da Imagem",
174
+ choices=[
175
+ "1:1 (Instagram)",
176
+ "4:5 (Retrato)",
177
+ "16:9 (Paisagem)",
178
+ "9:16 (Stories)"
179
+ ],
180
+ value="1:1 (Instagram)",
181
+ info="Escolha o formato ideal para sua necessidade"
182
+ )
183
+
184
+ generate_btn = gr.Button(
185
+ "✨ Gerar Imagem Ultra-Realista",
186
+ variant="primary",
187
+ size="lg"
188
+ )
189
+
190
+ gr.Markdown("---")
191
+ gr.Markdown("### 💡 Dicas para Prompts Perfeitos:")
192
+ gr.Markdown("""
193
+ **Nano Banana Pro é especializado em:**
194
+ - 🎯 **Texto em imagens:** Logos, pôsteres, diagramas com texto legível
195
+ - 🌍 **Conhecimento do mundo:** Usa Google Search para precisão factual
196
+ - 🎨 **Composição avançada:** Até 14 imagens de referência
197
+ - 📐 **Alta resolução:** Até 4K nativo
198
+
199
+ **Estrutura ideal do prompt:**
200
+ 1. Descrição do assunto principal
201
+ 2. Estilo de fotografia/arte
202
+ 3. Iluminação e atmosfera
203
+ 4. Qualidade técnica (8k, ultra detailed)
204
+ 5. Detalhes específicos
205
+
206
+ **Exemplo:**
207
+ "Professional portrait, golden hour lighting, bokeh background, 8k, cinematic composition"
208
+ """)
209
+
210
+ with gr.Column(scale=1):
211
+ gr.Markdown("## 🖼️ Resultado")
212
+
213
+ output_image = gr.Image(
214
+ label="Imagem Gerada com Nano Banana Pro",
215
+ type="pil",
216
+ height=600,
217
+ show_label=True
218
+ )
219
+
220
+ output_text = gr.Textbox(
221
+ label="Status da Geração",
222
+ lines=5,
223
+ interactive=False,
224
+ show_label=True
225
+ )
226
+
227
+ gr.Markdown("""
228
+ <div style="background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; padding: 12px; margin-top: 12px;">
229
+ <strong>🚀 Nano Banana Pro Features:</strong><br>
230
+ • Texto legível em múltiplas línguas<br>
231
+ • Search grounding para precisão factual<br>
232
+ • Resolução até 4K<br>
233
+ • Watermark SynthID incluído<br>
234
+ • Pensamento iterativo para melhor composição
235
+ </div>
236
+ """)
237
+
238
+ # Exemplos
239
+ gr.Markdown("---")
240
+ gr.Markdown("## 📚 Exemplos de Prompts Profissionais")
241
+ gr.Markdown("*Clique em um exemplo para carregar as configurações*")
242
+
243
+ gr.Examples(
244
+ examples=examples,
245
+ inputs=[prompt, negative_prompt, aspect_ratio],
246
+ label="Exemplos testados e aprovados"
247
+ )
248
+
249
+ # Casos de uso
250
+ gr.Markdown("---")
251
+ gr.Markdown("## 🎯 Casos de Uso do Nano Banana Pro")
252
+
253
+ with gr.Row():
254
+ with gr.Column():
255
+ gr.Markdown("""
256
+ ### 🎨 Design & Marketing
257
+ - Pôsteres com texto legível
258
+ - Campanhas multilíngues
259
+ - Mockups de produtos
260
+ - Identidade visual consistente
261
+ """)
262
+
263
+ with gr.Column():
264
+ gr.Markdown("""
265
+ ### 📊 Informação & Educação
266
+ - Infográficos precisos
267
+ - Diagramas técnicos
268
+ - Material didático
269
+ - Visualização de dados
270
+ """)
271
+
272
+ with gr.Column():
273
+ gr.Markdown("""
274
+ ### 🎬 Criativo & Arte
275
+ - Storyboards
276
+ - Concept art
277
+ - Character design
278
+ - Edição de imagens
279
+ """)
280
+
281
+ # Footer
282
+ gr.HTML("""
283
+ <div style="text-align: center; margin-top: 50px; padding: 25px; border-top: 1px solid #e5e7eb;">
284
+ <div style="display: inline-flex; align-items: center; gap: 8px; margin-bottom: 12px;">
285
+ <span style="width: 12px; height: 12px; background: #39FF14; border-radius: 50%;"></span>
286
+ <strong style="font-weight: 800;">Leicam · Tech</strong>
287
+ </div>
288
+ <p style="color: #6b7280; font-size: 14px; margin: 8px 0;">
289
+ Ferramentas práticas para criar mais e melhor
290
+ </p>
291
+ <p style="color: #9ca3af; font-size: 12px; margin-top: 8px;">
292
+ Powered by Nano Banana Pro (Gemini 3 Pro Image)
293
+ </p>
294
+ <p style="color: #9ca3af; font-size: 11px; margin-top: 12px;">
295
+ © 2024 Leicam. Todos os direitos reservados.
296
+ </p>
297
+ </div>
298
+ """)
299
+
300
+ # Eventos
301
+ generate_btn.click(
302
+ fn=generate_image,
303
+ inputs=[prompt, negative_prompt, aspect_ratio],
304
+ outputs=[output_image, output_text]
305
+ )
306
+
307
+ # Lançar app
308
+ if __name__ == "__main__":
309
+ demo.launch()