commit 91625af67fc05bb526bbbda9c6d64c3bde39488d Author: Michael Sloan Date: Thu Jul 30 13:14:57 2026 -0400 Add portable PDF to DXF converter for BricsCAD workflows. Includes vector/vectorize/raster modes, page review before convert, bundled OCR data, and a single-file AppData launcher build. Co-authored-by: Cursor diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9dcd9be --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.venv/ +__pycache__/ +*.pyc +build/ +dist/ +*.spec +*.dxf +*_images/ +.pytest_cache/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..1eb3da8 --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# PDF to DXF Converter + +Windows desktop app that converts PDF drawings to **DXF** for BricsCAD (and other CAD software), with a live page preview. Optionally saves **DWG** through your installed BricsCAD. + +## Features + +- PDF page preview with previous/next navigation +- Conversion modes: **auto**, **vector**, **vectorize**, **raster** +- True vector PDFs → editable lines/polylines/text in DXF +- Flattened / image-only drawing PDFs → traced to editable polylines (`vectorize`) +- Optional raster underlay mode for scans you want as images +- Optional DWG export via BricsCAD `SAVEAS` + +## Requirements + +- Windows 10/11 +- Python 3.10+ (for development) +- BricsCAD (optional, only needed for DWG export) + +## Run from source + +```powershell +cd "PDF to DWG converter" +python -m venv .venv +.\.venv\Scripts\Activate.ps1 +pip install -r requirements.txt +python main.py +``` + +## Build the EXE + +```powershell +.\build_exe.ps1 +``` + +Output (share this one file): +- `dist\PDF_to_DXF.exe` — single EXE, no `_internal` folder to copy + +On first run it installs into `%LOCALAPPDATA%\PDF_to_DXF\app\`. Later launches reuse that install. + +## Share with other PCs (no Python needed) + +1. Send **`PDF_to_DXF.exe`** only +2. They double-click it (first run shows a short setup into AppData) +3. Done + +OCR language data is bundled — no separate Tesseract install. +Optional only: BricsCAD for DWG save. + +## Usage + +1. Click **Open PDF…** and pick a file +2. Preview pages with ◀ / ▶ +3. Choose mode (`auto` recommended), pages, and scale (1.0 = PDF size; use your own multiplier) +4. Click **Convert & Save…** — review each page (vector / image / vectorize / skip), then pick the DXF path +5. Optionally enable **Also save DWG via BricsCAD** + +### Modes + +| Mode | Best for | Result | +|------|----------|--------| +| `auto` | Mixed PDFs | Native vectors when present; traces image-only drawing pages | +| `vector` | CAD-exported PDFs | Editable geometry and text (traces if the page is only a bitmap) | +| `vectorize` | Flattened / printed drawing PDFs | Raster-to-vector polylines (set **Trace detail** to high/maximum) | +| `raster` | Photos / underlays | Full-page image in the DXF | + +### BricsCAD DWG + +If BricsCAD is installed in a standard location, it is detected automatically. To override: + +```powershell +$env:BRICSCAD_PATH = "C:\Program Files\Bricsys\BricsCAD V25 en_US\bricscad.exe" +``` + +## Notes + +- DXF is the primary format; BricsCAD opens it natively. +- Scanned pages become image underlays in v1 (not commercial-grade auto-trace). +- Raster/hybrid conversions write images next to the DXF in a `*_images` folder — keep that folder with the DXF when moving files. diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..1e45235 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,3 @@ +"""PDF to DXF converter application package.""" + +__version__ = "1.4.1" diff --git a/app/bricscad_export.py b/app/bricscad_export.py new file mode 100644 index 0000000..be797bc --- /dev/null +++ b/app/bricscad_export.py @@ -0,0 +1,219 @@ +"""Detect BricsCAD and optionally convert DXF to DWG via scripted SAVEAS.""" + +from __future__ import annotations + +import os +import subprocess +import tempfile +import time +import winreg +from pathlib import Path + + +COMMON_BRICSCAD_PATHS = [ + r"C:\Program Files\Bricsys\BricsCAD V26 en_US\bricscad.exe", + r"C:\Program Files\Bricsys\BricsCAD V25 en_US\bricscad.exe", + r"C:\Program Files\Bricsys\BricsCAD V24 en_US\bricscad.exe", + r"C:\Program Files\Bricsys\BricsCAD V23 en_US\bricscad.exe", + r"C:\Program Files\Bricsys\BricsCAD V22 en_US\bricscad.exe", + r"C:\Program Files\Bricsys\BricsCAD V21 en_US\bricscad.exe", + r"C:\Program Files\Bricsys\BricsCAD V20 en_US\bricscad.exe", + r"C:\Program Files (x86)\Bricsys\BricsCAD V26 en_US\bricscad.exe", + r"C:\Program Files (x86)\Bricsys\BricsCAD V25 en_US\bricscad.exe", +] + + +def _registry_bricscad() -> Path | None: + """Try to find BricsCAD.exe via Windows uninstall / App Paths registry.""" + roots = [ + (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Bricsys"), + (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Bricsys"), + (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Bricsys"), + ] + for root, subkey in roots: + try: + with winreg.OpenKey(root, subkey) as key: + i = 0 + while True: + try: + name = winreg.EnumKey(key, i) + except OSError: + break + i += 1 + try: + with winreg.OpenKey(key, name) as ver_key: + for value_name in ("InstallDir", "InstallPath", "Path"): + try: + val, _ = winreg.QueryValueEx(ver_key, value_name) + exe = Path(val) / "bricscad.exe" + if exe.is_file(): + return exe + except OSError: + continue + # Sometimes the key itself points at the install folder + try: + default, _ = winreg.QueryValueEx(ver_key, None) + if default: + exe = Path(default) / "bricscad.exe" + if exe.is_file(): + return exe + except OSError: + pass + except OSError: + continue + except OSError: + continue + + # App Paths + try: + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\bricscad.exe", + ) as key: + val, _ = winreg.QueryValueEx(key, None) + exe = Path(val) + if exe.is_file(): + return exe + except OSError: + pass + + return None + + +def _scan_bricsys_folders() -> Path | None: + bases = [ + Path(r"C:\Program Files\Bricsys"), + Path(r"C:\Program Files (x86)\Bricsys"), + ] + found: list[Path] = [] + for base in bases: + if not base.is_dir(): + continue + for child in base.iterdir(): + if not child.is_dir(): + continue + exe = child / "bricscad.exe" + if exe.is_file(): + found.append(exe) + if not found: + return None + # Prefer highest version-looking folder name + found.sort(key=lambda p: p.parent.name, reverse=True) + return found[0] + + +def find_bricscad() -> Path | None: + """Locate BricsCAD.exe on this machine, or return None.""" + env = os.environ.get("BRICSCAD_PATH") + if env: + p = Path(env) + if p.is_file(): + return p + + for candidate in COMMON_BRICSCAD_PATHS: + p = Path(candidate) + if p.is_file(): + return p + + reg = _registry_bricscad() + if reg: + return reg + + return _scan_bricsys_folders() + + +def is_bricscad_available() -> bool: + return find_bricscad() is not None + + +def dxf_to_dwg( + dxf_path: str | Path, + dwg_path: str | Path | None = None, + bricscad_exe: str | Path | None = None, + timeout_sec: float = 120.0, +) -> Path: + """ + Open a DXF in BricsCAD and SAVEAS to DWG, then quit. + + Uses a temporary AutoLISP/script file passed with /b (batch script). + """ + dxf_path = Path(dxf_path).resolve() + if not dxf_path.is_file(): + raise FileNotFoundError(f"DXF not found: {dxf_path}") + + if dwg_path is None: + dwg_path = dxf_path.with_suffix(".dwg") + else: + dwg_path = Path(dwg_path).resolve() + + exe = Path(bricscad_exe) if bricscad_exe else find_bricscad() + if exe is None or not exe.is_file(): + raise FileNotFoundError( + "BricsCAD was not found. Install BricsCAD or set BRICSCAD_PATH." + ) + + # BricsCAD script: open DXF, save as DWG, quit + # Use forward slashes in paths for script compatibility + dxf_s = str(dxf_path).replace("\\", "/") + dwg_s = str(dwg_path).replace("\\", "/") + + script_lines = [ + f'_.OPEN "{dxf_s}"', + f'_.SAVEAS 2013 "{dwg_s}"', + "_.QUIT", + "", + ] + + with tempfile.NamedTemporaryFile( + mode="w", + suffix=".scr", + delete=False, + encoding="utf-8", + newline="\n", + ) as tmp: + tmp.write("\n".join(script_lines)) + script_path = Path(tmp.name) + + try: + # /b runs a script; /nologo reduces splash noise when supported + cmd = [str(exe), "/b", str(script_path)] + proc = subprocess.Popen( + cmd, + cwd=str(dxf_path.parent), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + deadline = time.time() + timeout_sec + while time.time() < deadline: + if proc.poll() is not None: + break + if dwg_path.is_file() and dwg_path.stat().st_size > 0: + # Give BricsCAD a moment to finish writing, then try to close + time.sleep(1.5) + if proc.poll() is None: + try: + proc.terminate() + except Exception: + pass + break + time.sleep(0.5) + else: + try: + proc.kill() + except Exception: + pass + raise TimeoutError( + f"BricsCAD did not finish converting within {timeout_sec:.0f}s." + ) + + if not dwg_path.is_file(): + raise RuntimeError( + "BricsCAD finished but the DWG file was not created. " + "Try opening the DXF manually and using SAVEAS." + ) + return dwg_path + finally: + try: + script_path.unlink(missing_ok=True) + except OSError: + pass diff --git a/app/converter.py b/app/converter.py new file mode 100644 index 0000000..359b1e4 --- /dev/null +++ b/app/converter.py @@ -0,0 +1,1301 @@ +"""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.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( + pdf_path: str | Path, + pages: list[int] | None = None, + *, + vector_threshold: int = 20, +) -> list[PageClassification]: + """Classify selected pages of a PDF for the pre-convert review dialog.""" + pdf = fitz.open(str(pdf_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 = fitz.open(str(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) diff --git a/app/ocr_support.py b/app/ocr_support.py new file mode 100644 index 0000000..d561bc4 --- /dev/null +++ b/app/ocr_support.py @@ -0,0 +1,67 @@ +"""Locate bundled Tesseract language data (no separate Tesseract install).""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + + +def resolve_tessdata_dir() -> Path | None: + """Return folder containing eng.traineddata, or None.""" + candidates: list[Path] = [] + + if getattr(sys, "frozen", False): + meipass = Path(getattr(sys, "_MEIPASS", Path(sys.executable).parent)) + exe_dir = Path(sys.executable).resolve().parent + candidates.extend( + [ + meipass / "tessdata", + exe_dir / "_internal" / "tessdata", + exe_dir / "tessdata", + ] + ) + else: + root = Path(__file__).resolve().parent.parent + candidates.append(root / "vendor" / "tessdata") + + # Also honor an explicit env override + env = os.environ.get("TESSDATA_PREFIX") + if env: + candidates.insert(0, Path(env)) + + for path in candidates: + try: + if (path / "eng.traineddata").is_file(): + return path.resolve() + except OSError: + continue + return None + + +def configure_bundled_ocr() -> Path | None: + """ + Point PyMuPDF / MuPDF OCR at our shipped tessdata. + + Call before OCR runs (ideally at process start). Returns the tessdata + path when available. + """ + tessdata = resolve_tessdata_dir() + if tessdata is None: + return None + # MuPDF / PyMuPDF read this when tessdata= is omitted; we also pass it + # explicitly in converter OCR calls. + os.environ["TESSDATA_PREFIX"] = str(tessdata) + try: + import fitz + + fitz.TESSDATA_PREFIX = str(tessdata) # type: ignore[attr-defined] + except Exception: + pass + return tessdata + + +def tessdata_arg() -> str | None: + """Value for get_textpage_ocr(..., tessdata=...).""" + path = resolve_tessdata_dir() + return str(path) if path else None diff --git a/app/page_review.py b/app/page_review.py new file mode 100644 index 0000000..0df0eae --- /dev/null +++ b/app/page_review.py @@ -0,0 +1,234 @@ +"""Pre-convert dialog: show what each PDF page is and ask how to handle it.""" + +from __future__ import annotations + +import customtkinter as ctk + +from app.converter import PageClassification + + +# UI label → internal mode key +ACTION_CHOICES: list[tuple[str, str]] = [ + ("Native vectors", "vector"), + ("Vectorize (trace lines)", "vectorize"), + ("Keep as image", "raster"), + ("Skip page", "skip"), +] +LABEL_BY_MODE = {mode: label for label, mode in ACTION_CHOICES} +MODE_BY_LABEL = {label: mode for label, mode in ACTION_CHOICES} + + +class PageReviewDialog(ctk.CTkToplevel): + """ + Modal review of each selected page. + Result: dict[page_index, mode] or None if cancelled. + """ + + def __init__( + self, + master, + classifications: list[PageClassification], + *, + default_mode: str | None = None, + ) -> None: + super().__init__(master) + self.title("Review pages before convert") + self.geometry("720x520") + self.minsize(640, 420) + self.transient(master) + self.grab_set() + self.result: dict[int, str] | None = None + self._vars: dict[int, ctk.StringVar] = {} + self._detail_labels: list[ctk.CTkLabel] = [] + self._intro_label: ctk.CTkLabel | None = None + + ctk.CTkLabel( + self, + text="Confirm how each page should be converted", + font=ctk.CTkFont(size=16, weight="bold"), + ).pack(padx=16, pady=(16, 4), anchor="w", fill="x") + + self._intro_label = ctk.CTkLabel( + self, + text=( + "Detected type is shown for each page. Change the action if you want " + "to keep a page as an image, force vectorize, or skip it." + ), + wraplength=680, + justify="left", + text_color=("gray30", "gray70"), + ) + self._intro_label.pack(padx=16, pady=(0, 10), anchor="w", fill="x") + + scroll = ctk.CTkScrollableFrame(self) + scroll.pack(fill="both", expand=True, padx=16, pady=4) + + # Header + header = ctk.CTkFrame(scroll, fg_color="transparent") + header.pack(fill="x", pady=(0, 6)) + ctk.CTkLabel(header, text="Page", width=50, anchor="w").pack(side="left") + ctk.CTkLabel(header, text="Detected", width=200, anchor="w").pack(side="left") + ctk.CTkLabel(header, text="Action", anchor="w").pack( + side="left", fill="x", expand=True + ) + + for info in classifications: + row = ctk.CTkFrame(scroll) + row.pack(fill="x", pady=4) + + ctk.CTkLabel( + row, + text=str(info.page_index + 1), + width=50, + anchor="w", + font=ctk.CTkFont(weight="bold"), + ).pack(side="left", padx=(8, 0), pady=8) + + detected = ctk.CTkFrame(row, fg_color="transparent") + detected.pack(side="left", fill="x", expand=True, padx=8, pady=6) + ctk.CTkLabel( + detected, + text=info.label, + anchor="w", + font=ctk.CTkFont(size=13, weight="bold"), + ).pack(anchor="w", fill="x") + detail = ctk.CTkLabel( + detected, + text=info.detail, + anchor="w", + wraplength=360, + justify="left", + font=ctk.CTkFont(size=11), + text_color=("gray35", "gray65"), + ) + detail.pack(anchor="w", fill="x") + self._detail_labels.append(detail) + + suggested = default_mode if default_mode in LABEL_BY_MODE else info.suggested + if suggested not in LABEL_BY_MODE: + suggested = info.suggested + var = ctk.StringVar( + value=LABEL_BY_MODE.get(suggested, "Vectorize (trace lines)") + ) + self._vars[info.page_index] = var + menu = ctk.CTkOptionMenu( + row, + variable=var, + values=[label for label, _ in ACTION_CHOICES], + width=200, + ) + menu.pack(side="right", padx=8, pady=8) + + # Quick actions + quick = ctk.CTkFrame(self, fg_color="transparent") + quick.pack(fill="x", padx=16, pady=(8, 0)) + ctk.CTkButton( + quick, + text="All → Vectorize", + width=120, + fg_color="transparent", + border_width=1, + command=lambda: self._set_all("vectorize"), + ).pack(side="left", padx=(0, 6)) + ctk.CTkButton( + quick, + text="All → Image", + width=110, + fg_color="transparent", + border_width=1, + command=lambda: self._set_all("raster"), + ).pack(side="left", padx=(0, 6)) + ctk.CTkButton( + quick, + text="Reset suggested", + width=120, + fg_color="transparent", + border_width=1, + command=lambda: self._reset_suggested(classifications), + ).pack(side="left") + + buttons = ctk.CTkFrame(self, fg_color="transparent") + buttons.pack(fill="x", padx=16, pady=16) + ctk.CTkButton( + buttons, + text="Cancel", + width=100, + fg_color="transparent", + border_width=1, + command=self._cancel, + ).pack(side="right", padx=(8, 0)) + ctk.CTkButton( + buttons, + text="Continue…", + width=120, + command=self._confirm, + ).pack(side="right") + + self.protocol("WM_DELETE_WINDOW", self._cancel) + self.bind("", lambda _e: self._cancel()) + self.bind("", self._on_resize) + self.after(50, self._focus) + + def _on_resize(self, _event) -> None: + try: + width = max(self.winfo_width() - 48, 280) + except Exception: + return + if self._intro_label is not None: + try: + self._intro_label.configure(wraplength=width) + except Exception: + pass + detail_wrap = max(width - 280, 180) + for label in self._detail_labels: + try: + label.configure(wraplength=detail_wrap) + except Exception: + pass + + def _focus(self) -> None: + try: + self.lift() + self.focus_force() + except Exception: + pass + + def _set_all(self, mode: str) -> None: + label = LABEL_BY_MODE.get(mode) + if not label: + return + for var in self._vars.values(): + var.set(label) + + def _reset_suggested(self, classifications: list[PageClassification]) -> None: + for info in classifications: + var = self._vars.get(info.page_index) + if var: + var.set(LABEL_BY_MODE.get(info.suggested, "Vectorize (trace lines)")) + + def _confirm(self) -> None: + out: dict[int, str] = {} + for page_index, var in self._vars.items(): + out[page_index] = MODE_BY_LABEL.get(var.get(), "vectorize") + self.result = out + self.grab_release() + self.destroy() + + def _cancel(self) -> None: + self.result = None + self.grab_release() + self.destroy() + + +def ask_page_modes( + master, + classifications: list[PageClassification], + *, + default_mode: str | None = None, +) -> dict[int, str] | None: + """Show modal page review; return chosen modes or None if cancelled.""" + if not classifications: + return {} + dialog = PageReviewDialog(master, classifications, default_mode=default_mode) + master.wait_window(dialog) + return dialog.result diff --git a/app/pdf_preview.py b/app/pdf_preview.py new file mode 100644 index 0000000..cad1ed1 --- /dev/null +++ b/app/pdf_preview.py @@ -0,0 +1,45 @@ +"""PDF page rendering for UI preview.""" + +from __future__ import annotations + +from pathlib import Path + +import fitz +from PIL import Image + + +def open_document(path: str | Path) -> fitz.Document: + return fitz.open(str(path)) + + +def page_count(doc: fitz.Document) -> int: + return doc.page_count + + +def render_page( + doc: fitz.Document, + page_index: int, + max_width: int = 900, + max_height: int = 700, + dpi: float = 120.0, +) -> Image.Image: + """Render a PDF page to a Pillow RGB image, scaled to fit max dimensions.""" + if page_index < 0 or page_index >= doc.page_count: + raise IndexError(f"Page index {page_index} out of range (0..{doc.page_count - 1})") + + page = doc.load_page(page_index) + zoom = dpi / 72.0 + mat = fitz.Matrix(zoom, zoom) + pix = page.get_pixmap(matrix=mat, alpha=False) + + image = Image.frombytes("RGB", (pix.width, pix.height), pix.samples) + + if image.width > max_width or image.height > max_height: + image.thumbnail((max_width, max_height), Image.Resampling.LANCZOS) + + return image + + +def close_document(doc: fitz.Document | None) -> None: + if doc is not None: + doc.close() diff --git a/app/raster_vectorize.py b/app/raster_vectorize.py new file mode 100644 index 0000000..104cdc8 --- /dev/null +++ b/app/raster_vectorize.py @@ -0,0 +1,271 @@ +"""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 diff --git a/app/ui.py b/app/ui.py new file mode 100644 index 0000000..c82b54b --- /dev/null +++ b/app/ui.py @@ -0,0 +1,483 @@ +"""Main CustomTkinter UI for PDF to DXF conversion.""" + +from __future__ import annotations + +import threading +from pathlib import Path +from tkinter import filedialog, messagebox + +import customtkinter as ctk +from app import __version__ +from app.bricscad_export import dxf_to_dwg, find_bricscad, is_bricscad_available +from app.converter import ( + ConvertMode, + ConvertOptions, + classify_pdf_pages, + convert_pdf_to_dxf, + parse_page_range, +) +from app.page_review import ask_page_modes +from app.pdf_preview import close_document, open_document, page_count, render_page + + +ctk.set_appearance_mode("System") +ctk.set_default_color_theme("blue") + + +class App(ctk.CTk): + def __init__(self) -> None: + super().__init__() + self.title(f"PDF to DXF Converter v{__version__}") + self.geometry("1100x720") + self.minsize(800, 520) + + self._doc = None + self._pdf_path: Path | None = None + self._page_index = 0 + self._preview_photo = None + self._busy = False + self._resize_after: str | None = None + self._last_preview_size = (0, 0) + self._wrap_labels: list[ctk.CTkLabel] = [] + + self._bricscad_path = find_bricscad() + self._build_ui() + self._update_bricscad_ui() + self.bind("", self._on_window_configure) + + def _build_ui(self) -> None: + # Left sidebar ~1/3, preview ~2/3 — both grow with the window + self.grid_columnconfigure(0, weight=1, minsize=280, uniform="cols") + self.grid_columnconfigure(1, weight=2, minsize=360, uniform="cols") + self.grid_rowconfigure(0, weight=1) + + # —— Left controls —— + left = ctk.CTkFrame(self, corner_radius=0) + left.grid(row=0, column=0, sticky="nsew") + left.grid_rowconfigure(0, weight=1) + left.grid_columnconfigure(0, weight=1) + self._left = left + + # Scrollable options area (grows/shrinks with height) + scroll = ctk.CTkScrollableFrame(left, fg_color="transparent") + scroll.grid(row=0, column=0, sticky="nsew", padx=0, pady=0) + scroll.grid_columnconfigure(0, weight=1) + self._left_scroll = scroll + + ctk.CTkLabel( + scroll, + text="PDF → DXF", + font=ctk.CTkFont(size=22, weight="bold"), + ).pack(padx=16, pady=(16, 4), anchor="w", fill="x") + + self._add_wrap_label( + scroll, + "Preview & convert for BricsCAD", + font=ctk.CTkFont(size=12), + text_color=("gray40", "gray70"), + pady=(0, 12), + ) + + ctk.CTkButton(scroll, text="Open PDF…", command=self._open_pdf).pack( + padx=16, pady=6, fill="x" + ) + + self.file_label = self._add_wrap_label( + scroll, + "No file loaded", + pady=(4, 12), + ) + + nav = ctk.CTkFrame(scroll, fg_color="transparent") + nav.pack(padx=16, pady=4, fill="x") + ctk.CTkButton(nav, text="◀", width=40, command=self._prev_page).pack(side="left") + self.page_label = ctk.CTkLabel(nav, text="Page — / —") + self.page_label.pack(side="left", expand=True, fill="x") + ctk.CTkButton(nav, text="▶", width=40, command=self._next_page).pack(side="right") + + ctk.CTkLabel(scroll, text="Conversion mode", anchor="w").pack( + padx=16, pady=(16, 2), fill="x" + ) + self.mode_var = ctk.StringVar(value="auto") + self.mode_menu = ctk.CTkOptionMenu( + scroll, + variable=self.mode_var, + values=["auto", "vector", "vectorize", "raster"], + ) + self.mode_menu.pack(padx=16, pady=4, fill="x") + + ctk.CTkLabel(scroll, text="Trace detail (image drawings)", anchor="w").pack( + padx=16, pady=(12, 2), fill="x" + ) + self.trace_detail_var = ctk.StringVar(value="high") + self.trace_detail_menu = ctk.CTkOptionMenu( + scroll, + variable=self.trace_detail_var, + values=["normal", "high", "maximum"], + ) + self.trace_detail_menu.pack(padx=16, pady=4, fill="x") + self._add_wrap_label( + scroll, + "Use maximum for finest linework (slower, larger DXF)", + font=ctk.CTkFont(size=11), + text_color=("gray40", "gray70"), + pady=(0, 4), + ) + + ctk.CTkLabel( + scroll, + text="Pages (e.g. all, 1, 1-3, 1,3-5)", + anchor="w", + ).pack(padx=16, pady=(12, 2), fill="x") + self.pages_entry = ctk.CTkEntry(scroll, placeholder_text="all") + self.pages_entry.pack(padx=16, pady=4, fill="x") + self.pages_entry.insert(0, "all") + + ctk.CTkButton( + scroll, + text="Use current page only", + fg_color="transparent", + border_width=1, + command=self._use_current_page, + ).pack(padx=16, pady=4, fill="x") + + ctk.CTkLabel(scroll, text="Scale", anchor="w").pack( + padx=16, pady=(12, 2), fill="x" + ) + self.scale_entry = ctk.CTkEntry(scroll) + self.scale_entry.pack(padx=16, pady=4, fill="x") + self.scale_entry.insert(0, "1.0") + self._add_wrap_label( + scroll, + "Your multiplier (1.0 = PDF size as-is)", + font=ctk.CTkFont(size=11), + text_color=("gray40", "gray70"), + pady=(0, 4), + ) + + self.import_text_var = ctk.BooleanVar(value=True) + ctk.CTkCheckBox( + scroll, + text="Import text (vector mode)", + variable=self.import_text_var, + ).pack(padx=16, pady=(12, 4), anchor="w", fill="x") + + self.ocr_text_var = ctk.BooleanVar(value=True) + ctk.CTkCheckBox( + scroll, + text="OCR outlined text (built-in)", + variable=self.ocr_text_var, + ).pack(padx=16, pady=4, anchor="w", fill="x") + + self.save_dwg_var = ctk.BooleanVar(value=False) + self.dwg_check = ctk.CTkCheckBox( + scroll, + text="Also save DWG via BricsCAD", + variable=self.save_dwg_var, + ) + self.dwg_check.pack(padx=16, pady=4, anchor="w", fill="x") + + self.brics_label = self._add_wrap_label( + scroll, + "", + font=ctk.CTkFont(size=11), + text_color=("gray40", "gray70"), + pady=(0, 8), + ) + + # Bottom bar stays visible while options scroll + bottom = ctk.CTkFrame(left, fg_color="transparent") + bottom.grid(row=1, column=0, sticky="ew", padx=0, pady=0) + bottom.grid_columnconfigure(0, weight=1) + + self.convert_btn = ctk.CTkButton( + bottom, + text="Convert & Save…", + height=40, + font=ctk.CTkFont(size=14, weight="bold"), + command=self._convert, + ) + self.convert_btn.pack(padx=16, pady=(12, 6), fill="x") + + self.status_label = self._add_wrap_label( + bottom, + "Ready", + font=ctk.CTkFont(size=11), + pady=(0, 12), + parent_is_pack=True, + ) + + # —— Right preview —— + right = ctk.CTkFrame(self, corner_radius=0) + right.grid(row=0, column=1, sticky="nsew") + right.grid_rowconfigure(0, weight=1) + right.grid_columnconfigure(0, weight=1) + + self.preview_frame = ctk.CTkFrame(right) + self.preview_frame.grid(row=0, column=0, sticky="nsew", padx=12, pady=12) + self.preview_frame.grid_rowconfigure(0, weight=1) + self.preview_frame.grid_columnconfigure(0, weight=1) + + self.preview_label = ctk.CTkLabel( + self.preview_frame, + text="Open a PDF to see a preview", + text_color=("gray40", "gray60"), + ) + self.preview_label.grid(row=0, column=0, sticky="nsew") + + self.preview_frame.bind("", self._on_preview_configure) + + self.protocol("WM_DELETE_WINDOW", self._on_close) + + def _add_wrap_label( + self, + parent, + text: str, + *, + font=None, + text_color=None, + pady=(0, 0), + parent_is_pack: bool = True, + ) -> ctk.CTkLabel: + kwargs = { + "text": text, + "wraplength": 240, + "justify": "left", + "anchor": "w", + } + if font is not None: + kwargs["font"] = font + if text_color is not None: + kwargs["text_color"] = text_color + label = ctk.CTkLabel(parent, **kwargs) + if parent_is_pack: + label.pack(padx=16, pady=pady, fill="x") + self._wrap_labels.append(label) + return label + + def _on_window_configure(self, _event) -> None: + # Keep wrapped text matching the current sidebar width + try: + width = max(self._left.winfo_width() - 48, 160) + except Exception: + return + for label in self._wrap_labels: + try: + if int(label.cget("wraplength") or 0) != width: + label.configure(wraplength=width) + except Exception: + pass + + def _on_preview_configure(self, event) -> None: + if event.widget is not self.preview_frame: + return + size = (event.width, event.height) + if size == self._last_preview_size or size[0] < 50 or size[1] < 50: + return + self._last_preview_size = size + if self._resize_after is not None: + try: + self.after_cancel(self._resize_after) + except Exception: + pass + self._resize_after = self.after(120, self._refresh_preview) + + def _update_bricscad_ui(self) -> None: + if self._bricscad_path: + self.dwg_check.configure(state="normal") + self.brics_label.configure( + text=f"BricsCAD: {self._bricscad_path.parent.name}" + ) + else: + self.save_dwg_var.set(False) + self.dwg_check.configure(state="disabled") + self.brics_label.configure( + text="BricsCAD not detected — DXF only (set BRICSCAD_PATH to override)" + ) + + def _set_status(self, text: str) -> None: + self.status_label.configure(text=text) + + def _set_busy(self, busy: bool) -> None: + self._busy = busy + state = "disabled" if busy else "normal" + self.convert_btn.configure(state=state) + + def _open_pdf(self) -> None: + if self._busy: + return + path = filedialog.askopenfilename( + title="Open PDF", + filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")], + ) + if not path: + return + try: + close_document(self._doc) + self._doc = open_document(path) + self._pdf_path = Path(path) + self._page_index = 0 + self.file_label.configure(text=self._pdf_path.name) + self._refresh_preview() + self._set_status(f"Loaded {page_count(self._doc)} page(s)") + except Exception as exc: + messagebox.showerror("Open failed", str(exc)) + self._set_status("Failed to open PDF") + + def _use_current_page(self) -> None: + if self._doc is None: + return + self.pages_entry.delete(0, "end") + self.pages_entry.insert(0, str(self._page_index + 1)) + + def _prev_page(self) -> None: + if self._doc is None or self._page_index <= 0: + return + self._page_index -= 1 + self._refresh_preview() + + def _next_page(self) -> None: + if self._doc is None: + return + if self._page_index >= page_count(self._doc) - 1: + return + self._page_index += 1 + self._refresh_preview() + + def _refresh_preview(self) -> None: + self._resize_after = None + if self._doc is None: + return + total = page_count(self._doc) + self.page_label.configure(text=f"Page {self._page_index + 1} / {total}") + + self.update_idletasks() + max_w = max(self.preview_frame.winfo_width() - 24, 120) + max_h = max(self.preview_frame.winfo_height() - 24, 120) + + image = render_page( + self._doc, + self._page_index, + max_width=max_w, + max_height=max_h, + dpi=120.0, + ) + self._preview_photo = ctk.CTkImage( + light_image=image, + dark_image=image, + size=image.size, + ) + self.preview_label.configure(image=self._preview_photo, text="") + + def _convert(self) -> None: + if self._busy: + return + if self._doc is None or self._pdf_path is None: + messagebox.showinfo("No PDF", "Open a PDF file first.") + return + + try: + scale = float(self.scale_entry.get().strip() or "1.0") + if scale <= 0: + raise ValueError("Scale must be positive") + except ValueError as exc: + messagebox.showerror("Invalid scale", str(exc)) + return + + total = page_count(self._doc) + try: + pages = parse_page_range(self.pages_entry.get(), total) + except ValueError as exc: + messagebox.showerror("Invalid pages", str(exc)) + return + + self._set_status("Scanning pages…") + self.update_idletasks() + try: + classifications = classify_pdf_pages(self._pdf_path, pages) + except Exception as exc: + messagebox.showerror("Page scan failed", str(exc)) + self._set_status("Ready") + return + + global_mode = self.mode_var.get() + default_override = None if global_mode == "auto" else global_mode + page_modes = ask_page_modes( + self, + classifications, + default_mode=default_override, + ) + if page_modes is None: + self._set_status("Convert cancelled") + return + + active_pages = [i for i, mode in page_modes.items() if mode != "skip"] + if not active_pages: + messagebox.showinfo( + "Nothing to convert", "All selected pages were set to Skip." + ) + self._set_status("Ready") + return + + default_name = self._pdf_path.with_suffix(".dxf").name + out = filedialog.asksaveasfilename( + title="Save DXF", + defaultextension=".dxf", + initialfile=default_name, + filetypes=[("DXF files", "*.dxf"), ("All files", "*.*")], + ) + if not out: + self._set_status("Ready") + return + + options = ConvertOptions( + mode=ConvertMode(global_mode), + pages=sorted(active_pages), + scale=scale, + import_text=bool(self.import_text_var.get()), + ocr_text=bool(self.ocr_text_var.get()), + trace_detail=self.trace_detail_var.get(), + page_modes=page_modes, + ) + also_dwg = bool(self.save_dwg_var.get()) and is_bricscad_available() + + self._set_busy(True) + self._set_status("Converting…") + + def worker() -> None: + try: + result = convert_pdf_to_dxf(self._pdf_path, out, options) + dwg_msg = "" + if also_dwg: + self.after(0, lambda: self._set_status("Saving DWG via BricsCAD…")) + dwg_path = Path(out).with_suffix(".dwg") + dxf_to_dwg(result.output_path, dwg_path, self._bricscad_path) + dwg_msg = f"\nDWG: {dwg_path}" + + summary = result.summary + dwg_msg + + def done() -> None: + self._set_busy(False) + self._set_status(summary) + messagebox.showinfo("Conversion complete", summary) + + self.after(0, done) + except Exception as exc: + def fail() -> None: + self._set_busy(False) + self._set_status(f"Error: {exc}") + messagebox.showerror("Conversion failed", str(exc)) + + self.after(0, fail) + + threading.Thread(target=worker, daemon=True).start() + + def _on_close(self) -> None: + close_document(self._doc) + self._doc = None + self.destroy() + + +def run_app() -> None: + app = App() + app.mainloop() diff --git a/build_exe.ps1 b/build_exe.ps1 new file mode 100644 index 0000000..b1474f2 --- /dev/null +++ b/build_exe.ps1 @@ -0,0 +1,127 @@ +# Build a single shareable EXE. +# First run unpacks the app into %LOCALAPPDATA%\PDF_to_DXF\app\ +# Usage: .\build_exe.ps1 + +$ErrorActionPreference = "Stop" +$Root = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $Root + +$VenvPython = Join-Path $Root ".venv\Scripts\python.exe" +if (-not (Test-Path $VenvPython)) { + Write-Host "Creating virtual environment..." + python -m venv .venv +} + +Write-Host "Installing dependencies..." +& $VenvPython -m pip install --upgrade pip +& $VenvPython -m pip install -r requirements.txt + +# Bundle Tesseract language data (OCR works without a separate Tesseract install) +$TessDir = Join-Path $Root "vendor\tessdata" +$EngData = Join-Path $TessDir "eng.traineddata" +New-Item -ItemType Directory -Force -Path $TessDir | Out-Null +if (-not (Test-Path $EngData)) { + Write-Host "Downloading bundled OCR language data (eng.traineddata)..." + $url = "https://github.com/tesseract-ocr/tessdata_fast/raw/main/eng.traineddata" + Invoke-WebRequest -Uri $url -OutFile $EngData -UseBasicParsing +} +if (-not (Test-Path $EngData)) { + throw "Missing vendor\tessdata\eng.traineddata" +} + +$AppDistName = "PDF_to_DXF_app" +$AppDistDir = Join-Path $Root "dist\$AppDistName" +$PayloadZip = Join-Path $Root "build\app_payload.zip" +$SingleExeDir = Join-Path $Root "dist\PDF_to_DXF_single" + +Write-Host "Building application (folder payload)..." +& $VenvPython -m PyInstaller ` + --noconfirm ` + --clean ` + --windowed ` + --name $AppDistName ` + --distpath (Join-Path $Root "dist") ` + --workpath (Join-Path $Root "build\pyi_app") ` + --collect-all customtkinter ` + --collect-all ezdxf ` + --collect-all cv2 ` + --collect-all pymupdf ` + --add-data "$TessDir;tessdata" ` + --hidden-import PIL._tkinter_finder ` + --hidden-import app.raster_vectorize ` + --hidden-import app.converter ` + --hidden-import app.bricscad_export ` + --hidden-import app.pdf_preview ` + --hidden-import app.ocr_support ` + --hidden-import app.page_review ` + main.py + +$AppExe = Join-Path $AppDistDir "$AppDistName.exe" +if (-not (Test-Path $AppExe)) { + throw "Build failed: $AppExe not found" +} + +# Rename inner exe to PDF_to_DXF.exe so AppData layout matches the launcher +$FinalAppExe = Join-Path $AppDistDir "PDF_to_DXF.exe" +if (Test-Path $FinalAppExe) { + Remove-Item -Force $FinalAppExe +} +Rename-Item -Path $AppExe -NewName "PDF_to_DXF.exe" + +Write-Host "Packaging AppData payload zip..." +New-Item -ItemType Directory -Force -Path (Join-Path $Root "build") | Out-Null +if (Test-Path $PayloadZip) { + Remove-Item -Force $PayloadZip +} +# Prefer Python zipfile — Compress-Archive often locks on PyInstaller outputs +& $VenvPython -c @" +import zipfile +from pathlib import Path +src = Path(r'$AppDistDir') +out = Path(r'$PayloadZip') +with zipfile.ZipFile(out, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf: + for path in src.rglob('*'): + if path.is_file(): + zf.write(path, path.relative_to(src).as_posix()) +print('payload bytes', out.stat().st_size) +"@ +if (-not (Test-Path $PayloadZip)) { + throw "Failed to create app_payload.zip" +} + +Write-Host "Building single-file launcher EXE..." +& $VenvPython -m PyInstaller ` + --noconfirm ` + --clean ` + --windowed ` + --onefile ` + --name "PDF_to_DXF" ` + --distpath $SingleExeDir ` + --workpath (Join-Path $Root "build\pyi_launcher") ` + --add-data "$PayloadZip;." ` + launcher.py + +$OutExe = Join-Path $SingleExeDir "PDF_to_DXF.exe" +if (-not (Test-Path $OutExe)) { + throw "Build failed: single-file EXE not found" +} + +# Convenience copy at dist\PDF_to_DXF.exe +$DistRootExe = Join-Path $Root "dist\PDF_to_DXF.exe" +Copy-Item -Force $OutExe $DistRootExe + +# README next to the single EXE +$ReadmeSrc = Join-Path $Root "packaging\PORTABLE_README.txt" +Copy-Item -Force $ReadmeSrc (Join-Path $SingleExeDir "README.txt") + +$ExeMb = [math]::Round(((Get-Item $OutExe).Length) / 1MB, 1) + +Write-Host "" +Write-Host "Single-file build ready." +Write-Host (" Share this one file: dist\PDF_to_DXF.exe ({0} MB)" -f $ExeMb) +Write-Host " Also at: dist\PDF_to_DXF_single\PDF_to_DXF.exe" +Write-Host "" +Write-Host "On first run it installs to:" +Write-Host " %LOCALAPPDATA%\PDF_to_DXF\app\" +Write-Host "No Python needed. OCR language data is bundled." +Write-Host "Optional: BricsCAD for DWG export." diff --git a/launcher.py b/launcher.py new file mode 100644 index 0000000..2ab3c6c --- /dev/null +++ b/launcher.py @@ -0,0 +1,180 @@ +""" +Single-file launcher: extracts the app into LocalAppData on first run +(or when the version changes), then starts the real GUI EXE from there. + +Distribute only this launcher EXE — no _internal folder for end users. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +import zipfile +from pathlib import Path + +# Keep in sync with app.__version__ +APP_VERSION = "1.4.1" +APP_NAME = "PDF_to_DXF" +PAYLOAD_NAME = "app_payload.zip" + + +def _local_app_data() -> Path: + base = os.environ.get("LOCALAPPDATA") + if base: + return Path(base) + return Path.home() / "AppData" / "Local" + + +def _install_root() -> Path: + return _local_app_data() / APP_NAME + + +def _app_dir() -> Path: + return _install_root() / "app" + + +def _version_file() -> Path: + return _install_root() / "version.txt" + + +def _payload_zip() -> Path: + if getattr(sys, "frozen", False): + return Path(sys._MEIPASS) / PAYLOAD_NAME # type: ignore[attr-defined] + # Dev fallback: look next to this file / in build/ + here = Path(__file__).resolve().parent + for candidate in ( + here / "build" / PAYLOAD_NAME, + here / PAYLOAD_NAME, + here / "dist" / PAYLOAD_NAME, + ): + if candidate.is_file(): + return candidate + return here / "build" / PAYLOAD_NAME + + +def _needs_install(app_dir: Path) -> bool: + exe = app_dir / f"{APP_NAME}.exe" + if not exe.is_file(): + return True + vf = _version_file() + if not vf.is_file(): + return True + try: + return vf.read_text(encoding="utf-8").strip() != APP_VERSION + except OSError: + return True + + +def _show_setup_window(): + """Minimal first-run progress window (std tkinter only).""" + import tkinter as tk + + root = tk.Tk() + root.title(f"{APP_NAME} Setup") + root.resizable(False, False) + root.attributes("-topmost", True) + frame = tk.Frame(root, padx=36, pady=28) + frame.pack() + tk.Label( + frame, + text=f"{APP_NAME}", + font=("Segoe UI", 14, "bold"), + ).pack(anchor="w") + status = tk.Label( + frame, + text="First run setup — copying files to AppData…\nThis only happens once per version.", + font=("Segoe UI", 10), + justify="left", + ) + status.pack(anchor="w", pady=(10, 0)) + root.update_idletasks() + # Center on screen + w, h = root.winfo_reqwidth(), root.winfo_reqheight() + x = max(0, (root.winfo_screenwidth() - w) // 2) + y = max(0, (root.winfo_screenheight() - h) // 2) + root.geometry(f"+{x}+{y}") + root.update() + return root, status + + +def _install(app_dir: Path, status_cb=None) -> None: + zip_path = _payload_zip() + if not zip_path.is_file(): + raise FileNotFoundError( + f"Missing app payload ({PAYLOAD_NAME}). Rebuild with build_exe.ps1." + ) + + root = _install_root() + root.mkdir(parents=True, exist_ok=True) + + # Replace previous app files for this install + if app_dir.exists(): + if status_cb: + status_cb("Updating previous install…") + shutil.rmtree(app_dir, ignore_errors=True) + app_dir.mkdir(parents=True, exist_ok=True) + + if status_cb: + status_cb("Extracting application files…\nPlease wait.") + + with zipfile.ZipFile(zip_path, "r") as zf: + zf.extractall(app_dir) + + exe = app_dir / f"{APP_NAME}.exe" + if not exe.is_file(): + raise FileNotFoundError(f"Extracted payload is missing {APP_NAME}.exe") + + _version_file().write_text(APP_VERSION, encoding="utf-8") + + +def _launch(app_dir: Path) -> None: + exe = app_dir / f"{APP_NAME}.exe" + # Detach so this launcher can exit and clean its temp unpack + subprocess.Popen( + [str(exe)], + cwd=str(app_dir), + close_fds=True, + ) + + +def main() -> int: + app_dir = _app_dir() + setup_root = None + try: + if _needs_install(app_dir): + setup_root, status = _show_setup_window() + + def set_status(text: str) -> None: + status.configure(text=text) + setup_root.update() + + _install(app_dir, status_cb=set_status) + set_status("Starting…") + setup_root.update() + + _launch(app_dir) + return 0 + except Exception as exc: + try: + import tkinter as tk + from tkinter import messagebox + + tmp = tk.Tk() + tmp.withdraw() + messagebox.showerror(APP_NAME, f"Could not start the application:\n\n{exc}") + tmp.destroy() + except Exception: + print(f"ERROR: {exc}", file=sys.stderr) + return 1 + finally: + if setup_root is not None: + try: + setup_root.destroy() + except Exception: + pass + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/main.py b/main.py new file mode 100644 index 0000000..b318a21 --- /dev/null +++ b/main.py @@ -0,0 +1,12 @@ +"""PDF to DXF Converter — application entry point.""" + +from app.ocr_support import configure_bundled_ocr + +# Wire bundled tessdata before PyMuPDF OCR is used +configure_bundled_ocr() + +from app.ui import run_app + + +if __name__ == "__main__": + run_app() diff --git a/packaging/PORTABLE_README.txt b/packaging/PORTABLE_README.txt new file mode 100644 index 0000000..0da53a9 --- /dev/null +++ b/packaging/PORTABLE_README.txt @@ -0,0 +1,38 @@ +PDF to DXF Converter — single EXE +================================= + +How to install on another PC +---------------------------- +1. Copy ONLY PDF_to_DXF.exe (this one file). +2. Double-click it. + +On first run it copies the app into: + %LOCALAPPDATA%\PDF_to_DXF\app\ + +Later runs start from there (fast). Updating to a new EXE version +re-installs automatically. + +What works with nothing else installed +-------------------------------------- +- Open PDF, preview pages +- Convert to DXF (vector / vectorize / raster / auto) +- High-detail tracing of flattened drawing PDFs +- OCR for outlined / non-selectable text (bundled language data) + +Optional (not required) +----------------------- +- "Also save DWG via BricsCAD" — only if BricsCAD is installed on that PC + +Requirements +------------ +- Windows 10 or 11 (64-bit) +- No admin rights needed + +If Windows SmartScreen blocks the app +------------------------------------- +Click "More info" → "Run anyway" (unsigned desktop apps often trigger this). + +Uninstall +--------- +Delete PDF_to_DXF.exe, then delete the folder: + %LOCALAPPDATA%\PDF_to_DXF\ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1f992ce --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +opencv-python-headless>=4.8.0 +customtkinter>=5.2.0 +pymupdf>=1.24.0 +ezdxf>=1.3.0 +Pillow>=10.0.0 +pyinstaller>=6.0.0 diff --git a/vendor/tessdata/eng.traineddata b/vendor/tessdata/eng.traineddata new file mode 100644 index 0000000..bbef467 Binary files /dev/null and b/vendor/tessdata/eng.traineddata differ