unittest.mock, from stand-ins to spies

Python · Testing

A mock is a stand-in you put where a real function or object used to be, for as long as a test runs. It answers the way you tell it to, it remembers every call it got, and when the test ends the original comes back. This guide covers both halves — controlling and recording — and then the part most tutorials skip: wraps=, a spy that lets the real code run.

A | B means either: reading union type hints in Python

Python · Type hints

def sensor_id(sensor: Sensor | int | None) -> int has three bars in one signature and looks like bit arithmetic. It is not arithmetic and it is not new syntax to memorise: each bar is the word or, and the whole annotation is one sentence — "a Sensor, or an int, or nothing".

The list that remembers: mutable default arguments in Python

Python · Language

def append_to(item, target=[]) looks like it starts from an empty list every time. It does not. One list is created when the def statement runs, and every call for the rest of the program's life shares it.

The loop variable that changed: late binding and default arguments in Python

Python · Language

You define a function inside a loop, collect the functions, call them later — and every single one returns the last value. The usual fix is a strange-looking line where the same name appears twice. Here is what is actually going on, and why the fix works.

pytest, from your first test to your own plugin

Python · Testing

Most pytest tutorials stop right after assert 1 + 1 == 2, which is roughly where the interesting part begins. This one keeps going — through fixtures, parametrization and the configuration that makes a suite pleasant to live with, and out the other side into hooks and plugins.

Understanding Python variable type hints (Dict, dict, and mypy)

When you read Python code, sooner or later you hit a line like this:

data: Dict[str, int] = {}

The : Dict[str, int] part looks strange the first time. In this post we'll figure out exactly what that one line means — and whether a "type hint" is actually enforced — using tiny runnable examples.

1. One line, three things at once

That single line is really three pieces glued together.

data  :  Dict[str, int]  =  {}
 │            │              │
name       type hint       actual
            (a note)        value
PieceMeaning
datathe variable name
: Dict[str, int]a type hint — "keys are str, values are int". Just a note for humans/editors
= {}the actual value = an empty dict

At runtime it is exactly the same as:

data = {}   # drop the hint and this is all that's left

2. = {} is just a dict

A dict is a "key → value" store. It has nothing to do with type hints — it's a basic built-in type that has always existed.

data = {}                 # empty dict
data["gemm"]   = "A"      # key (str) -> value
data["conv2d"] = "B"
print(data)               # {'gemm': 'A', 'conv2d': 'B'}
print(data["gemm"])       # A
print(list(data))         # ['gemm', 'conv2d']

3. : Dict[str, int] is a "type hint"

Dict[str, int] is a note saying "a dict whose keys are strings and values are integers". Python does not enforce that note when it runs.

from typing import Dict

ages: Dict[str, int] = {}   # at runtime this is just ages = {}
ages["alice"] = 30
ages["bob"]   = 25
print(ages)                 # {'alice': 30, 'bob': 25}

4. Is it really not enforced? — break it on purpose

Violating the hint does not raise an error. Let's prove it.

from typing import Dict

ages: Dict[str, int] = {}   # promise: "str keys, int values"
ages["alice"] = 30          # keeps the promise
ages["oops"]  = "not-int"   # value is a string -> breaks it
ages[123]     = 99          # key is an int      -> breaks it
print(ages)

Output:

{'alice': 30, 'oops': 'not-int', 123: 99}
Key point: a type hint is not enforced. The Python interpreter simply ignores it at runtime, so breaking it still runs fine.

5. So why write hints at all?

If they're not enforced, why bother? Because they're a "quality tool", not a rule.

  • Humans — reading the code, you instantly see "this is a str→int dict".
  • Editors (IDEs) — autocomplete, and a red squiggle when you misuse it.
  • Static checkers (mypy) — run mypy file.py separately and it catches violations before you run the code.
A hint is "a promise + documentation", not a check. To actually catch violations, run a tool like mypy yourself — the interpreter won't.

