Skip to content
Merged
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
63 changes: 50 additions & 13 deletions fmcib/utils/idc_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,53 +190,90 @@ def download_RADIO(path, samples=None):
download_from_manifest(df, save_dir, samples)


def process_series_dir(series_dir):
def process_series_dir(series_dir: Path):
"""
Process the series directory and extract relevant information.
Args:
series_dir (Path): The path to the series directory.
Returns:
dict: A dictionary containing the extracted information, including the image path, patient ID, and coordinates.
dict: A dictionary containing the extracted information, including the
image path, patient ID, and centroid coordinates.
None: If there's no RTSTRUCT or SEG file, or any step fails.
Raises:
None
"""
# Check if RTSTRUCT file exists
rtstuct_files = list(series_dir.glob("*RTSTRUCT*"))
rt_struct_files = list(series_dir.glob("*RTSTRUCT*"))
seg_files = list(series_dir.glob("*SEG*"))

if len(rtstuct_files) != 0:
dcmrtstruct2nii(str(rtstuct_files[0]), str(series_dir), str(series_dir))
# Convert DICOM to NIfTI based on whether it's RTSTRUCT or SEG
if len(rt_struct_files) != 0:
dcmrtstruct2nii(str(rt_struct_files[0]), str(series_dir), str(series_dir))
Comment on lines +213 to +214
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for RTSTRUCT conversion.

The dcmrtstruct2nii call should be wrapped in a try-except block to handle potential conversion failures gracefully.

 if len(rt_struct_files) != 0:
-    dcmrtstruct2nii(str(rt_struct_files[0]), str(series_dir), str(series_dir))
+    try:
+        dcmrtstruct2nii(str(rt_struct_files[0]), str(series_dir), str(series_dir))
+    except Exception as e:
+        logger.error(f"Failed to convert RTSTRUCT to NIfTI: {e}")
+        return None

Committable suggestion skipped: line range outside the PR's diff.


elif len(seg_files) != 0:
dcmseg2nii(str(seg_files[0]), str(series_dir), tag="GTV-")

series_id = str(list(series_dir.glob("CT*.dcm"))[0]).split("_")[-2]

# Build the main image NIfTI
try:
series_id = str(list(series_dir.glob("CT*.dcm"))[0]).split("_")[-2]
except IndexError:
logger.warning(f"No 'CT*.dcm' file found under {series_dir}. Skipping.")
return None

dicom_image = DcmInputAdapter().ingest(str(series_dir), series_id=series_id)
nii_output_adapter = NiiOutputAdapter()
nii_output_adapter.write(dicom_image, f"{series_dir}/image", gzip=True)

else:
logger.warning("Skipped file without any RTSTRUCT or SEG file")
logger.warning(f"No RTSTRUCT or SEG file found in {series_dir}. Skipping.")
return None

# Read the image (generated above)
image_path = series_dir / "image.nii.gz"
if not image_path.exists():
logger.warning(f"No image file found at {image_path}. Skipping.")
return None

image = sitk.ReadImage(str(series_dir / "image.nii.gz"))
mask = sitk.ReadImage(str(list(series_dir.glob("*GTV-1*"))[0]))
try:
image = sitk.ReadImage(str(image_path))
except Exception as e:
logger.error(f"Failed to read image {image_path}: {e}")
return None

# Find the GTV-1 mask files
gtv1_masks = list(series_dir.glob("*GTV-1*.nii.gz"))
if not gtv1_masks:
logger.warning(f"No GTV-1 mask found in {series_dir}. Skipping.")
return None

mask_path = gtv1_masks[0]
try:
mask = sitk.ReadImage(str(mask_path))
except Exception as e:
logger.error(f"Failed to read mask {mask_path}: {e}")
return None

# Get centroid from label shape filter
# Extract centroid from the mask
label_shape_filter = sitk.LabelShapeStatisticsImageFilter()
label_shape_filter.Execute(mask)

# Some masks label is 1, others are 255; try 255 first, else 1
try:
centroid = label_shape_filter.GetCentroid(255)
except:
centroid = label_shape_filter.GetCentroid(1)
try:
centroid = label_shape_filter.GetCentroid(1)
except Exception as e:
logger.warning(f"Could not extract centroid from mask {mask_path}: {e}")
return None
Comment on lines +263 to +271
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Replace bare except with specific exception type.

The bare except clause should catch specific exceptions for better error handling.

     try:
         centroid = label_shape_filter.GetCentroid(255)
-    except:
+    except RuntimeError:
         try:
             centroid = label_shape_filter.GetCentroid(1)
-        except Exception as e:
+        except RuntimeError as e:
             logger.warning(f"Could not extract centroid from mask {mask_path}: {e}")
             return None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Some masks label is 1, others are 255; try 255 first, else 1
try:
centroid = label_shape_filter.GetCentroid(255)
except:
centroid = label_shape_filter.GetCentroid(1)
try:
centroid = label_shape_filter.GetCentroid(1)
except Exception as e:
logger.warning(f"Could not extract centroid from mask {mask_path}: {e}")
return None
# Some masks label is 1, others are 255; try 255 first, else 1
try:
centroid = label_shape_filter.GetCentroid(255)
except RuntimeError:
try:
centroid = label_shape_filter.GetCentroid(1)
except RuntimeError as e:
logger.warning(f"Could not extract centroid from mask {mask_path}: {e}")
return None
🧰 Tools
🪛 Ruff (0.8.2)

266-266: Do not use bare except

(E722)


x, y, z = centroid

row = {
"image_path": str(series_dir / "image.nii.gz"),
"image_path": str(image_path),
"PatientID": series_dir.parent.name,
"coordX": x,
"coordY": y,
Expand Down
Loading