File size: 3,267 Bytes
25f4110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import rhino3dm
import json
import tempfile
import os
import zipfile
import traceback
from concurrent.futures import ThreadPoolExecutor, as_completed

def process_3dm_file(file_path):
    file_name = os.path.basename(file_path)
    try:
        doc = rhino3dm.File3dm.Read(file_path)
        if not doc:
            raise ValueError("File could not be read as 3DM.")

        payload = {
            "algo": "definition.gh",  # must match GH definition name
            "values": []
        }

        geom_list = []
        for obj in doc.Objects:
            if obj.Geometry:
                encoded_geom = json.dumps(
                    rhino3dm.CommonObject.Encode(obj.Geometry)
                )
                geom_list.append({"type": "System.Object", "data": encoded_geom})

        if not geom_list:
            raise ValueError("No geometry found in file.")

        payload["values"].append({
            "ParamName": "Geometry",
            "InnerTree": {"{0}": geom_list}
        })

        json_data = json.dumps(payload, indent=2)
        return True, file_name, json_data

    except Exception as e:
        return False, file_name, f"❌ Failed: {file_name} — {str(e)}\n{traceback.format_exc()}"

def convert_zip_to_json(uploaded_zip):
    logs = []
    temp_extract_dir = tempfile.mkdtemp()

    try:
        with zipfile.ZipFile(uploaded_zip.name, 'r') as zf:
            zf.extractall(temp_extract_dir)
    except Exception as e:
        logs.append(f"❌ Failed to extract ZIP: {str(e)}")
        return None, "\n".join(logs)

    files = []
    for root, _, filenames in os.walk(temp_extract_dir):
        for fn in filenames:
            if fn.lower().endswith(".3dm"):
                files.append(os.path.join(root, fn))

    if not files:
        logs.append("❌ No .3dm files found in uploaded ZIP.")
        return None, "\n".join(logs)

    output_zip_path = os.path.join(tempfile.gettempdir(), "converted_jsons.zip")
    with zipfile.ZipFile(output_zip_path, "w") as zipf:
        with ThreadPoolExecutor(max_workers=4) as executor:
            futures = {executor.submit(process_3dm_file, f): f for f in files}
            for future in as_completed(futures):
                success, file_name, result = future.result()
                if success:
                    json_filename = os.path.splitext(file_name)[0] + ".json"
                    zipf.writestr(json_filename, result)
                    logs.append(f"✅ Success: {file_name}")
                else:
                    logs.append(result)

    return output_zip_path, "\n".join(logs)

file_input = gr.File(file_types=[".zip"], file_count="single", label="Upload ZIP containing .3dm files")

demo = gr.Interface(
    fn=convert_zip_to_json,
    inputs=file_input,
    outputs=[
        gr.File(label="Download All JSONs (ZIP)"),
        gr.Textbox(label="Conversion Log", lines=20)
    ],
    title="DA-Batch 3DM to JSON Converter (ZIP input/output)",
    description="Upload a ZIP of .3dm files for faster processing. Converts each to Rhino.Compute JSON format and returns all in one ZIP, with logs."
)

if __name__ == "__main__":
    demo.launch()