Skip to content

Config

LogCfg(name='deepvisiontools', level=logging.WARNING, enabled=True, duplicate_filter=True) dataclass

Bases: deepvisiontools.config.config._Updatable

Logging configuration.

Parameters:

Name Type Description Default
name str

Logger name. Defaults to "deepvisiontools".

'deepvisiontools'
level int

Standard logging level (e.g., logging.INFO). See logging parameters for all levels. Defaults to logging.WARNING.

logging.WARNING
enabled bool

If False, logging can be globally disabled by clients. Defaults to True.

True
duplicate_filter bool

If True, prevent duplicate handler messages. Defaults to True.

True
Usage
# naive usage
cfg = LogCfg(level=logging.INFO)
cfg.level == logging.INFO
>>> True
# recommended : modify at the global config level
cfg = current().log.update(level=logging.INFO)
set_current(cfg)

VizCfg(window_mode='dual', desired_min_size=1200, mask_alpha=0.6, box_line_width=3, outline_width=2, font_size_factor=1 / 55, class_colors=None, instance_colors=None, group_class_color=True, show_scores=True, categories=None) dataclass

Bases: deepvisiontools.config.config._Updatable

Visualization parameters used by default in visualization outputs.

Parameters:

Name Type Description Default
window_mode typing.Literal['single', 'dual']

Display mode. "single" shows only the annotated image. "dual" concatenates the original image with the annotated image. Defaults to "dual".

'dual'
desired_min_size int

Minimum height/width used when resizing visualizations while preserving proportions. Defaults to 1200.

1200
mask_alpha float

Transparency level used for mask annotations. Defaults to 0.6.

0.6
box_line_width int

Width of bounding-box lines. Defaults to 3.

3
outline_width int

Width of polygon and contour outlines. Defaults to 2.

2
font_size_factor float

Relative text-size factor based on image size. Defaults to 1 / 55.

1 / 55
class_colors list[collections.abc.Sequence[int]] | None

RGB colors used for class-level masks or labels. If None, library defaults are used. Defaults to None.

None
instance_colors list[collections.abc.Sequence[int]] | None

RGB colors used for instance annotations. If None, library defaults are used. Defaults to None.

None
group_class_color bool

If True, detection and instance visualizations use one shared color per class. Defaults to True.

True
show_scores bool

Whether to display confidence scores for prediction tasks that provide scores. Defaults to True.

True
categories dict[int, str] | None

Mapping from class id to class name. If None, class ids are used as labels. Defaults to None.

None
Usage
from deepvisiontools.config import current, set_current

# Direct usage
v = VizCfg(mask_alpha=0.4)
v2 = v.update(window_mode="single")
(v.window_mode, v2.window_mode)
>>> ("dual", "single")

# Recommended: modify visualization options at global config level.
cfg = current().update_viz(window_mode="single", show_scores=False)
set_current(cfg)
current().viz.window_mode
>>> "single"

BboxCfg(type='bbox', num_classes=1, min_size=5, conf_threshold=0.5, nms_threshold=0.5, max_det=500) dataclass

Bases: deepvisiontools.config.config.DataCfgBase

Configuration for bounding box detection tasks.

Parameters:

Name Type Description Default
type str

Fixed to "bbox".

'bbox'
min_size int

Minimum (w or h) in pixels to keep a box (sanitization). Defaults to 5.

5
conf_threshold float

Default confidence threshold. Defaults to 0.5.

0.5
nms_threshold float

IoU threshold for NMS. Defaults to 0.5.

0.5
max_det int

Maximum detections per image. Defaults to 500.

500

InstanceMaskCfg(type='instance_mask', num_classes=1, min_size=5, conf_threshold=0.5, nms_threshold=0.5, mask_logits_threshold=0.5, max_det=500, split_separated_objects=False) dataclass

Bases: deepvisiontools.config.config.DataCfgBase

Configuration for instance segmentation tasks.

Parameters:

Name Type Description Default
type str

Fixed to "instance_mask".

'instance_mask'
min_size int

Minimum object size (in pixels) to retain after sanitization. Defaults to 5.

5
conf_threshold float

Default confidence threshold. Defaults to 0.5.

0.5
nms_threshold float

IoU threshold for NMS. Defaults to 0.5.

0.5
mask_logits_threshold float

Binarization threshold for mask logits. Defaults to 0.5.

0.5
max_det int

Maximum instances per image. Defaults to 500.

500
split_separated_objects bool

If True, sanitize splits disconnected components of a single instance into independent instances, duplicating labels and scores for each component. Useful in presence of crop style augmentations. Defaults to False.

False

SemanticMaskCfg(type='semantic_mask', num_classes=1, min_size=0, binary_logits_threshold=0.5, logits_combine='avg') dataclass

Bases: deepvisiontools.config.config.DataCfgBase

Configuration for semantic segmentation.

Parameters:

Name Type Description Default
type str

Fixed to "semantic_mask".

'semantic_mask'
min_size int

Classes with total pixel count below this may be dropped. Defaults to 0.

0
binary_logits_threshold float

Threshold for binary class logits (when num_classes==1). Defaults to 0.5.

0.5
logits_combine typing.Literal['avg', 'min', 'max']

Strategy to merge logits across tiles/augmentations. Defaults to "avg".

'avg'

DVConfig(device='cpu', log=LogCfg(), viz=VizCfg(), data_box=BboxCfg(), data_instance_mask=InstanceMaskCfg(), data_semantic_mask=SemanticMaskCfg(), amp=True) dataclass

Bases: deepvisiontools.config.config._Updatable

Top-level DeepVision configuration (context-local via ContextVar). From this class, you can configure a wide range of the library parameters.

Parameters:

Name Type Description Default
device typing.Literal['cpu', 'cuda']

Default device for models. Defaults to "cpu".

'cpu'
log deepvisiontools.config.config.LogCfg

Logging configuration. Defaults to LogCfg().

deepvisiontools.config.config.LogCfg()
viz deepvisiontools.config.config.VizCfg

Visualization configuration. Defaults to VizCfg().

deepvisiontools.config.config.VizCfg()
data_box deepvisiontools.config.config.BboxCfg

Detection data config. Defaults to BboxCfg().

deepvisiontools.config.config.BboxCfg()
data_instance_mask deepvisiontools.config.config.InstanceMaskCfg

Instance seg data config. Defaults to InstanceMaskCfg().

deepvisiontools.config.config.InstanceMaskCfg()
data_semantic_mask deepvisiontools.config.config.SemanticMaskCfg

Semantic seg data config. Defaults to SemanticMaskCfg().

deepvisiontools.config.config.SemanticMaskCfg()
amp bool

Default automatic mixed precision switch for models. Defaults to True.

True
Note
  • Check arguments for the different accessors. Some will return specific config types (like log, viz, data of all types etc.). Others are simple attributes of DVConfig (like device etc.)
  • For concrete usage please check documentation of current and set_current functions.

update_bbox(**kw)

Return a new config with data_box fields updated immutably.

Source code in src/deepvisiontools/config/config.py
293
294
295
def update_bbox(self, **kw) -> DVConfig:
    """Return a new config with `data_box` fields updated immutably."""
    return self.update(data_box=self.data_box.update(**kw))

update_instance_mask(**kw)

Return a new config with data_instance_mask fields updated immutably.

Source code in src/deepvisiontools/config/config.py
297
298
299
def update_instance_mask(self, **kw) -> DVConfig:
    """Return a new config with `data_instance_mask` fields updated immutably."""
    return self.update(data_instance_mask=self.data_instance_mask.update(**kw))

update_semantic_mask(**kw)

Return a new config with data_semantic_mask fields updated immutably.

Source code in src/deepvisiontools/config/config.py
301
302
303
def update_semantic_mask(self, **kw) -> DVConfig:
    """Return a new config with `data_semantic_mask` fields updated immutably."""
    return self.update(data_semantic_mask=self.data_semantic_mask.update(**kw))

update_device(val)

Return a new config with the global fallback device updated.

Accepted
  • "cpu"
  • "cuda"
  • "cuda:0", "cuda:1", ...
  • "auto"
Source code in src/deepvisiontools/config/config.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def update_device(self, val: str) -> DVConfig:
    """
    Return a new config with the global fallback device updated.

    Accepted:
      - "cpu"
      - "cuda"
      - "cuda:0", "cuda:1", ...
      - "auto"
    """
    if val is None:
        raise TypeError("device must be a string, got None.")

    dev = str(val).strip().lower()
    if dev == "":
        raise ValueError("device cannot be an empty string.")

    ok = dev in {"cpu", "cuda", "auto"} or dev.startswith("cuda:")
    if not ok:
        raise ValueError(
            "device must be one of 'cpu', 'cuda', 'cuda:N', or 'auto'. "
            f"Got {val!r}."
        )

    return self.update(device=dev)

current()

Get the current global DVConfig (context-local) object. You can configure a lot of options from the usage of current together with set_current

Returns:

Name Type Description
DVConfig deepvisiontools.config.config.DVConfig

The active configuration object.

Tips
  • Using ContextVar makes the config safe for async/task contexts
  • override it in a context manager with use_config(...) block without affecting other concurrent tasks.
Usage
from deepvisiontools.config import current, set_current, use_config
# Access global configs values with current()
cfg = current()
isinstance(cfg, DVConfig)
>>> True
cfg.log.level
>>> 30  # warning level from logging library
cfg.device
>>> "cpu"
cfg.data_box.max_det = 500
# Set a config as a global config
cfg1 = DVConfig(device="cuda")
cfg2 = DVConfig(device="cpu")
set_current(cfg1)
current().device
>>> "cuda"
set_current(cfg2)
>>> "cpu"
# Use a context manager for temporary config
set_current(cfg1)
with cfg2:
    print(current().device)
