ArrcttacsrjksX commited on
Commit
76dcdc9
·
verified ·
1 Parent(s): 3bcc021

Upload app(46).py

Browse files
Files changed (1) hide show
  1. Backup/app(46).py +214 -0
Backup/app(46).py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import tempfile
5
+ import datetime
6
+ from pathlib import Path
7
+ from huggingface_hub import upload_file
8
+ from typing import Optional, Tuple, List, Union
9
+ import logging
10
+ import shutil
11
+
12
+ # Configure logging
13
+ logging.basicConfig(
14
+ level=logging.INFO,
15
+ format='%(asctime)s - %(levelname)s - %(message)s'
16
+ )
17
+ logger = logging.getLogger(__name__)
18
+
19
+ class ImageToDxfConverter:
20
+ def __init__(self):
21
+ """Initialize the converter with configuration."""
22
+ # For Hugging Face Spaces, executable should be in the root directory
23
+ self.executable_path = Path("SimpleImageToDxfHavePass")
24
+ self.hf_token = os.getenv("HF_TOKEN")
25
+ self.repo_id = "ArrcttacsrjksX/ImageToAutocadData"
26
+
27
+ # Make executable file executable (Hugging Face Spaces specific)
28
+ try:
29
+ os.chmod(self.executable_path, 0o755)
30
+ logger.info(f"Set executable permissions for {self.executable_path}")
31
+ except Exception as e:
32
+ logger.error(f"Failed to set executable permissions: {e}")
33
+
34
+ def _ensure_directory(self, path: Union[str, Path]) -> Path:
35
+ """Ensure directory exists and return Path object."""
36
+ path = Path(path)
37
+ path.mkdir(parents=True, exist_ok=True)
38
+ return path
39
+
40
+ def _generate_output_paths(self, output_folder: Path, timestamp: str) -> dict:
41
+ """Generate all required output paths."""
42
+ return {
43
+ 'output_dxf': output_folder / f"{timestamp}_output.dxf",
44
+ 'debug_png': output_folder / f"{timestamp}_debug.png",
45
+ 'temp_dxf': output_folder / "_output.dxf",
46
+ 'temp_debug': output_folder / "_debug.png"
47
+ }
48
+
49
+ def convert_image(self,
50
+ image_path: Optional[str],
51
+ output_folder: Optional[str] = None,
52
+ use_lines: bool = False) -> Tuple[Optional[str], Optional[str], List[str]]:
53
+ """Convert image to DXF format."""
54
+ try:
55
+ # Input validation
56
+ if not image_path:
57
+ return "No image provided", None, []
58
+
59
+ # Setup output directory
60
+ output_dir = self._ensure_directory(output_folder if output_folder else tempfile.mkdtemp())
61
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
62
+ paths = self._generate_output_paths(output_dir, timestamp)
63
+
64
+ # Prepare conversion command
65
+ command = [
66
+ f"./{self.executable_path}", # Use relative path with ./
67
+ f"--imagePath={image_path}",
68
+ f"--outputPath={paths['temp_dxf']}",
69
+ f"--debug-output={paths['temp_debug']}"
70
+ ]
71
+ if use_lines:
72
+ command.append("--use-lines")
73
+
74
+ # Execute conversion
75
+ try:
76
+ result = subprocess.run(
77
+ command,
78
+ check=True,
79
+ capture_output=True,
80
+ text=True
81
+ )
82
+ logger.info(f"Conversion output: {result.stdout}")
83
+ except subprocess.CalledProcessError as e:
84
+ error_msg = f"Conversion failed: {e.stderr}"
85
+ logger.error(error_msg)
86
+ return error_msg, None, []
87
+
88
+ # Move temporary files to final locations
89
+ shutil.move(paths['temp_dxf'], paths['output_dxf'])
90
+ if use_lines and os.path.exists(paths['temp_debug']):
91
+ shutil.move(paths['temp_debug'], paths['debug_png'])
92
+
93
+ # Upload files to Hugging Face
94
+ uploaded_files = []
95
+ if self.hf_token:
96
+ try:
97
+ date_folder = timestamp
98
+
99
+ # Upload input image
100
+ uploaded_input = upload_file(
101
+ path_or_fileobj=image_path,
102
+ path_in_repo=f"datasets/{self.repo_id}/{date_folder}/{Path(image_path).name}",
103
+ repo_id=self.repo_id,
104
+ token=self.hf_token
105
+ )
106
+ uploaded_files.append(uploaded_input)
107
+
108
+ # Upload DXF output
109
+ uploaded_dxf = upload_file(
110
+ path_or_fileobj=str(paths['output_dxf']),
111
+ path_in_repo=f"datasets/{self.repo_id}/{date_folder}/{paths['output_dxf'].name}",
112
+ repo_id=self.repo_id,
113
+ token=self.hf_token
114
+ )
115
+ uploaded_files.append(uploaded_dxf)
116
+
117
+ # Upload debug image if available
118
+ if use_lines and os.path.exists(paths['debug_png']):
119
+ uploaded_debug = upload_file(
120
+ path_or_fileobj=str(paths['debug_png']),
121
+ path_in_repo=f"datasets/{self.repo_id}/{date_folder}/{paths['debug_png'].name}",
122
+ repo_id=self.repo_id,
123
+ token=self.hf_token
124
+ )
125
+ uploaded_files.append(uploaded_debug)
126
+ except Exception as e:
127
+ logger.error(f"Upload failed: {str(e)}")
128
+
129
+ return (
130
+ str(paths['output_dxf']),
131
+ str(paths['debug_png']) if use_lines and os.path.exists(paths['debug_png']) else None,
132
+ uploaded_files
133
+ )
134
+
135
+ except Exception as e:
136
+ error_msg = f"Conversion failed: {str(e)}"
137
+ logger.error(error_msg)
138
+ return error_msg, None, []
139
+
140
+ def create_gradio_interface():
141
+ """Create and configure the Gradio interface."""
142
+ converter = ImageToDxfConverter()
143
+
144
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
145
+ gr.Markdown("""
146
+ # Image to DXF Converter
147
+ Convert your images to DXF format for CAD software.
148
+ """)
149
+
150
+ with gr.Row():
151
+ with gr.Column(scale=2):
152
+ image_input = gr.Image(
153
+ type="filepath",
154
+ label="Input Image",
155
+ elem_id="image_input"
156
+ )
157
+ with gr.Column(scale=1):
158
+ output_folder = gr.Textbox(
159
+ label="Output Folder (optional)",
160
+ placeholder="Leave blank for temporary folder",
161
+ elem_id="output_folder"
162
+ )
163
+ use_lines_checkbox = gr.Checkbox(
164
+ label="Enable line detection",
165
+ value=False,
166
+ elem_id="use_lines"
167
+ )
168
+ convert_btn = gr.Button(
169
+ "Convert to DXF",
170
+ variant="primary"
171
+ )
172
+
173
+ with gr.Row():
174
+ with gr.Column():
175
+ dxf_output = gr.File(
176
+ label="DXF Output",
177
+ elem_id="dxf_output"
178
+ )
179
+ with gr.Column():
180
+ debug_output = gr.Image(
181
+ type="filepath",
182
+ label="Debug Preview",
183
+ elem_id="debug_output"
184
+ )
185
+
186
+ status_output = gr.Textbox(
187
+ label="Status",
188
+ value="Ready",
189
+ interactive=False
190
+ )
191
+
192
+ # Event handler
193
+ convert_btn.click(
194
+ fn=converter.convert_image,
195
+ inputs=[image_input, output_folder, use_lines_checkbox],
196
+ outputs=[dxf_output, debug_output, status_output]
197
+ )
198
+
199
+ return demo
200
+
201
+ def main():
202
+ """Main entry point with proper error handling."""
203
+ try:
204
+ demo = create_gradio_interface()
205
+ demo.launch(
206
+ server_name="0.0.0.0",
207
+ server_port=7860
208
+ )
209
+ except Exception as e:
210
+ logger.critical(f"Application failed to start: {str(e)}")
211
+ raise
212
+
213
+ if __name__ == "__main__":
214
+ main()