6. Dict vs dict — and when did this syntax appear?

The dict itself is old; the type-hint syntax is the newer part.

SyntaxImport needed?Introduced
Dict[str, int] (capital)from typing import DictPython 3.5 (2015)
dict[str, int] (lowercase)none (built-in)Python 3.9 (2020)
dict (plain)nonealways

Annotating a variable with x: int = 0 has been possible since Python 3.6 (2016). Both forms mean the same thing, so new code usually prefers the lowercase dict[...].

scores: dict[str, float] = {}   # 3.9+ : lowercase, no import

Summary

  • name: Type = value == name = value + (a type note)
  • = {} is just an empty dict (old, ordinary syntax)
  • : Dict[str, int] is a hint that is not enforced — breaking it still runs
  • hints are documentation for humans / editors / mypy; the checking is done by mypy, separately

AWS SAM Troubleshooting - Fixing pip/runtime and AWS CLI Issues


🔧 AWS SAM Troubleshooting - Fixing pip/runtime and AWS CLI Issues

If you're deploying AWS Lambda functions with SAM (Serverless Application Model), you may have encountered frustrating build errors. This guide explains the two most common issues and how to fix them permanently.

Note: This guide uses generic examples (<YOUR_STACK_NAME>) and is safe to share publicly.

🚨 The Two Common Problems

Problem A — sam build fails with pip/runtime error

You may see this error:

Error: PythonPipBuilder:ResolveDependencies - Failed to find a Python runtime containing pip on the PATH.

What this means: SAM is trying to build for a specific Lambda runtime (like python3.11), but your shell has:

  • python from one location (e.g., conda environment)
  • pip from another location (e.g., ~/.local/bin or /usr/bin)

SAM requires a matching pair - the pip must belong to the same Python interpreter that matches your Lambda runtime version.

Problem B — AWS CLI crashes with botocore conflicts

You may see errors like:

KeyError: 'opsworkscm'
ModuleNotFoundError: No module named 'dateutil'

What this means: Your system AWS CLI (/usr/bin/aws) is accidentally importing incompatible botocore or boto3 packages from ~/.local/lib/python..., causing version conflicts.

🔍 Quick Diagnosis (5 Commands)

Run these from your SAM project directory to diagnose the issue:

# 1. What Python runtime does your template.yaml require?
grep "Runtime: python" template.yaml

# 2. What python are you using?
which python
python -V

# 3. What pip are you using?
which pip
pip -V

# 4. Does pip belong to this python?
python -m pip -V

🚩 Red flag: If pip -V and python -m pip -V show different paths or Python versions, your PATH is contaminated.

✅ The Fix: Dedicated Environment + Clean PATH

The solution is to create an isolated environment that matches your Lambda runtime and force clean PATH ordering.

Step 1: Create an environment matching your Lambda runtime

If your template.yaml specifies Runtime: python3.11, create a Python 3.11 environment:

# Using conda (recommended)
conda create -n aws-sam-py311 python=3.11 pip -y
conda activate aws-sam-py311

# Or using venv
python3.11 -m venv ~/.virtualenvs/aws-sam-py311
source ~/.virtualenvs/aws-sam-py311/bin/activate

Step 2: Install SAM CLI and AWS CLI inside the environment

# Upgrade pip first
python -m pip install --upgrade pip

# Install SAM CLI
python -m pip install aws-sam-cli

# Optional: Install AWS CLI v2 (avoids system aws/botocore conflicts)
# Using conda-forge:
conda install -c conda-forge awscli -y

# Or using pip:
python -m pip install awscli

Step 3: Disable user-site imports and fix PATH ordering

This is the critical step that prevents ~/.local contamination:

# Disable user site-packages (~/.local)
export PYTHONNOUSERSITE=1

# Force clean PATH (conda/venv bin first, then system)
export PATH="$CONDA_PREFIX/bin:/usr/bin:/bin"

