from __future__ import annotations

import gc
import inspect
import os
import time
from pathlib import Path
from typing import List
from unittest.mock import MagicMock, Mock, patch

import dill as pickle
import pytest
import torch
from inference.core.entities.responses.inference import (
    InferenceResponseImage, ObjectDetectionInferenceResponse,
    ObjectDetectionPrediction)
from inference.core.models.inference_models_adapters import \
    InferenceModelsObjectDetectionAdapter
from inference_models.models.base.types import PreprocessingMetadata


def codeflash_wrap(codeflash_wrapped, codeflash_test_module_name, codeflash_test_class_name, codeflash_test_name, codeflash_function_name, codeflash_line_id, codeflash_loop_index, *args, **kwargs):
    test_id = f'{codeflash_test_module_name}:{codeflash_test_class_name}:{codeflash_test_name}:{codeflash_line_id}:{codeflash_loop_index}'
    if not hasattr(codeflash_wrap, 'index'):
        codeflash_wrap.index = {}
    if test_id in codeflash_wrap.index:
        codeflash_wrap.index[test_id] += 1
    else:
        codeflash_wrap.index[test_id] = 0
    codeflash_test_index = codeflash_wrap.index[test_id]
    invocation_id = f'{codeflash_line_id}_{codeflash_test_index}'
    test_stdout_tag = f"{codeflash_test_module_name}:{(codeflash_test_class_name + '.' if codeflash_test_class_name else '')}{codeflash_test_name}:{codeflash_function_name}:{codeflash_loop_index}:{invocation_id}"
    print(f'!$######{test_stdout_tag}######$!')
    exception = None
    _codeflash_should_sync_cuda = torch.cuda.is_available() and torch.cuda.is_initialized()
    _codeflash_should_sync_mps = not _codeflash_should_sync_cuda and hasattr(torch.backends, 'mps') and torch.backends.mps.is_available() and hasattr(torch.mps, 'synchronize')
    gc.disable()
    try:
        if _codeflash_should_sync_cuda:
            torch.cuda.synchronize()
        elif _codeflash_should_sync_mps:
            torch.mps.synchronize()
        counter = time.perf_counter_ns()
        return_value = codeflash_wrapped(*args, **kwargs)
        if _codeflash_should_sync_cuda:
            torch.cuda.synchronize()
        elif _codeflash_should_sync_mps:
            torch.mps.synchronize()
        codeflash_duration = time.perf_counter_ns() - counter
    except Exception as e:
        codeflash_duration = time.perf_counter_ns() - counter
        exception = e
    gc.enable()
    print(f'!######{test_stdout_tag}######!')
    iteration = os.environ['CODEFLASH_TEST_ITERATION']
    with Path('{codeflash_run_tmp_dir_client_side}', f'test_return_values_{iteration}.bin').open('ab') as f:
        pickled_values = pickle.dumps((args, kwargs, exception)) if exception else pickle.dumps((args, kwargs, return_value))
        _test_name = f"{codeflash_test_module_name}:{(codeflash_test_class_name + '.' if codeflash_test_class_name else '')}{codeflash_test_name}:{codeflash_function_name}:{codeflash_line_id}".encode('ascii')
        f.write(len(_test_name).to_bytes(4, byteorder='big'))
        f.write(_test_name)
        f.write(codeflash_duration.to_bytes(8, byteorder='big'))
        f.write(len(pickled_values).to_bytes(4, byteorder='big'))
        f.write(pickled_values)
        f.write(codeflash_loop_index.to_bytes(8, byteorder='big'))
        f.write(len(invocation_id).to_bytes(4, byteorder='big'))
        f.write(invocation_id.encode('ascii'))
    if exception:
        raise exception
    return return_value

class MockSize:

    def __init__(self, height: int, width: int):
        self.height = height
        self.width = width

class MockPreprocessingMetadata:

    def __init__(self, height: int, width: int):
        self.original_size = MockSize(height, width)

class MockDetections:

    def __init__(self, xyxy, confidence, class_id):
        self._xyxy = xyxy
        self._confidence = confidence
        self._class_id = class_id

    @property
    def xyxy(self):
        return self._xyxy

    @property
    def confidence(self):
        return self._confidence

    @property
    def class_id(self):
        return self._class_id

def test_postprocess_single_detection_single_image():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with a single detection in a single image.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car', 'dog']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[100.0, 100.0, 200.0, 200.0]])
    confidence = torch.tensor([0.95])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_single_detection_single_image', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    pred = result[0].predictions[0]

