Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decorators for function call added to image/bitmap reader functions and segmentation function. Please see if it could be merged. #828

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
69 changes: 50 additions & 19 deletions invesalius/gui/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
class ConsoleLogHandler(logging.StreamHandler):
def __init__(self, textctrl):
logging.StreamHandler.__init__(self)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
#formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - (%(funcName)s) - %(message)s")
formatter = logging.Formatter("%(asctime)s - %(message)s")
self.setFormatter(formatter)
self.textctrl = textctrl

Expand Down Expand Up @@ -127,7 +128,7 @@ def __init__(self):
"console_logging_level": 0,
"base_logging_level": logging.DEBUG,
#'logging_format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
"logging_format": "%(asctime)s - %(levelname)s - %(message)s",
"logging_format": "%(asctime)s - %(message)s",
}
self.ReadConfigFile()
self._logger.setLevel(self._config["base_logging_level"])
Expand All @@ -144,10 +145,10 @@ def GetConfig(self, key, default_value=None):

def ReadConfigFile(self, fPath=LOG_CONFIG_PATH):
try:
print(fPath, os.path.abspath(fPath))
#print(fPath, os.path.abspath(fPath))
self._read_config_from_json(fPath)
print("Reading Log config file ", fPath)
print(self._config)
#print(self._config)
except Exception as e1:
print("Error reading config file in ReadConfigFile:", e1)
return True
Expand All @@ -171,6 +172,10 @@ def getLogger(self, lname=__name__):
# logger = logging.getLogger(lname)
return self._logger

def formMessage(fName, className, funcName):
msg = "Hello ..."
return msg

def logMessage(self, level, msg):
level = level.upper()
if level == "DEBUG":
Expand All @@ -190,35 +195,35 @@ def configureLogging(self):
append_log_file = self._config["append_log_file"]
logging_file = self._config["logging_file"]
logging_file = os.path.abspath(logging_file)
print("logging_file:", logging_file)
#print("logging_file:", logging_file)
console_logging = self._config["console_logging"]
console_logging_level = self._config["console_logging_level"]

self._logger.setLevel(self._config["base_logging_level"])

if (self._frame == None) & (console_logging != 0):
print("Initiating console logging ...")
# self._frame = ConsoleLogFrame(self.getLogger())

self._frame = ConsoleLogFrame(self.getLogger())
'''
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
ch = logging.StreamHandler(sys.stderr)
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
self._logger.addHandler(ch)

print("Initiated console logging ...")
'''
#print("Initiated console logging ...")
self._logger.info("Initiated console logging ...")

msg = "file_logging: {}, console_logging: {}".format(file_logging, console_logging)
print(msg)
#msg = "file_logging: {}, console_logging: {}".format(file_logging, console_logging)
#print(msg)

self._logger.info(msg)
self._logger.info("configureLogging called ...")
self.logMessage("info", msg)
#self._logger.info(msg)
#self._logger.info("configureLogging called ...")
#self.logMessage("info", msg)

if file_logging:
# print('file_logging called ...')
self._logger.info("file_logging called ...")
#self._logger.info("file_logging called ...")
file_logging_level = getattr(
logging, const.LOGGING_LEVEL_TYPES[file_logging_level].upper(), None
)
Expand Down Expand Up @@ -263,7 +268,7 @@ def configureLogging(self):

fh.setFormatter(formatter)
self._logger.addHandler(fh)
msg = "Added file handler {}".format(logging_file)
msg = "Initiated file log in {}".format(logging_file)
self._logger.info(msg)
else:
self.closeFileLogging()
Expand All @@ -285,6 +290,7 @@ def closeConsoleLogging(self):
if self._frame != None:
self._frame = None


def closeLogging(self):
self.closeFileLogging()
self.closeConsoleLogging()
Expand All @@ -293,15 +299,40 @@ def flushHandlers(self):
for handler in self._logger.handlers:
handler.flush()


def call_tracking_decorator(function: Callable[[str], None]):
#####################################################################################
# Decorators for logging

def call_tracking_decorator(fileName, className, functionName=''):
def decorator(func):
def wrapper(*args, **kwargs):
invLogger._logger.debug(f"Entered File {fileName}, Class {className}, Function {functionName}" )
func(*args, **kwargs)
return wrapper
return decorator

def decorator_with_args(arg1, arg2):
def actual_decorator(func):
def wrapper( * args, ** kwargs):
print(f"Decorator argument 1: {arg1}")
print(f"Decorator argument 2: {arg2}")
func( * args, ** kwargs)
return wrapper
return actual_decorator

def call_tracking_decorator00(function: Callable[[str], None]):
def wrapper_accepting_arguments(*args):
msg = "Function {} called".format(function.__name__)
invLogger._logger.info(msg)
invLogger._logger.debug(msg)
function(*args)

return wrapper_accepting_arguments

class DecorateAllMethods:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
for attr, value in cls.__dict__.items():
if callable(value):
setattr(cls, attr, call_tracking_decorator00(value))

#####################################################################################
# Decorators for error handling
Expand Down
2 changes: 1 addition & 1 deletion invesalius/gui/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ def __init__(self, parent):

self.Layout()

@log.call_tracking_decorator
@log.call_tracking_decorator00
def OnModifyButton(self, e):
logging_file = self.tc_log_file_name.GetValue()
path, fname = os.path.split(logging_file)
Expand Down
10 changes: 6 additions & 4 deletions invesalius/reader/bitmap_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import invesalius.utils as utils
from invesalius import inv_paths
from invesalius.pubsub import pub as Publisher
import invesalius.gui.log as log