# Or for venv:
# export PATH="$VIRTUAL_ENV/bin:/usr/bin:/bin"

# Clear shell hash table
hash -r

Step 4: Verify the fix

# All should point to your environment
which python
which pip
which sam
which aws

# Verify versions match
python -V      # Should be 3.11.x
pip -V         # Should show python 3.11
sam --version  # Should work without errors
aws --version  # Should work without errors

Step 5: Build and deploy

sam build --cached --parallel
sam deploy --no-confirm-changeset --stack-name <YOUR_STACK_NAME> --region <YOUR_AWS_REGION>

🐳 Alternative: Container Build (Docker)

If you have Docker installed, you can avoid all Python toolchain issues by building in a container:

sam build --use-container
sam deploy --no-confirm-changeset --stack-name <YOUR_STACK_NAME> --region <YOUR_AWS_REGION>

Pros:

  • ✅ No need to match local Python version
  • ✅ Builds in environment identical to Lambda
  • ✅ Most reproducible approach

Cons:

  • ❌ Slower than native builds
  • ❌ Requires Docker installed and running

⚡ Quick Fix for Broken AWS CLI (Emergency)

If you need to use system AWS CLI right now and it's broken:

# Force it to ignore user-site packages
PYTHONNOUSERSITE=1 /usr/bin/aws --version
PYTHONNOUSERSITE=1 /usr/bin/aws sts get-caller-identity
PYTHONNOUSERSITE=1 /usr/bin/aws s3 ls

But the proper fix is: Install AWS CLI inside your dedicated environment (see Step 2 above).

🤔 Why Lambda is python3.11 but my machine uses python3.12?

This is a common source of confusion. They are different things:

Component What It Is Where It's Defined
Lambda Runtime Python version AWS runs in production template.yaml → Runtime: python3.11
Your Local Python Python version for development/training/scripts Your system default or conda environment

Key point: When SAM builds your Lambda functions, it must build dependencies compatible with the Lambda runtime, even if your system default is Python 3.12.

Example from template.yaml:

AnprDeviceLicenseValidateFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: anpr_device_license_validate/
    Handler: app.lambda_handler
    Runtime: python3.11          # ← Lambda uses 3.11
    Architectures:
      - x86_64

So you have three options:

  1. Match local environment to Lambda (recommended) - Create python3.11 env for SAM work
  2. Use container build - Let Docker handle it with sam build --use-container
  3. Upgrade Lambda runtime - Change template.yaml to python3.12 (requires testing)

📋 Complete Example: Deploy Script

Here's a complete bash script that implements all the fixes:

#!/usr/bin/env bash
set -euo pipefail

# Activate conda environment (matches Lambda runtime)
source ~/anaconda3/etc/profile.d/conda.sh
conda activate aws-sam-py311

# Critical: Clean PATH and disable user-site
export PYTHONNOUSERSITE=1
export PATH="$CONDA_PREFIX/bin:/usr/bin:/bin"
hash -r

echo "Environment ready:"
echo "  Python: $(python -V)"
echo "  SAM: $(sam --version | head -1)"
echo "  AWS: $(aws --version)"

# Build and deploy
sam build --cached --parallel
sam deploy --no-confirm-changeset

🎯 Troubleshooting Checklist

Issue Check Fix
sam build fails which pip vs python -m pip -V Create dedicated env, fix PATH
aws command crashes echo $PYTHONNOUSERSITE Set PYTHONNOUSERSITE=1
Wrong Python version python -V vs Lambda runtime Create env matching Lambda
Multiple pip versions which -a pip Fix PATH ordering
Conda conflicts conda env list Create separate env for SAM

🔒 Security Best Practices

⚠️ When sharing code publicly:

  • ❌ Never publish template.yaml with secrets (API keys, tokens, webhook URLs)
  • ✅ Use AWS Secrets Manager or SSM Parameter Store for secrets
  • ✅ Redact from logs:
    • AWS account IDs
    • API Gateway URLs
    • Stack names and ARNs
    • Any access keys/tokens

