ArrcttacsrjksX commited on
Commit
6ebda09
·
verified ·
1 Parent(s): 574116a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -20
app.py CHANGED
@@ -9,6 +9,7 @@ from typing import Optional, Tuple, List, Union
9
  import logging
10
  from functools import partial
11
  import shutil
 
12
 
13
  # Configure logging
14
  logging.basicConfig(
@@ -18,20 +19,50 @@ logging.basicConfig(
18
  logger = logging.getLogger(__name__)
19
 
20
  class ImageToDxfConverter:
21
- def __init__(self, executable_path: str = "./SimpleImageToDxfHavePass"):
22
  """Initialize the converter with configuration."""
23
- self.executable_path = Path(executable_path)
24
  self.hf_token = os.getenv("HF_TOKEN")
25
  self.repo_id = "ArrcttacsrjksX/ImageToAutocadData"
26
 
27
- # Validate executable exists
28
- if not self.executable_path.exists():
29
- raise FileNotFoundError(f"Executable not found: {executable_path}")
30
-
31
  # Validate HF token
32
  if not self.hf_token:
33
  logger.warning("HF_TOKEN environment variable not set")
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def _ensure_directory(self, path: Union[str, Path]) -> Path:
36
  """Ensure directory exists and return Path object."""
37
  path = Path(path)
@@ -49,7 +80,18 @@ class ImageToDxfConverter:
49
 
50
  def _execute_conversion(self, command_args: List[str]) -> subprocess.CompletedProcess:
51
  """Execute the conversion command with proper error handling."""
 
 
 
 
 
 
52
  try:
 
 
 
 
 
53
  result = subprocess.run(
54
  command_args,
55
  check=True,
@@ -62,6 +104,10 @@ class ImageToDxfConverter:
62
  error_msg = f"Conversion failed: {e.stderr}"
63
  logger.error(error_msg)
64
  raise RuntimeError(error_msg)
 
 
 
 
65
 
66
  def _upload_to_huggingface(self,
67
  file_path: Path,
@@ -97,6 +143,12 @@ class ImageToDxfConverter:
97
  if not image_path:
98
  raise ValueError("No image provided")
99
 
 
 
 
 
 
 
100
  # Setup output directory
101
  output_dir = self._ensure_directory(output_folder if output_folder else tempfile.mkdtemp())
102
  timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
@@ -156,19 +208,35 @@ class ImageToDxfConverter:
156
 
157
  except Exception as e:
158
  logger.error(f"Conversion failed: {str(e)}")
159
- return None, None, []
160
 
161
  def create_gradio_interface():
162
  """Create and configure the Gradio interface."""
163
  converter = ImageToDxfConverter()
164
 
 
 
 
 
165
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
166
  with gr.Tabs():
167
  with gr.TabItem("Image to DXF"):
168
- gr.Markdown("""
169
- # Image to DXF Converter
170
- Convert your images to DXF format for CAD software.
171
- """)
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
  with gr.Row():
174
  with gr.Column(scale=2):
@@ -191,7 +259,8 @@ def create_gradio_interface():
191
  convert_btn = gr.Button(
192
  "Convert to DXF",
193
  variant="primary",
194
- elem_id="convert_btn"
 
195
  )
196
 
197
  with gr.Row():
@@ -211,7 +280,7 @@ def create_gradio_interface():
211
  error_output = gr.Textbox(
212
  label="Status",
213
  interactive=False,
214
- visible=False,
215
  elem_id="error_output"
216
  )
217
 
@@ -233,13 +302,18 @@ def create_gradio_interface():
233
  2. (Optional) Specify output folder
234
  3. Toggle line detection if needed
235
  4. Click Convert
 
 
 
 
 
236
  """)
237
 
238
  # Setup event handlers
239
  convert_btn.click(
240
  fn=converter.convert_image,
241
  inputs=[image_input, output_folder, use_lines_checkbox],
242
- outputs=[dxf_output, debug_output, error_output],
243
  api_name="convert"
244
  )
245
 
@@ -248,15 +322,9 @@ def create_gradio_interface():
248
  def main():
249
  """Main entry point with proper error handling."""
250
  try:
251
- # Ensure executable permissions
252
- executable = Path("./SimpleImageToDxfHavePass")
253
- if executable.exists():
254
- executable.chmod(0o755)
255
-
256
  # Create and launch the interface
257
  demo = create_gradio_interface()
258
  demo.launch(
259
- share=True,
260
  server_name="0.0.0.0",
261
  server_port=7860,
262
  show_error=True
 
9
  import logging
10
  from functools import partial
11
  import shutil
12
+ import sys
13
 
14
  # Configure logging
15
  logging.basicConfig(
 
19
  logger = logging.getLogger(__name__)
20
 
21
  class ImageToDxfConverter:
22
+ def __init__(self):
23
  """Initialize the converter with configuration."""
24
+ self.executable_path = self._find_executable()
25
  self.hf_token = os.getenv("HF_TOKEN")
26
  self.repo_id = "ArrcttacsrjksX/ImageToAutocadData"
27
 
 
 
 
 
28
  # Validate HF token
29
  if not self.hf_token:
30
  logger.warning("HF_TOKEN environment variable not set")
31
 
32
+ def _find_executable(self) -> Optional[Path]:
33
+ """Find the converter executable in various possible locations."""
34
+ possible_paths = [
35
+ Path("./SimpleImageToDxfHavePass"),
36
+ Path("./SimpleImageToDxfHavePass.exe"),
37
+ Path("/app/SimpleImageToDxfHavePass"), # Common Docker path
38
+ Path(os.path.dirname(os.path.abspath(__file__))) / "SimpleImageToDxfHavePass",
39
+ Path.home() / "SimpleImageToDxfHavePass"
40
+ ]
41
+
42
+ # Add system PATH locations
43
+ if sys.platform == "win32":
44
+ if "PATH" in os.environ:
45
+ for path in os.environ["PATH"].split(os.pathsep):
46
+ possible_paths.append(Path(path) / "SimpleImageToDxfHavePass.exe")
47
+ else:
48
+ for path in ["/usr/local/bin", "/usr/bin", "/bin"]:
49
+ possible_paths.append(Path(path) / "SimpleImageToDxfHavePass")
50
+
51
+ for path in possible_paths:
52
+ if path.exists():
53
+ try:
54
+ # Make executable on Unix-like systems
55
+ if sys.platform != "win32":
56
+ path.chmod(path.stat().st_mode | 0o111)
57
+ logger.info(f"Found executable at: {path}")
58
+ return path
59
+ except Exception as e:
60
+ logger.warning(f"Found executable at {path} but couldn't set permissions: {e}")
61
+ continue
62
+
63
+ logger.error("SimpleImageToDxfHavePass executable not found in any standard location")
64
+ return None
65
+
66
  def _ensure_directory(self, path: Union[str, Path]) -> Path:
67
  """Ensure directory exists and return Path object."""
68
  path = Path(path)
 
80
 
81
  def _execute_conversion(self, command_args: List[str]) -> subprocess.CompletedProcess:
82
  """Execute the conversion command with proper error handling."""
83
+ if not self.executable_path:
84
+ raise RuntimeError(
85
+ "SimpleImageToDxfHavePass executable not found. Please ensure it's installed "
86
+ "and available in your system PATH or in the same directory as the script."
87
+ )
88
+
89
  try:
90
+ # Add executable verification step
91
+ if not os.access(str(self.executable_path), os.X_OK) and sys.platform != "win32":
92
+ logger.warning(f"Setting executable permissions for {self.executable_path}")
93
+ os.chmod(str(self.executable_path), 0o755)
94
+
95
  result = subprocess.run(
96
  command_args,
97
  check=True,
 
104
  error_msg = f"Conversion failed: {e.stderr}"
105
  logger.error(error_msg)
106
  raise RuntimeError(error_msg)
107
+ except Exception as e:
108
+ error_msg = f"Unexpected error during conversion: {str(e)}"
109
+ logger.error(error_msg)
110
+ raise RuntimeError(error_msg)
111
 
112
  def _upload_to_huggingface(self,
113
  file_path: Path,
 
143
  if not image_path:
144
  raise ValueError("No image provided")
145
 
146
+ if not self.executable_path:
147
+ raise RuntimeError(
148
+ "SimpleImageToDxfHavePass executable not found. Please ensure it's installed "
149
+ "and available in your system PATH or in the same directory as the script."
150
+ )
151
+
152
  # Setup output directory
153
  output_dir = self._ensure_directory(output_folder if output_folder else tempfile.mkdtemp())
154
  timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
 
208
 
209
  except Exception as e:
210
  logger.error(f"Conversion failed: {str(e)}")
211
+ return str(e), None, []
212
 
213
  def create_gradio_interface():
214
  """Create and configure the Gradio interface."""
215
  converter = ImageToDxfConverter()
216
 
217
+ # Early validation of executable
218
+ if not converter.executable_path:
219
+ logger.error("No valid executable found - interface will show error message")
220
+
221
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
222
  with gr.Tabs():
223
  with gr.TabItem("Image to DXF"):
224
+ if not converter.executable_path:
225
+ gr.Markdown("""
226
+ # ⚠️ System Configuration Error
227
+
228
+ The SimpleImageToDxfHavePass executable was not found. Please ensure:
229
+ 1. The executable is in the same directory as this script
230
+ 2. The executable has proper permissions
231
+ 3. The executable is available in your system PATH
232
+
233
+ Check the logs for more details.
234
+ """)
235
+ else:
236
+ gr.Markdown("""
237
+ # Image to DXF Converter
238
+ Convert your images to DXF format for CAD software.
239
+ """)
240
 
241
  with gr.Row():
242
  with gr.Column(scale=2):
 
259
  convert_btn = gr.Button(
260
  "Convert to DXF",
261
  variant="primary",
262
+ elem_id="convert_btn",
263
+ interactive=bool(converter.executable_path)
264
  )
265
 
266
  with gr.Row():
 
280
  error_output = gr.Textbox(
281
  label="Status",
282
  interactive=False,
283
+ visible=True,
284
  elem_id="error_output"
285
  )
286
 
 
302
  2. (Optional) Specify output folder
303
  3. Toggle line detection if needed
304
  4. Click Convert
305
+
306
+ ### System Requirements:
307
+ - SimpleImageToDxfHavePass executable must be available
308
+ - Proper file permissions
309
+ - HF_TOKEN environment variable for Hugging Face integration
310
  """)
311
 
312
  # Setup event handlers
313
  convert_btn.click(
314
  fn=converter.convert_image,
315
  inputs=[image_input, output_folder, use_lines_checkbox],
316
+ outputs=[error_output, debug_output, dxf_output],
317
  api_name="convert"
318
  )
319
 
 
322
  def main():
323
  """Main entry point with proper error handling."""
324
  try:
 
 
 
 
 
325
  # Create and launch the interface
326
  demo = create_gradio_interface()
327
  demo.launch(
 
328
  server_name="0.0.0.0",
329
  server_port=7860,
330
  show_error=True