Hamed744 commited on
Commit
3a247e4
·
verified ·
1 Parent(s): e570148

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -25
app.py CHANGED
@@ -24,7 +24,7 @@ def translate_prompt_to_english(text, api_key, model="gemini-2.0-flash-exp"):
24
 
25
  client = genai.Client(api_key=api_key.strip())
26
 
27
- pre_prompt = "Translate this to English accurately:"
28
  full_text = pre_prompt + "\n" + text
29
 
30
  contents = [
@@ -59,7 +59,8 @@ def generate_with_api(api_key, text, file_name, model="gemini-2.0-flash-exp"):
59
  client = genai.Client(api_key=api_key.strip())
60
  files = [client.files.upload(file=file_name)]
61
 
62
- full_text = "Apply this edit to the image: " + text
 
63
 
64
  contents = [
65
  types.Content(
@@ -78,9 +79,11 @@ def generate_with_api(api_key, text, file_name, model="gemini-2.0-flash-exp"):
78
  top_p=0.95,
79
  top_k=40,
80
  max_output_tokens=8192,
81
- response_modalities=["image"],
 
82
  )
83
 
 
84
  image_path = None
85
  with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
86
  temp_path = tmp.name
@@ -96,9 +99,11 @@ def generate_with_api(api_key, text, file_name, model="gemini-2.0-flash-exp"):
96
  save_binary_file(temp_path, candidate.inline_data.data)
97
  image_path = temp_path
98
  break
 
 
99
 
100
  del files
101
- return image_path, ""
102
 
103
  def process_single_api(api_key, prompt, file_name, model):
104
  if not api_key:
@@ -106,14 +111,14 @@ def process_single_api(api_key, prompt, file_name, model):
106
 
107
  try:
108
  translated_prompt = translate_prompt_to_english(prompt, api_key, model)
109
- image_path, _ = generate_with_api(api_key, translated_prompt, file_name, model)
110
 
111
  if image_path:
112
  result_img = Image.open(image_path)
113
  if result_img.mode == "RGBA":
114
  result_img = result_img.convert("RGB")
115
  return result_img, ""
116
- return None, "No image generated"
117
 
118
  except Exception as e:
119
  return None, f"Error with API {api_key[-4:]}: {str(e)}"
@@ -153,12 +158,12 @@ def process_image_and_prompt(composite_pil, prompt):
153
  os.unlink(composite_path)
154
 
155
  if not result_images:
156
- return None, "\n".join(error_messages)
157
 
158
  return result_images, ""
159
 
160
  except Exception as e:
161
- raise gr.Error(f"خطا در پردازش: {e}")
162
 
163
  css = """
164
  footer { visibility: hidden; }
@@ -168,7 +173,7 @@ display: none !important;
168
  }
169
  """
170
 
171
- with gr.Blocks(css=css) as demo:
172
  gr.HTML(
173
  """
174
  <div class="header-container">
@@ -182,30 +187,48 @@ with gr.Blocks(css=css) as demo:
182
  """
183
  )
184
 
185
- with gr.Accordion("⚠️ راهنمای استفاده", open=False):
 
 
 
 
 
 
 
 
 
186
  gr.Markdown("""
187
- - تصویر خود را آپلود کنید
188
- - دستور ویرایش را وارد کنید
189
- - نتیجه را دریافت نمایید
 
 
190
  """)
191
 
192
- with gr.Row():
193
- with gr.Column():
194
  image_input = gr.Image(
195
  type="pil",
196
  label="تصویر را آپلود کنید",
197
- image_mode="RGBA"
 
 
198
  )
199
  prompt_input = gr.Textbox(
200
  lines=2,
201
- placeholder="دستور ویرایش خود را وارد کنید...",
202
- label="دستور ویرایش"
 
203
  )
204
- submit_btn = gr.Button("اعمال تغییرات")
205
 
206
- with gr.Column():
207
- output_gallery = gr.Gallery(label="نتایج")
208
- output_text = gr.Textbox(label="پیام سیستم")
 
 
 
 
209
 
210
  submit_btn.click(
211
  fn=process_image_and_prompt,
@@ -213,15 +236,23 @@ with gr.Blocks(css=css) as demo:
213
  outputs=[output_gallery, output_text],
214
  )
215
 
 
 
216
  examples = [
217
- ["data/1.webp", 'متن را به "امیر" تغییر بده'],
218
- ["data/2.webp", "قاشق را از دست حذف کن"],
219
- ["data/3.webp", 'متن را به "بساز" تغییر بده'],
 
 
 
 
 
220
  ]
221
 
222
  gr.Examples(
223
  examples=examples,
224
  inputs=[image_input, prompt_input],
 
225
  )
226
 
227
  demo.queue(max_size=50).launch()
 
24
 
25
  client = genai.Client(api_key=api_key.strip())
26
 
27
+ pre_prompt = "Translate this to English:"
28
  full_text = pre_prompt + "\n" + text
29
 
30
  contents = [
 
59
  client = genai.Client(api_key=api_key.strip())
60
  files = [client.files.upload(file=file_name)]
61
 
62
+ pre_prompt = "Apply these changes to the image:"
63
+ full_text = pre_prompt + "\n" + text
64
 
65
  contents = [
66
  types.Content(
 
79
  top_p=0.95,
80
  top_k=40,
81
  max_output_tokens=8192,
82
+ response_modalities=["image", "text"],
83
+ response_mime_type="text/plain",
84
  )
85
 
86
+ text_response = ""
87
  image_path = None
88
  with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
89
  temp_path = tmp.name
 
99
  save_binary_file(temp_path, candidate.inline_data.data)
100
  image_path = temp_path
101
  break
102
+ else:
103
+ text_response += chunk.text + "\n"
104
 
105
  del files
106
+ return image_path, text_response
107
 
108
  def process_single_api(api_key, prompt, file_name, model):
109
  if not api_key:
 
111
 
112
  try:
113
  translated_prompt = translate_prompt_to_english(prompt, api_key, model)
114
+ image_path, text_response = generate_with_api(api_key, translated_prompt, file_name, model)
115
 
116
  if image_path:
117
  result_img = Image.open(image_path)
118
  if result_img.mode == "RGBA":
119
  result_img = result_img.convert("RGB")
120
  return result_img, ""
121
+ return None, text_response if text_response else "No image generated"
122
 
123
  except Exception as e:
124
  return None, f"Error with API {api_key[-4:]}: {str(e)}"
 
158
  os.unlink(composite_path)
159
 
160
  if not result_images:
161
+ return None, "\n".join(error_messages) + "\n\n**توجه**: اگر تصویر تولید نشد، لطفاً دستور خود را واضح‌تر بنویسید یا دوباره امتحان کنید."
162
 
163
  return result_images, ""
164
 
165
  except Exception as e:
166
+ raise gr.Error(f"خطا در پردازش: {e}", duration=5)
167
 
168
  css = """
169
  footer { visibility: hidden; }
 
173
  }
174
  """
175
 
176
+ with gr.Blocks(css_paths="style.css", css=css) as demo:
177
  gr.HTML(
178
  """
179
  <div class="header-container">
 
187
  """
188
  )
189
 
190
+ with gr.Accordion("⚠️ راهنمای استفاده", open=False, elem_classes="config-accordion"):
191
+ gr.Markdown("""
192
+ ### راهنمای استفاده
193
+ - تصویر خود را آپلود کرده و دستور ویرایش را وارد کنید
194
+ - در صورت بروز خطا، پیام مربوطه نمایش داده خواهد شد
195
+ - فقط تصاویر با فرمت PNG آپلود کنید
196
+ - از آپلود تصاویر نامناسب خودداری کنید
197
+ """)
198
+
199
+ with gr.Accordion("📌 دستورالعمل‌های ویرایش", open=False, elem_classes="instructions-accordion"):
200
  gr.Markdown("""
201
+ ### نمونه دستورات ویرایش
202
+ - متن تصویر را به \"متن جدید\" تغییر بده
203
+ - شیء خاصی را از تصویر حذف کن
204
+ - استایل خاصی به بخشی از تصویر اضافه کن
205
+ - تغییرات رنگی روی تصویر اعمال کن
206
  """)
207
 
208
+ with gr.Row(elem_classes="main-content"):
209
+ with gr.Column(elem_classes="input-column"):
210
  image_input = gr.Image(
211
  type="pil",
212
  label="تصویر را آپلود کنید",
213
+ image_mode="RGBA",
214
+ elem_id="image-input",
215
+ elem_classes="upload-box"
216
  )
217
  prompt_input = gr.Textbox(
218
  lines=2,
219
+ placeholder="تصویر چیکار بشه؟ اینجا بنویسید...",
220
+ label="دستور ویرایش",
221
+ elem_classes="prompt-input"
222
  )
223
+ submit_btn = gr.Button("اعمال تغییرات", elem_classes="generate-btn")
224
 
225
+ with gr.Column(elem_classes="output-column"):
226
+ output_gallery = gr.Gallery(label="تصاویر ویرایش شده", elem_classes="output-gallery")
227
+ output_text = gr.Textbox(
228
+ label="پیام سیستم",
229
+ placeholder="در صورت بروز خطا، پیام مربوطه اینجا نمایش داده می‌شود.",
230
+ elem_classes="output-text"
231
+ )
232
 
233
  submit_btn.click(
234
  fn=process_image_and_prompt,
 
236
  outputs=[output_gallery, output_text],
237
  )
238
 
239
+ gr.Markdown("## نمونه‌های آماده", elem_classes="gr-examples-header")
240
+
241
  examples = [
242
+ ["data/1.webp", 'متن را به "امیر" تغییر بده', ""],
243
+ ["data/2.webp", "قاشق را از دست حذف کن", ""],
244
+ ["data/3.webp", 'متن را به "بساز" تغییر بده', ""],
245
+ ["data/1.jpg", "فقط روی صورت استایل جوکر اضافه کن", ""],
246
+ ["data/1777043.jpg", "فقط روی صورت استایل جوکر اضافه کن", ""],
247
+ ["data/2807615.jpg", "فقط روی لب‌ها رژ لب اضافه کن", ""],
248
+ ["data/76860.jpg", "فقط روی لب‌ها رژ لب اضافه کن", ""],
249
+ ["data/2807615.jpg", "فقط صورت را شادتر کن", ""],
250
  ]
251
 
252
  gr.Examples(
253
  examples=examples,
254
  inputs=[image_input, prompt_input],
255
+ elem_id="examples-grid"
256
  )
257
 
258
  demo.queue(max_size=50).launch()