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

Refactor logging in SDK #1135

Merged
merged 1 commit into from
Dec 8, 2023
Merged
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
5 changes: 3 additions & 2 deletions depthai_sdk/src/depthai_sdk/classes/packet_handlers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import logging

import os
from abc import abstractmethod
from queue import Queue, Empty
Expand All @@ -8,6 +8,7 @@

from depthai_sdk.classes.packets import BasePacket
from depthai_sdk.components.component import Component, ComponentOutput
from depthai_sdk.logger import LOGGER
from depthai_sdk.oak_outputs.fps import FPS
from depthai_sdk.oak_outputs.syncing import TimestampSync
from depthai_sdk.oak_outputs.xout.xout_base import XoutBase, ReplayStream
Expand Down Expand Up @@ -65,7 +66,7 @@ def configure_syncing(self,
"""
if enable_sync:
if len(self.outputs) < 2:
logging.error('Syncing requires at least 2 outputs! Skipping syncing.')
LOGGER.error('Syncing requires at least 2 outputs! Skipping syncing.')
return
self.sync = TimestampSync(len(self.outputs), threshold_ms)

Expand Down
8 changes: 4 additions & 4 deletions depthai_sdk/src/depthai_sdk/components/camera_component.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import logging
from typing import Dict

from depthai_sdk.classes.enum import ResizeMode
from depthai_sdk.components.camera_control import CameraControl
from depthai_sdk.components.camera_helper import *
from depthai_sdk.components.component import Component, ComponentOutput
from depthai_sdk.components.parser import parse_resolution, parse_encode, encoder_profile_to_fourcc
from depthai_sdk.logger import LOGGER
from depthai_sdk.oak_outputs.xout.xout_base import XoutBase, StreamXout, ReplayStream
from depthai_sdk.oak_outputs.xout.xout_frames import XoutFrames
from depthai_sdk.replay import Replay
Expand Down Expand Up @@ -297,7 +297,7 @@ def control_with_nn(self, detection_component: 'NNComponent', auto_focus=True, a
"""

if not auto_focus and not auto_exposure:
logging.error('Attempted to control camera with NN, '
LOGGER.error('Attempted to control camera with NN, '
'but both Auto-Focus and Auto-Exposure were disabled! Attempt ignored.')
return

Expand Down Expand Up @@ -337,12 +337,12 @@ def config_color_camera(self,
chroma_denoise: Optional[int] = None,
) -> None:
if not self.is_color():
logging.info('Attempted to configure ColorCamera, '
LOGGER.info('Attempted to configure ColorCamera, '
'but this component doesn\'t have it. Config attempt ignored.')
return

if self.is_replay():
logging.info('Tried configuring ColorCamera, but replaying is enabled. Config attempt ignored.')
LOGGER.info('Tried configuring ColorCamera, but replaying is enabled. Config attempt ignored.')
return

if interleaved is not None: self.node.setInterleaved(interleaved)
Expand Down
84 changes: 41 additions & 43 deletions depthai_sdk/src/depthai_sdk/components/camera_control.py

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions depthai_sdk/src/depthai_sdk/components/nn_component.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import json
import logging
import warnings
from collections import defaultdict
from pathlib import Path
Expand All @@ -22,6 +21,7 @@
from depthai_sdk.classes.enum import ResizeMode
from depthai_sdk.components.parser import *
from depthai_sdk.components.stereo_component import StereoComponent
from depthai_sdk.logger import LOGGER
from depthai_sdk.visualize.visualizer_helper import depth_to_disp_factor
from depthai_sdk.oak_outputs.xout.xout_base import StreamXout, XoutBase
from depthai_sdk.oak_outputs.xout.xout_frames import XoutFrames
Expand Down Expand Up @@ -178,7 +178,7 @@ def __init__(self,
self.node.input.setBlocking(True)
self.node.input.setQueueSize(20)
else:
logging.debug('Using on-host decoding for multi-stage NN')
LOGGER.debug('Using on-host decoding for multi-stage NN')
# Custom NN
self.image_manip.setResize(*self._size)
self.image_manip.setMaxOutputFrameSize(self._size[0] * self._size[1] * 3)
Expand Down Expand Up @@ -246,7 +246,7 @@ def _parse_model(self, model):
model = models[str(model)] / 'config.json'
self._parse_config(model)
elif str(model) in zoo_models:
logging.warning(
LOGGER.warning(
'Models from the OpenVINO Model Zoo do not carry any metadata'
' (e.g., label map, decoding logic). Please keep this in mind when using models from Zoo.'
)
Expand Down Expand Up @@ -322,7 +322,7 @@ def _parse_config(self, model_config: Union[Path, str, Dict]):
self._handler = loadModule(model_config.parent / self._config["handler"])

if not callable(getattr(self._handler, "decode", None)):
logging.debug("Custom model handler does not contain 'decode' method!")
LOGGER.debug("Custom model handler does not contain 'decode' method!")
else:
self._decode_fn = self._handler.decode if self._decode_fn is None else self._decode_fn

Expand Down Expand Up @@ -410,7 +410,7 @@ def config_multistage_nn(self,
num_frame_pool (int, optional): Number of frames to pool for inference. If None, will use the default value.
"""
if not self.is_multi_stage():
logging.warning("Input to this model was not a NNComponent, so 2-stage NN inferencing isn't possible!"
LOGGER.warning("Input to this model was not a NNComponent, so 2-stage NN inferencing isn't possible!"
"This configuration attempt will be ignored.")
return

Expand Down Expand Up @@ -520,7 +520,7 @@ def config_yolo(self,
Configures (Spatial) Yolo Detection Network node.
"""
if not self.is_yolo():
logging.warning('This is not a YOLO detection network! This configuration attempt will be ignored.')
LOGGER.warning('This is not a YOLO detection network! This configuration attempt will be ignored.')
return

if not self.node:
Expand Down Expand Up @@ -569,7 +569,7 @@ def config_spatial(self,
calc_algo (dai.SpatialLocationCalculatorAlgorithm, optional): Specifies spatial location calculator algorithm: Average/Min/Max
"""
if not self.is_spatial():
logging.warning('This is not a Spatial Detection network! This configuration attempt will be ignored.')
LOGGER.warning('This is not a Spatial Detection network! This configuration attempt will be ignored.')
return

if bb_scale_factor is not None:
Expand Down
10 changes: 5 additions & 5 deletions depthai_sdk/src/depthai_sdk/components/stereo_component.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
import warnings
from enum import Enum
from typing import Optional, Union, Any, Dict, Tuple, List
Expand All @@ -12,6 +11,7 @@
from depthai_sdk.components.parser import parse_median_filter, parse_encode, encoder_profile_to_fourcc
from depthai_sdk.components.stereo_control import StereoControl
from depthai_sdk.components.undistort import _get_mesh
from depthai_sdk.logger import LOGGER
from depthai_sdk.oak_outputs.xout.xout_base import XoutBase, StreamXout
from depthai_sdk.oak_outputs.xout.xout_depth import XoutDisparityDepth
from depthai_sdk.oak_outputs.xout.xout_disparity import XoutDisparity
Expand Down Expand Up @@ -115,12 +115,12 @@ def __init__(self,
laser = laser if laser is not None else 800
if 0 < laser:
device.setIrLaserDotProjectorBrightness(laser)
logging.info(f'Setting IR laser dot projector brightness to {laser}mA')
LOGGER.info(f'Setting IR laser dot projector brightness to {laser}mA')

led = self._args.get('irFloodBrightness', None)
if led is not None:
device.setIrFloodLightBrightness(int(led))
logging.info(f'Setting IR flood LED brightness to {int(led)}mA')
LOGGER.info(f'Setting IR flood LED brightness to {int(led)}mA')

input_size = self._get_stream_size(self.left)
if input_size:
Expand All @@ -139,7 +139,7 @@ def __init__(self,
manip = pipeline.create(dai.node.ImageManip)
new_h = int(h * (1280 / w))
manip.setResize(1280, new_h)
logging.info(f'Input frame size to stereo component was {w}x{h}, added downscalling to 1280x{new_h}')
LOGGER.info(f'Input frame size to stereo component was {w}x{h}, added downscalling to 1280x{new_h}')
manip.setMaxOutputFrameSize(1280 * new_h)
# Stereo works on GRAY8 frames
manip.setFrameType(dai.ImgFrame.Type.GRAY8)
Expand All @@ -153,7 +153,7 @@ def __init__(self,
manip = pipeline.create(dai.node.ImageManip)
new_h = int(h * (1280 / w))
manip.setResize(1280, new_h)
logging.info(f'Input frame size to stereo component was {w}x{h}, added downscalling to 1280x{new_h}')
LOGGER.info(f'Input frame size to stereo component was {w}x{h}, added downscalling to 1280x{new_h}')
manip.setMaxOutputFrameSize(1280 * new_h)
# Stereo works on GRAY8 frames
manip.setFrameType(dai.ImgFrame.Type.GRAY8)
Expand Down
24 changes: 11 additions & 13 deletions depthai_sdk/src/depthai_sdk/components/stereo_control.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import depthai as dai
from itertools import cycle
import logging
from depthai_sdk.components.parser import parse_median_filter

logger = logging.getLogger(__name__)
from depthai_sdk.logger import LOGGER

LIMITS = {
'confidence_threshold': (0, 255),
Expand Down Expand Up @@ -43,15 +41,15 @@ def switch_median_filter(self):
Switch between auto white balance modes.
"""
mode = next(self._cycle_median_filter)
logger.info(f'Switching median filter to {mode}')
LOGGER.info(f'Switching median filter to {mode}')
self.send_controls({'postprocessing': {'median': mode}})

def confidence_threshold_up(self, step=10):
"""
Increase confidence threshold by step
"""
if LIMITS['confidence_threshold'][1] < self._current_vals['conf_threshold'] + step:
logger.error(f'Confidence threshold cannot be greater than {LIMITS["confidence_threshold"][1]}')
LOGGER.error(f'Confidence threshold cannot be greater than {LIMITS["confidence_threshold"][1]}')
return
self._current_vals['conf_threshold'] += step
self.send_controls({'cost_matching': {'confidence_threshold': self._current_vals['conf_threshold']}})
Expand All @@ -61,7 +59,7 @@ def confidence_threshold_down(self, step=10):
Decrease confidence threshold by step
"""
if LIMITS['confidence_threshold'][0] > self._current_vals['conf_threshold'] - step:
logger.error(f'Confidence threshold cannot be less than {LIMITS["confidence_threshold"][0]}')
LOGGER.error(f'Confidence threshold cannot be less than {LIMITS["confidence_threshold"][0]}')
return
self._current_vals['conf_threshold'] -= step
self.send_controls({'cost_matching': {'confidence_threshold': self._current_vals['conf_threshold']}})
Expand All @@ -71,7 +69,7 @@ def dot_projector_up(self, step=50):
Increase dot projector power by step
"""
if LIMITS['dot_projector'][1] < self._current_vals['dot_projector'] + step:
logger.error(f'Dot projector power cannot be greater than {LIMITS["dot_projector"][1]}')
LOGGER.error(f'Dot projector power cannot be greater than {LIMITS["dot_projector"][1]}')
return
self._current_vals['dot_projector'] += step
self.device.setIrFloodLightBrightness(self._current_vals['dot_projector'])
Expand All @@ -81,7 +79,7 @@ def dot_projector_down(self, step=50):
Decrease dot projector power by step
"""
if LIMITS['dot_projector'][0] > self._current_vals['dot_projector'] - step:
logger.error(f'Dot projector power cannot be less than {LIMITS["dot_projector"][0]}')
LOGGER.error(f'Dot projector power cannot be less than {LIMITS["dot_projector"][0]}')
return
self._current_vals['dot_projector'] -= step
self.device.setIrFloodLightBrightness(self._current_vals['dot_projector'])
Expand All @@ -91,7 +89,7 @@ def illumination_led_up(self, step=50):
Increase illumination led power by step
"""
if LIMITS['illumination_led'][1] < self._current_vals['illumination_led'] + step:
logger.error(f'Illumination led power cannot be greater than {LIMITS["illumination_led"][1]}')
LOGGER.error(f'Illumination led power cannot be greater than {LIMITS["illumination_led"][1]}')
return
self._current_vals['illumination_led'] += step
self.device.setIrLaserDotProjectorBrightness(self._current_vals['illumination_led'])
Expand All @@ -101,7 +99,7 @@ def illumination_led_down(self, step=50):
Decrease illumination led power by step
"""
if LIMITS['illumination_led'][0] > self._current_vals['illumination_led'] - step:
logger.error(f'Illumination led power cannot be less than {LIMITS["illumination_led"][0]}')
LOGGER.error(f'Illumination led power cannot be less than {LIMITS["illumination_led"][0]}')
return
self._current_vals['illumination_led'] -= step
self.device.setIrLaserDotProjectorBrightness(self._current_vals['illumination_led'])
Expand Down Expand Up @@ -183,15 +181,15 @@ def send_controls(self, controls: dict):
}
"""
if self.queue is None:
logger.error('Cannot send controls when replaying.')
LOGGER.error('Cannot send controls when replaying.')
return

logger.info(f'Sending controls to StereoDepth node: {controls}')
LOGGER.info(f'Sending controls to StereoDepth node: {controls}')

ctrl = dai.StereoDepthConfig()

if controls.get('reset', None) and controls['reset']:
logger.info('Resetting camera controls.')
LOGGER.info('Resetting camera controls.')
self.raw_cfg = ctrl.get()
ctrl.set(self.raw_cfg)
self.queue.send(ctrl)
Expand Down
8 changes: 4 additions & 4 deletions depthai_sdk/src/depthai_sdk/integrations/roboflow.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import json
import logging
from pathlib import Path
from typing import Dict, Optional
from zipfile import ZipFile

import depthai as dai
from depthai_sdk.logger import LOGGER
import requests

ROBOFLOW_MODELS = Path.home() / Path('.cache/roboflow-models')
Expand Down Expand Up @@ -48,9 +48,9 @@ def device_update(self, device: dai.Device) -> Path:
raise ValueError("This Roboflow's model is not from YOLO family!")

if not str(ret['modelType']).endswith('n'):
logging.info('We recommend using a lighter version of the model to get a better performance!')
LOGGER.info('We recommend using a lighter version of the model to get a better performance!')

logging.info(f"Downloading '{ret['name']}' model from Roboflow server")
LOGGER.info(f"Downloading '{ret['name']}' model from Roboflow server")

zip_file_req = requests.get(ret['model'])
zip_file_req.raise_for_status()
Expand All @@ -61,7 +61,7 @@ def device_update(self, device: dai.Device) -> Path:
with open(zip_file_path, 'wb') as f:
f.write(zip_file_req.content)

logging.info(f"Downloaded the model to {zip_file_path}")
LOGGER.info(f"Downloaded the model to {zip_file_path}")

with ZipFile(zip_file_path, 'r') as zObject: # Extract the zip
zObject.extractall(str(ROBOFLOW_MODELS / name))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import logging
from queue import Queue
from threading import Thread
from typing import Dict, Any

import rclpy

from depthai_sdk.integrations.ros.ros_base import RosBase
from depthai_sdk.logger import LOGGER


def ros_thread(queue: Queue):
Expand All @@ -18,7 +18,7 @@ def ros_thread(queue: Queue):
for topic, msg in msgs.items():
if topic not in publishers:
publishers[topic] = node.create_publisher(type(msg), topic, 10)
logging.info(f'SDK started publishing ROS messages to {topic}')
LOGGER.info(f'SDK started publishing ROS messages to {topic}')
publishers[topic].publish(msg)
rclpy.spin_once(node, timeout_sec=0.001) # 1ms timeout

Expand Down
15 changes: 9 additions & 6 deletions depthai_sdk/src/depthai_sdk/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,24 @@

__all__ = ['set_logging_level']

LOGGER = logging.getLogger(__name__)
"""The DepthAI SDK logger."""

def _configure_logger():
"""
Configure the logging module.
"""
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')

handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
LOGGER.addHandler(handler)

def set_logging_level(level):
"""
Set the logging level for the root logger.
Set the logging level for the DepthAI SDK logger.
"""
logging.getLogger().setLevel(level)
LOGGER.setLevel(level)


_configure_logger()
10 changes: 5 additions & 5 deletions depthai_sdk/src/depthai_sdk/oak_camera.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import logging
import time
import warnings
from pathlib import Path
from typing import Dict, Any, Optional, List, Union, Callable

from depthai_sdk.logger import LOGGER
from depthai_sdk import CV2_HAS_GUI_SUPPORT
from depthai_sdk.types import Resolution
from depthai_sdk.visualize.visualizer import Visualizer
Expand Down Expand Up @@ -127,7 +127,7 @@ def __init__(self,
if replay is not None:
self.replay = Replay(replay)
self.replay.initPipeline(self.pipeline)
logging.info(f'Available streams from recording: {self.replay.getStreams()}')
LOGGER.info(f'Available streams from recording: {self.replay.getStreams()}')
self._calibration = self._init_calibration()

def camera(self,
Expand Down Expand Up @@ -453,7 +453,7 @@ def __exit__(self, exc_type, exc_value, tb):
self.close()

def close(self):
logging.info("Closing OAK camera")
LOGGER.info("Closing OAK camera")
if self.replay:
self.replay.close()

Expand Down Expand Up @@ -503,7 +503,7 @@ def start(self, blocking=False):
# self._polling.append()
if self._pipeine_graph is not None:
self._pipeine_graph.create_graph(self.pipeline.serializeToJson()['pipeline'], self.device)
logging.info('Pipeline graph process started')
LOGGER.info('Pipeline graph process started')

# Call on_pipeline_started() for each component
for comp in self._components:
Expand Down Expand Up @@ -691,5 +691,5 @@ def _init_calibration(self) -> dai.CalibrationHandler:
else:
calibration = self.device.readCalibration()
if calibration is None:
logging.warning("No calibration data found on the device or in replay")
LOGGER.warning("No calibration data found on the device or in replay")
return calibration
Loading
Loading