ArrcttacsrjksX commited on
Commit
d300389
·
verified ·
1 Parent(s): 76ece9b

Upload app(47).py

Browse files
Files changed (1) hide show
  1. Backup/app(47).py +200 -0
Backup/app(47).py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ use_lines: bool = False) -> Tuple[Optional[str], Optional[str], List[str]]:
52
+ """Convert image to DXF format."""
53
+ try:
54
+ # Input validation
55
+ if not image_path:
56
+ return None, None, []
57
+
58
+ # Setup output directory with fixed path
59
+ output_dir = self._ensure_directory("OutputPDF")
60
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
61
+ paths = self._generate_output_paths(output_dir, timestamp)
62
+
63
+ # Prepare conversion command
64
+ command = [
65
+ f"./{self.executable_path}", # Use relative path with ./
66
+ f"--imagePath={image_path}",
67
+ f"--outputPath={paths['temp_dxf']}",
68
+ f"--debug-output={paths['temp_debug']}"
69
+ ]
70
+ if use_lines:
71
+ command.append("--use-lines")
72
+
73
+ # Execute conversion
74
+ try:
75
+ result = subprocess.run(
76
+ command,
77
+ check=True,
78
+ capture_output=True,
79
+ text=True
80
+ )
81
+ logger.info(f"Conversion output: {result.stdout}")
82
+ except subprocess.CalledProcessError as e:
83
+ logger.error(f"Conversion failed: {e.stderr}")
84
+ return None, None, []
85
+
86
+ # Move temporary files to final locations
87
+ shutil.move(paths['temp_dxf'], paths['output_dxf'])
88
+ if use_lines and os.path.exists(paths['temp_debug']):
89
+ shutil.move(paths['temp_debug'], paths['debug_png'])
90
+
91
+ # Upload files to Hugging Face
92
+ uploaded_files = []
93
+ if self.hf_token:
94
+ try:
95
+ date_folder = timestamp
96
+
97
+ # Upload input image
98
+ uploaded_input = upload_file(
99
+ path_or_fileobj=image_path,
100
+ path_in_repo=f"datasets/{self.repo_id}/{date_folder}/{Path(image_path).name}",
101
+ repo_id=self.repo_id,
102
+ token=self.hf_token
103
+ )
104
+ uploaded_files.append(uploaded_input)
105
+
106
+ # Upload DXF output
107
+ uploaded_dxf = upload_file(
108
+ path_or_fileobj=str(paths['output_dxf']),
109
+ path_in_repo=f"datasets/{self.repo_id}/{date_folder}/{paths['output_dxf'].name}",
110
+ repo_id=self.repo_id,
111
+ token=self.hf_token
112
+ )
113
+ uploaded_files.append(uploaded_dxf)
114
+
115
+ # Upload debug image if available
116
+ if use_lines and os.path.exists(paths['debug_png']):
117
+ uploaded_debug = upload_file(
118
+ path_or_fileobj=str(paths['debug_png']),
119
+ path_in_repo=f"datasets/{self.repo_id}/{date_folder}/{paths['debug_png'].name}",
120
+ repo_id=self.repo_id,
121
+ token=self.hf_token
122
+ )
123
+ uploaded_files.append(uploaded_debug)
124
+ except Exception as e:
125
+ logger.error(f"Upload failed: {str(e)}")
126
+
127
+ return (
128
+ str(paths['output_dxf']),
129
+ str(paths['debug_png']) if use_lines and os.path.exists(paths['debug_png']) else None,
130
+ uploaded_files
131
+ )
132
+
133
+ except Exception as e:
134
+ logger.error(f"Conversion failed: {str(e)}")
135
+ return None, None, []
136
+
137
+ def create_gradio_interface():
138
+ """Create and configure the Gradio interface."""
139
+ converter = ImageToDxfConverter()
140
+
141
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
142
+ gr.Markdown("""
143
+ # Image to DXF Converter
144
+ Convert your images to DXF format for CAD software.
145
+ """)
146
+
147
+ with gr.Row():
148
+ with gr.Column(scale=2):
149
+ image_input = gr.Image(
150
+ type="filepath",
151
+ label="Input Image",
152
+ elem_id="image_input"
153
+ )
154
+ with gr.Column(scale=1):
155
+ use_lines_checkbox = gr.Checkbox(
156
+ label="Enable line detection",
157
+ value=False,
158
+ elem_id="use_lines"
159
+ )
160
+ convert_btn = gr.Button(
161
+ "Convert to DXF",
162
+ variant="primary"
163
+ )
164
+
165
+ with gr.Row():
166
+ with gr.Column():
167
+ dxf_output = gr.File(
168
+ label="DXF Output",
169
+ elem_id="dxf_output"
170
+ )
171
+ with gr.Column():
172
+ debug_output = gr.Image(
173
+ type="filepath",
174
+ label="Debug Preview",
175
+ elem_id="debug_output"
176
+ )
177
+
178
+ # Event handler
179
+ convert_btn.click(
180
+ fn=converter.convert_image,
181
+ inputs=[image_input, use_lines_checkbox],
182
+ outputs=[dxf_output, debug_output]
183
+ )
184
+
185
+ return demo
186
+
187
+ def main():
188
+ """Main entry point with proper error handling."""
189
+ try:
190
+ demo = create_gradio_interface()
191
+ demo.launch(
192
+ server_name="0.0.0.0",
193
+ server_port=7860
194
+ )
195
+ except Exception as e:
196
+ logger.critical(f"Application failed to start: {str(e)}")
197
+ raise
198
+
199
+ if __name__ == "__main__":
200
+ main()