Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 6 additions & 14 deletions package/src/pyaslreport/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,16 @@ def get_dicom_header(dicom_dir: str):
# Get all files in the directory
all_files = [f for f in os.listdir(dicom_dir) if os.path.isfile(os.path.join(dicom_dir, f))]

# Try to find DICOM files by attempting to read them with pydicom
dcm_files = []
# Return the first readable DICOM header instead of scanning the whole directory
# and reading the winning file a second time.
for file in all_files:
file_path = os.path.join(dicom_dir, file)
try:
# Try to read the file as DICOM
pydicom.dcmread(file_path, stop_before_pixels=True)
dcm_files.append(file)
dcm_header = pydicom.dcmread(file_path, stop_before_pixels=True)
log.info(f"Found a readable DICOM file in {dicom_dir}: {file}")
return dcm_header
except (InvalidDicomError, OSError, PermissionError):
# File is not a valid DICOM file or cannot be read
continue

log.info(f"Found {len(dcm_files)} DICOM files in {dicom_dir}")

if not dcm_files:
raise ValueError(f"No DICOM files found in directory: {dicom_dir}")

# Read the first valid DICOM file
dcm_header = pydicom.dcmread(os.path.join(dicom_dir, dcm_files[0]))

return dcm_header
raise ValueError(f"No DICOM files found in directory: {dicom_dir}")
23 changes: 23 additions & 0 deletions package/src/pyaslreport/tests/test_get_dicom_header.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from pathlib import Path
from unittest.mock import patch

from pyaslreport.main import get_dicom_header


def test_get_dicom_header_returns_first_valid_header_without_scanning_rest(tmp_path):
first_file = tmp_path / "first.dcm"
second_file = tmp_path / "second.dcm"
first_file.write_bytes(b"first")
second_file.write_bytes(b"second")

calls = []

def fake_dcmread(path, stop_before_pixels=True):
calls.append(Path(path).name)
return {"path": Path(path).name}

with patch("pyaslreport.main.pydicom.dcmread", side_effect=fake_dcmread):
header = get_dicom_header(str(tmp_path))

assert header == {"path": "first.dcm"}
assert calls == ["first.dcm"]