Gertie01 commited on
Commit
7aacd35
·
verified ·
1 Parent(s): 15f5e3b

Update app.py from anycoder

Browse files
Files changed (1) hide show
  1. app.py +167 -123
app.py CHANGED
@@ -1,87 +1,127 @@
1
  import gradio as gr
2
  import time
3
  import numpy as np
4
- from PIL import Image, ImageEnhance
5
  import random
6
 
7
- def simulate_gemini_flash_processing(image_editor_data, prompt, mode, strength):
8
  """
9
- Simulates the behavior of a high-speed AI image editing model (like Gemini 2.0 Flash).
10
- Since we cannot connect to the actual paid/private API without a key,
11
- this function simulates the processing latency and applies a visual transformation
12
- to demonstrate the UI flow.
13
  """
14
- if image_editor_data is None:
15
- gr.Warning("Please upload an image first!")
16
- return None
17
 
18
- # Simulate "Flash" speed inference
19
- yield gr.Info("🚀 Gemini 2.0 Flash is processing...")
20
- time.sleep(1.2)
 
 
 
21
 
22
- # Extract the composite image (background + layers + brush strokes)
23
- # In a real app, this would be sent to the API with the prompt
 
 
24
 
25
- if isinstance(image_editor_data, dict) and "composite" in image_editor_data:
26
- img = image_editor_data["composite"]
27
- elif isinstance(image_editor_data, np.ndarray):
28
- img = image_editor_data
29
- else:
30
- # Fallback for different data structures
31
- return image_editor_data
32
-
33
- # Convert to PIL for processing
34
- if isinstance(img, np.ndarray):
35
- pil_img = Image.fromarray(img)
36
- else:
37
- pil_img = img
38
-
39
- # --- SIMULATED AI EFFECTS ---
40
- # We apply deterministic but varied effects based on the prompt hash or mode
41
- # to show that "something happened".
42
 
43
- width, height = pil_img.size
 
44
 
