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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -66
app.py CHANGED
@@ -24,13 +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 = (
28
- "Translate the following text to English accurately and naturally, as a native English speaker would phrase it. "
29
- "The text could be in Persian (Farsi), Urdu, Pashto, Arabic, Kurdish, or other languages. "
30
- "Keep the translation concise and clear, avoiding unnecessary words or literal translations. "
31
- "For example, if the Persian text is 'متن را به \"امیر\" تغییر بده', translate it to 'Change the text to \"Amir\"'. "
32
- "Do not include any additional explanations or context in the translation."
33
- )
34
  full_text = pre_prompt + "\n" + text
35
 
36
  contents = [
@@ -65,11 +59,7 @@ def generate_with_api(api_key, text, file_name, model="gemini-2.0-flash-exp"):
65
  client = genai.Client(api_key=api_key.strip())
66
  files = [client.files.upload(file=file_name)]
67
 
68
- pre_prompt = (
69
- "The following instruction is in English. Process it carefully. "
70
- "Ensure the new text matches the style, font, and position of the original text as closely as possible. Generate an edited image with the changes applied."
71
- )
72
- full_text = pre_prompt + "\n" + text
73
 
74
  contents = [
75
  types.Content(
@@ -88,11 +78,9 @@ def generate_with_api(api_key, text, file_name, model="gemini-2.0-flash-exp"):
88
  top_p=0.95,
89
  top_k=40,
90
  max_output_tokens=8192,
91
- response_modalities=["image", "text"],
92
- response_mime_type="text/plain",
93
  )
94
 
95
- text_response = ""
96
  image_path = None
97
  with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
98
  temp_path = tmp.name
@@ -108,11 +96,9 @@ def generate_with_api(api_key, text, file_name, model="gemini-2.0-flash-exp"):
108
  save_binary_file(temp_path, candidate.inline_data.data)
109
  image_path = temp_path
110
  break
111
- else:
112
- text_response += chunk.text + "\n"
113
 
114
  del files
115
- return image_path, text_response
116
 
117
  def process_single_api(api_key, prompt, file_name, model):
118
  if not api_key:
@@ -120,14 +106,14 @@ def process_single_api(api_key, prompt, file_name, model):
120
 
121
  try:
122
  translated_prompt = translate_prompt_to_english(prompt, api_key, model)
123
- image_path, text_response = generate_with_api(api_key, translated_prompt, file_name, model)
124
 
125
  if image_path:
126
  result_img = Image.open(image_path)
127
  if result_img.mode == "RGBA":
128
  result_img = result_img.convert("RGB")
129
  return result_img, ""
130
- return None, text_response if text_response else "No image generated"
131
 
132
  except Exception as e:
133
  return None, f"Error with API {api_key[-4:]}: {str(e)}"
@@ -149,7 +135,6 @@ def process_image_and_prompt(composite_pil, prompt):
149
  result_images = []
150
  error_messages = []
151
 
152
- # اجرای همزمان با 4 thread (هر API در یک thread جدا)
153
  with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
154
  futures = {
155
  executor.submit(
@@ -168,12 +153,12 @@ def process_image_and_prompt(composite_pil, prompt):
168
  os.unlink(composite_path)
169
 
170
  if not result_images:
171
- return None, "\n".join(error_messages) + "\n\n**توجه**: اگر تصویر تولید نشد، لطفاً دستور خود را واضح‌تر بنویسید یا دوباره امتحان کنید."
172
 
173
  return result_images, ""
174
 
175
  except Exception as e:
176
- raise gr.Error(f"خطا در پردازش: {e}", duration=5)
177
 
178
  css = """
179
  footer { visibility: hidden; }
@@ -183,7 +168,7 @@ display: none !important;
183
  }
184
  """
185
 
186
- with gr.Blocks(css_paths="style.css", css=css) as demo:
187
  gr.HTML(
188
  """
189
  <div class="header-container">
@@ -197,48 +182,30 @@ with gr.Blocks(css_paths="style.css", css=css) as demo:
197
  """
198
  )
199
 
200
- with gr.Accordion("⚠️ راهنمای استفاده", open=False, elem_classes="config-accordion"):
201
  gr.Markdown("""
202
- ### راهنمای استفاده
203
- - تصویر خود را آپلود کرده و دستور ویرایش را وارد کنید
204
- - در صورت بروز خطا، پیام مربوطه نمایش داده خواهد شد
205
- - فقط تصاویر با فرمت PNG آپلود کنید
206
- - از آپلود تصاویر نامناسب خودداری کنید
207
  """)
208
 
209
- with gr.Accordion("📌 دستورالعمل‌های ویرایش", open=False, elem_classes="instructions-accordion"):
210
- gr.Markdown("""
211
- ### نمونه دستورات ویرایش
212
- - متن تصویر را به \"متن جدید\" تغییر بده
213
- - شیء خاصی را از تصویر حذف کن
214
- - استایل خاصی به بخشی از تصویر اضافه کن
215
- - تغییرات رنگی روی تصویر اعمال کن
216
- """)
217
-
218
- with gr.Row(elem_classes="main-content"):
219
- with gr.Column(elem_classes="input-column"):
220
  image_input = gr.Image(
221
  type="pil",
222
  label="تصویر را آپلود کنید",
223
- image_mode="RGBA",
224
- elem_id="image-input",
225
- elem_classes="upload-box"
226
  )
227
  prompt_input = gr.Textbox(
228
  lines=2,
229
- placeholder="تصویر چیکار بشه؟ اینجا بنویسید...",
230
- label="دستور ویرایش",
231
- elem_classes="prompt-input"
232
  )
233
- submit_btn = gr.Button("اعمال تغییرات", elem_classes="generate-btn")
234
 
235
- with gr.Column(elem_classes="output-column"):
236
- output_gallery = gr.Gallery(label="تصاویر ویرایش شده", elem_classes="output-gallery")
237
- output_text = gr.Textbox(
238
- label="پیام سیستم",
239
- placeholder="در صورت بروز خطا، پیام مربوطه اینجا نمایش داده می‌شود.",
240
- elem_classes="output-text"
241
- )
242
 
243
  submit_btn.click(
244
  fn=process_image_and_prompt,
@@ -246,23 +213,15 @@ with gr.Blocks(css_paths="style.css", css=css) as demo:
246
  outputs=[output_gallery, output_text],
247
  )
248
 
249
- gr.Markdown("## نمونه‌های آماده", elem_classes="gr-examples-header")
250
-
251
  examples = [
252
- ["data/1.webp", 'متن را به "امیر" تغییر بده', ""],
253
- ["data/2.webp", "قاشق را از دست حذف کن", ""],
254
- ["data/3.webp", 'متن را به "بساز" تغییر بده', ""],
255
- ["data/1.jpg", "فقط روی صورت استایل جوکر اضافه کن", ""],
256
- ["data/1777043.jpg", "فقط روی صورت استایل جوکر اضافه کن", ""],
257
- ["data/2807615.jpg", "فقط روی لب‌ها رژ لب اضافه کن", ""],
258
- ["data/76860.jpg", "فقط روی لب‌ها رژ لب اضافه کن", ""],
259
- ["data/2807615.jpg", "فقط صورت را شادتر کن", ""],
260
  ]
261
 
262
  gr.Examples(
263
  examples=examples,
264
  inputs=[image_input, prompt_input],
265
- elem_id="examples-grid"
266
  )
267
 
268
  demo.queue(max_size=50).launch()
 
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
  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
  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
  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
 
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)}"
 
135
  result_images = []
136
  error_messages = []
137
 
 
138
  with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
139
  futures = {
140
  executor.submit(
 
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
  }
169
  """
170
 
171
+ with gr.Blocks(css=css) as demo:
172
  gr.HTML(
173
  """
174
  <div class="header-container">
 
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
  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()