86 lines
2.4 KiB
Python
86 lines
2.4 KiB
Python
"""
|
|
General utility functions for DICOM operations.
|
|
"""
|
|
import os
|
|
import json
|
|
from datetime import datetime
|
|
from utils.logger import main_logger as logger
|
|
|
|
def create_directory_if_not_exists(directory_path):
|
|
"""
|
|
Create directory if it doesn't exist.
|
|
|
|
Args:
|
|
directory_path (str): Path to directory
|
|
"""
|
|
if not os.path.exists(directory_path):
|
|
os.makedirs(directory_path, exist_ok=True)
|
|
logger.info(f"Created directory: {directory_path}")
|
|
|
|
def save_json_data(data, filename, directory):
|
|
"""
|
|
Save data as JSON to specified directory.
|
|
|
|
Args:
|
|
data (dict): Data to save
|
|
filename (str): Filename without path
|
|
directory (str): Directory to save to
|
|
|
|
Returns:
|
|
str: Full path to saved file
|
|
"""
|
|
create_directory_if_not_exists(directory)
|
|
file_path = os.path.join(directory, filename)
|
|
|
|
with open(file_path, 'w') as f:
|
|
json.dump(data, f, indent=2)
|
|
|
|
logger.info(f"Saved JSON data to {file_path}")
|
|
return file_path
|
|
|
|
def parse_dicom_date(date_str):
|
|
"""
|
|
Parse DICOM date format (YYYYMMDD) to Python datetime.
|
|
|
|
Args:
|
|
date_str (str): DICOM formatted date string
|
|
|
|
Returns:
|
|
datetime: Python datetime object
|
|
"""
|
|
if not date_str or len(date_str) != 8:
|
|
return None
|
|
|
|
try:
|
|
return datetime.strptime(date_str, '%Y%m%d')
|
|
except ValueError:
|
|
logger.error(f"Invalid DICOM date format: {date_str}")
|
|
return None
|
|
|
|
def parse_dicom_datetime(datetime_str):
|
|
"""
|
|
Parse DICOM datetime format (YYYYMMDDHHMMSS) to Python datetime.
|
|
|
|
Args:
|
|
datetime_str (str): DICOM formatted datetime string
|
|
|
|
Returns:
|
|
datetime: Python datetime object
|
|
"""
|
|
if not datetime_str:
|
|
return None
|
|
|
|
# Handle various DICOM datetime formats
|
|
try:
|
|
if len(datetime_str) == 14: # YYYYMMDDHHMMSS
|
|
return datetime.strptime(datetime_str, '%Y%m%d%H%M%S')
|
|
elif len(datetime_str) == 12: # YYYYMMDDHHMM
|
|
return datetime.strptime(datetime_str, '%Y%m%d%H%M')
|
|
elif len(datetime_str) == 8: # YYYYMMDD
|
|
return datetime.strptime(datetime_str, '%Y%m%d')
|
|
else:
|
|
logger.warning(f"Unexpected DICOM datetime format: {datetime_str}")
|
|
return None
|
|
except ValueError:
|
|
logger.error(f"Invalid DICOM datetime format: {datetime_str}")
|
|
return None |