💡 Pro Tips

1. Create a deployment script

Instead of remembering all these environment variables, create a deploy.sh script:

#!/usr/bin/env bash
set -euo pipefail

# Activate environment
source ~/anaconda3/etc/profile.d/conda.sh
conda activate aws-sam-py311

# Clean environment
export PYTHONNOUSERSITE=1
export PATH="$CONDA_PREFIX/bin:/usr/bin:/bin"
hash -r

# Build and deploy
sam build --cached --parallel
sam deploy --no-confirm-changeset

echo "✅ Deployment complete!"

Make it executable: chmod +x deploy.sh

2. Use SAM build cache for faster builds

# First build (slow)
sam build

# Subsequent builds (much faster!)
sam build --cached --parallel

3. Test locally before deploying

# Invoke function locally
sam local invoke MyFunction --event events/test.json

# Start local API
sam local start-api

4. Skip changeset confirmation in CI/CD

# Manual deployment - shows changes
sam deploy

# CI/CD deployment - no prompts
sam deploy --no-confirm-changeset

📊 Before vs After

❌ Before (Broken)
$ sam build
Error: Failed to find Python runtime containing pip

$ aws --version
KeyError: 'opsworkscm'

$ which pip
/home/user/.local/bin/pip  # Wrong location!

$ pip -V
pip 24.0 (python 3.12)     # Wrong version!
✅ After (Fixed)
$ conda activate aws-sam-py311
$ export PYTHONNOUSERSITE=1
$ export PATH="$CONDA_PREFIX/bin:/usr/bin:/bin"

$ sam build
Build Succeeded ✨

$ aws --version
aws-cli/2.32.26 Python/3.11.14

$ which pip
/home/user/anaconda3/envs/aws-sam-py311/bin/pip  # Correct!

$ pip -V
pip 25.3 (python 3.11)     # Matches Lambda runtime!

🎓 Summary

The root cause of most SAM build failures is PATH contamination - your shell mixes Python versions and pip locations from different sources (~/.local, /usr/bin, conda environments).

The complete fix:

  1. ✅ Create dedicated environment matching Lambda runtime (python3.11)
  2. ✅ Install SAM CLI and AWS CLI inside that environment
  3. ✅ Set PYTHONNOUSERSITE=1 to disable user-site packages
  4. ✅ Fix PATH ordering: export PATH="$CONDA_PREFIX/bin:/usr/bin:/bin"
  5. ✅ Run hash -r to clear shell cache

After this, sam build and aws commands will work reliably! 🚀

🔗 Additional Resources


Tags: AWS, SAM, Lambda, Python, DevOps, Deployment, Troubleshooting, ServerlessFramework, CICD, CloudComputing

FREE ANPR/ALPR/LPR API - Try Before You Buy (1000 Requests/Day)


🎁 FREE License Plate Recognition API - No Credit Card Required!

Want to try ANPR (Automatic Number Plate Recognition) / ALPR (Automatic License Plate Recognition) / LPR (License Plate Recognition) without buying a license? We offer a completely FREE test API with 1000 requests per day!

✨ What You Get (FREE!)

  • ✅ 1000 requests/day - Perfect for testing and evaluation
  • ✅ No credit card required
  • ✅ No registration needed
  • ✅ 5 regions supported: Korea, Europe, USA/Canada, China, Universal
  • ✅ Multiple models to test (pico to large)
  • ✅ Works instantly - just install and run!

🚀 Quick Start (30 Seconds)

# Install
pip install marearts-anpr

# Test immediately (NO CONFIG NEEDED!)
ma-anpr test-api your-plate.jpg --region eup

# That's it! 🎉

🌍 Supported Regions

Region Code Coverage Example
kr South Korea 123가4567
eup Europe (EU standards) AB-123-CD
na USA, Canada, Mexico ABC-1234
cn China 京A·12345
univ Universal (all) Any format

