-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdicom_printer_service.py
More file actions
295 lines (266 loc) · 11.7 KB
/
Copy pathdicom_printer_service.py
File metadata and controls
295 lines (266 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import logging
import subprocess
import threading
import time
from pathlib import Path
from typing import Optional
def _to_bool(value, default=False):
if isinstance(value, bool):
return value
if value is None:
return default
return str(value).strip().lower() in ("1", "true", "yes", "on")
class DicomPrinterRuntime:
def __init__(self, root_dir: Path, config: dict):
self.root_dir = Path(root_dir)
self.config = self._normalize_config(config or {})
self.stop_event = threading.Event()
self.worker_thread = None
self.receiver_proc = None
self.generated_cfg_path = self.root_dir / "dicom-printer" / "runtime_printer.cfg"
self._processed = set()
def _normalize_config(self, cfg: dict) -> dict:
base = self.root_dir / "dicom-printer"
receiver = cfg.get("receiver", {}) if isinstance(cfg.get("receiver"), dict) else {}
worker = cfg.get("worker", {}) if isinstance(cfg.get("worker"), dict) else {}
return {
"enabled": _to_bool(cfg.get("enabled"), False),
"receiver": {
"aet": str(receiver.get("aet", "VPRINTSCP")).strip() or "VPRINTSCP",
"profile": str(receiver.get("profile", "FLOWWORKLIST_PRINTER")).strip() or "FLOWWORKLIST_PRINTER",
"target_host": str(receiver.get("target_host", "127.0.0.1")).strip() or "127.0.0.1",
"port": int(receiver.get("port", 4100) or 4100),
"dcmtk_bin": str(receiver.get("dcmtk_bin", r"C:\dcmtk\bin")).strip() or r"C:\dcmtk\bin",
"spool_dir": str(worker.get("spool_dir", str(base / "spool"))).strip() or str(base / "spool"),
},
"worker": {
"database_dir": str(worker.get("database_dir", str(base / "database"))).strip() or str(base / "database"),
"out_dir": str(worker.get("out_dir", str(base / "out"))).strip() or str(base / "out"),
"sumatra_path": str(worker.get("sumatra_path", r"C:\Program Files\SumatraPDF\SumatraPDF.exe")).strip() or r"C:\Program Files\SumatraPDF\SumatraPDF.exe",
"printer_name": str(worker.get("printer_name", "")).strip(),
"paper_size": str(worker.get("paper_size", "A3")).strip().upper() or "A3",
"print_settings": str(worker.get("print_settings", "fit")).strip() or "fit",
"delete_after_success": _to_bool(worker.get("delete_after_success"), False),
"sp_time_window_seconds": int(worker.get("sp_time_window_seconds", 120) or 120),
"poll_interval_seconds": float(worker.get("poll_interval_seconds", 1.0) or 1.0),
},
}
def start(self):
self._prepare_directories()
self._write_runtime_cfg()
self._start_receiver()
self._start_worker()
logging.info(
"Virtual DICOM printer enabled: receiver AET=%s port=%s",
self.config["receiver"]["aet"],
self.config["receiver"]["port"],
)
def stop(self):
self.stop_event.set()
if self.worker_thread and self.worker_thread.is_alive():
self.worker_thread.join(timeout=8)
self.worker_thread = None
if self.receiver_proc:
try:
self.receiver_proc.terminate()
self.receiver_proc.wait(timeout=8)
except Exception:
try:
self.receiver_proc.kill()
except Exception:
pass
finally:
self.receiver_proc = None
def _prepare_directories(self):
Path(self.config["receiver"]["spool_dir"]).mkdir(parents=True, exist_ok=True)
Path(self.config["worker"]["database_dir"]).mkdir(parents=True, exist_ok=True)
Path(self.config["worker"]["out_dir"]).mkdir(parents=True, exist_ok=True)
self.generated_cfg_path.parent.mkdir(parents=True, exist_ok=True)
def _write_runtime_cfg(self):
receiver = self.config["receiver"]
lines = [
"# Auto-generated by FlowWorklist",
"",
"[[GENERAL]]",
"",
"[PRINT]",
f"Directory = {receiver['spool_dir']}",
"DetailedLog = true",
"BinaryLog = false",
"DeletePrintJobs = false",
"",
"[DATABASE]",
f"Directory = {self.config['worker']['database_dir']}",
"",
"[[COMMUNICATION]]",
"",
f"[{receiver['profile']}]",
"type = LOCALPRINTER",
f"hostname = {receiver['target_host']}",
f"port = {receiver['port']}",
f"aetitle = {receiver['aet']}",
"description = FlowWorklist DICOM Print SCP",
"DisplayFormat = 1,1\\1,2\\2,2\\2,3\\3,3\\3,4\\4,4",
"FilmSizeID = 14INX17IN\\10INX12IN\\8INX10IN\\24CMX30CM\\A3\\A4",
"MagnificationType = CUBIC\\BILINEAR\\REPLICATE\\NONE",
"MediumType = BLUE FILM\\CLEAR FILM\\PAPER",
"FilmDestination = PROCESSOR\\MAGAZINE\\BIN_1\\BIN_2",
"Supports12Bit = true",
"SupportsPresentationLUT = true",
"PresentationLUTinFilmSession = false",
"PresentationLUTMatchRequired = true",
"SupportsTrim = true",
"SupportsDecimateCrop = false",
"SupportsImageSize = true",
"MaxPDU = 32768",
"ImplicitOnly = false",
"DisableNewVRs = false",
]
self.generated_cfg_path.write_text("\n".join(lines), encoding="utf-8")
def _start_receiver(self):
receiver = self.config["receiver"]
dcmprscp = Path(receiver["dcmtk_bin"]) / "dcmprscp.exe"
if not dcmprscp.exists():
raise RuntimeError(f"dcmprscp.exe not found at: {dcmprscp}")
cmd = [
str(dcmprscp),
"-c",
str(self.generated_cfg_path),
"-p",
receiver["profile"],
"+d",
"-v",
]
self.receiver_proc = subprocess.Popen(cmd, cwd=str(self.root_dir / "dicom-printer"))
time.sleep(1)
if self.receiver_proc.poll() is not None:
raise RuntimeError("dcmprscp exited immediately; check printer configuration/log output")
def _start_worker(self):
self.worker_thread = threading.Thread(target=self._worker_loop, name="dicom-printer-worker", daemon=True)
self.worker_thread.start()
def _worker_loop(self):
worker_cfg = self.config["worker"]
db_dir = Path(worker_cfg["database_dir"])
poll = max(0.25, float(worker_cfg["poll_interval_seconds"]))
logging.info("Virtual printer worker started. Watching: %s", db_dir)
while not self.stop_event.is_set():
try:
for dcm_file in sorted(db_dir.glob("HG_*.dcm")):
key = str(dcm_file.resolve()).lower()
if key in self._processed:
continue
if not self._wait_stable(dcm_file):
continue
self._processed.add(key)
self._process_hg(dcm_file)
except Exception as exc:
logging.exception("Virtual printer worker loop error: %s", exc)
self.stop_event.wait(poll)
def _wait_stable(self, path: Path, timeout=20):
deadline = time.time() + timeout
last_size = -1
while time.time() < deadline and not self.stop_event.is_set():
try:
size = path.stat().st_size
except FileNotFoundError:
time.sleep(0.2)
continue
if size > 0 and size == last_size:
return True
last_size = size
time.sleep(0.3)
return False
def _process_hg(self, hg_path: Path):
png_path = None
pdf_path = None
worker_cfg = self.config["worker"]
try:
center_time = hg_path.stat().st_mtime
png_path = self._dicom_to_png(hg_path)
pdf_path = self._png_to_pdf(png_path)
self._print_pdf(pdf_path)
logging.info("Virtual printer sent to printer: %s", hg_path.name)
if worker_cfg["delete_after_success"]:
self._safe_delete(pdf_path)
self._safe_delete(png_path)
self._safe_delete(hg_path)
self._delete_related_sp(center_time, Path(worker_cfg["database_dir"]), int(worker_cfg["sp_time_window_seconds"]))
except Exception as exc:
logging.exception("Virtual printer failed processing %s: %s", hg_path.name, exc)
def _dicom_to_png(self, dcm_path: Path) -> Path:
worker_cfg = self.config["worker"]
receiver = self.config["receiver"]
out_png = Path(worker_cfg["out_dir"]) / f"{dcm_path.stem}.png"
dcm2img = Path(receiver["dcmtk_bin"]) / "dcm2img.exe"
if not dcm2img.exists():
raise RuntimeError(f"dcm2img.exe not found at: {dcm2img}")
subprocess.run(
[str(dcm2img), "+on", "--write-png", str(dcm_path), str(out_png)],
check=True,
capture_output=True,
text=True,
)
return out_png
def _page_size(self):
from reportlab.lib.pagesizes import A3, A4, LETTER, LEGAL
paper = self.config["worker"]["paper_size"].upper()
mapping = {
"A3": A3,
"A4": A4,
"LETTER": LETTER,
"LEGAL": LEGAL,
}
return mapping.get(paper, A3)
def _png_to_pdf(self, png_path: Path) -> Path:
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas
pdf_path = png_path.with_suffix(".pdf")
img = ImageReader(str(png_path))
iw, ih = img.getSize()
w, h = self._page_size()
c = canvas.Canvas(str(pdf_path), pagesize=(w, h))
scale = min(w / iw, h / ih)
nw, nh = iw * scale, ih * scale
x = (w - nw) / 2
y = (h - nh) / 2
c.drawImage(img, x, y, width=nw, height=nh, preserveAspectRatio=True, mask="auto")
c.showPage()
c.save()
return pdf_path
def _print_pdf(self, pdf_path: Path):
worker_cfg = self.config["worker"]
sumatra = Path(worker_cfg["sumatra_path"])
if not sumatra.exists():
raise RuntimeError(f"SumatraPDF not found at: {sumatra}")
printer_name = worker_cfg["printer_name"]
print_settings = worker_cfg["print_settings"]
paper = worker_cfg["paper_size"]
if paper:
print_settings = f"{print_settings},paper={paper}"
cmd = [str(sumatra)]
if printer_name:
cmd.extend(["-print-to", printer_name])
cmd.extend(["-silent", "-print-settings", print_settings, str(pdf_path)])
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
stderr = (result.stderr or "").strip()
stdout = (result.stdout or "").strip()
raise RuntimeError(f"Print failed (code={result.returncode}): {stderr or stdout}")
def _delete_related_sp(self, center_time: float, db_dir: Path, window_seconds: int):
deleted = 0
for sp in db_dir.glob("SP_*.dcm"):
try:
if abs(sp.stat().st_mtime - center_time) <= window_seconds:
sp.unlink(missing_ok=True)
deleted += 1
except Exception:
pass
if deleted:
logging.info("Virtual printer deleted related SP files: %s", deleted)
def _safe_delete(self, path: Optional[Path]):
if not path:
return
try:
path.unlink(missing_ok=True)
except Exception:
pass