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 <cursoragent@cursor.com>
This commit is contained in:
commit
91625af67f
16 files changed
+3074
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""PDF to DXF converter application package."""
|
||||
|
||||
__version__ = "1.4.1"
|
||||
@@ -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
|
||||
+1301
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -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("<Escape>", lambda _e: self._cancel())
|
||||
self.bind("<Configure>", 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
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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("<Configure>", 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("<Configure>", 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()
|
||||
Reference in new issue
Block a user