def test_postprocess_multiple_detections_single_image():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with multiple detections in a single image.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car', 'dog']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[10.0, 10.0, 100.0, 100.0], [150.0, 150.0, 300.0, 250.0], [400.0, 200.0, 500.0, 350.0]])
    confidence = torch.tensor([0.9, 0.85, 0.75])
    class_id = torch.tensor([0, 1, 2])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_multiple_detections_single_image', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_multiple_images():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with multiple images.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640), MockPreprocessingMetadata(height=720, width=1280)]
    xyxy1 = torch.tensor([[50.0, 50.0, 150.0, 150.0]])
    confidence1 = torch.tensor([0.9])
    class_id1 = torch.tensor([0])
    detections1 = MockDetections(xyxy1, confidence1, class_id1)
    xyxy2 = torch.tensor([[100.0, 100.0, 200.0, 200.0], [400.0, 300.0, 600.0, 500.0]])
    confidence2 = torch.tensor([0.95, 0.85])
    class_id2 = torch.tensor([1, 0])
    detections2 = MockDetections(xyxy2, confidence2, class_id2)
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = [detections1, detections2]
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[detections1, detections2], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_multiple_images', 'postprocess', '15', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_with_class_filter():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with class filtering enabled.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car', 'dog']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[10.0, 10.0, 100.0, 100.0], [150.0, 150.0, 300.0, 250.0], [400.0, 200.0, 500.0, 350.0]])
    confidence = torch.tensor([0.9, 0.85, 0.75])
    class_id = torch.tensor([0, 1, 2])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata, class_filter=['person', 'car'])
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_with_class_filter', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_empty_detections():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with empty detection results.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([]).reshape(0, 4)
    confidence = torch.tensor([])
    class_id = torch.tensor([])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_empty_detections', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_high_confidence_prediction():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with high confidence predictions.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([0.9999])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_high_confidence_prediction', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_low_confidence_prediction():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with low confidence predictions.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([0.01])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_low_confidence_prediction', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_invalid_class_id_out_of_range():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing when class_id is out of range of class_names.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([5])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_invalid_class_id_out_of_range', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_negative_class_id():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with negative class_id.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([-1])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_negative_class_id', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_zero_size_bounding_box():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with zero-size bounding boxes (x1==x2 or y1==y2).'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[100.0, 100.0, 100.0, 200.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_zero_size_bounding_box', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_very_large_bounding_box():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with very large bounding boxes exceeding image dimensions.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[-1000.0, -1000.0, 5000.0, 5000.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_very_large_bounding_box', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    pred = result[0].predictions[0]

def test_postprocess_fractional_coordinates():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with fractional bounding box coordinates.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[10.5, 20.75, 100.25, 150.125]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_fractional_coordinates', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    pred = result[0].predictions[0]

def test_postprocess_empty_class_names_list():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with empty class_names list.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = []
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_empty_class_names_list', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_class_filter_filters_all_detections():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing where class_filter excludes all detections.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car', 'dog']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[10.0, 10.0, 100.0, 100.0], [150.0, 150.0, 300.0, 250.0]])
    confidence = torch.tensor([0.9, 0.85])
    class_id = torch.tensor([0, 2])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata, class_filter=['car'])
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_class_filter_filters_all_detections', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_class_filter_empty_list():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with empty class_filter list.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata, class_filter=[])
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_class_filter_empty_list', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_single_pixel_image():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with single pixel image dimensions.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=1, width=1)]
    xyxy = torch.tensor([[0.0, 0.0, 1.0, 1.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_single_pixel_image', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_very_large_image_dimensions():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with very large image dimensions.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=10000, width=10000)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_very_large_image_dimensions', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_confidence_zero():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with zero confidence predictions.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([0.0])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_confidence_zero', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_confidence_exactly_one():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with confidence exactly equal to 1.0.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0]])
    confidence = torch.tensor([1.0])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_confidence_exactly_one', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_class_name_with_special_characters():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with class names containing special characters.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person-adult', 'car@sedan', 'dog_puppy']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[0.0, 0.0, 100.0, 100.0], [100.0, 100.0, 200.0, 200.0], [200.0, 200.0, 300.0, 300.0]])
    confidence = torch.tensor([0.9, 0.85, 0.8])
    class_id = torch.tensor([0, 1, 2])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_class_name_with_special_characters', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_postprocess_many_detections_single_image():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with many detections in a single image (scalability).'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car', 'dog']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=1080, width=1920)]
    num_detections = 500
    xyxy_list = []
    for i in range(num_detections):
        x1 = i % 20 * 90
        y1 = i // 20 * 50
        x2 = x1 + 80
        y2 = y1 + 40
        xyxy_list.append([float(x1), float(y1), float(x2), float(y2)])
    xyxy = torch.tensor(xyxy_list)
    confidence = torch.tensor([0.5 + i % 50 / 100.0 for i in range(num_detections)])
    class_id = torch.tensor([i % 3 for i in range(num_detections)])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_many_detections_single_image', 'postprocess', '14', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    for i, pred in enumerate(result[0].predictions):
        pass

