Allow PNG/JPG/TIFF/BMP/GIF/WebP alongside PDF for preview and DXF conversion. Co-authored-by: Cursor <cursoragent@cursor.com>
1303 lines
40 KiB
Python
1303 lines
40 KiB
Python
"""Convert PDF pages to DXF using vector extraction and/or raster underlays."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import colorsys
|
||
import math
|
||
import re
|
||
from dataclasses import dataclass, field
|
||
from enum import Enum
|
||
from pathlib import Path
|
||
|
||
import ezdxf
|
||
import fitz
|
||
from ezdxf import units
|
||
|
||
from app.input_document import open_input_document
|
||
from app.raster_vectorize import vectorize_page
|
||
|
||
|
||
class ConvertMode(str, Enum):
|
||
AUTO = "auto"
|
||
VECTOR = "vector"
|
||
VECTORIZE = "vectorize" # trace bitmap/flattened drawing pages to polylines
|
||
RASTER = "raster"
|
||
|
||
|
||
@dataclass
|
||
class ConvertOptions:
|
||
mode: ConvertMode = ConvertMode.AUTO
|
||
pages: list[int] | None = None # 0-based; None = all
|
||
scale: float = 1.0
|
||
dpi: float = 150.0
|
||
vector_threshold: int = 20 # drawings below this → treat as raster in AUTO
|
||
import_text: bool = True
|
||
# OCR outlined / non-selectable text (equipment tags drawn as paths)
|
||
ocr_text: bool = True
|
||
ocr_dpi: float = 250.0
|
||
# Raster-to-vector quality: normal | high | maximum
|
||
trace_detail: str = "high"
|
||
# Optional per-page override (0-based). Values: vector|vectorize|raster|skip
|
||
# When set, takes precedence over global mode for that page.
|
||
page_modes: dict[int, str] | None = None
|
||
dxf_version: str = "R2010"
|
||
|
||
|
||
@dataclass
|
||
class PageClassification:
|
||
"""What a PDF page looks like before conversion."""
|
||
|
||
page_index: int # 0-based
|
||
kind: str # vector | image_drawing | mixed | empty
|
||
drawings: int
|
||
images: int
|
||
text_spans: int
|
||
suggested: str # vector | vectorize | raster | skip
|
||
label: str # short human description
|
||
detail: str # longer explanation
|
||
|
||
|
||
def _count_text_spans(page: fitz.Page) -> int:
|
||
try:
|
||
blocks = page.get_text("dict", flags=fitz.TEXT_PRESERVE_WHITESPACE)["blocks"]
|
||
except Exception:
|
||
return 0
|
||
n = 0
|
||
for block in blocks:
|
||
if block.get("type") != 0:
|
||
continue
|
||
for line in block.get("lines", []):
|
||
n += len(line.get("spans") or [])
|
||
return n
|
||
|
||
|
||
def classify_page(
|
||
page: fitz.Page,
|
||
page_index: int,
|
||
*,
|
||
vector_threshold: int = 20,
|
||
) -> PageClassification:
|
||
"""Detect whether a page is native vectors, a flattened image drawing, etc."""
|
||
drawings = _drawings_count(page)
|
||
images = len(page.get_images(full=True) or [])
|
||
text_spans = _count_text_spans(page)
|
||
|
||
if drawings >= vector_threshold:
|
||
return PageClassification(
|
||
page_index=page_index,
|
||
kind="vector",
|
||
drawings=drawings,
|
||
images=images,
|
||
text_spans=text_spans,
|
||
suggested="vector",
|
||
label="Native vector drawing",
|
||
detail=(
|
||
f"{drawings} vector paths"
|
||
+ (f", {text_spans} text spans" if text_spans else "")
|
||
+ (f", {images} image(s)" if images else "")
|
||
),
|
||
)
|
||
|
||
if images >= 1 and drawings < vector_threshold:
|
||
return PageClassification(
|
||
page_index=page_index,
|
||
kind="image_drawing",
|
||
drawings=drawings,
|
||
images=images,
|
||
text_spans=text_spans,
|
||
suggested="vectorize",
|
||
label="Image / flattened drawing",
|
||
detail=(
|
||
f"No usable PDF vectors ({drawings} paths). "
|
||
f"{images} embedded image(s)"
|
||
+ (f", {text_spans} text spans" if text_spans else "")
|
||
+ ". Suggest tracing (vectorize) or keep as image."
|
||
),
|
||
)
|
||
|
||
if drawings == 0 and images == 0:
|
||
return PageClassification(
|
||
page_index=page_index,
|
||
kind="empty",
|
||
drawings=0,
|
||
images=0,
|
||
text_spans=text_spans,
|
||
suggested="skip",
|
||
label="Empty / no content",
|
||
detail="No drawings or images detected on this page.",
|
||
)
|
||
|
||
return PageClassification(
|
||
page_index=page_index,
|
||
kind="mixed",
|
||
drawings=drawings,
|
||
images=images,
|
||
text_spans=text_spans,
|
||
suggested="vector",
|
||
label="Mixed / light vector content",
|
||
detail=(
|
||
f"{drawings} vector paths, {images} image(s)"
|
||
+ (f", {text_spans} text spans" if text_spans else "")
|
||
),
|
||
)
|
||
|
||
|
||
def classify_pdf_pages(
|
||
input_path: str | Path,
|
||
pages: list[int] | None = None,
|
||
*,
|
||
vector_threshold: int = 20,
|
||
) -> list[PageClassification]:
|
||
"""Classify selected pages of a PDF or image for pre-convert review."""
|
||
pdf = open_input_document(input_path)
|
||
try:
|
||
indices = _page_indices(pdf, pages)
|
||
return [
|
||
classify_page(pdf.load_page(i), i, vector_threshold=vector_threshold)
|
||
for i in indices
|
||
]
|
||
finally:
|
||
pdf.close()
|
||
|
||
|
||
@dataclass
|
||
class PageResult:
|
||
page_index: int
|
||
mode_used: str
|
||
entity_count: int = 0
|
||
text_count: int = 0
|
||
has_image: bool = False
|
||
|
||
|
||
@dataclass
|
||
class ConvertResult:
|
||
output_path: Path
|
||
pages: list[PageResult] = field(default_factory=list)
|
||
|
||
@property
|
||
def total_entities(self) -> int:
|
||
return sum(p.entity_count for p in self.pages)
|
||
|
||
@property
|
||
def summary(self) -> str:
|
||
parts = [
|
||
f"Saved: {self.output_path.name}",
|
||
f"Pages: {len(self.pages)}",
|
||
f"Entities: {self.total_entities}",
|
||
]
|
||
modes = ", ".join(f"p{p.page_index + 1}={p.mode_used}" for p in self.pages)
|
||
if modes:
|
||
parts.append(f"Modes: {modes}")
|
||
return " | ".join(parts)
|
||
|
||
|
||
def _page_indices(doc: fitz.Document, pages: list[int] | None) -> list[int]:
|
||
if pages is None:
|
||
return list(range(doc.page_count))
|
||
out: list[int] = []
|
||
for i in pages:
|
||
if 0 <= i < doc.page_count:
|
||
out.append(i)
|
||
return out
|
||
|
||
|
||
def _pdf_y_to_cad(y: float, page_height: float) -> float:
|
||
"""PDF origin is top-left; CAD is bottom-left."""
|
||
return page_height - y
|
||
|
||
|
||
def _rgb01_to_bytes(r: float, g: float, b: float) -> tuple[int, int, int]:
|
||
return (
|
||
max(0, min(255, int(round(r * 255)))),
|
||
max(0, min(255, int(round(g * 255)))),
|
||
max(0, min(255, int(round(b * 255)))),
|
||
)
|
||
|
||
|
||
def _luminance(r: float, g: float, b: float) -> float:
|
||
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||
|
||
|
||
def _is_wipeout_fill(fill) -> bool:
|
||
"""
|
||
CAD PDFs use near-white filled rects as wipeouts/masking.
|
||
Converting those to solid hatches covers linework — skip them.
|
||
"""
|
||
if not fill or len(fill) < 3:
|
||
return True
|
||
r, g, b = float(fill[0]), float(fill[1]), float(fill[2])
|
||
if _luminance(r, g, b) >= 0.90:
|
||
return True
|
||
if r >= 0.92 and g >= 0.92 and b >= 0.92:
|
||
return True
|
||
return False
|
||
|
||
|
||
# AutoCAD Color Index used for all imported text
|
||
TEXT_ACI = 32
|
||
BYLAYER = 256
|
||
|
||
# PDF font name → (DXF style name, Windows TTF file, width factor)
|
||
# TTF files are standard on Windows and work in BricsCAD when installed.
|
||
_PDF_FONT_STYLES: dict[str, tuple[str, str, float]] = {
|
||
"arialnarrow": ("ARIALN", "arialn.ttf", 1.0),
|
||
"arialnarrowbold": ("ARIALNB", "arialnb.ttf", 1.0),
|
||
"arialnarrowitalic": ("ARIALNI", "arialni.ttf", 1.0),
|
||
"arialnarrowbolditalic": ("ARIALNZ", "arialnbi.ttf", 1.0),
|
||
"arial": ("ARIAL", "arial.ttf", 1.0),
|
||
"arialmt": ("ARIAL", "arial.ttf", 1.0),
|
||
"arialbold": ("ARIALBD", "arialbd.ttf", 1.0),
|
||
"arialblack": ("ARIALBK", "ariblk.ttf", 1.0),
|
||
"arialitalic": ("ARIALI", "ariali.ttf", 1.0),
|
||
"arialbolditalic": ("ARIALBI", "arialbi.ttf", 1.0),
|
||
"helvetica": ("ARIAL", "arial.ttf", 1.0),
|
||
"helveticabold": ("ARIALBD", "arialbd.ttf", 1.0),
|
||
"courier": ("COURIER", "cour.ttf", 1.0),
|
||
"couriernew": ("COURIER", "cour.ttf", 1.0),
|
||
"courierbold": ("COURIERBD", "courbd.ttf", 1.0),
|
||
"times": ("TIMES", "times.ttf", 1.0),
|
||
"timesnewroman": ("TIMES", "times.ttf", 1.0),
|
||
"timesbold": ("TIMESBD", "timesbd.ttf", 1.0),
|
||
"timesroman": ("TIMES", "times.ttf", 1.0),
|
||
}
|
||
|
||
|
||
def _normalize_font_key(font_name: str, flags: int = 0) -> str:
|
||
"""Normalize PDF font + flags into a lookup key."""
|
||
name = (font_name or "Arial").strip().lower()
|
||
name = name.replace(" ", "").replace("-", "").replace("_", "")
|
||
# PDF often uses "ArialNarrow,Bold"
|
||
name = name.replace(",", "")
|
||
is_bold = "bold" in name or bool(flags & 16)
|
||
is_italic = (
|
||
"italic" in name
|
||
or "oblique" in name
|
||
or bool(flags & 2)
|
||
)
|
||
# Strip style tokens then re-append in canonical order
|
||
base = (
|
||
name.replace("bold", "")
|
||
.replace("italic", "")
|
||
.replace("oblique", "")
|
||
.replace("regular", "")
|
||
)
|
||
# ArialMT → arial (only strip trailing MT suffix)
|
||
if base.endswith("mt") and len(base) > 2:
|
||
base = base[:-2]
|
||
if not base:
|
||
base = "arial"
|
||
if is_bold:
|
||
base += "bold"
|
||
if is_italic:
|
||
base += "italic"
|
||
return base
|
||
|
||
|
||
def _resolve_font_style(font_name: str, flags: int = 0) -> tuple[str, str, float]:
|
||
"""Return (style_name, ttf_filename, width_factor) for a PDF font."""
|
||
key = _normalize_font_key(font_name, flags)
|
||
if key in _PDF_FONT_STYLES:
|
||
return _PDF_FONT_STYLES[key]
|
||
# Fuzzy: narrow / condensed without exact map entry
|
||
if "narrow" in key or "condensed" in key:
|
||
if "bold" in key:
|
||
return _PDF_FONT_STYLES["arialnarrowbold"]
|
||
return _PDF_FONT_STYLES["arialnarrow"]
|
||
if "bold" in key and "italic" in key:
|
||
return _PDF_FONT_STYLES["arialbolditalic"]
|
||
if "bold" in key:
|
||
return _PDF_FONT_STYLES["arialbold"]
|
||
if "italic" in key:
|
||
return _PDF_FONT_STYLES["arialitalic"]
|
||
return _PDF_FONT_STYLES["arial"]
|
||
|
||
|
||
def _ensure_text_style(
|
||
doc: ezdxf.document.Drawing,
|
||
style_name: str,
|
||
font_file: str,
|
||
width_factor: float = 1.0,
|
||
) -> str:
|
||
"""Create a DXF text style pointing at a TrueType font if missing."""
|
||
if style_name not in doc.styles:
|
||
style = doc.styles.new(
|
||
style_name,
|
||
dxfattribs={
|
||
"font": font_file,
|
||
"width": float(width_factor),
|
||
},
|
||
)
|
||
else:
|
||
style = doc.styles.get(style_name)
|
||
# Keep existing; still allow width update if unset-ish
|
||
try:
|
||
if abs(float(style.dxf.width) - 1.0) < 1e-9 and width_factor != 1.0:
|
||
style.dxf.width = float(width_factor)
|
||
except Exception:
|
||
pass
|
||
return style_name
|
||
|
||
|
||
# PDF font "size" is em-square height. DXF TrueType TEXT height is capital-letter
|
||
# height (~0.70 of em for Arial / Arial Narrow). Using em size 1:1 makes text look too big.
|
||
TEXT_EM_TO_CAP = 0.70
|
||
|
||
|
||
def _text_height_from_span(span: dict, scale: float) -> float:
|
||
"""Convert PDF font size to DXF text height (capital height)."""
|
||
size = float(span.get("size") or 10.0) * scale
|
||
return max(size * TEXT_EM_TO_CAP, 0.01)
|
||
|
||
|
||
# Equipment / tag patterns common on electrical layouts
|
||
_EQUIP_TAG_RE = re.compile(
|
||
r"^[A-Z0-9]{1,8}-[A-Z0-9]{2,}(?:-[A-Z0-9]+)*$",
|
||
re.IGNORECASE,
|
||
)
|
||
_HAS_EQUIP_RE = re.compile(
|
||
r"[A-Z0-9]{2,}-[A-Z0-9]{2,}(?:-[A-Z0-9]+)?",
|
||
re.IGNORECASE,
|
||
)
|
||
|
||
|
||
def _normalize_label(text: str) -> str:
|
||
"""Normalize for duplicate detection (O/0, I/1 confusion)."""
|
||
t = re.sub(r"\s+", "", text.upper())
|
||
return t.replace("O", "0").replace("I", "1").replace("L", "1")
|
||
|
||
|
||
def _is_useful_ocr_label(text: str) -> bool:
|
||
"""Keep OCR results that look like equipment tags; drop hatch / icon noise."""
|
||
t = (text or "").strip()
|
||
if len(t) < 4:
|
||
return False
|
||
if any(ord(c) < 32 or c == "\ufffd" for c in t):
|
||
return False
|
||
if re.search(r"(.)\1{3,}", t):
|
||
return False
|
||
# CAD equipment tags are almost always uppercase
|
||
if sum(1 for c in t if c.islower()) > 2:
|
||
return False
|
||
compact = t.replace(" ", "")
|
||
if not re.search(r"\d", compact):
|
||
return False
|
||
alnum = sum(1 for c in compact if c.isalnum() or c in "-_/")
|
||
if alnum / max(len(compact), 1) < 0.9:
|
||
return False
|
||
# Require hyphenated tag form: AA-BB or AA-BB-CC
|
||
if not _EQUIP_TAG_RE.match(compact):
|
||
return False
|
||
parts = compact.split("-")
|
||
head = parts[0]
|
||
# Reject long nonsense heads like DHOFOXCO (real tags are short: DH01, TRNB, 126)
|
||
if len(head) > 6 and not re.search(r"\d", head):
|
||
return False
|
||
return True
|
||
|
||
|
||
def _rects_overlap(a: fitz.Rect, b: fitz.Rect, iou_thresh: float = 0.2) -> bool:
|
||
inter = a & b
|
||
if inter.is_empty:
|
||
# center proximity fallback
|
||
ac = fitz.Point((a.x0 + a.x1) / 2, (a.y0 + a.y1) / 2)
|
||
bc = fitz.Point((b.x0 + b.x1) / 2, (b.y0 + b.y1) / 2)
|
||
tol_x = max(10.0, min(a.width, b.width) * 0.4)
|
||
tol_y = max(6.0, min(a.height, b.height) * 0.6)
|
||
return abs(ac.x - bc.x) <= tol_x and abs(ac.y - bc.y) <= tol_y
|
||
smaller = min(a.get_area(), b.get_area()) or 1.0
|
||
return (inter.get_area() / smaller) >= iou_thresh
|
||
|
||
|
||
def _collect_native_text_rects(page: fitz.Page) -> list[tuple[str, fitz.Rect]]:
|
||
out: list[tuple[str, fitz.Rect]] = []
|
||
try:
|
||
blocks = page.get_text("dict", flags=fitz.TEXT_PRESERVE_WHITESPACE)["blocks"]
|
||
except Exception:
|
||
return out
|
||
for block in blocks:
|
||
if block.get("type") != 0:
|
||
continue
|
||
for line in block.get("lines", []):
|
||
for span in line.get("spans", []):
|
||
text = (span.get("text") or "").strip()
|
||
if not text:
|
||
continue
|
||
out.append((text, fitz.Rect(span["bbox"])))
|
||
return out
|
||
|
||
|
||
def _ocr_outlined_labels(
|
||
page: fitz.Page,
|
||
dpi: float = 250.0,
|
||
) -> list[dict]:
|
||
"""
|
||
OCR regions that are not already real PDF text (outlined / path text).
|
||
Returns dicts: text, bbox (fitz.Rect), dir, size.
|
||
"""
|
||
from app.ocr_support import configure_bundled_ocr, tessdata_arg
|
||
|
||
configure_bundled_ocr()
|
||
tessdata = tessdata_arg()
|
||
|
||
dpi_i = max(72, int(round(dpi)))
|
||
ocr_kwargs: dict = {
|
||
"flags": 0,
|
||
"language": "eng",
|
||
"dpi": dpi_i,
|
||
}
|
||
if tessdata:
|
||
ocr_kwargs["tessdata"] = tessdata
|
||
|
||
textpage = None
|
||
try:
|
||
textpage = page.get_textpage_ocr(full=False, **ocr_kwargs)
|
||
except Exception:
|
||
try:
|
||
textpage = page.get_textpage_ocr(full=True, **ocr_kwargs)
|
||
except Exception:
|
||
return []
|
||
|
||
try:
|
||
data = page.get_text("dict", textpage=textpage)
|
||
except Exception:
|
||
return []
|
||
|
||
native = _collect_native_text_rects(page)
|
||
native_norms = {_normalize_label(t) for t, _ in native if len(t) >= 3}
|
||
|
||
results: list[dict] = []
|
||
seen_norms: set[str] = set()
|
||
|
||
for block in data.get("blocks", []):
|
||
if block.get("type") != 0:
|
||
continue
|
||
for line in block.get("lines", []):
|
||
spans = line.get("spans") or []
|
||
text = "".join(s.get("text", "") for s in spans).strip()
|
||
if not _is_useful_ocr_label(text):
|
||
continue
|
||
|
||
bbox = fitz.Rect(line.get("bbox") or (0, 0, 0, 0))
|
||
if bbox.is_empty or bbox.width < 1 or bbox.height < 1:
|
||
continue
|
||
|
||
# Skip if overlaps an existing native text span
|
||
if any(_rects_overlap(bbox, nr) for _, nr in native):
|
||
continue
|
||
|
||
norm = _normalize_label(text)
|
||
# Skip OCR re-reads of native tags (even if slightly misplaced)
|
||
if norm in native_norms or norm in seen_norms:
|
||
continue
|
||
seen_norms.add(norm)
|
||
|
||
# Font size ≈ bbox height for horizontal text
|
||
direction = line.get("dir") or (1.0, 0.0)
|
||
if abs(direction[0]) >= abs(direction[1]):
|
||
size = float(bbox.height)
|
||
else:
|
||
size = float(bbox.width)
|
||
|
||
results.append(
|
||
{
|
||
"text": text,
|
||
"bbox": bbox,
|
||
"dir": direction,
|
||
"size": max(size, 1.0),
|
||
"origin": (bbox.x0, bbox.y1), # baseline-ish bottom-left in PDF
|
||
}
|
||
)
|
||
|
||
return results
|
||
|
||
|
||
def _add_ocr_text_entities(
|
||
doc: ezdxf.document.Drawing,
|
||
msp,
|
||
page: fitz.Page,
|
||
page_index: int,
|
||
scale: float,
|
||
stack_offset_y: float,
|
||
page_h: float,
|
||
ocr_dpi: float,
|
||
) -> int:
|
||
"""Add OCR'd outlined labels on E_P*_OCR layer. Returns entity count."""
|
||
labels = _ocr_outlined_labels(page, dpi=ocr_dpi)
|
||
if not labels:
|
||
return 0
|
||
|
||
ocr_layer = _ensure_layer(
|
||
doc,
|
||
f"E_P{page_index + 1}_OCR",
|
||
aci=TEXT_ACI,
|
||
)
|
||
_ensure_text_style(doc, "ARIALN", "arialn.ttf", 1.0)
|
||
|
||
def tx(x: float) -> float:
|
||
return x * scale
|
||
|
||
def ty(y: float) -> float:
|
||
return (_pdf_y_to_cad(y, page_h) + stack_offset_y) * scale
|
||
|
||
count = 0
|
||
for lab in labels:
|
||
direction = lab["dir"]
|
||
dx = float(direction[0])
|
||
dy_pdf = float(direction[1])
|
||
rotation = math.degrees(math.atan2(-dy_pdf, dx))
|
||
if rotation > 180:
|
||
rotation -= 360
|
||
elif rotation <= -180:
|
||
rotation += 360
|
||
|
||
origin = lab["origin"]
|
||
insert = (tx(float(origin[0])), ty(float(origin[1])))
|
||
height = max(float(lab["size"]) * scale * TEXT_EM_TO_CAP, 0.5)
|
||
|
||
msp.add_text(
|
||
lab["text"],
|
||
height=height,
|
||
dxfattribs={
|
||
"layer": ocr_layer,
|
||
"style": "ARIALN",
|
||
"insert": insert,
|
||
"rotation": rotation,
|
||
"color": TEXT_ACI,
|
||
},
|
||
)
|
||
count += 1
|
||
return count
|
||
|
||
|
||
# Condensed electrical-drawing layer families (alike PDF colors → one layer)
|
||
# name → (canonical RGB for layer display, preferred ACI)
|
||
_LAYER_FAMILIES: dict[str, tuple[tuple[int, int, int], int]] = {
|
||
"BLACK": ((0, 0, 0), 7),
|
||
"GRAY": ((150, 150, 150), 8),
|
||
"RED": ((200, 40, 40), 1),
|
||
"ORANGE": ((255, 124, 0), 30),
|
||
"YELLOW": ((220, 200, 40), 2),
|
||
"GREEN": ((0, 154, 70), 3),
|
||
"BLUE": ((0, 95, 133), 5),
|
||
"MAGENTA": ((180, 40, 140), 6),
|
||
"OTHER": ((128, 128, 128), 9),
|
||
}
|
||
|
||
|
||
def _classify_color(rgb) -> str:
|
||
"""
|
||
Map a PDF RGB (0–1) into a condensed electrical layer family.
|
||
|
||
Grays (hatch ticks, secondary linework) collapse to GRAY.
|
||
Near-black outlines → BLACK.
|
||
Saturated hues → GREEN / ORANGE / BLUE / etc. for onelines & systems.
|
||
"""
|
||
if not rgb or len(rgb) < 3:
|
||
return "BLACK"
|
||
|
||
r, g, b = float(rgb[0]), float(rgb[1]), float(rgb[2])
|
||
spread = max(r, g, b) - min(r, g, b)
|
||
luma = _luminance(r, g, b)
|
||
|
||
# Neutral / gray family (most hatch patterns in electrical PDFs)
|
||
if spread < 0.08:
|
||
if luma < 0.12:
|
||
return "BLACK"
|
||
return "GRAY"
|
||
|
||
h, _l, s = colorsys.rgb_to_hls(r, g, b)
|
||
# Weak tint → still treat as gray unless clearly chromatic
|
||
if s < 0.12 and spread < 0.15:
|
||
return "GRAY" if luma >= 0.12 else "BLACK"
|
||
|
||
# Hue wheel buckets (HLS h is 0–1). Cyan/teal merges into BLUE for fewer layers.
|
||
if h < 0.03 or h >= 0.96:
|
||
return "RED"
|
||
if h < 0.10:
|
||
return "ORANGE"
|
||
if h < 0.18:
|
||
return "YELLOW"
|
||
if h < 0.45:
|
||
return "GREEN"
|
||
if h < 0.72:
|
||
return "BLUE" # includes cyan/teal oneline colors
|
||
if h < 0.85:
|
||
return "MAGENTA"
|
||
return "RED"
|
||
|
||
|
||
def _rgb_key(rgb) -> tuple[int, int, int]:
|
||
"""RGB bytes for solid-fill hatch pattern color (keep original fill shade)."""
|
||
if not rgb or len(rgb) < 3:
|
||
return (0, 0, 0)
|
||
return _rgb01_to_bytes(float(rgb[0]), float(rgb[1]), float(rgb[2]))
|
||
|
||
|
||
def _ensure_layer(
|
||
doc: ezdxf.document.Drawing,
|
||
name: str,
|
||
rgb: tuple[int, int, int] | None = None,
|
||
aci: int | None = None,
|
||
) -> str:
|
||
"""Create layer if needed; set layer color (ByLayer entities inherit this)."""
|
||
if name not in doc.layers:
|
||
doc.layers.add(name)
|
||
layer = doc.layers.get(name)
|
||
if aci is not None:
|
||
layer.color = max(1, min(255, int(aci)))
|
||
if rgb is not None:
|
||
layer.rgb = (int(rgb[0]), int(rgb[1]), int(rgb[2]))
|
||
return name
|
||
|
||
|
||
def _family_layer(
|
||
doc: ezdxf.document.Drawing,
|
||
page_index: int,
|
||
family: str,
|
||
*,
|
||
is_fill: bool = False,
|
||
) -> str:
|
||
"""
|
||
Condensed layer name for electrical drawings.
|
||
|
||
Strokes: E_P1_GREEN, E_P1_GRAY, …
|
||
Fills: E_P1_FILL_GREEN (solid fills stay freeze-able separately)
|
||
"""
|
||
family = family if family in _LAYER_FAMILIES else "OTHER"
|
||
rgb, aci = _LAYER_FAMILIES[family]
|
||
if is_fill:
|
||
name = f"E_P{page_index + 1}_FILL_{family}"
|
||
else:
|
||
name = f"E_P{page_index + 1}_{family}"
|
||
return _ensure_layer(doc, name, rgb=rgb, aci=aci)
|
||
|
||
|
||
CURVE_SEGMENTS = 16 # denser Bézier tessellation for more detail
|
||
|
||
|
||
def _approx_cubic(
|
||
p0: tuple[float, float],
|
||
p1: tuple[float, float],
|
||
p2: tuple[float, float],
|
||
p3: tuple[float, float],
|
||
segments: int = CURVE_SEGMENTS,
|
||
) -> list[tuple[float, float]]:
|
||
pts: list[tuple[float, float]] = []
|
||
for i in range(1, segments + 1):
|
||
t = i / segments
|
||
u = 1.0 - t
|
||
x = (
|
||
u**3 * p0[0]
|
||
+ 3 * u**2 * t * p1[0]
|
||
+ 3 * u * t**2 * p2[0]
|
||
+ t**3 * p3[0]
|
||
)
|
||
y = (
|
||
u**3 * p0[1]
|
||
+ 3 * u**2 * t * p1[1]
|
||
+ 3 * u * t**2 * p2[1]
|
||
+ t**3 * p3[1]
|
||
)
|
||
pts.append((x, y))
|
||
return pts
|
||
|
||
|
||
def _pt_xy(pt) -> tuple[float, float]:
|
||
return (float(pt.x), float(pt.y))
|
||
|
||
|
||
def _extract_subpaths(items) -> list[list[tuple[float, float]]]:
|
||
"""Convert PyMuPDF path items into lists of polyline points (PDF coords)."""
|
||
subpaths: list[list[tuple[float, float]]] = []
|
||
current: list[tuple[float, float]] = []
|
||
|
||
def flush() -> None:
|
||
nonlocal current
|
||
if len(current) >= 2:
|
||
subpaths.append(current)
|
||
current = []
|
||
|
||
for item in items:
|
||
op = item[0]
|
||
if op == "l":
|
||
p1, p2 = item[1], item[2]
|
||
if not current:
|
||
current.append(_pt_xy(p1))
|
||
elif abs(current[-1][0] - p1.x) > 1e-6 or abs(current[-1][1] - p1.y) > 1e-6:
|
||
current.append(_pt_xy(p1))
|
||
current.append(_pt_xy(p2))
|
||
elif op == "c":
|
||
if len(item) >= 5:
|
||
p1, p2, p3, p4 = item[1], item[2], item[3], item[4]
|
||
if not current:
|
||
current.append(_pt_xy(p1))
|
||
elif abs(current[-1][0] - p1.x) > 1e-6 or abs(current[-1][1] - p1.y) > 1e-6:
|
||
current.append(_pt_xy(p1))
|
||
current.extend(
|
||
_approx_cubic(_pt_xy(p1), _pt_xy(p2), _pt_xy(p3), _pt_xy(p4))
|
||
)
|
||
elif len(item) == 4:
|
||
if not current:
|
||
continue
|
||
cp1, cp2, end = item[1], item[2], item[3]
|
||
current.extend(
|
||
_approx_cubic(current[-1], _pt_xy(cp1), _pt_xy(cp2), _pt_xy(end))
|
||
)
|
||
elif op == "re":
|
||
flush()
|
||
r = item[1]
|
||
x0, y0, x1, y1 = float(r.x0), float(r.y0), float(r.x1), float(r.y1)
|
||
subpaths.append(
|
||
[(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]
|
||
)
|
||
elif op == "qu":
|
||
flush()
|
||
try:
|
||
q = item[1]
|
||
pts = [_pt_xy(pt) for pt in q]
|
||
if pts:
|
||
if pts[0] != pts[-1]:
|
||
pts.append(pts[0])
|
||
subpaths.append(pts)
|
||
except Exception:
|
||
pass
|
||
elif op == "m":
|
||
flush()
|
||
current = [_pt_xy(item[1])]
|
||
|
||
flush()
|
||
return subpaths
|
||
|
||
|
||
def _to_cad_pts(
|
||
pts: list[tuple[float, float]],
|
||
tx,
|
||
ty,
|
||
) -> list[tuple[float, float]]:
|
||
return [(tx(x), ty(y)) for x, y in pts]
|
||
|
||
|
||
def _add_solid_hatch(
|
||
msp,
|
||
cad_paths: list[list[tuple[float, float]]],
|
||
layer: str,
|
||
fill_rgb,
|
||
even_odd: bool,
|
||
) -> int:
|
||
"""Add a solid HATCH on a condensed color family layer (entity color ByLayer)."""
|
||
closed_paths = []
|
||
for pts in cad_paths:
|
||
if len(pts) < 3:
|
||
continue
|
||
path = list(pts)
|
||
if path[0] != path[-1]:
|
||
path.append(path[0])
|
||
if len(path) >= 4:
|
||
closed_paths.append(path)
|
||
if not closed_paths:
|
||
return 0
|
||
|
||
rb = _rgb_key(fill_rgb)
|
||
hatch = msp.add_hatch(dxfattribs={"layer": layer, "color": BYLAYER})
|
||
hatch.set_solid_fill(color=7, style=0, rgb=rb)
|
||
|
||
for i, path in enumerate(closed_paths):
|
||
edge = path[:-1] if path[0] == path[-1] else path
|
||
flags = 1 if i == 0 else 0
|
||
hatch.paths.add_polyline_path(edge, is_closed=True, flags=flags)
|
||
if even_odd:
|
||
hatch.dxf.hatch_style = 0
|
||
return 1
|
||
|
||
|
||
def _drawings_count(page: fitz.Page) -> int:
|
||
try:
|
||
return len(page.get_drawings())
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
def _page_is_mostly_raster(page: fitz.Page, threshold: int) -> bool:
|
||
drawings = _drawings_count(page)
|
||
images = page.get_images(full=True)
|
||
if drawings < threshold and len(images) >= 1:
|
||
return True
|
||
if drawings == 0:
|
||
return True
|
||
return False
|
||
|
||
|
||
def _add_vector_page(
|
||
doc: ezdxf.document.Drawing,
|
||
page: fitz.Page,
|
||
page_index: int,
|
||
scale: float,
|
||
import_text: bool,
|
||
stack_offset_y: float,
|
||
ocr_text: bool = True,
|
||
ocr_dpi: float = 250.0,
|
||
) -> PageResult:
|
||
msp = doc.modelspace()
|
||
rect = page.rect
|
||
page_h = float(rect.height)
|
||
entity_count = 0
|
||
text_count = 0
|
||
|
||
def tx(x: float) -> float:
|
||
return x * scale
|
||
|
||
def ty(y: float) -> float:
|
||
return (_pdf_y_to_cad(y, page_h) + stack_offset_y) * scale
|
||
|
||
drawings = page.get_drawings()
|
||
try:
|
||
drawings = sorted(drawings, key=lambda d: d.get("seqno", 0))
|
||
except Exception:
|
||
pass
|
||
|
||
for path in drawings:
|
||
path_type = (path.get("type") or "s") or "s"
|
||
fill = path.get("fill")
|
||
stroke = path.get("color")
|
||
|
||
do_fill = (
|
||
"f" in path_type
|
||
and fill is not None
|
||
and not _is_wipeout_fill(fill)
|
||
)
|
||
do_stroke = "s" in path_type and stroke is not None
|
||
|
||
if "f" in path_type and not do_fill and not do_stroke:
|
||
continue
|
||
|
||
width = path.get("width")
|
||
line_width = float(width) * scale if width else 0.0
|
||
closed_hint = bool(path.get("closePath") or path.get("close_path"))
|
||
even_odd = bool(path.get("even_odd"))
|
||
|
||
subpaths = _extract_subpaths(path.get("items") or [])
|
||
if not subpaths:
|
||
continue
|
||
|
||
cad_paths = [_to_cad_pts(sp, tx, ty) for sp in subpaths]
|
||
|
||
if do_fill:
|
||
family = _classify_color(fill)
|
||
hatch_layer = _family_layer(doc, page_index, family, is_fill=True)
|
||
entity_count += _add_solid_hatch(
|
||
msp, cad_paths, hatch_layer, fill, even_odd
|
||
)
|
||
|
||
# Stroke linework on condensed family layers (ByLayer color)
|
||
if do_stroke:
|
||
family = _classify_color(stroke)
|
||
stroke_layer = _family_layer(doc, page_index, family, is_fill=False)
|
||
stroke_attribs = {"layer": stroke_layer, "color": BYLAYER}
|
||
for cad_pts in cad_paths:
|
||
if len(cad_pts) < 2:
|
||
continue
|
||
pts = list(cad_pts)
|
||
close = closed_hint
|
||
if close and pts[0] != pts[-1]:
|
||
pts.append(pts[0])
|
||
|
||
if len(pts) == 2 or (len(pts) == 3 and pts[0] == pts[-1]):
|
||
msp.add_line(pts[0], pts[1], dxfattribs=stroke_attribs)
|
||
else:
|
||
pline = msp.add_lwpolyline(
|
||
pts,
|
||
close=close,
|
||
dxfattribs=stroke_attribs,
|
||
)
|
||
if line_width > 0:
|
||
pline.dxf.const_width = max(line_width, 0.0)
|
||
entity_count += 1
|
||
|
||
if import_text:
|
||
try:
|
||
blocks = page.get_text("dict", flags=fitz.TEXT_PRESERVE_WHITESPACE)["blocks"]
|
||
except Exception:
|
||
blocks = []
|
||
|
||
text_layer = _ensure_layer(
|
||
doc,
|
||
f"E_P{page_index + 1}_TEXT",
|
||
aci=TEXT_ACI,
|
||
)
|
||
|
||
for block in blocks:
|
||
if block.get("type") != 0:
|
||
continue
|
||
for line in block.get("lines", []):
|
||
spans = line.get("spans", [])
|
||
if not spans:
|
||
continue
|
||
|
||
# PDF dir is in top-left Y-down space; flip Y for CAD rotation
|
||
direction = line.get("dir") or (1.0, 0.0)
|
||
dx = float(direction[0])
|
||
dy_pdf = float(direction[1])
|
||
rotation = math.degrees(math.atan2(-dy_pdf, dx))
|
||
if rotation > 180:
|
||
rotation -= 360
|
||
elif rotation <= -180:
|
||
rotation += 360
|
||
|
||
# One TEXT entity per span so font + size stay accurate
|
||
for span in spans:
|
||
text = (span.get("text") or "").strip()
|
||
if not text:
|
||
continue
|
||
|
||
style_name, font_file, width_factor = _resolve_font_style(
|
||
span.get("font") or "Arial",
|
||
int(span.get("flags") or 0),
|
||
)
|
||
_ensure_text_style(doc, style_name, font_file, width_factor)
|
||
|
||
height = _text_height_from_span(span, scale)
|
||
|
||
origin = span.get("origin")
|
||
if origin is not None:
|
||
insert = (tx(float(origin[0])), ty(float(origin[1])))
|
||
else:
|
||
bbox = span.get("bbox", (0, 0, 0, 0))
|
||
insert = (tx(bbox[0]), ty(bbox[3]))
|
||
|
||
msp.add_text(
|
||
text,
|
||
height=height,
|
||
dxfattribs={
|
||
"layer": text_layer,
|
||
"style": style_name,
|
||
"insert": insert,
|
||
"rotation": rotation,
|
||
"color": TEXT_ACI,
|
||
"width": width_factor,
|
||
},
|
||
)
|
||
entity_count += 1
|
||
text_count += 1
|
||
|
||
# Recover outlined / non-selectable text (common for equipment tags)
|
||
if ocr_text:
|
||
ocr_count = _add_ocr_text_entities(
|
||
doc,
|
||
msp,
|
||
page,
|
||
page_index,
|
||
scale,
|
||
stack_offset_y,
|
||
page_h,
|
||
ocr_dpi,
|
||
)
|
||
entity_count += ocr_count
|
||
text_count += ocr_count
|
||
|
||
return PageResult(
|
||
page_index=page_index,
|
||
mode_used="vector",
|
||
entity_count=entity_count,
|
||
text_count=text_count,
|
||
has_image=False,
|
||
)
|
||
|
||
|
||
def _add_vectorized_page(
|
||
doc: ezdxf.document.Drawing,
|
||
pdf: fitz.Document,
|
||
page: fitz.Page,
|
||
page_index: int,
|
||
scale: float,
|
||
stack_offset_y: float,
|
||
import_text: bool = True,
|
||
ocr_text: bool = True,
|
||
ocr_dpi: float = 250.0,
|
||
trace_detail: str = "high",
|
||
) -> PageResult:
|
||
"""Trace image-only / flattened drawing pages into editable polylines."""
|
||
msp = doc.modelspace()
|
||
rect = page.rect
|
||
page_h = float(rect.height)
|
||
entity_count = 0
|
||
text_count = 0
|
||
|
||
def tx(x: float) -> float:
|
||
return x * scale
|
||
|
||
def ty(y: float) -> float:
|
||
return (_pdf_y_to_cad(y, page_h) + stack_offset_y) * scale
|
||
|
||
layer = _family_layer(doc, page_index, "BLACK", is_fill=False)
|
||
attribs = {"layer": layer, "color": BYLAYER}
|
||
|
||
for path in vectorize_page(pdf, page, detail=trace_detail):
|
||
pts = [(tx(x), ty(y)) for x, y in path.points]
|
||
if len(pts) < 2:
|
||
continue
|
||
close = bool(path.closed)
|
||
if close and pts[0] != pts[-1]:
|
||
pts = pts + [pts[0]]
|
||
if len(pts) == 2 or (len(pts) == 3 and pts[0] == pts[-1]):
|
||
msp.add_line(pts[0], pts[1], dxfattribs=attribs)
|
||
else:
|
||
msp.add_lwpolyline(pts, close=close, dxfattribs=attribs)
|
||
entity_count += 1
|
||
|
||
if import_text and ocr_text:
|
||
ocr_count = _add_ocr_text_entities(
|
||
doc,
|
||
msp,
|
||
page,
|
||
page_index,
|
||
scale,
|
||
stack_offset_y,
|
||
page_h,
|
||
ocr_dpi,
|
||
)
|
||
entity_count += ocr_count
|
||
text_count += ocr_count
|
||
|
||
return PageResult(
|
||
page_index=page_index,
|
||
mode_used=f"vectorize:{trace_detail}",
|
||
entity_count=entity_count,
|
||
text_count=text_count,
|
||
has_image=False,
|
||
)
|
||
|
||
|
||
def _add_raster_page(
|
||
doc: ezdxf.document.Drawing,
|
||
page: fitz.Page,
|
||
page_index: int,
|
||
scale: float,
|
||
dpi: float,
|
||
stack_offset_y: float,
|
||
image_dir: Path,
|
||
) -> PageResult:
|
||
msp = doc.modelspace()
|
||
layer = f"PDF_Page_{page_index + 1}"
|
||
_ensure_layer(doc, layer)
|
||
|
||
rect = page.rect
|
||
page_w = float(rect.width)
|
||
page_h = float(rect.height)
|
||
|
||
zoom = dpi / 72.0
|
||
pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), alpha=False)
|
||
img_path = image_dir / f"page_{page_index + 1}.png"
|
||
pix.save(str(img_path))
|
||
|
||
# Image insert: lower-left at (0, stack_offset_y * scale), size = page size * scale
|
||
width = page_w * scale
|
||
height = page_h * scale
|
||
insert = (0.0, stack_offset_y * scale)
|
||
|
||
# ezdxf IMAGE requires an IMAGEDEF
|
||
image_def = doc.add_image_def(filename=str(img_path), size_in_pixel=(pix.width, pix.height))
|
||
msp.add_image(
|
||
insert=insert,
|
||
size_in_units=(width, height),
|
||
image_def=image_def,
|
||
rotation=0,
|
||
dxfattribs={"layer": layer},
|
||
)
|
||
|
||
# Outline rectangle for reference
|
||
msp.add_lwpolyline(
|
||
[
|
||
(insert[0], insert[1]),
|
||
(insert[0] + width, insert[1]),
|
||
(insert[0] + width, insert[1] + height),
|
||
(insert[0], insert[1] + height),
|
||
(insert[0], insert[1]),
|
||
],
|
||
dxfattribs={"layer": layer, "color": 8},
|
||
)
|
||
|
||
return PageResult(
|
||
page_index=page_index,
|
||
mode_used="raster",
|
||
entity_count=2,
|
||
text_count=0,
|
||
has_image=True,
|
||
)
|
||
|
||
|
||
def convert_pdf_to_dxf(
|
||
pdf_path: str | Path,
|
||
output_path: str | Path,
|
||
options: ConvertOptions | None = None,
|
||
) -> ConvertResult:
|
||
"""Convert selected PDF pages to a DXF file."""
|
||
options = options or ConvertOptions()
|
||
pdf_path = Path(pdf_path)
|
||
output_path = Path(output_path)
|
||
|
||
pdf = open_input_document(pdf_path)
|
||
try:
|
||
indices = _page_indices(pdf, options.pages)
|
||
if not indices:
|
||
raise ValueError("No valid pages selected for conversion.")
|
||
|
||
dxf = ezdxf.new(dxfversion=options.dxf_version)
|
||
dxf.units = units.MM
|
||
dxf.header["$INSUNITS"] = 4 # millimeters
|
||
|
||
results: list[PageResult] = []
|
||
stack_offset_y = 0.0
|
||
gap_factor = 1.15
|
||
|
||
# Images for IMAGE entities should live next to the DXF so relative paths work
|
||
image_dir = output_path.parent / f"{output_path.stem}_images"
|
||
page_modes = options.page_modes or {}
|
||
|
||
def resolve_mode(page_index: int, mostly_raster: bool, has_images: bool) -> str:
|
||
override = (page_modes.get(page_index) or "").strip().lower()
|
||
if override in ("vector", "vectorize", "raster", "skip"):
|
||
return override
|
||
if options.mode == ConvertMode.RASTER:
|
||
return "raster"
|
||
if options.mode == ConvertMode.VECTORIZE:
|
||
return "vectorize"
|
||
if options.mode == ConvertMode.VECTOR:
|
||
return "vector"
|
||
# AUTO
|
||
if mostly_raster and has_images:
|
||
return "vectorize"
|
||
return "vector"
|
||
|
||
for page_index in indices:
|
||
page = pdf.load_page(page_index)
|
||
page_h = float(page.rect.height)
|
||
|
||
drawings = _drawings_count(page)
|
||
has_images = bool(page.get_images(full=True))
|
||
mostly_raster = _page_is_mostly_raster(page, options.vector_threshold)
|
||
page_mode = resolve_mode(page_index, mostly_raster, has_images)
|
||
|
||
if page_mode == "skip":
|
||
continue
|
||
|
||
if page_mode == "raster":
|
||
if not image_dir.exists():
|
||
image_dir.mkdir(parents=True, exist_ok=True)
|
||
result = _add_raster_page(
|
||
dxf,
|
||
page,
|
||
page_index,
|
||
options.scale,
|
||
options.dpi,
|
||
stack_offset_y,
|
||
image_dir,
|
||
)
|
||
elif page_mode == "vectorize":
|
||
result = _add_vectorized_page(
|
||
dxf,
|
||
pdf,
|
||
page,
|
||
page_index,
|
||
options.scale,
|
||
stack_offset_y,
|
||
import_text=options.import_text,
|
||
ocr_text=options.ocr_text and options.import_text,
|
||
ocr_dpi=options.ocr_dpi,
|
||
trace_detail=options.trace_detail,
|
||
)
|
||
if result.entity_count == 0 and has_images:
|
||
if not image_dir.exists():
|
||
image_dir.mkdir(parents=True, exist_ok=True)
|
||
result = _add_raster_page(
|
||
dxf,
|
||
page,
|
||
page_index,
|
||
options.scale,
|
||
options.dpi,
|
||
stack_offset_y,
|
||
image_dir,
|
||
)
|
||
else:
|
||
# Native PDF vectors
|
||
result = _add_vector_page(
|
||
dxf,
|
||
page,
|
||
page_index,
|
||
options.scale,
|
||
options.import_text,
|
||
stack_offset_y,
|
||
ocr_text=options.ocr_text and options.import_text,
|
||
ocr_dpi=options.ocr_dpi,
|
||
)
|
||
# Only auto-fallback when no explicit per-page choice was made
|
||
explicit = page_index in page_modes
|
||
if (
|
||
not explicit
|
||
and options.mode == ConvertMode.AUTO
|
||
and result.entity_count == 0
|
||
and has_images
|
||
):
|
||
result = _add_vectorized_page(
|
||
dxf,
|
||
pdf,
|
||
page,
|
||
page_index,
|
||
options.scale,
|
||
stack_offset_y,
|
||
import_text=options.import_text,
|
||
ocr_text=options.ocr_text and options.import_text,
|
||
ocr_dpi=options.ocr_dpi,
|
||
trace_detail=options.trace_detail,
|
||
)
|
||
|
||
results.append(result)
|
||
stack_offset_y -= page_h * gap_factor
|
||
|
||
if not results:
|
||
raise ValueError("No pages were converted (all skipped?).")
|
||
|
||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||
dxf.saveas(str(output_path))
|
||
|
||
# Clean up empty image dir
|
||
if image_dir.exists() and not any(image_dir.iterdir()):
|
||
try:
|
||
image_dir.rmdir()
|
||
except OSError:
|
||
pass
|
||
|
||
return ConvertResult(output_path=output_path, pages=results)
|
||
finally:
|
||
pdf.close()
|
||
|
||
|
||
def parse_page_range(spec: str, page_count: int) -> list[int] | None:
|
||
"""
|
||
Parse a page range string like '1,3-5' into 0-based indices.
|
||
Empty / 'all' → None (all pages).
|
||
"""
|
||
spec = (spec or "").strip().lower()
|
||
if not spec or spec == "all":
|
||
return None
|
||
|
||
indices: set[int] = set()
|
||
for part in spec.split(","):
|
||
part = part.strip()
|
||
if not part:
|
||
continue
|
||
if "-" in part:
|
||
a, b = part.split("-", 1)
|
||
start = int(a.strip())
|
||
end = int(b.strip())
|
||
if start > end:
|
||
start, end = end, start
|
||
for p in range(start, end + 1):
|
||
if 1 <= p <= page_count:
|
||
indices.add(p - 1)
|
||
else:
|
||
p = int(part)
|
||
if 1 <= p <= page_count:
|
||
indices.add(p - 1)
|
||
|
||
return sorted(indices)
|