💻 Usage Examples

Command Line (Easiest!)

# European plates
ma-anpr test-api eu-plate.jpg --region eup

# Korean plates
ma-anpr test-api kr-plate.jpg --region kr

# US plates
ma-anpr test-api us-plate.jpg --region na

# Chinese plates
ma-anpr test-api cn-plate.jpg --region cn

# Unknown region? Use universal
ma-anpr test-api unknown-plate.jpg --region univ

Python Script

#!/usr/bin/env python3
import subprocess

def test_free_anpr(image_path, region='eup'):
    """Test free ANPR API - no credentials needed!"""
    
    cmd = f'ma-anpr test-api "{image_path}" --region {region}'
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    
    if result.returncode == 0:
        print(result.stdout)
        return True
    else:
        print(f"Error: {result.stderr}")
        return False

# Test European plate
test_free_anpr("plate.jpg", "eup")

# Test Korean plate
test_free_anpr("plate2.jpg", "kr")

Test Multiple Regions

# Test same image with different regions
for region in eup kr na cn univ; do
    echo "Testing $region..."
    ma-anpr test-api plate.jpg --region $region
done

🎯 Advanced Options

Try Different Models

# List all available models
ma-anpr test-api --list-models

# Try different detector models
ma-anpr test-api plate.jpg --region eup --detector small_640p_fp32
ma-anpr test-api plate.jpg --region eup --detector medium_640p_fp32
ma-anpr test-api plate.jpg --region eup --detector large_640p_fp32

# Try different OCR models
ma-anpr test-api plate.jpg --region eup --ocr small_fp32
ma-anpr test-api plate.jpg --region eup --ocr medium_fp32
ma-anpr test-api plate.jpg --region eup --ocr large_fp32

Batch Testing