def test_postprocess_many_images():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with many images (scalability).'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    num_images = 100
    preproc_metadata = [MockPreprocessingMetadata(height=480 + i, width=640 + i) for i in range(num_images)]
    detections_list = []
    for i in range(num_images):
        xyxy = torch.tensor([[10.0 + i, 10.0 + i, 100.0 + i, 100.0 + i]])
        confidence = torch.tensor([0.5 + i % 50 / 100.0])
        class_id = torch.tensor([i % 2])
        detections_list.append(MockDetections(xyxy, confidence, class_id))
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections_list
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=detections_list, preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_many_images', 'postprocess', '10', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    for i, response in enumerate(result):
        pass

def test_postprocess_many_detections_many_images():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with many detections across many images.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car', 'dog', 'cat']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    num_images = 50
    detections_per_image = 10
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640) for _ in range(num_images)]
    detections_list = []
    for img_idx in range(num_images):
        xyxy_list = []
        for det_idx in range(detections_per_image):
            x1 = det_idx * 60
            y1 = det_idx * 40
            x2 = x1 + 50
            y2 = y1 + 30
            xyxy_list.append([float(x1), float(y1), float(x2), float(y2)])
        xyxy = torch.tensor(xyxy_list)
        confidence = torch.tensor([0.7 + det_idx / 100.0 for _ in range(detections_per_image)])
        class_id = torch.tensor([(img_idx + det_idx) % 4 for _ in range(detections_per_image)])
        detections_list.append(MockDetections(xyxy, confidence, class_id))
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections_list
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=detections_list, preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_many_detections_many_images', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    total_predictions = sum((len(resp.predictions) for resp in result))

def test_postprocess_large_class_names_list():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with a large number of class names.'
    num_classes = 500
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = [f'class_{i}' for i in range(num_classes)]
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    num_detections = 100
    xyxy_list = []
    class_ids_list = []
    for i in range(num_detections):
        xyxy_list.append([float(i * 5), float(i * 3), float(i * 5 + 50), float(i * 3 + 40)])
        class_ids_list.append(i % num_classes)
    xyxy = torch.tensor(xyxy_list)
    confidence = torch.tensor([0.5 + i % 50 / 100.0 for i in range(num_detections)])
    class_id = torch.tensor(class_ids_list)
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_large_class_names_list', 'postprocess', '16', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    for i, pred in enumerate(result[0].predictions):
        expected_class_id = i % num_classes
        expected_class_name = f'class_{expected_class_id}'

def test_postprocess_mixed_valid_and_invalid_class_ids():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with mix of valid and out-of-range class IDs at scale.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car', 'dog']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    num_detections = 100
    class_ids = []
    for i in range(num_detections):
        if i % 5 == 0:
            class_ids.append(10 + i)
        else:
            class_ids.append(i % 3)
    xyxy = torch.tensor([[float(i * 6), float(i * 4), float(i * 6 + 50), float(i * 4 + 40)] for i in range(num_detections)])
    confidence = torch.tensor([0.5 + i % 50 / 100.0 for i in range(num_detections)])
    class_id = torch.tensor(class_ids)
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_mixed_valid_and_invalid_class_ids', 'postprocess', '14', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    class_names_used = set((p.__dict__['class'] for p in result[0].predictions))

def test_postprocess_extreme_float_values_in_coordinates():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with extreme floating-point values in coordinates.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    xyxy = torch.tensor([[1000000.0, 1000000.0, 10000000.0, 10000000.0]])
    confidence = torch.tensor([0.9])
    class_id = torch.tensor([0])
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_extreme_float_values_in_coordinates', 'postprocess', '11', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    pred = result[0].predictions[0]

def test_postprocess_with_selective_class_filter_at_scale():
    torch.manual_seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test postprocessing with class filtering on large number of detections.'
    adapter = MagicMock(spec=InferenceModelsObjectDetectionAdapter)
    adapter.class_names = ['person', 'car', 'dog', 'cat', 'bike']
    adapter.map_inference_kwargs = lambda kwargs: kwargs
    preproc_metadata = [MockPreprocessingMetadata(height=480, width=640)]
    num_detections = 200
    xyxy_list = []
    class_ids = []
    for i in range(num_detections):
        xyxy_list.append([float(i * 3), float(i * 2), float(i * 3 + 50), float(i * 2 + 40)])
        class_ids.append(i % 5)
    xyxy = torch.tensor(xyxy_list)
    confidence = torch.tensor([0.5 + i % 50 / 100.0 for i in range(num_detections)])
    class_id = torch.tensor(class_ids)
    detections = [MockDetections(xyxy, confidence, class_id)]
    adapter._model = MagicMock()
    adapter._model.post_process.return_value = detections
    _call__bound__arguments = inspect.signature(InferenceModelsObjectDetectionAdapter.postprocess).bind(adapter, predictions=[MockDetections(xyxy, confidence, class_id)], preprocess_return_metadata=preproc_metadata, class_filter=['person', 'car'])
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(InferenceModelsObjectDetectionAdapter.postprocess, 'tests.inference.unit_tests.test_postprocess__unit_test_1', None, 'test_postprocess_with_selective_class_filter_at_scale', 'postprocess', '15', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output
    for pred in result[0].predictions:
        pass