>>> "cpu"
Source code in src/deepvisiontools/config/config.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def current() -> DVConfig:
    """
    Get the current global `DVConfig` (context-local) object. You can configure a lot of options from the usage of `current` together with `set_current`

    Returns:
        DVConfig: The active configuration object.

    ???+ tip "Tips"
        - Using `ContextVar` makes the config safe for async/task contexts
        - override it in a context manager `with use_config(...)` block without affecting other concurrent tasks.

    ???+ example "Usage"
        ```Python
        from deepvisiontools.config import current, set_current, use_config
        # Access global configs values with current()
        cfg = current()
        isinstance(cfg, DVConfig)
        >>> True
        cfg.log.level
        >>> 30  # warning level from logging library
        cfg.device
        >>> "cpu"
        cfg.data_box.max_det = 500
        # Set a config as a global config
        cfg1 = DVConfig(device="cuda")
        cfg2 = DVConfig(device="cpu")
        set_current(cfg1)
        current().device
        >>> "cuda"
        set_current(cfg2)
        >>> "cpu"
        # Use a context manager for temporary config
        set_current(cfg1)
        with cfg2:
            print(current().device)
        >>> "cpu"
        ```
    """
    cfg = _CURRENT.get()
    if cfg is None:
        cfg = DVConfig()
        _CURRENT.set(cfg)
    return cfg

set_current(cfg)

Set the current DVConfig globally. You can configure a lot of options from the usage of current together with set_current

Parameters:

Name Type Description Default
cfg deepvisiontools.config.config.DVConfig

The configuration to activate.

required
Note

This replaces the active config until another set_current(...) or a use_config(...) context overrides it.

Usage
from deepvisiontools.config import current, set_current, use_config
# Access global configs values with current()
cfg = current()
isinstance(cfg, DVConfig)
>>> True
cfg.log.level
>>> 30  # warning level from logging library
cfg.device
>>> "cpu"
cfg.data_box.max_det = 500
# Set a config as a global config
cfg1 = DVConfig(device="cuda")
cfg2 = DVConfig(device="cpu")
set_current(cfg1)
current().device
>>> "cuda"
set_current(cfg2)
>>> "cpu"
# Use a context manager for temporary config
set_current(cfg1)
with cfg2:
    print(current().device)
>>> "cpu"
Source code in src/deepvisiontools/config/config.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
def set_current(cfg: DVConfig) -> None:
    """
    Set the current `DVConfig` globally. You can configure a lot of options from the usage of `current` together with `set_current`

    Args:
        cfg (DVConfig): The configuration to activate.

    ???+ note "Note"
        This replaces the active config until another `set_current(...)` or a `use_config(...)`
        context overrides it.

    ???+ example "Usage"
        ```Python
        from deepvisiontools.config import current, set_current, use_config
        # Access global configs values with current()
        cfg = current()
        isinstance(cfg, DVConfig)
        >>> True
        cfg.log.level
        >>> 30  # warning level from logging library
        cfg.device
        >>> "cpu"
        cfg.data_box.max_det = 500
        # Set a config as a global config
        cfg1 = DVConfig(device="cuda")
        cfg2 = DVConfig(device="cpu")
        set_current(cfg1)
        current().device
        >>> "cuda"
        set_current(cfg2)
        >>> "cpu"
        # Use a context manager for temporary config
        set_current(cfg1)
        with cfg2:
            print(current().device)
        >>> "cpu"
        ```
    """
    _CURRENT.set(cfg)

use_config(cfg)

Temporarily activate a configuration inside a with block (context manager).

Parameters:

Name Type Description Default
cfg deepvisiontools.config.config.DVConfig

The configuration to use within the context.

required
Usage
from deepvisiontools.config import current, set_current, use_config
# Access global configs values with current()
cfg = current()
isinstance(cfg, DVConfig)
>>> True
cfg.log.level
>>> 30  # warning level from logging library
cfg.device
>>> "cpu"
cfg.data_box.max_det = 500
# Set a config as a global config
cfg1 = DVConfig(device="cuda")
cfg2 = DVConfig(device="cpu")
set_current(cfg1)
current().device
>>> "cuda"
set_current(cfg2)
>>> "cpu"
# Use a context manager for temporary config
set_current(cfg1)
with cfg2:
    print(current().device)
>>> "cpu"
Source code in src/deepvisiontools/config/config.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
@contextmanager
def use_config(cfg: DVConfig):
    """
    Temporarily activate a configuration inside a `with` block (context manager).

    Args:
        cfg (DVConfig): The configuration to use within the context.

    ???+ example "Usage"
        ```Python
        from deepvisiontools.config import current, set_current, use_config
        # Access global configs values with current()
        cfg = current()
        isinstance(cfg, DVConfig)
        >>> True
        cfg.log.level
        >>> 30  # warning level from logging library
        cfg.device
        >>> "cpu"
        cfg.data_box.max_det = 500
        # Set a config as a global config
        cfg1 = DVConfig(device="cuda")
        cfg2 = DVConfig(device="cpu")
        set_current(cfg1)
        current().device
        >>> "cuda"
        set_current(cfg2)
        >>> "cpu"
        # Use a context manager for temporary config
        set_current(cfg1)
        with cfg2:
            print(current().device)
        >>> "cpu"
        ```
    """
    token = _CURRENT.set(cfg)
    try:
        yield cfg
    finally:
        _CURRENT.reset(token)