# Test all images in a folder
for img in ./plates/*.jpg; do
    echo "Processing $img..."
    ma-anpr test-api "$img" --region eup
done

📊 Sample Output

{
  "results": [
    {
      "ocr": "AB-123-CD",
      "ocr_conf": 98.5,
      "ltrb": [120, 230, 380, 290],
      "ltrb_conf": 95
    }
  ],
  "ltrb_proc_sec": 0.15,
  "ocr_proc_sec": 0.03,
  "status": "success"
}

🆓 FREE vs PAID Comparison

Feature FREE Test API Paid License
Requests/Day 1000 Unlimited
Speed ~0.5s (cloud) ~0.02s (local GPU)
Internet Required Yes No (offline OK)
Configuration None One-time setup
Regions All 5 All 5
Models All All
Price $0 Contact sales

🎓 Use Cases for Free API

  • ✅ Evaluation: Try before buying a license
  • ✅ Prototyping: Build POC applications
  • ✅ Testing: Test accuracy on your specific plates
  • ✅ Education: Learn ANPR/ALPR/LPR technology
  • ✅ Small Projects: Personal projects under 1000/day
  • ✅ Region Testing: Find which region works best
  • ✅ Model Comparison: Compare different model sizes

📈 When to Upgrade to Paid License?

Consider upgrading when you need:

  • 🚀 Unlimited requests (no daily limit)
  • ⚡ 10-100x faster processing (local GPU)
  • 🔒 Offline operation (no internet needed)
  • 🏢 Commercial deployment
  • 📹 Real-time video processing
  • 🎯 High-volume applications (>1000/day)

💡 Pro Tips

# 1. Use specific regions for best accuracy
ma-anpr test-api plate.jpg --region eup  # ✅ Better
ma-anpr test-api plate.jpg --region univ # ⚠️ OK but less accurate

# 2. Test different models to find best speed/accuracy balance
ma-anpr test-api plate.jpg --region eup --detector small_640p_fp32   # Faster
ma-anpr test-api plate.jpg --region eup --detector large_640p_fp32   # More accurate

# 3. Check remaining quota
ma-anpr test-api --check-quota

# 4. Get help
ma-anpr test-api --help

# 5. See all options
ma-anpr test-api --list-models

🔍 Troubleshooting

Rate limit exceeded?

# Wait until midnight UTC (resets daily)
# OR upgrade to paid license for unlimited requests

No plates detected?

# Try different detector models
ma-anpr test-api plate.jpg --region eup --detector large_640p_fp32

# Try universal region
ma-anpr test-api plate.jpg --region univ

Wrong text recognized?

# Make sure you're using correct region!
ma-anpr test-api plate.jpg --region kr   # For Korean plates
ma-anpr test-api plate.jpg --region eup  # For European plates

# Try larger OCR model
ma-anpr test-api plate.jpg --region eup --ocr large_fp32

📖 Complete Example Script

#!/usr/bin/env python3
"""
Free ANPR Test Script
Test license plate recognition with different regions and models
"""
import subprocess
import json

def test_anpr_free(image_path, region='eup', detector='medium_640p_fp32', ocr='medium_fp32'):
    """Test free ANPR API"""
    
    cmd = [
        'ma-anpr', 'test-api', image_path,
        '--region', region,
        '--detector', detector,
        '--ocr', ocr
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode == 0:
        try:
            data = json.loads(result.stdout)
            return data
        except:
            return result.stdout
    else:
        return {"error": result.stderr}

# Test European plate with different models
image = "eu-plate.jpg"

print("Testing different detector models...")
for detector in ['small_640p_fp32', 'medium_640p_fp32', 'large_640p_fp32']:
    result = test_anpr_free(image, 'eup', detector)
    print(f"{detector}: {result}")

print("\nTesting different regions...")
for region in ['eup', 'kr', 'na', 'univ']:
    result = test_anpr_free(image, region)
    print(f"{region}: {result}")

🎯 Real-World Example

# Parking lot monitoring (Europe)
ma-anpr test-api parking-cam.jpg --region eup

# Toll booth (USA)
ma-anpr test-api toll-booth.jpg --region na

# Security gate (Korea)
ma-anpr test-api security-cam.jpg --region kr

# Traffic enforcement (China)
ma-anpr test-api traffic.jpg --region cn

# Multi-national (airport parking)
ma-anpr test-api airport.jpg --region univ

🌟 Why Choose MareArts ANPR?

  • ✅ FREE tier available - Try before you buy!
  • ✅ State-of-the-art AI - Latest deep learning models
  • ✅ Multi-region support - Works worldwide
  • ✅ Fast processing - ~0.02s with GPU
  • ✅ Easy integration - Python, HTTP API, CLI
  • ✅ Regular updates - New models and features
  • ✅ Commercial ready - Production-grade quality

🚀 Get Started Now!

# Install (takes 10 seconds)
pip install marearts-anpr

# Test (takes 20 seconds)
ma-anpr test-api your-plate.jpg --region eup

# Celebrate! 🎉
# You just recognized your first license plate!

📞 Need More?

💬 What People Are Saying

"Finally, an ANPR API I can test without entering my credit card!" - Developer

"1000 requests/day is perfect for my small parking lot project." - Small Business Owner

"Tested all 5 regions before buying. Confident in my purchase!" - System Integrator

🎁 Summary

MareArts ANPR offers a completely FREE test API with 1000 requests per day. No credit card, no registration, no strings attached. Just install and start recognizing license plates!

  • ✅ Install: pip install marearts-anpr
  • ✅ Test: ma-anpr test-api plate.jpg --region eup
  • ✅ Evaluate: Try all regions and models
  • ✅ Upgrade: When ready for unlimited use

Start your ANPR/ALPR/LPR journey today - completely FREE! 🚗📸



MareArts ANPR V14 - Advanced Manual Processing & Performance Tuning

 

⚡ MareArts ANPR V14 - Advanced Manual Processing

Ready to take control? In this advanced guide, I'll show you how to manually process detections, measure performance, and optimize for your specific use case.

🎯 Why Manual Processing?

  • Full control over detection pipeline
  • Custom filtering and post-processing
  • Performance measurement and optimization
  • Integration with existing computer vision pipelines
  • Custom confidence thresholds per stage

🔧 Manual Detection & OCR Pipeline

from marearts_anpr import ma_anpr_detector_v14, ma_anpr_ocr_v14
import cv2
from PIL import Image
import time

# Initialize models
detector = ma_anpr_detector_v14(
    "medium_640p_fp32",
    user_name, serial_key, signature,
    backend="cpu",
    conf_thres=0.25,
    iou_thres=0.5
)

ocr = ma_anpr_ocr_v14("medium_fp32", "eup", user_name, serial_key, signature)

# Load image
img = cv2.imread("plate.jpg")

# Step 1: Detect license plates
start = time.time()
detections = detector.detector(img)
detection_time = time.time() - start

print(f"Detection time: {detection_time:.4f}s")
print(f"Found {len(detections)} plate(s)")

# Step 2: Process each detection
results = []
ocr_time = 0

for i, box_info in enumerate(detections):
    # Get bounding box
    bbox = box_info['bbox']  # [x1, y1, x2, y2]
    score = box_info['score']  # Detection confidence
    
    # Crop plate region
    x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
    crop = img[y1:y2, x1:x2]
    
    if crop.size == 0:
        continue
    
    # Convert to PIL for OCR
    pil_img = Image.fromarray(crop)
    if pil_img.mode != "RGB":
        pil_img = pil_img.convert("RGB")
    
    # Run OCR
    start = time.time()
    text, confidence = ocr.predict(pil_img)
    elapsed = time.time() - start
    ocr_time += elapsed
    
    print(f"Plate {i+1}: {text} ({confidence}%) - {elapsed:.4f}s")
    
    results.append({
        "ocr": text,
        "ocr_conf": confidence,
        "bbox": [x1, y1, x2, y2],
        "det_conf": int(score * 100)
    })

print(f"\nTotal time: {detection_time + ocr_time:.4f}s")

📊 Detection Object Structure

# detector.detector(img) returns list of dictionaries:
[
    {
        'bbox': [x1, y1, x2, y2],  # Bounding box coordinates
        'score': 0.95,              # Detection confidence (0-1)
        'class': 'license_plate'    # Object class
    },
    ...
]

# ocr.predict(pil_image) returns tuple:
("ABC1234", 98.5)  # (text, confidence_percentage)

🚀 Backend Performance Comparison

backends = ["cpu", "cuda"]  # Add "directml" on Windows

for backend_name in backends:
    try:
        print(f"\n🔧 Testing {backend_name}...")
        
        # Initialize with specific backend
        test_detector = ma_anpr_detector_v14(
            "medium_640p_fp32",
            user_name, serial_key, signature,
            backend=backend_name,
            conf_thres=0.25
        )
        
        # Measure performance
        start = time.time()
        detections = test_detector.detector(img)
        elapsed = time.time() - start
        
        print(f"Detected {len(detections)} plates in {elapsed:.4f}s")
        print(f"Speed: {1/elapsed:.1f} FPS")
        
    except Exception as e:
        print(f"⚠️ {backend_name} not available: {e}")

⚙️ Performance Results (Typical)

Backend Detection OCR Total FPS
CPU (i7) ~0.15s ~0.03s ~0.18s ~5.5
CUDA (RTX 3060) ~0.008s ~0.002s ~0.01s ~100

Result: GPU acceleration = 18x faster! 🚀

🎛️ Custom Filtering

# Filter detections by confidence
min_detection_conf = 0.50
min_ocr_conf = 80.0

filtered_results = []

for box_info in detections:
    if box_info['score'] < min_detection_conf:
        continue  # Skip low confidence detections
    
    # Process with OCR...
    text, conf = ocr.predict(plate_crop)
    
    if conf < min_ocr_conf:
        continue  # Skip low confidence OCR
    
    filtered_results.append({
        "text": text,
        "confidence": conf,
        "bbox": bbox
    })

print(f"After filtering: {len(filtered_results)} high-confidence plates")

🎨 Custom Visualization

import cv2

# Draw boxes and text on image
for result in results:
    x1, y1, x2, y2 = result['bbox']
    text = result['ocr']
    conf = result['ocr_conf']
    
    # Draw rectangle
    cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
    
    # Draw text
    label = f"{text} ({conf}%)"
    cv2.putText(img, label, (x1, y1-10), 
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

cv2.imwrite("result.jpg", img)

📹 Video Processing Pipeline

import cv2

# Open video
cap = cv2.VideoCapture("traffic.mp4")

frame_count = 0
plate_history = {}

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    
    frame_count += 1
    
    # Process every N frames (skip frames for speed)
    if frame_count % 5 != 0:
        continue
    
    # Detect plates
    detections = detector.detector(frame)
    
    for det in detections:
        bbox = det['bbox']
        x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
        crop = frame[y1:y2, x1:x2]
        
        if crop.size == 0:
            continue
        
        # OCR
        pil_crop = Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB))
        text, conf = ocr.predict(pil_crop)
        
        # Track plates (simple tracking by position)
        plate_id = f"{x1//50}_{y1//50}"
        
        if plate_id not in plate_history:
            plate_history[plate_id] = []
        plate_history[plate_id].append(text)
        
        # Draw
        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
        cv2.putText(frame, text, (x1, y1-10), 
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    
    cv2.imshow('ANPR', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

# Print detected plates
print("\nDetected plates:")
for plate_id, texts in plate_history.items():
    # Most common text for this plate
    most_common = max(set(texts), key=texts.count)
    print(f"  {most_common} (seen {len(texts)} times)")

💾 Batch Processing from Directory

import os
from pathlib import Path

image_dir = Path("./images")
results_all = {}

for img_path in image_dir.glob("*.jpg"):
    print(f"Processing {img_path.name}...")
    
    img = cv2.imread(str(img_path))
    detections = detector.detector(img)
    
    plates = []
    for det in detections:
        bbox = det['bbox']
        x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
        crop = img[y1:y2, x1:x2]
        
        if crop.size > 0:
            pil_crop = Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB))
            text, conf = ocr.predict(pil_crop)
            plates.append({"text": text, "conf": conf})
    
    results_all[img_path.name] = plates

# Save results
import json
with open("results.json", "w") as f:
    json.dump(results_all, f, indent=2)

print(f"\nProcessed {len(results_all)} images")

🎓 Advanced Tips

  • GPU Memory: Use cuda backend for 10-100x speedup
  • Confidence Tuning: Lower conf_thres to 0.15-0.20 for difficult images
  • IOU Threshold: Increase iou_thres to reduce duplicate detections
  • Batch Processing: Process multiple crops at once with ocr.predict([img1, img2, ...])
  • Frame Skipping: Process every Nth frame in videos for speed
  • Multi-threading: Run detector and OCR in separate threads

🔍 Troubleshooting

No detections?

  • Lower conf_thres to 0.15
  • Try larger model (large_640p_fp32)
  • Check image quality and resolution

Wrong OCR results?

  • Verify correct region (kr, eup, na, cn)
  • Try larger OCR model (large_fp32)
  • Check plate crop quality

Slow performance?

  • Use GPU backend (cuda or directml)
  • Use smaller models (small_640p_fp32, small_fp32)
  • Skip video frames
  • Batch process multiple images

💡 Conclusion

Manual processing gives you complete control over the ANPR pipeline. Use it for:

  • ✅ Custom filtering and validation
  • ✅ Performance optimization
  • ✅ Video stream processing
  • ✅ Integration with existing CV pipelines
  • ✅ Advanced visualization and tracking

Happy optimizing! ⚡🚗