Ssabahi's picture
Upload 2 files
9f1155b verified
Raw History Blame Contribute Delete
3.39 kB
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", # Replace with your actual GH definition filename
"values": []
}
geom_list = []
for obj in doc.Objects:
if obj.Geometry:
# Encode geometry as dict, no json.dumps here!
encoded_geom = 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", # Must match GH input name exactly
"InnerTree": {"{0}": geom_list}
})
# Dump entire payload to JSON string once here
json_data = json.dumps(payload, indent=2)
return True, file_name, json_data
except Exception as e:
error_msg = f"❌ Failed: {file_name} — {str(e)}\n{traceback.format_exc()}"
return False, file_name, error_msg
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-Rhino.Compute Compatible 3DM to JSON Converter",
description="Upload a ZIP of .3dm files. Converts each to JSON exactly in Rhino.Compute input format."
)
if __name__ == "__main__":
demo.launch()