ArrcttacsrjksX commited on
Commit
49511f7
·
verified ·
1 Parent(s): 5951d47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -25
app.py CHANGED
@@ -169,6 +169,8 @@ class ImageToDxfConverter:
169
  logger.error(f"Conversion failed: {str(e)}")
170
  return None, None, []
171
 
 
 
172
  def create_gradio_interface():
173
  """Create and configure the Gradio interface."""
174
  converter = ImageToDxfConverter()
@@ -180,9 +182,14 @@ def create_gradio_interface():
180
  Press Ctrl+V to paste image from clipboard.
181
  """)
182
 
 
 
 
183
  with gr.Row():
184
  with gr.Column(scale=2):
185
  image_input = gr.Image(
 
 
186
  type="filepath",
187
  label="Input Image",
188
  elem_id="image_input",
@@ -214,45 +221,67 @@ def create_gradio_interface():
214
  height=300
215
  )
216
 
217
- # Thêm JavaScript để xử lý paste từ clipboard
218
  demo.load(js="""
219
- function setupPasteHandler() {
220
- document.addEventListener('paste', async function(e) {
 
 
221
  e.preventDefault();
 
 
222
  const items = e.clipboardData.items;
223
 
224
  for (let i = 0; i < items.length; i++) {
225
- if (items[i].type.indexOf('image') !== -1) {
226
- const blob = items[i].getAsFile();
 
 
 
227
  const reader = new FileReader();
228
 
229
  reader.onload = function(event) {
230
- const base64data = event.target.result;
231
- const imgElement = document.querySelector('#image_input img');
232
- if (imgElement) {
233
- imgElement.src = base64data;
234
-
235
- // Trigger conversion after image is loaded
236
- imgElement.onload = function() {
237
- const convertBtn = document.querySelector('#convert_btn');
238
- if (convertBtn) {
239
- convertBtn.click();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  }
241
- }
242
- }
243
  };
244
 
245
- reader.readAsDataURL(blob);
246
  break;
247
  }
248
  }
249
  });
250
  }
251
-
 
252
  if (document.readyState === 'complete') {
253
- setupPasteHandler();
254
  } else {
255
- window.addEventListener('load', setupPasteHandler);
256
  }
257
  """)
258
 
@@ -260,7 +289,8 @@ def create_gradio_interface():
260
  convert_btn.click(
261
  fn=converter.convert_image,
262
  inputs=[image_input, use_lines_checkbox],
263
- outputs=[dxf_output, debug_output]
 
264
  )
265
 
266
  return demo
@@ -269,12 +299,12 @@ def main():
269
  """Main entry point with proper error handling."""
270
  try:
271
  demo = create_gradio_interface()
272
- demo.queue() # Enable queuing for better handling of concurrent requests
273
  demo.launch(
274
  server_name="0.0.0.0",
275
  server_port=7860,
276
- show_api=False, # Disable API documentation page
277
- share=False, # Disable public URL generation
278
  )
279
  except Exception as e:
280
  logger.critical(f"Application failed to start: {str(e)}")
 
169
  logger.error(f"Conversion failed: {str(e)}")
170
  return None, None, []
171
 
172
+ # ... (các phần import và class ImageToDxfConverter giữ nguyên) ...
173
+
174
  def create_gradio_interface():
175
  """Create and configure the Gradio interface."""
176
  converter = ImageToDxfConverter()
 
182
  Press Ctrl+V to paste image from clipboard.
183
  """)
184
 
185
+ # Thêm state để lưu base64 data
186
+ clipboard_image = gr.State()
187
+
188
  with gr.Row():
189
  with gr.Column(scale=2):
190
  image_input = gr.Image(
191
+ source="upload", # Thêm source parameter
192
+ tool="select", # Chỉ cho phép select
193
  type="filepath",
194
  label="Input Image",
195
  elem_id="image_input",
 
221
  height=300
222
  )
223
 
224
+ # Cập nhật JavaScript để xử lý paste
225
  demo.load(js="""
226
+ function initPasteHandler() {
227
+ // Lắng nghe sự kiện paste trên toàn document
228
+ document.addEventListener('paste', function(e) {
229
+ // Ngăn hành vi paste mặc định
230
  e.preventDefault();
231
+
232
+ // Lấy dữ liệu từ clipboard
233
  const items = e.clipboardData.items;
234
 
235
  for (let i = 0; i < items.length; i++) {
236
+ const item = items[i];
237
+
238
+ // Kiểm tra nếu là ảnh
239
+ if (item.type.indexOf('image') !== -1) {
240
+ const file = item.getAsFile();
241
  const reader = new FileReader();
242
 
243
  reader.onload = function(event) {
244
+ // Tạo một đối tượng File từ dữ liệu base64
245
+ fetch(event.target.result)
246
+ .then(res => res.blob())
247
+ .then(blob => {
248
+ const file = new File([blob], "pasted_image.png", { type: "image/png" });
249
+
250
+ // Tạo một sự kiện drag and drop giả
251
+ const dt = new DataTransfer();
252
+ dt.items.add(file);
253
+
254
+ // Tìm input file trong Gradio interface
255
+ const fileInput = document.querySelector('#image_input input[type="file"]');
256
+ if (fileInput) {
257
+ // Cập nhật files của input
258
+ fileInput.files = dt.files;
259
+
260
+ // Trigger sự kiện change
261
+ const event = new Event('change', { bubbles: true });
262
+ fileInput.dispatchEvent(event);
263
+
264
+ // Auto click nút convert sau khi paste
265
+ setTimeout(() => {
266
+ const convertBtn = document.querySelector('#convert_btn');
267
+ if (convertBtn) convertBtn.click();
268
+ }, 100);
269
  }
270
+ });
 
271
  };
272
 
273
+ reader.readAsDataURL(file);
274
  break;
275
  }
276
  }
277
  });
278
  }
279
+
280
+ // Đảm bảo DOM đã load xong
281
  if (document.readyState === 'complete') {
282
+ initPasteHandler();
283
  } else {
284
+ window.addEventListener('load', initPasteHandler);
285
  }
286
  """)
287
 
 
289
  convert_btn.click(
290
  fn=converter.convert_image,
291
  inputs=[image_input, use_lines_checkbox],
292
+ outputs=[dxf_output, debug_output],
293
+ api_name=False # Disable API endpoint for this event
294
  )
295
 
296
  return demo
 
299
  """Main entry point with proper error handling."""
300
  try:
301
  demo = create_gradio_interface()
302
+ demo.queue()
303
  demo.launch(
304
  server_name="0.0.0.0",
305
  server_port=7860,
306
+ show_api=False,
307
+ share=False,
308
  )
309
  except Exception as e:
310
  logger.critical(f"Application failed to start: {str(e)}")