Includes vector/vectorize/raster modes, page review before convert, bundled OCR data, and a single-file AppData launcher build. Co-authored-by: Cursor <cursoragent@cursor.com>
272 lines
8.1 KiB
Python
272 lines
8.1 KiB
Python
"""Trace bitmap PDF pages (flat drawing exports) into CAD polylines."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
import cv2
|
|
import fitz
|
|
import numpy as np
|
|
|
|
|
|
@dataclass
|
|
class TracedPath:
|
|
"""Polyline in PDF page coordinates (Y down, origin top-left)."""
|
|
|
|
points: list[tuple[float, float]]
|
|
closed: bool
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TraceSettings:
|
|
"""Controls how aggressively the tracer simplifies / filters geometry."""
|
|
|
|
max_dimension: int # 0 = never downscale
|
|
min_area: float
|
|
min_perimeter: float
|
|
epsilon_frac: float
|
|
epsilon_min: float
|
|
morph_open: bool
|
|
adaptive: bool
|
|
chain_approx: int
|
|
render_dpi: float
|
|
edge_pass: bool
|
|
|
|
|
|
# Presets: higher detail = more entities, larger DXF, better fine line capture
|
|
TRACE_DETAIL_PRESETS: dict[str, TraceSettings] = {
|
|
"normal": TraceSettings(
|
|
max_dimension=4500,
|
|
min_area=12.0,
|
|
min_perimeter=30.0,
|
|
epsilon_frac=0.0012,
|
|
epsilon_min=0.9,
|
|
morph_open=True,
|
|
adaptive=False,
|
|
chain_approx=cv2.CHAIN_APPROX_SIMPLE,
|
|
render_dpi=200.0,
|
|
edge_pass=False,
|
|
),
|
|
"high": TraceSettings(
|
|
max_dimension=0,
|
|
min_area=2.0,
|
|
min_perimeter=8.0,
|
|
epsilon_frac=0.0003,
|
|
epsilon_min=0.3,
|
|
morph_open=False,
|
|
adaptive=True,
|
|
chain_approx=cv2.CHAIN_APPROX_SIMPLE,
|
|
render_dpi=300.0,
|
|
edge_pass=False,
|
|
),
|
|
"maximum": TraceSettings(
|
|
max_dimension=0,
|
|
min_area=1.0,
|
|
min_perimeter=4.0,
|
|
epsilon_frac=0.00012,
|
|
epsilon_min=0.15,
|
|
morph_open=False,
|
|
adaptive=True,
|
|
chain_approx=cv2.CHAIN_APPROX_NONE,
|
|
render_dpi=400.0,
|
|
edge_pass=True,
|
|
),
|
|
}
|
|
|
|
DEFAULT_TRACE_DETAIL = "high"
|
|
|
|
|
|
def resolve_trace_settings(detail: str | None) -> TraceSettings:
|
|
key = (detail or DEFAULT_TRACE_DETAIL).strip().lower()
|
|
if key in ("max", "ultra"):
|
|
key = "maximum"
|
|
return TRACE_DETAIL_PRESETS.get(key, TRACE_DETAIL_PRESETS[DEFAULT_TRACE_DETAIL])
|
|
|
|
|
|
def _pixmap_to_gray(pix: fitz.Pixmap) -> np.ndarray:
|
|
if pix.alpha:
|
|
pix = fitz.Pixmap(fitz.csRGB, pix)
|
|
arr = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, pix.n)
|
|
if pix.n >= 3:
|
|
return cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
|
|
return arr[:, :, 0].copy()
|
|
|
|
|
|
def _ink_mask(gray: np.ndarray, settings: TraceSettings) -> np.ndarray:
|
|
"""Binary mask: white = ink / linework."""
|
|
_, otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
|
|
if not settings.adaptive:
|
|
bw = otsu
|
|
else:
|
|
# Adaptive catches thin gray antialiased strokes Otsu can miss
|
|
adapt = cv2.adaptiveThreshold(
|
|
gray,
|
|
255,
|
|
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
|
cv2.THRESH_BINARY_INV,
|
|
11,
|
|
6,
|
|
)
|
|
bw = cv2.bitwise_or(otsu, adapt)
|
|
# Drop very light paper noise from adaptive
|
|
bw[gray > 245] = 0
|
|
|
|
if settings.morph_open:
|
|
bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8))
|
|
return bw
|
|
|
|
|
|
def _contours_to_paths(
|
|
contours: list,
|
|
settings: TraceSettings,
|
|
) -> list[tuple[list[tuple[float, float]], bool]]:
|
|
out: list[tuple[list[tuple[float, float]], bool]] = []
|
|
for contour in contours:
|
|
area = float(cv2.contourArea(contour))
|
|
peri = float(cv2.arcLength(contour, True))
|
|
if area < settings.min_area and peri < settings.min_perimeter:
|
|
continue
|
|
eps = max(settings.epsilon_frac * peri, settings.epsilon_min)
|
|
approx = cv2.approxPolyDP(contour, eps, True)
|
|
if len(approx) < 2:
|
|
continue
|
|
pts = [(float(p[0][0]), float(p[0][1])) for p in approx]
|
|
closed = len(pts) >= 3
|
|
if closed and pts[0] != pts[-1]:
|
|
pts = pts + [pts[0]]
|
|
out.append((pts, closed))
|
|
return out
|
|
|
|
|
|
def _trace_binary(
|
|
gray: np.ndarray,
|
|
settings: TraceSettings,
|
|
) -> list[tuple[list[tuple[float, float]], bool]]:
|
|
"""Return pixel-space polylines (closed flag) from a grayscale drawing."""
|
|
bw = _ink_mask(gray, settings)
|
|
contours, _ = cv2.findContours(bw, cv2.RETR_LIST, settings.chain_approx)
|
|
paths = _contours_to_paths(contours, settings)
|
|
|
|
if settings.edge_pass:
|
|
# Extra pass for hairline geometry that barely fills a contour
|
|
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
|
|
edges = cv2.Canny(blurred, 40, 120, apertureSize=3, L2gradient=True)
|
|
edges = cv2.dilate(edges, np.ones((2, 2), np.uint8), iterations=1)
|
|
edge_contours, _ = cv2.findContours(
|
|
edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE
|
|
)
|
|
# Slightly tighter filter so Canny noise doesn't explode entity count
|
|
edge_settings = TraceSettings(
|
|
max_dimension=settings.max_dimension,
|
|
min_area=max(settings.min_area, 4.0),
|
|
min_perimeter=max(settings.min_perimeter, 16.0),
|
|
epsilon_frac=settings.epsilon_frac,
|
|
epsilon_min=settings.epsilon_min,
|
|
morph_open=False,
|
|
adaptive=False,
|
|
chain_approx=cv2.CHAIN_APPROX_SIMPLE,
|
|
render_dpi=settings.render_dpi,
|
|
edge_pass=False,
|
|
)
|
|
paths.extend(_contours_to_paths(edge_contours, edge_settings))
|
|
|
|
return paths
|
|
|
|
|
|
def _map_pixel_paths_to_page(
|
|
pixel_paths: list[tuple[list[tuple[float, float]], bool]],
|
|
img_w: int,
|
|
img_h: int,
|
|
bbox: fitz.Rect,
|
|
) -> list[TracedPath]:
|
|
"""Map image pixel coords into PDF page space using the image's page bbox."""
|
|
bw = float(bbox.width)
|
|
bh = float(bbox.height)
|
|
x0 = float(bbox.x0)
|
|
y0 = float(bbox.y0)
|
|
sx = bw / max(img_w, 1)
|
|
sy = bh / max(img_h, 1)
|
|
|
|
traced: list[TracedPath] = []
|
|
for pts, closed in pixel_paths:
|
|
mapped = [(x0 + px * sx, y0 + py * sy) for px, py in pts]
|
|
if len(mapped) >= 2:
|
|
traced.append(TracedPath(points=mapped, closed=closed))
|
|
return traced
|
|
|
|
|
|
def extract_page_images_gray(
|
|
pdf: fitz.Document,
|
|
page: fitz.Page,
|
|
*,
|
|
render_dpi: float = 200.0,
|
|
) -> list[tuple[np.ndarray, fitz.Rect]]:
|
|
"""
|
|
Extract embedded page images as grayscale + their page rectangles.
|
|
Falls back to a high-DPI page render when no embed is usable.
|
|
"""
|
|
results: list[tuple[np.ndarray, fitz.Rect]] = []
|
|
for img in page.get_images(full=True):
|
|
xref = img[0]
|
|
try:
|
|
rects = page.get_image_rects(xref) or []
|
|
except Exception:
|
|
rects = []
|
|
if not rects:
|
|
try:
|
|
rects = [page.get_image_bbox(img)]
|
|
except Exception:
|
|
continue
|
|
try:
|
|
pix = fitz.Pixmap(pdf, xref)
|
|
except Exception:
|
|
continue
|
|
try:
|
|
gray = _pixmap_to_gray(pix)
|
|
except Exception:
|
|
continue
|
|
for rect in rects:
|
|
if rect.width <= 1 or rect.height <= 1:
|
|
continue
|
|
results.append((gray, fitz.Rect(rect)))
|
|
|
|
if results:
|
|
return results
|
|
|
|
zoom = float(render_dpi) / 72.0
|
|
pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), alpha=False)
|
|
gray = _pixmap_to_gray(pix)
|
|
return [(gray, fitz.Rect(page.rect))]
|
|
|
|
|
|
def vectorize_page(
|
|
pdf: fitz.Document,
|
|
page: fitz.Page,
|
|
*,
|
|
detail: str = DEFAULT_TRACE_DETAIL,
|
|
) -> list[TracedPath]:
|
|
"""
|
|
Trace all drawing bitmaps on a page into PDF-space polylines.
|
|
|
|
`detail`: normal | high | maximum
|
|
"""
|
|
settings = resolve_trace_settings(detail)
|
|
traced: list[TracedPath] = []
|
|
for gray, bbox in extract_page_images_gray(
|
|
pdf, page, render_dpi=settings.render_dpi
|
|
):
|
|
h, w = gray.shape[:2]
|
|
work = gray
|
|
max_dim = settings.max_dimension
|
|
if max_dim > 0 and max(h, w) > max_dim:
|
|
scale = max_dim / float(max(h, w))
|
|
work = cv2.resize(
|
|
gray,
|
|
(max(1, int(round(w * scale))), max(1, int(round(h * scale)))),
|
|
interpolation=cv2.INTER_AREA,
|
|
)
|
|
wh, ww = work.shape[:2]
|
|
pixel_paths = _trace_binary(work, settings)
|
|
traced.extend(_map_pixel_paths_to_page(pixel_paths, ww, wh, bbox))
|
|
return traced
|