45
- # 1. Simple "Refinement" (Sharpening/Contrast)
46
- if mode == "Refinement":
47
- enhancer = ImageEnhance.Contrast(pil_img)
48
- pil_img = enhancer.enhance(1.1 + (strength * 0.2))
49
- enhancer = ImageEnhance.Sharpness(pil_img)
50
- pil_img = enhancer.enhance(1.1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- # 2. Simple "Style Transfer" (Simulated via color shift/filter)
53
- elif mode == "Style Transfer":
54
- # Split channels and shift them slightly
55
- r, g, b = pil_img.split()
56
- r = r.point(lambda i: i * 1.05)
57
- b = b.point(lambda i: i * 0.95)
58
- pil_img = Image.merge("RGB", (r, g, b))
59
 
60
- # 3. "Inpainting" / "Magic Fill" (Simulated via slight blur/smooth in masked areas logic)
61
- # Since we don't have the mask explicitly separated in the composite easily without complex logic,
62
- # we'll just apply a brightness boost to signify "filling light".
63
- elif mode == "Inpainting":
64
- enhancer = ImageEnhance.Brightness(pil_img)
65
- pil_img = enhancer.enhance(1.05 + (strength * 0.1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- # Convert back to numpy for Gradio
68
- result = np.array(pil_img)
 
 
69
 
70
- gr.Success("✨ Generation Complete!")
71
- return result
72
 
73
  # --- Gradio 6 Application Setup ---
74
 
75
  with gr.Blocks() as demo:
76
 
77
- # Header Section
78
  gr.HTML("""
79
- <div style="text-align: center; margin-bottom: 20px; border-bottom: 1px solid #e5e7eb; padding-bottom: 20px;">
80
- <h1 style="margin: 0; font-size: 2.5rem; background: linear-gradient(90deg, #FF6B6B, #FF8E53); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
81
- Gemini 2.0 Flash Live Image Editor
82
  </h1>
83
- <p style="color: #6b7280; margin-top: 10px;">
84
- Unlimited Online Free Demo • Upload, Sketch, and Edit with AI
85
  </p>
86
  <div style="margin-top: 15px;">
87
  <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank"
@@ -95,113 +135,117 @@ with gr.Blocks() as demo:
95
  """)
96
 
97
  with gr.Row():
98
- # Left Column: Canvas
99
  with gr.Column(scale=3):
 
100
  editor = gr.ImageEditor(
101
- label="Interactive Canvas",
102
  type="numpy",
103
  layers=True,
104
  sources=["upload", "webcam", "clipboard"],
105
- transforms=["crop"],
106
  brush=gr.Brush(
107
- colors=["#FFFFFF", "#000000", "#FF0000", "#00FF00", "#0000FF", "#FFFF00"],
108
- default_size="20",
109
  color_mode="fixed"
110
  ),
111
  eraser=gr.Eraser(default_size="20"),
112
- height=600
113
  )
114
 
115
- # Instructions
116
- gr.Markdown("""
117
- **How to use:**
118
- 1. Upload an image or take a photo.
119
- 2. Use the **Brush** to mark areas you want to change.
120
- 3. Type your instruction in the box on the right.
121
- 4. Click **Generate**.
122
- """)
123
-
124
- # Right Column: Controls
125
- with gr.Column(scale=1):
126
- gr.Markdown("### ⚙️ AI Controls")
127
-
128
- prompt_input = gr.Textbox(
129
- label="Instruction Prompt",
130
- placeholder="e.g. 'Remove the background', 'Make it look like a painting', 'Fix the lighting'",
131
- lines=3,
132
- interactive=True
133
  )
 
 
 
 
134
 
135
- mode = gr.Radio(
136
- choices=["Inpainting", "Refinement", "Style Transfer"],
137
- value="Inpainting",
138
- label="Processing Mode",
139
- info="Select the type of AI modification"
 
140
  )
141
 
142
- strength = gr.Slider(
143
- minimum=0.1,
144
- maximum=1.0,
145
- value=0.7,
146
- step=0.1,
147
- label="Effect Strength"
148
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
  generate_btn = gr.Button(
151
- " Generate with Flash AI",
152
  variant="primary",
153
  size="lg"
154
  )
155
 
156
- # Output Preview
157
- result_image = gr.Image(
158
- label="AI Result",
159
- interactive=False,
160
- show_download_button=True
161
- )
162
-
163
- with gr.Accordion("Advanced Settings", open=False):
164
- seed = gr.Number(label="Seed (Random)", value=-1, precision=0)
165
- steps = gr.Slider(minimum=1, maximum=50, value=25, step=1, label="Inference Steps")
166
 
167
- # Examples Section
168
  gr.Examples(
169
  examples=[
170
- ["https://images.unsplash.com/photo-1542204165-65bf26472b9b?w=600", "Make the sky more dramatic", "Refinement", 0.8],
171
- ["https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=600", "Apply a vintage filter", "Style Transfer", 0.6],
 
172
  ],
173
  inputs=[editor, prompt_input, mode, strength],
174
  cache_examples=False,
175
- label="Try these examples"
176
  )
177
 
178
  # Event Listeners
179
  generate_btn.click(
180
- fn=simulate_gemini_flash_processing,
181
- inputs=[editor, prompt_input, mode, strength],
182
- outputs=[result_image],
183
  api_visibility="public"
184
  )
185
 
186
  # Launch Configuration (Gradio 6 Syntax)
187
  demo.launch(
188
  theme=gr.themes.Soft(
189
- primary_hue="orange", # "Flash" theme color
190
- secondary_hue="blue",
191
- neutral_hue="gray",
192
- font=gr.themes.GoogleFont("Inter"),
193
  text_size="lg",
194
  spacing_size="lg",
195
  radius_size="md"
196
  ).set(
197
- button_primary_background_fill="*primary_500",
198
- button_primary_background_fill_hover="*primary_600",
199
  button_primary_text_color="white",
200
- block_background_fill="*background_fill_secondary",
 
 
201
  ),
202
  footer_links=[
203
  {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
204
  {"label": "Gradio", "url": "https://gradio.app"},
205
- {"label": "View API", "url": "https://gradio.app"} # Placeholder for internal API link
206
  ]
207
  )
 
1
  import gradio as gr
2
  import time
3
  import numpy as np
4
+ from PIL import Image, ImageEnhance, ImageFilter
5
  import random
6
 
7
+ def gemini_chatbot_processor(image_input, chat_history, prompt, mode, strength):
8
  """
9
+ Simulates a GPT-ChatBot experience powered by 'Gemini 2.0 Flash'.
10
+ Handles both Image Generation (Text-to-Image) and Image Editing (Image-to-Image).
 
 
11
  """
 
 
 
12
 
13
+ # 1. Update Chat History with User Message
14
+ if not prompt:
15
+ gr.Warning("Please enter a prompt.")
16
+ return chat_history, image_input
17
+
18
+ chat_history = chat_history + [[prompt, None]]
19
 
20
+ # 2. Simulate AI "Thinking" (Streaming effect simulation)
21
+ time.sleep(0.5)
22
+ chat_history[-1][1] = "🤔 Thinking..."
23
+ yield chat_history, None
24
 
25
+ time.sleep(0.8)
26
+
27
+ # 3. Determine Logic: Generation vs Editing
28
+ result_image = None
29
+ response_text = ""
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # Check if user uploaded an image or wants to generate new
32
+ has_image = image_input is not None
33
 
34
+ if mode == "Generate New Image" or not has_image:
35
+ # --- TEXT-TO-IMAGE GENERATION SIMULATION ---
36
+ chat_history[-1][1] = "✨ Generating new image based on your prompt..."
37
+
38
+ # Simulate processing time
39
+ time.sleep(1.0)
40
+
41
+ # Create a procedural "generated" image based on prompt hash (deterministic random)
42
+ # This simulates the AI creating something unique based on text
43
+ width, height = 512, 512
44
+
45
+ # Create a gradient/pattern based on prompt string
46
+ hash_val = hash(prompt)
47
+ random.seed(hash_val)
48
+
49
+ # Create a base color
50
+ r = random.randint(50, 200)
51
+ g = random.randint(50, 200)
52
+ b = random.randint(50, 200)
53
+
54
+ img = Image.new("RGB", (width, height), (r, g, b))
55
+ pixels = img.load()
56
+
57
+ # Add some "AI" noise/pattern
58
+ for i in range(width):
59
+ for j in range(height):
60
+ noise = random.randint(-20, 20)
61
+ pixels[i, j] = (
62
+ max(0, min(255, r + noise)),
63
+ max(0, min(255, g + noise)),
64
+ max(0, min(255, b + noise))
65
+ )
66
+
67
+ # Add a geometric pattern to look like a "generated" abstract art
68
+ img = img.filter(ImageFilter.SMOOTH)
69
+
70
+ result_image = np.array(img)
71
+ response_text = f"Here is a new image generated for: '{prompt}'"
72
 
73
+ else:
74
+ # --- IMAGE EDITING SIMULATION ---
75
+ chat_history[-1][1] = "🎨 Analyzing image and applying edits..."
76
+ time.sleep(1.2)
 
 
 
77
 
78
+ # Extract image
79
+ if isinstance(image_input, dict) and "composite" in image_input:
80
+ pil_img = Image.fromarray(image_input["composite"])
81
+ elif isinstance(image_input, np.ndarray):
82
+ pil_img = Image.fromarray(image_input)
83
+ else:
84
+ pil_img = image_input
85
+
86
+ # Apply simulated effects
87
+ if mode == "Enhance / Refine":
88
+ factor = 1.0 + (strength * 0.5)
89
+ pil_img = ImageEnhance.Contrast(pil_img).enhance(factor)
90
+ pil_img = ImageEnhance.Sharpness(pil_img).enhance(1.2)
91
+ response_text = "I've enhanced the sharpness and contrast of your image."
92
+
93
+ elif mode == "Change Style":
94
+ # Simulate style transfer with a tint
95
+ r, g, b = pil_img.split()
96
+ r = r.point(lambda i: i * 1.1)
97
+ pil_img = Image.merge("RGB", (r, g, b))
98
+ response_text = "I've applied a stylistic filter to the image."
99
+
100
+ elif mode == "Magic Fill / Inpaint":
101
+ # Simulate inpainting by slightly brightening masked areas (simulated logic)
102
+ pil_img = ImageEnhance.Brightness(pil_img).enhance(1.1)
103
+ response_text = "I've filled in the areas and adjusted the lighting."
104
 
105
+ result_image = np.array(pil_img)
106
+
107
+ # 4. Final Chat Update
108
+ chat_history[-1][1] = response_text
109
 
110
+ gr.Success("✨ Operation Complete!")
111
+ return chat_history, result_image
112
 
113
  # --- Gradio 6 Application Setup ---
114
 
115
  with gr.Blocks() as demo:
116
 
117
+ # Header with Branding
118
  gr.HTML("""
119
+ <div style="text-align: center; margin-bottom: 25px; border-bottom: 1px solid #e5e7eb; padding-bottom: 20px;">
120
+ <h1 style="margin: 0; font-size: 2.5rem; background: linear-gradient(90deg, #4285F4, #34A853, #FBBC05, #EA4335); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
121
+ GPT-ChatBot x Gemini 2.0 Flash
122
  </h1>
123
+ <p style="color: #6b7280; margin-top: 10px; font-size: 1.1rem;">
124
+ Unlimited Online Free Demo • AI Image Generation & Editing
125
  </p>
126
  <div style="margin-top: 15px;">
127
  <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank"
 
135
  """)
136
 
137
  with gr.Row():
138
+ # Left Column: Editor & Canvas
139
  with gr.Column(scale=3):
140
+ gr.Markdown("### 🖼️ Canvas")
141
  editor = gr.ImageEditor(
142
+ label="Upload or Sketch",
143
  type="numpy",
144
  layers=True,
145
  sources=["upload", "webcam", "clipboard"],
146
+ transforms=["crop", "rotate"],
147
  brush=gr.Brush(
148
+ colors=["#FFFFFF", "#000000", "#FF0000", "#00FF00"],
149
+ default_size="15",
150
  color_mode="fixed"
151
  ),
152
  eraser=gr.Eraser(default_size="20"),
153
+ height=550
154
  )
155
 
156
+ # Output Image Display
157
+ output_image = gr.Image(
158
+ label="Result",
159
+ interactive=False,
160
+ show_download_button=True,
161
+ height=400
 
 
 
 
 
 
 
 
 
 
 
 
162
  )
163
+
164
+ # Right Column: Chatbot & Controls
165
+ with gr.Column(scale=2):
166
+ gr.Markdown("### 🤖 AI Chat Interface")
167
 
168
+ # Chatbot History
169
+ chatbot = gr.Chatbot(
170
+ label="Conversation History",
171
+ height=300,
172
+ show_copy_button=True,
173
+ avatar_images=(None, "https://www.gstatic.com/lamda/images/gemini_sparkle_v002_d47a511478e8.svg") # Generic AI avatar
174
  )
175
 
176
+ # Controls
177
+ with gr.Accordion("⚙️ Generation Settings", open=True):
178
+ prompt_input = gr.Textbox(
179
+ label="Your Instruction",
180
+ placeholder="Describe the image you want to generate or how to edit the current one...",
181
+ lines=3,
182
+ autofocus=True
183
+ )
184
+
185
+ mode = gr.Radio(
186
+ choices=["Generate New Image", "Enhance / Refine", "Change Style", "Magic Fill / Inpaint"],
187
+ value="Enhance / Refine",
188
+ label="Operation Mode",
189
+ info="Choose to create new or edit existing"
190
+ )
191
+
192
+ strength = gr.Slider(
193
+ minimum=0.1,
194
+ maximum=1.0,
195
+ value=0.7,
196
+ step=0.1,
197
+ label="Effect Intensity"
198
+ )
199
 
200
  generate_btn = gr.Button(
201
+ "🚀 Send to Gemini Flash",
202
  variant="primary",
203
  size="lg"
204
  )
205
 
206
+ clear_btn = gr.ClearButton([prompt_input, chatbot, output_image], value="🗑️ Clear History")
 
 
 
 
 
 
 
 
 
207
 
208
+ # Examples
209
  gr.Examples(
210
  examples=[
211
+ [None, "A futuristic cyberpunk city at night with neon lights", "Generate New Image", 0.8],
212
+ [None, "A cute oil painting of a cat in a garden", "Generate New Image", 0.7],
213
+ ["https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=600", "Make this look like a vintage photo", "Change Style", 0.9],
214
  ],
215
  inputs=[editor, prompt_input, mode, strength],
216
  cache_examples=False,
217
+ label="Quick Start Examples"
218
  )
219
 
220
  # Event Listeners
221
  generate_btn.click(
222
+ fn=gemini_chatbot_processor,
223
+ inputs=[editor, chatbot, prompt_input, mode, strength],
224
+ outputs=[chatbot, output_image],
225
  api_visibility="public"
226
  )
227
 
228
  # Launch Configuration (Gradio 6 Syntax)
229
  demo.launch(
230
  theme=gr.themes.Soft(
231
+ primary_hue="blue", # Google Blue
232
+ secondary_hue="green", # Google Green
233
+ neutral_hue="slate",
234
+ font=gr.themes.GoogleFont("Google Sans", "Inter"),
235
  text_size="lg",
236
  spacing_size="lg",
237
  radius_size="md"
238
  ).set(
239
+ button_primary_background_fill="*primary_600",
240
+ button_primary_background_fill_hover="*primary_700",
241
  button_primary_text_color="white",
242
+ # Custom Chatbot styling
243
+ chatbot_message_background_fill_user="*primary_100",
244
+ chatbot_message_background_fill_bot="*background_fill_secondary",
245
  ),
246
  footer_links=[
247
  {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
248
  {"label": "Gradio", "url": "https://gradio.app"},
249
+ {"label": "Google DeepMind", "url": "https://deepmind.google"}
250
  ]
251
  )