# flag to control vtk error in read files
no_error = True
Expand Down Expand Up @@ -151,6 +152,7 @@ def __init__(self, bmp_file, filepath):

self.run()

@log.call_tracking_decorator(os.path.basename(__file__), "LoadBitmap", "Run")
def run(self):
global vtk_error

Expand Down Expand Up @@ -296,7 +298,7 @@ def VtkErrorPNGWriter(obj, f):
global vtk_error
vtk_error = True


@log.call_tracking_decorator(os.path.basename(__file__), "", "ScipyRead")
def ScipyRead(filepath):
try:
r = imread(filepath, flatten=True)
Expand All @@ -312,7 +314,7 @@ def ScipyRead(filepath):
except IOError:
return False


@log.call_tracking_decorator(os.path.basename(__file__), "", "VtkRead")
def VtkRead(filepath, t):
if not const.VTK_WARNING:
log_path = os.path.join(inv_paths.USER_LOG_DIR, "vtkoutput.txt")
Expand Down Expand Up @@ -362,7 +364,7 @@ def VtkRead(filepath, t):
no_error = True
return False


@log.call_tracking_decorator(os.path.basename(__file__), "", "ReadBitmap")
def ReadBitmap(filepath):
t = VerifyDataType(filepath)

Expand Down Expand Up @@ -391,7 +393,7 @@ def ReadBitmap(filepath):

return img_array


@log.call_tracking_decorator(os.path.basename(__file__), "", "GetPixelSpacingFromInfoFile")
def GetPixelSpacingFromInfoFile(filepath):
filepath = utils.decode(filepath, const.FS_ENCODE)

Expand Down
2 changes: 1 addition & 1 deletion invesalius/reader/dicom_grouper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# ---------------------------------------------------------------------
# ---------------------------------------------------------------------
# Software: InVesalius Software de Reconstrucao 3D de Imagens Medicas

# Copyright: (c) 2001 Centro de Pesquisas Renato Archer
Expand Down
3 changes: 3 additions & 0 deletions invesalius/reader/dicom_reader.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

# --------------------------------------------------------------------------
# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright: (C) 2001 Centro de Pesquisas Renato Archer
Expand Down Expand Up @@ -44,6 +45,7 @@
from invesalius import inv_paths
from invesalius.data import imagedata_utils
from invesalius.pubsub import pub as Publisher
import invesalius.gui.log as log

if sys.platform == "win32":
try:
Expand Down Expand Up @@ -113,6 +115,7 @@ def __init__(self, grouper, filepath):
self.filepath = utils.decode(filepath, const.FS_ENCODE)
self.run()

@log.call_tracking_decorator(os.path.basename(__file__), "LoadDicom", "Run")
def run(self):
grouper = self.grouper
reader = gdcm.ImageReader()
Expand Down
3 changes: 2 additions & 1 deletion invesalius/reader/others_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@

import invesalius.constants as const
from invesalius import inv_paths
import invesalius.gui.log as log


@log.call_tracking_decorator(os.path.basename(__file__), "", "ReadOthers")
def ReadOthers(dir_):
"""
Read the given Analyze, NIfTI, Compressed NIfTI or PAR/REC file,
Expand Down
9 changes: 8 additions & 1 deletion invesalius/segmentation/deep_learning/segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@
from invesalius.data.converters import to_vtk
from invesalius.net.utils import download_url_to_file
from invesalius.utils import new_name_by_pattern
import invesalius.gui.log as log

from . import utils

SIZE = 48


@log.call_tracking_decorator(os.path.basename(__file__), "", "gen_patches")
def gen_patches(image, patch_size, overlap):
overlap = int(patch_size * overlap / 100)
sz, sy, sx = image.shape
Expand All @@ -45,6 +46,7 @@ def gen_patches(image, patch_size, overlap):
yield (idx + 1.0) / len(i_cuts), sub_image, ((iz, ez), (iy, ey), (ix, ex))


@log.call_tracking_decorator(os.path.basename(__file__), "", "predict_patch")
def predict_patch(sub_image, patch, nn_model, patch_size):
(iz, ez), (iy, ey), (ix, ex) = patch
sub_mask = nn_model.predict(sub_image.reshape(1, patch_size, patch_size, patch_size, 1))
Expand All @@ -53,6 +55,7 @@ def predict_patch(sub_image, patch, nn_model, patch_size):
]


@log.call_tracking_decorator(os.path.basename(__file__), "", "predict_patch")
def predict_patch_torch(sub_image, patch, nn_model, device, patch_size):
import torch

Expand All @@ -72,6 +75,7 @@ def predict_patch_torch(sub_image, patch, nn_model, device, patch_size):
]


@log.call_tracking_decorator(os.path.basename(__file__), "", "predict_patch")
def segment_keras(image, weights_file, overlap, probability_array, comm_array, patch_size):
import keras

Expand Down Expand Up @@ -102,6 +106,7 @@ def _download_callback(value):
return _download_callback


@log.call_tracking_decorator(os.path.basename(__file__), "", "segment_torch")
def segment_torch(
image, weights_file, overlap, device_id, probability_array, comm_array, patch_size
):
Expand Down Expand Up @@ -134,6 +139,7 @@ def segment_torch(
comm_array[0] = np.Inf


@log.call_tracking_decorator(os.path.basename(__file__), "", "segment_torch_jit")
def segment_torch_jit(
image,
weights_file,
Expand Down Expand Up @@ -256,6 +262,7 @@ def __init__(

self.mask = None

@log.call_tracking_decorator(os.path.basename(__file__), "SegmentProcess", "run")
def run(self):
try:
self._run_segmentation()
Expand Down
Loading