Ava2lon commited on
Commit
8f0ced3
·
verified ·
1 Parent(s): 64f1013

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -195
app.py DELETED
@@ -1,195 +0,0 @@
1
- import json
2
- import os
3
- import time
4
- import uuid
5
- import tempfile
6
- from PIL import Image, ImageDraw, ImageFont
7
- import gradio as gr
8
- import base64
9
- import mimetypes
10
-
11
- from google import genai
12
- from google.genai import types
13
-
14
- def save_binary_file(file_name, data):
15
- with open(file_name, "wb") as f:
16
- f.write(data)
17
-
18
- def generate(text, file_name, api_key, model="gemini-2.0-flash-exp"):
19
- # Initialize client using provided api_key (or fallback to env variable)
20
- client = genai.Client(api_key=(api_key.strip() if api_key and api_key.strip() != ""
21
- else os.environ.get("GEMINI_API_KEY")))
22
-
23
- files = [ client.files.upload(file=file_name) ]
24
-
25
- contents = [
26
- types.Content(
27
- role="user",
28
- parts=[
29
- types.Part.from_uri(
30
- file_uri=files[0].uri,
31
- mime_type=files[0].mime_type,
32
- ),
33
- types.Part.from_text(text=text),
34
- ],
35
- ),
36
- ]
37
- generate_content_config = types.GenerateContentConfig(
38
- temperature=1,
39
- top_p=0.95,
40
- top_k=40,
41
- max_output_tokens=8192,
42
- response_modalities=["image", "text"],
43
- response_mime_type="text/plain",
44
- )
45
-
46
- text_response = ""
47
- image_path = None
48
- # Create a temporary file to potentially store image data.
49
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
50
- temp_path = tmp.name
51
- for chunk in client.models.generate_content_stream(
52
- model=model,
53
- contents=contents,
54
- config=generate_content_config,
55
- ):
56
- if not chunk.candidates or not chunk.candidates[0].content or not chunk.candidates[0].content.parts:
57
- continue
58
- candidate = chunk.candidates[0].content.parts[0]
59
- # Check for inline image data
60
- if candidate.inline_data:
61
- save_binary_file(temp_path, candidate.inline_data.data)
62
- print(f"File of mime type {candidate.inline_data.mime_type} saved to: {temp_path} and prompt input: {text}")
63
- image_path = temp_path
64
- # If an image is found, we assume that is the desired output.
65
- break
66
- else:
67
- # Accumulate text response if no inline_data is present.
68
- text_response += chunk.text + "\n"
69
-
70
- del files
71
- return image_path, text_response
72
-
73
- def process_image_and_prompt(composite_pil, prompt, gemini_api_key):
74
- try:
75
- # Save the composite image to a temporary file.
76
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
77
- composite_path = tmp.name
78
- composite_pil.save(composite_path)
79
-
80
- file_name = composite_path
81
- input_text = prompt
82
- model = "gemini-2.0-flash-exp"
83
-
84
- image_path, text_response = generate(text=input_text, file_name=file_name, api_key=gemini_api_key, model=model)
85
-
86
- if image_path:
87
- # Load and convert the image if needed.
88
- result_img = Image.open(image_path)
89
- if result_img.mode == "RGBA":
90
- result_img = result_img.convert("RGB")
91
- return [result_img], "" # Return image in gallery and empty text output.
92
- else:
93
- # Return no image and the text response.
94
- return None, text_response
95
- except Exception as e:
96
- raise gr.Error(f"Error Getting {e}", duration=5)
97
-
98
-
99
- # Build a Blocks-based interface with a custom HTML header and CSS
100
- with gr.Blocks(css_paths="style.css",) as demo:
101
- # Custom HTML header with proper class for styling
102
- gr.HTML(
103
- """
104
- <div class="header-container">
105
- <div>
106
- <img src="https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png" alt="Gemini logo">
107
- </div>
108
- <div>
109
- <h1>Gemini for Image Editing</h1>
110
- <p>Powered by <a href="https://gradio.app/">Gradio</a>⚡️|
111
- <a href="https://huggingface.co/spaces/ameerazam08/Gemini-Image-Edit?duplicate=true">Duplicate</a> this Repo |
112
- <a href="https://aistudio.google.com/apikey">Get an API Key</a> |
113
- Follow me on Twitter: <a href="https://x.com/Ameerazam18">Ameerazam18</a></p>
114
- </div>
115
- </div>
116
- """
117
- )
118
-
119
- with gr.Accordion("⚠️ API Configuration ⚠️", open=False, elem_classes="config-accordion"):
120
- gr.Markdown("""
121
- - **Issue:** ❗ Sometimes the model returns text instead of an image.
122
- ### 🔧 Steps to Address:
123
- 1. **🛠️ Duplicate the Repository**
124
- - Create a separate copy for modifications.
125
- 2. **🔑 Use Your Own Gemini API Key**
126
- - You **must** configure your own Gemini key for generation!
127
- """)
128
-
129
- with gr.Accordion("📌 Usage Instructions", open=False, elem_classes="instructions-accordion"):
130
- gr.Markdown("""
131
- ### 📌 Usage
132
- - Upload an image and enter a prompt to generate outputs.
133
- - If text is returned instead of an image, it will appear in the text output.
134
- - Upload Only PNG Image
135
- - ❌ **Do not use NSFW images!**
136
- """)
137
-
138
- with gr.Row(elem_classes="main-content"):
139
- with gr.Column(elem_classes="input-column"):
140
- image_input = gr.Image(
141
- type="pil",
142
- label="Upload Image",
143
- image_mode="RGBA",
144
- elem_id="image-input",
145
- elem_classes="upload-box"
146
- )
147
- gemini_api_key = gr.Textbox(
148
- lines=1,
149
- placeholder="Enter Gemini API Key (optional)",
150
- label="Gemini API Key (optional)",
151
- elem_classes="api-key-input"
152
- )
153
- prompt_input = gr.Textbox(
154
- lines=2,
155
- placeholder="Enter prompt here...",
156
- label="Prompt",
157
- elem_classes="prompt-input"
158
- )
159
- submit_btn = gr.Button("Generate", elem_classes="generate-btn")
160
-
161
- with gr.Column(elem_classes="output-column"):
162
- output_gallery = gr.Gallery(label="Generated Outputs", elem_classes="output-gallery")
163
- output_text = gr.Textbox(
164
- label="Gemini Output",
165
- placeholder="Text response will appear here if no image is generated.",
166
- elem_classes="output-text"
167
- )
168
-
169
- # Set up the interaction with two outputs.
170
- submit_btn.click(
171
- fn=process_image_and_prompt,
172
- inputs=[image_input, prompt_input, gemini_api_key],
173
- outputs=[output_gallery, output_text],
174
- )
175
-
176
- gr.Markdown("## Try these examples", elem_classes="gr-examples-header")
177
-
178
- examples = [
179
- ["data/1.webp", 'change text to "AMEER"', ""],
180
- ["data/2.webp", "remove the spoon from hand only", ""],
181
- ["data/3.webp", 'change text to "Make it "', ""],
182
- ["data/1.jpg", "add joker style only on face", ""],
183
- ["data/1777043.jpg", "add joker style only on face", ""],
184
- ["data/2807615.jpg", "add lipstick on lip only", ""],
185
- ["data/76860.jpg", "add lipstick on lip only", ""],
186
- ["data/2807615.jpg", "make it happy looking face only", ""],
187
- ]
188
-
189
- gr.Examples(
190
- examples=examples,
191
- inputs=[image_input, prompt_input,],
192
- elem_id="examples-grid"
193
- )
194
-
195
- demo.queue(max_size=50).launch(mcp_server=True)