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()