Skip to content

Commit

Permalink
Merge pull request #86 from JoHof/fix/logging_config
Browse files Browse the repository at this point in the history
package logger and no logging propagation
  • Loading branch information
JoHof authored Jul 10, 2023
2 parents 6668ca9 + 4d3e879 commit b7cb379
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 27 deletions.
10 changes: 5 additions & 5 deletions lungmask/__main__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import argparse
import logging
import os
import sys

Expand All @@ -8,6 +7,7 @@
import SimpleITK as sitk

from lungmask import LMInferer, utils
from lungmask.logger import logger


def path(string):
Expand Down Expand Up @@ -86,18 +86,18 @@ def main():
args = parser.parse_args(argsin)

if args.classes is not None:
logging.warn(
logger.warn(
"!!! Warning: The `classes` parameter is deprecated and will be removed in the next version !!!"
)

batchsize = args.batchsize
if args.cpu:
batchsize = 1

logging.info("Load model")
logger.info("Load model")

input_image = utils.load_input_image(args.input, disable_tqdm=args.noprogress)
logging.info("Infer lungmask")
logger.info("Infer lungmask")
if args.modelname == "LTRCLobes_R231":
assert (
args.modelpath is None
Expand Down Expand Up @@ -132,7 +132,7 @@ def main():

result_out = sitk.GetImageFromArray(result)
result_out.CopyInformation(input_image)
logging.info(f"Save result to: {args.output}")
logger.info(f"Save result to: {args.output}")
sitk.WriteImage(result_out, args.output)


Expand Down
13 changes: 13 additions & 0 deletions lungmask/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import logging
import sys

logger = logging.getLogger("lungmask")
logger.setLevel(logging.INFO)
logger.propagate = False
formatter = logging.Formatter(
fmt="lungmask %(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
17 changes: 5 additions & 12 deletions lungmask/mask.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
import os
import sys
import warnings
Expand All @@ -12,16 +11,10 @@
from tqdm import tqdm

from lungmask import utils
from lungmask.logger import logger

from .resunet import UNet

logging.basicConfig(
stream=sys.stdout,
format="lungmask %(asctime)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO,
)

warnings.filterwarnings("ignore", category=UserWarning)


Expand Down Expand Up @@ -130,7 +123,7 @@ def __init__(
if torch.cuda.is_available():
self.device = torch.device("cuda")
else:
logging.info("No GPU found, using CPU instead")
logger.info("No GPU found, using CPU instead")
self.model.to(self.device)

self.fillmodelm = None
Expand Down Expand Up @@ -241,14 +234,14 @@ def apply(self, image: Union[sitk.Image, np.ndarray]) -> np.ndarray:
if self.fillmodel is None:
return self._inference(image, self.model)
else:
logging.info(f"Apply: {self.modelname}")
logger.info(f"Apply: {self.modelname}")
res_l = self._inference(image, self.model)
logging.info(f"Apply: {self.fillmodel}")
logger.info(f"Apply: {self.fillmodel}")
res_r = self._inference(image, self.fillmodelm)
spare_value = res_l.max() + 1
res_l[np.logical_and(res_l == 0, res_r > 0)] = spare_value
res_l[res_r == 0] = 0
logging.info("Fusing results... this may take up to several minutes!")
logger.info("Fusing results... this may take up to several minutes!")
return utils.postprocessing(res_l, spare=[spare_value])


Expand Down
19 changes: 10 additions & 9 deletions lungmask/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
import os
import sys
from typing import Tuple
Expand All @@ -13,6 +12,8 @@
from torch.utils.data import Dataset
from tqdm import tqdm

from lungmask.logger import logger


def preprocess(
img: np.ndarray, resolution: list = [192, 192]
Expand Down Expand Up @@ -169,8 +170,8 @@ def read_dicoms(path, primary=True, original=True, disable_tqdm=False):
dcm_header_info.append(h_info)

except Exception as e:
logging.error("Unexpected error:", e)
logging.warning("Doesn't seem to be DICOM, will be skipped: ", fname)
logger.error("Unexpected error:", e)
logger.warning("Doesn't seem to be DICOM, will be skipped: ", fname)

conc = [x[1] for x in dcm_header_info]
sidx = np.argsort(conc)
Expand All @@ -179,9 +180,9 @@ def read_dicoms(path, primary=True, original=True, disable_tqdm=False):
vol_unique = np.unique(conc, return_index=1, return_inverse=1) # unique volumes
n_vol = len(vol_unique[1])
if n_vol == 1:
logging.info("There is " + str(n_vol) + " volume in the study")
logger.info("There is " + str(n_vol) + " volume in the study")
else:
logging.info("There are " + str(n_vol) + " volumes in the study")
logger.info("There are " + str(n_vol) + " volumes in the study")

relevant_series = []
relevant_volumes = []
Expand Down Expand Up @@ -215,17 +216,17 @@ def load_input_image(path: str, disable_tqdm=False) -> sitk.Image:
sitk.Image: Loaded image
"""
if os.path.isfile(path):
logging.info(f"Read input: {path}")
logger.info(f"Read input: {path}")
input_image = sitk.ReadImage(path)
else:
logging.info(f"Looking for dicoms in {path}")
logger.info(f"Looking for dicoms in {path}")
dicom_vols = read_dicoms(
path, original=False, primary=False, disable_tqdm=disable_tqdm
)
if len(dicom_vols) < 1:
sys.exit("No dicoms found!")
if len(dicom_vols) > 1:
logging.warning(
logger.warning(
"There are more than one volume in the path, will take the largest one"
)
input_image = dicom_vols[
Expand All @@ -252,7 +253,7 @@ def postprocessing(
Returns:
np.ndarray: Postprocessed volume
"""
logging.info("Postprocessing")
logger.info("Postprocessing")

# CC analysis
regionmask = skimage.measure.label(label_image)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="lungmask",
version="0.2.15",
version="0.2.16",
author="Johannes Hofmanninger",
author_email="johannes.hofmanninger@gmail.com",
description="Package for automated lung segmentation in CT",
Expand Down

0 comments on commit b7cb379

Please sign in to comment.