Skip to content

Strengthen the types - #16

Merged
agfianf merged 1 commit into
mainfrom
claude/strengthen-types-mjz2gveyupfvween-x4UBa
Jan 4, 2026
Merged

Strengthen the types#16
agfianf merged 1 commit into
mainfrom
claude/strengthen-types-mjz2gveyupfvween-x4UBa

Conversation

@agfianf

@agfianf agfianf commented Jan 4, 2026

Copy link
Copy Markdown
Owner

User description

  • Replace Any types with TypedDict in device_info.py for device specs
  • Add ColorDiffMetrics and ColorDiffResult TypedDicts for calc_color_diff_patches
  • Add DetectionParams and CorrectionParams TypedDicts for analyzer
  • Update loose dict and list types with proper type parameters
  • Add CorrectionModel type alias in _factory.py
  • Update docstrings to reflect new type annotations
  • Add noqa comments for intentional Any usage in **kwargs

PR Type

Enhancement


Description

  • Replace loose dict and list types with specific type parameters

  • Add TypedDict definitions for structured data (ColorDiffMetrics, ColorDiffResult, DetectionParams, CorrectionParams, DeviceSpecsDict)

  • Add CorrectionModel type alias for correction model union type

  • Improve error handling in CorrectionModelFactory with validation

  • Update docstrings to reflect new type annotations and add noqa comments for intentional Any usage


Diagram Walkthrough

flowchart LR
  A["Loose dict/list types"] -->|"Replace with"| B["Specific type parameters"]
  C["Unstructured data"] -->|"Define as"| D["TypedDict definitions"]
  E["Union return types"] -->|"Create"| F["Type aliases"]
  G["Factory method"] -->|"Add"| H["Error handling & validation"]
Loading

File Walkthrough

Relevant files
Enhancement
det_yv8_onnx.py
Strengthen type annotations in YOLOv8 detector                     

color_correction/core/card_detection/det_yv8_onnx.py

  • Update docstring type annotations from list to list[str] for
    input/output names
  • Update input_shape type from tuple to tuple[int, ...] for better
    specificity
+3/-3     
_factory.py
Add type alias and improve factory error handling               

color_correction/core/correction/_factory.py

  • Add CorrectionModel type alias for union of correction model classes
  • Replace str parameter with LiteralModelCorrection for type safety
  • Replace dict with Any for **kwargs with noqa comment
  • Add comprehensive docstring with parameter and return type
    documentation
  • Implement error handling with KeyError for invalid model names
  • Update return type annotation to use new CorrectionModel alias
+37/-5   
polynomial.py
Strengthen polynomial model type annotations                         

color_correction/core/correction/polynomial.py

  • Import Pipeline type from sklearn for proper type annotation
  • Replace dict with Any for **kwargs with noqa comments
  • Update self.model type from untyped to Pipeline | None
  • Update self.degree type annotation to int
  • Change fit() return type from np.ndarray to Pipeline
  • Update docstrings to reflect new type annotations
+12/-11 
color_correction.py
Add TypedDicts for color difference metrics                           

color_correction/services/color_correction.py

  • Add ColorDiffMetrics TypedDict for color difference metrics (min, max,
    mean, std)
  • Add ColorDiffResult TypedDict for structured color difference results
  • Replace dict with Any for **kwargs with noqa comment
  • Update calc_color_diff_patches() return type from dict to
    ColorDiffResult
  • Simplify and clarify docstring for return type using TypedDict
+29/-15 
correction_analyzer.py
Add TypedDicts for detection and correction parameters     

color_correction/services/correction_analyzer.py

  • Add DetectionParams TypedDict with optional detection_conf_th
    parameter
  • Add CorrectionParams TypedDict with optional degree parameter
  • Replace loose dict types with specific TypedDict types in method
    signatures
  • Update parameter types from np.ndarray to ImageBGR for clarity
  • Update return type from dict to dict[str, Any] for specificity
  • Update docstrings to reference new TypedDict types
+36/-23 
device_info.py
Add DeviceSpecsDict TypedDict for hardware detection         

color_correction/utils/device_info.py

  • Add DeviceSpecsDict TypedDict for device specifications with optional
    fields
  • Replace dict[str, Any] parameters with DeviceSpecsDict in
    detect_darwin, detect_linux, detect_windows functions
  • Update detector_map type annotation to dict[str,
    Callable[[DeviceSpecsDict], DeviceSpecsDict]]
  • Initialize specs variable with explicit DeviceSpecsDict type
    annotation
  • Remove unused Any import and add Callable import
+22/-12 
report_generator.py
Strengthen report generator type annotations                         

color_correction/utils/report_generator.py

  • Update generate_table() method signature with specific type parameters
  • Change headers parameter type from list to list[Any]
  • Change rows parameter type from list to list[str]
  • Update docstring to clarify parameter types
+5/-4     

- Replace Any types with TypedDict in device_info.py for device specs
- Add ColorDiffMetrics and ColorDiffResult TypedDicts for calc_color_diff_patches
- Add DetectionParams and CorrectionParams TypedDicts for analyzer
- Update loose dict and list types with proper type parameters
- Add CorrectionModel type alias in _factory.py
- Update docstrings to reflect new type annotations
- Add noqa comments for intentional Any usage in **kwargs
@qodo-code-review

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix incorrect model factory instantiation

**Refactor the model factory to instantiate only the selected model class on
demand. This fixes a bug where all models were instantiated on every call and
kwargs were incorrectly passed.

color_correction/core/correction/_factory.py [43-53]

-model_registry: dict[str, CorrectionModel] = {
-    "least_squares": LeastSquaresRegression(),
-    "polynomial": Polynomial(**kwargs),
-    "linear_reg": LinearRegression(),
-    "affine_reg": AffineRegression(),
+model_map = {
+    "least_squares": LeastSquaresRegression,
+    "polynomial": Polynomial,
+    "linear_reg": LinearRegression,
+    "affine_reg": AffineRegression,
 }
-model = model_registry.get(model_name)
-if model is None:
-    valid_models = list(model_registry.keys())
+model_class = model_map.get(model_name)
+
+if model_class is None:
+    valid_models = list(model_map.keys())
     raise KeyError(f"Unknown model '{model_name}'. Valid options: {valid_models}")
-return model
 
+if model_class is Polynomial:
+    return model_class(**kwargs)
+
+return model_class()
+
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a bug where Polynomial(**kwargs) is executed on every call, potentially causing crashes if kwargs are passed for other models. The proposed fix correctly applies the factory pattern, improving efficiency and preventing runtime errors.

High
General
Use explicit degree parameter

**In the Polynomial class constructor, replace the generic kwargs with an
explicit degree: int = 2 parameter to make the API clearer and prevent
unsupported arguments.

color_correction/core/correction/polynomial.py [29-46]

-def __init__(self, **kwargs: Any) -> None:  # noqa: ANN401
+def __init__(self, degree: int = 2) -> None:
     self.model: Pipeline | None = None
-    self.degree: int = kwargs.get("degree", 2)
+    self.degree: int = degree
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly proposes changing **kwargs to an explicit degree parameter in the __init__ method, which improves API clarity and enables type checking. This is a valuable improvement for code maintainability and robustness.

Medium
  • More

@agfianf
agfianf merged commit d71a6df into main Jan 4, 2026
0 of 6 checks passed
@agfianf
agfianf deleted the claude/strengthen-types-mjz2gveyupfvween-x4UBa branch January 20, 2026 14:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants