File size: 5,046 Bytes
6be5e70
 
3ee6e2d
e0f4bef
66d3400
 
6be5e70
e0f4bef
6be5e70
e0f4bef
 
 
 
 
 
 
66d3400
 
e0f4bef
66d3400
 
e0f4bef
66d3400
 
e0f4bef
 
 
 
 
 
 
 
66d3400
 
 
e0f4bef
 
 
 
66d3400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0f4bef
6be5e70
e0f4bef
 
6be5e70
 
86c4c0d
3ee6e2d
e0f4bef
3ee6e2d
 
e0f4bef
 
3ee6e2d
e0f4bef
 
 
 
3ee6e2d
e0f4bef
66d3400
e0f4bef
 
3ee6e2d
e0f4bef
 
 
 
 
 
 
3ee6e2d
 
6be5e70
19845fc
 
 
d00e361
 
 
 
 
e0f4bef
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import gradio as gr
import subprocess
import os
import tempfile
import datetime
from huggingface_hub import upload_file

def convert_image_to_dxf(image_file, output_folder=None):
    try:
        # Validate input image
        if image_file is None:
            return "No image provided", None, None
        
        # Define output folder, using a temp directory if none is specified
        if not output_folder:
            output_folder = tempfile.mkdtemp()
        else:
            os.makedirs(output_folder, exist_ok=True)
        
        # Generate the date-based output file name
        current_date = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        image_path = image_file
        output_path = os.path.join(output_folder, f"{current_date}_output.dxf")
        debug_output_path = os.path.join(output_folder, f"{current_date}_debug.png")
        
        # Execute conversion command
        result = subprocess.run(
            ["./SimpleImageToDxfHavePass", "--use-lines", f"--imagePath={image_path}", f"--outputPath={output_path}", f"--debug-output={debug_output_path}"],
            check=True,
            capture_output=True
        )
        
        # Log stdout for debugging
        print(result.stdout.decode('utf-8'))
        
        # Check if conversion was successful
        if not os.path.exists(output_path):
            return "Conversion failed: DXF file was not created.", None, None
        
        # Prepare folder structure for upload
        date_folder = f"{current_date}"
        
        hf_token = os.getenv("HF_TOKEN")
        if not hf_token:
            return "Hugging Face token not found", None, None
        
        # Upload input image, output DXF, and debug image to Hugging Face in a date-based folder
        uploaded_files = []
        
        # Upload input image
        uploaded_input = upload_file(
            path_or_fileobj=image_path,
            path_in_repo=f"ImageToAutocadData/{date_folder}/{os.path.basename(image_path)}",
            repo_id="ArrcttacsrjksX/ImageToAutocadData",
            token=hf_token
        )
        uploaded_files.append(uploaded_input)

        # Upload DXF output
        uploaded_dxf = upload_file(
            path_or_fileobj=output_path,
            path_in_repo=f"ImageToAutocadData/{date_folder}/{os.path.basename(output_path)}",
            repo_id="ArrcttacsrjksX/ImageToAutocadData",
            token=hf_token
        )
        uploaded_files.append(uploaded_dxf)

        # Upload debug image
        uploaded_debug = upload_file(
            path_or_fileobj=debug_output_path,
            path_in_repo=f"ImageToAutocadData/{date_folder}/{os.path.basename(debug_output_path)}",
            repo_id="ArrcttacsrjksX/ImageToAutocadData",
            token=hf_token
        )
        uploaded_files.append(uploaded_debug)

        # Generate download links for each uploaded file
        links = [f"https://huggingface.co/{uploaded_file.repo_id}/blob/main/{uploaded_file.path_in_repo}" for uploaded_file in uploaded_files]

        return f"Files uploaded successfully. Download links:\n" + "\n".join(links), debug_output_path, output_path
    
    except subprocess.CalledProcessError as e:
        error_msg = f"Error converting image to DXF: {e.stderr.decode('utf-8') if e.stderr else e}"
        return error_msg, None, None

def main():
    with gr.Blocks() as demo:
        with gr.Tabs():
            # Tab for conversion
            with gr.TabItem("Image to DXF"):
                gr.Markdown("# SimpleImageToDxfHavePass")
                
                # Input row for image and optional output folder
                with gr.Row():
                    image_input = gr.Image(type="filepath", label="Input Image (PNG/JPG)")
                    output_folder = gr.Textbox(label="Output Folder (optional)", placeholder="Leave blank to use a temporary folder")
                
                # Outputs: Debug image and DXF file download link
                with gr.Row():
                    debug_output = gr.Image(type="filepath", label="Debug Output Preview")
                    dxf_output = gr.Textbox(label="DXF File Download Link", placeholder="The link will appear here")
                
                # Conversion button with event binding
                convert_btn = gr.Button("Convert to DXF")
                convert_btn.click(
                    convert_image_to_dxf, 
                    inputs=[image_input, output_folder], 
                    outputs=[dxf_output, debug_output, dxf_output]
                )
            
            # About tab
            with gr.TabItem("About"):
                gr.Markdown("This Gradio app allows users to convert an image to a DXF file using the SimpleImageToDxfHavePass command-line tool.")

    demo.launch()

if __name__ == "__main__":
    try:
        subprocess.run(['chmod', '+x', './SimpleImageToDxfHavePass'], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Error setting permissions: {e}")
        exit(1)
    main()