Newer
Older
CNCTools / ReferenceSurfaceGenerator / backend / app / dxf_parser.py
import ezdxf
from typing import List, Tuple

def parse_dxf_for_viewing(filepath: str) -> dict:
    """
    Parses a DXF file and extracts POLYLINE entities into a JSON-serializable format.

    Args:
        filepath: The full path to the DXF file.

    Returns:
        A dictionary containing the geometric data, e.g., {"polylines": [...]}.
    
    Raises:
        IOError: If the file cannot be read.
        Exception: For other parsing errors.
    """
    try:
        doc = ezdxf.readfile(filepath)
        msp = doc.modelspace()
        
        polylines: List[List[Tuple[float, float, float]]] = []
        for pline in msp.query('POLYLINE'):
            # A polyline is a sequence of vertices
            polylines.append([list(p) for p in pline.points()])

        return {"polylines": polylines}
    except IOError as e:
        # Re-raise with a more specific context if needed
        raise IOError(f"Could not read the DXF file: {filepath}") from e
    except Exception as e:
        # Catch other potential ezdxf errors
        raise Exception(f"Failed to parse DXF file: {filepath}") from e