import cv2
import numpy as np
import os
import sys
import argparse
import gc
import lacinfer

from pathlib import Path

_HELPER_SEARCH_PATH = Path(__file__).resolve()
for _parent in _HELPER_SEARCH_PATH.parents:
    if (_parent / "lacinfer_subprocess_pipeline.py").exists():
        sys.path.insert(0, str(_parent))
        break
from lacinfer_subprocess_pipeline import (
    add_pipeline_args,
    monitor_stage_memory,
    run_split_quant_compile_pipeline,
    run_split_compile_infer_pipeline,
    run_worker_child,
    should_spawn_worker_child,
    should_split_compile_infer,
    should_split_quant_compile,
    validate_args,
)


class YOLOv5:
    def __init__(self, cocopath, modelpath, calpath, action, modelformat, quantonly, savelirs,
                 force_i8_output=False, obj_thres=0.25, iou_thres=0.45, per_channel_ops=None,
                 asymmetric_activation_ops=None,
                 output_prefix=None, save_uncompiled_lir=True, save_compiled_lir=True, skip_infer=False,
                 offload_copy=True, exhaustive_tune=True):
        self.objectThreshold = obj_thres
        self.nmsThreshold = iou_thres
        # Per-output dequantization scales; populated when the program emits int8 outputs
        # (force_i8_output path). None means outputs are plain floating point.
        self.output_scales = None
        # 获取模型检测的类别信息
        self.classNames = list(map(lambda x: x.strip(), open(cocopath, 'r').readlines()))

        # 解析推理模型
        if modelformat == "onnx":
            self.model = lacinfer.parse_onnx(modelpath)
        elif modelformat == "lir" or modelformat == "lir-compiled":
            self.model = lacinfer.load(modelpath, format="msgpack")
        else:
            raise ValueError(f"Unexpected model format: {modelformat}")

        # 获取模型的输入name
        self.inputName = self.model.get_parameter_names()[0]

        # 获取模型的输入尺寸
        inputShape = self.model.get_parameter_shapes()[self.inputName].lens()
        self.inputHeight = int(inputShape[2])
        self.inputWidth = int(inputShape[3])
        print("inputName:{0} \ninputShape:{1}".format(self.inputName, inputShape))

        # 量化
        if action == "quant-int8" or action == "quant-fp16":
            if action == "quant-fp16":
                print("quantizing to fp16...")
                lacinfer.quantize_fp16(self.model)
            else:
                print("quantizing to int8...")
                if per_channel_ops:
                    print("using per-channel quantization:", per_channel_ops)
                if asymmetric_activation_ops:
                    print("using asymmetric activation quantization:", asymmetric_activation_ops)
                print("using calibration:", calpath)
                caldata = []
                images = []
                image_files = [f for f in os.listdir(calpath) if f.endswith(('.png', '.jpg', '.jpeg'))]
                for image_file in image_files:
                  calname = os.path.join(calpath, image_file)
                  srcimg = cv2.imread(calname, 1)
                  input_img = self.prepare_input(srcimg)
                  images.append(input_img)
                caldata = [{self.inputName: lacinfer.argument(img)} for img in images]
                print("calibration num:", len(caldata))
                if force_i8_output:
                    print("force int8 output enabled")
                lacinfer.quantize_int8(self.model, lacinfer.get_target("gpu"), caldata,
                                       force_i8_output=force_i8_output,
                                       asymmetric_activation_ops=(asymmetric_activation_ops or set()),
                                       per_channel_ops=(per_channel_ops or set()))
                del caldata
                del images
                gc.collect()
        elif action != "infer":
            raise ValueError(f"Unexpected action: {action}")

        # Recover per-output dequantization scales.
        # - Uncompiled graph: read from quantizelinear ops feeding @return (before compile,
        #   since optimization passes fold/rewrite them afterwards).
        # - Compiled binary: read q_scale from the fused gpu::asm_code_object kernel
        #   (..._dq_add_sigmoid_q) that produces each int8 output.
        self._collect_output_scales()

        model_base = os.path.splitext(os.path.basename(modelpath))[0]
        save_prefix = output_prefix or f"{model_base}-{action}"

        if quantonly or savelirs:
            if modelformat != "lir-compiled" and save_uncompiled_lir:
                print("saving lir:", f"{save_prefix}.lir")
                lacinfer.save(self.model, f"{save_prefix}.lir")

        # 模型编译
        if modelformat != "lir-compiled" and not quantonly:
            print("compiling...")
            self.model.compile(t=lacinfer.get_target("gpu"), offload_copy=offload_copy, exhaustive_tune=exhaustive_tune)  # device_id: 设置GPU设备，默认为0号设备
            if savelirs and save_compiled_lir:
                print("saving lir:", f"{save_prefix}-compiled.lir")
                lacinfer.save(self.model, f"{save_prefix}-compiled.lir")

    def _collect_output_scales(self):
        # Recover per-output dequantization scales. Handles both uncompiled and compiled graphs.
        self.output_scales = None
        try:
            mm = self.model.get_main_module()
        except Exception:
            return
        ret_ins = next((ins for ins in mm if ins.name() == "@return"), None)
        if ret_ins is None:
            return
        ret_inputs = ret_ins.inputs()
        # Uncompiled graph: each output is wrapped in a quantizelinear whose scale literal we read.
        scales = [self._scale_from_quantizelinear(ins) for ins in ret_inputs]
        # Compiled binary: the quantizelinear is fused into a gpu::asm_code_object kernel
        # (symbol_name ends with _dq_add_sigmoid_q) whose q_scale is the output dequant scale.
        if all(s is None for s in scales):
            scales = [self._scale_from_compiled_chain(ins) for ins in ret_inputs]
        if any(s is not None for s in scales):
            self.output_scales = scales
            print("detected int8 program outputs, dequant scales:", scales)

    def _scale_from_quantizelinear(self, ins):
        if ins.name() != "quantizelinear":
            return None
        ql_inputs = ins.inputs()
        # quantizelinear inputs: [data, scale, zero_point]; scale is a multibroadcast of a scalar literal
        if len(ql_inputs) < 2:
            return None
        scale_src = ql_inputs[1]
        if scale_src.name() in ("multibroadcast", "broadcast"):
            scale_src = scale_src.inputs()[0]
        if scale_src.name() != "@literal":
            return None
        val = np.array(scale_src.get_literal()).reshape(-1)
        if val.size > 0:
            return float(val[0])
        return None

    def _scale_from_compiled_chain(self, ins):
        # Keys detect revisits by id; values keep temporary LACInfer wrappers
        # alive so Python cannot reuse their ids during this traversal.
        seen = {}
        frontier = [ins]
        for _ in range(32):
            nxt = []
            for cur in frontier:
                if id(cur) in seen:
                    continue
                seen[id(cur)] = cur
                name = cur.name()
                if name in ("@param", "@literal"):
                    continue
                try:
                    vals = cur.op().values()
                except Exception:
                    vals = {}
                if vals.get("q_scale") is not None:
                    return float(vals["q_scale"])
                if name == "lac::sync_stream":
                    inputs = cur.inputs()
                    if inputs:
                        nxt.append(inputs[0])
                else:
                    nxt.extend(cur.inputs())
            if not nxt:
                break
            frontier = nxt
        return None

    def _outputs_are_int8(self, result):
        try:
            return any(r.get_shape().type() == lacinfer.shape.type_t.int8_type for r in result)
        except Exception:
            return False

    def _dequantize_outputs(self, result):
        # Convert int8 program outputs back to float using the captured per-output scale
        # (float_val = int8_val * scale, since zero_point is 0). Non-int8 outputs pass through.
        if self.output_scales is None:
            return result
        deq = []
        for i, out in enumerate(result):
            arr = np.array(out)
            scale = self.output_scales[i] if i < len(self.output_scales) else None
            if scale is not None and arr.dtype.kind in ('i', 'u'):
                arr = arr.astype(np.float32) * np.float32(scale)
            deq.append(arr)
        return deq

    def detect(self, image, anchors):
        # 输入图片预处理
        input_img = self.prepare_input(image)

        # 执行推理
        print("running...")
        result = self.model.run({self.inputName: input_img})

        # Detect int8 program outputs and auto-dequantize them back to float for post-processing.
        if self._outputs_are_int8(result) and self.output_scales is None:
            print("WARNING: int8 output detected but no scale captured; "
                  "load the uncompiled quantized model or re-run with --forceInt8Output")
        result = self._dequantize_outputs(result)

        # 模型输出结果后处理
        boxes, scores, class_ids = self.process_output(result, anchors)

        if boxes is not None:
            boxes[:, [0, 2]] -= self.pad_left
            boxes[:, [1, 3]] -= self.pad_top
            boxes[:, [0, 2]] /= self.scale_ratio
            boxes[:, [1, 3]] /= self.scale_ratio
            boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, self.img_width)
            boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, self.img_height)

        return boxes, scores, class_ids

    def prepare_input(self, image):
        # letterbox
        self.img_height, self.img_width = image.shape[:2]
        self.scale_ratio = min(self.inputWidth / self.img_width, self.inputHeight / self.img_height)
        new_w = int(self.img_width * self.scale_ratio)
        new_h = int(self.img_height * self.scale_ratio)
        resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
        canvas = np.full((self.inputHeight, self.inputWidth, 3), 114, dtype=np.uint8)
        self.pad_top = (self.inputHeight - new_h) // 2
        self.pad_left = (self.inputWidth - new_w) // 2
        canvas[self.pad_top:self.pad_top+new_h, self.pad_left:self.pad_left+new_w] = resized
        input_img = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
        input_img = input_img.transpose(2, 0, 1)
        input_img = np.expand_dims(input_img, 0)
        input_img = np.ascontiguousarray(input_img)
        input_img = input_img.astype(np.float32)
        input_img = input_img / 255.0

        return input_img

    def box_process(self, position, anchors):
        grid_h, grid_w = position.shape[2:4]
        col, row = np.meshgrid(np.arange(0, grid_w), np.arange(0, grid_h))
        col = col.reshape(1, 1, grid_h, grid_w)
        row = row.reshape(1, 1, grid_h, grid_w)
        grid = np.concatenate((col, row), axis=1)
        stride = np.array([self.inputHeight//grid_h, self.inputWidth//grid_w]).reshape(1,2,1,1)
    
        col = col.repeat(len(anchors), axis=0)
        row = row.repeat(len(anchors), axis=0)
        anchors = np.array(anchors)
        anchors = anchors.reshape(*anchors.shape, 1, 1)
    
        box_xy = position[:,:2,:,:]*2 - 0.5
        box_wh = pow(position[:,2:4,:,:]*2, 2) * anchors
    
        box_xy += grid
        box_xy *= stride
        box = np.concatenate((box_xy, box_wh), axis=1)
    
        # Convert [c_x, c_y, w, h] to [x1, y1, x2, y2]
        xyxy = np.copy(box)
        xyxy[:, 0, :, :] = box[:, 0, :, :] - box[:, 2, :, :]/ 2  # top left x
        xyxy[:, 1, :, :] = box[:, 1, :, :] - box[:, 3, :, :]/ 2  # top left y
        xyxy[:, 2, :, :] = box[:, 0, :, :] + box[:, 2, :, :]/ 2  # bottom right x
        xyxy[:, 3, :, :] = box[:, 1, :, :] + box[:, 3, :, :]/ 2  # bottom right y
    
        return xyxy

    def filter_boxes(self, boxes, box_confidences, box_class_probs):
        """Filter boxes with object threshold.
        """
        box_confidences = box_confidences.reshape(-1)
        class_max_score = np.max(box_class_probs, axis=-1)
        classes = np.argmax(box_class_probs, axis=-1)
    
        _class_pos = np.where(class_max_score* box_confidences >= self.objectThreshold)
        scores = (class_max_score* box_confidences)[_class_pos]
    
        boxes = boxes[_class_pos]
        classes = classes[_class_pos]
    
        return boxes, classes, scores

    def nms_boxes(self, boxes, scores):
        """Suppress non-maximal boxes.
        # Returns
            keep: ndarray, index of effective boxes.
        """
        x = boxes[:, 0]
        y = boxes[:, 1]
        w = boxes[:, 2] - boxes[:, 0]
        h = boxes[:, 3] - boxes[:, 1]
    
        areas = w * h
        order = scores.argsort()[::-1]
    
        keep = []
        while order.size > 0:
            i = order[0]
            keep.append(i)
    
            xx1 = np.maximum(x[i], x[order[1:]])
            yy1 = np.maximum(y[i], y[order[1:]])
            xx2 = np.minimum(x[i] + w[i], x[order[1:]] + w[order[1:]])
            yy2 = np.minimum(y[i] + h[i], y[order[1:]] + h[order[1:]])
    
            w1 = np.maximum(0.0, xx2 - xx1 + 0.00001)
            h1 = np.maximum(0.0, yy2 - yy1 + 0.00001)
            inter = w1 * h1
    
            ovr = inter / (areas[i] + areas[order[1:]] - inter)
            inds = np.where(ovr <= self.nmsThreshold)[0]
            order = order[inds + 1]
        keep = np.array(keep)
        return keep

    def process_output(self, output, anchors):
        boxes, scores, classes_conf = [], [], []
        # 1*255*h*w -> 3*85*h*w
        output = [np.array(out) for out in output]
        output = [_in.reshape([len(anchors[0]),-1]+list(_in.shape[-2:])) for _in in output]
        for i in range(len(output)):
            boxes.append(self.box_process(output[i][:,:4,:,:], anchors[i]))
            scores.append(output[i][:,4:5,:,:])
            classes_conf.append(output[i][:,5:,:,:])
    
        def sp_flatten(_in):
            ch = _in.shape[1]
            _in = _in.transpose(0,2,3,1)
            return _in.reshape(-1, ch)
    
        boxes = [sp_flatten(_v) for _v in boxes]
        classes_conf = [sp_flatten(_v) for _v in classes_conf]
        scores = [sp_flatten(_v) for _v in scores]
    
        boxes = np.concatenate(boxes)
        classes_conf = np.concatenate(classes_conf)
        scores = np.concatenate(scores)
   
        # filter according to threshold
        boxes, classes, scores = self.filter_boxes(boxes, scores, classes_conf)
    
        # nms
        nboxes, nclasses, nscores = [], [], []
    
        for c in set(classes):
            inds = np.where(classes == c)
            b = boxes[inds]
            c = classes[inds]
            s = scores[inds]
            keep = self.nms_boxes(b, s)
    
            if len(keep) != 0:
                nboxes.append(b[keep])
                nclasses.append(c[keep])
                nscores.append(s[keep])
    
        if not nclasses and not nscores:
            return None, None, None
    
        boxes = np.concatenate(nboxes)
        classes = np.concatenate(nclasses)
        scores = np.concatenate(nscores)
    
        return boxes, scores, classes

    def draw_detections(self, image, boxes, scores, class_ids):
        for box, score, cl in zip(boxes, scores, class_ids):
            top, left, right, bottom = [int(_b) for _b in box]

            # 绘制检测物体框
            cv2.rectangle(image, (top, left), (right, bottom), (255, 0, 0), 2)
            cv2.putText(image, '{0} {1:.2f}'.format(self.classNames[cl], score),
                        (top, left - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)


def parse_expect(expect_str):
    """Parse --expect argument into (class_name, min_count) list.

    Syntax:
      --expect bus                     -> [('bus', 1)]
      --expect bus,person              -> [('bus', 1), ('person', 1)]
      --expect person:3,bus:1          -> [('person', 3), ('bus', 1)]
    """
    expect_list = []
    for item in expect_str.split(','):
        item = item.strip()
        if ':' in item:
            name, count = item.rsplit(':', 1)
            expect_list.append((name.strip(), int(count)))
        else:
            expect_list.append((item, 1))
    return expect_list


def verify_results(classNames, class_ids, scores, expect_specs, min_confidence=0.5):
    """Verify detection results automatically.

    Args:
        classNames: list of COCO class name strings
        class_ids: array of detected class IDs
        scores: corresponding confidence scores
        expect_specs: list of (class_name, min_count) tuples
        min_confidence: minimum confidence threshold for expected classes

    Returns:
        (passed, details): whether verification passed, detailed message string
    """
    if class_ids is None:
        details_lines = []
        details_lines.append("=" * 50)
        details_lines.append("Detection Result Verification")
        details_lines.append("=" * 50)
        details_lines.append("  No objects detected!")
        details_lines.append("")
        for expect_class, _ in expect_specs:
            details_lines.append(f"  ✗ expected '{expect_class}' not detected!")
        details_lines.append("")
        details_lines.append(">>>  verdict: FAIL  <<<")
        details_lines.append("=" * 50)
        return False, "\n".join(details_lines)

    # count detections per class and track max confidence
    detected_count = {}
    detected_max_score = {}
    for cls_id, score in zip(class_ids, scores):
        name = classNames[cls_id]
        detected_count[name] = detected_count.get(name, 0) + 1
        if name not in detected_max_score or score > detected_max_score[name]:
            detected_max_score[name] = score

    details_lines = []
    details_lines.append("=" * 50)
    details_lines.append("Detection Result Verification")
    details_lines.append("=" * 50)
    details_lines.append(f"Total {len(class_ids)} objects detected:")
    for cls_id, score in sorted(zip(class_ids, scores), key=lambda x: -x[1]):
        details_lines.append(f"  - {classNames[cls_id]:20s} confidence: {score:.4f}")

    details_lines.append("")
    all_pass = True
    for expect_class, expect_count in expect_specs:
        actual_count = detected_count.get(expect_class, 0)
        max_score = detected_max_score.get(expect_class, 0.0)
        if actual_count >= expect_count and max_score >= min_confidence:
            details_lines.append(
                f"  ✓ expected '{expect_class}' "
                f"(count {actual_count} >= {expect_count}, max confidence {max_score:.4f} >= {min_confidence})")
        elif actual_count >= expect_count and max_score < min_confidence:
            details_lines.append(
                f"  ⚠ expected '{expect_class}' count OK ({actual_count} >= {expect_count}) "
                f"but confidence too low ({max_score:.4f} < {min_confidence})")
            all_pass = False
        elif actual_count < expect_count and max_score >= min_confidence:
            details_lines.append(
                f"  ⚠ expected '{expect_class}' confidence OK ({max_score:.4f} >= {min_confidence}) "
                f"but count insufficient ({actual_count} < {expect_count})")
            all_pass = False
        else:
            details_lines.append(
                f"  ✗ expected '{expect_class}' not satisfied "
                f"(count {actual_count} < {expect_count}, max confidence {max_score:.4f} < {min_confidence})")
            all_pass = False

    details_lines.append("")
    if all_pass:
        details_lines.append(">>>  verdict: PASS  <<<")
    else:
        details_lines.append(">>>  verdict: FAIL  <<<")
    details_lines.append("=" * 50)

    return all_pass, "\n".join(details_lines)


def yolov5_Static(imgpath, cocopath, modelpath, calpath, action, modelformat, quantonly,
                  savelirs, forceInt8Output, objectThreshold, nmsThreshold, respath, anchors,
                  expect_specs=None, min_confidence=0.5, per_channel_ops=None,
                  asymmetric_activation_ops=None,
                 output_prefix=None, save_uncompiled_lir=True, save_compiled_lir=True, skip_infer=False,
                 offload_copy=True, exhaustive_tune=True):
    yolov5_detector = YOLOv5(cocopath, modelpath, calpath, action, modelformat, quantonly,
                             savelirs, force_i8_output=forceInt8Output,
                             obj_thres=objectThreshold, iou_thres=nmsThreshold,
                             per_channel_ops=per_channel_ops,
                             asymmetric_activation_ops=asymmetric_activation_ops,
                             output_prefix=output_prefix,
                             save_uncompiled_lir=save_uncompiled_lir,
                             save_compiled_lir=save_compiled_lir,
                             offload_copy=offload_copy,
                             exhaustive_tune=exhaustive_tune)

    if not quantonly and not skip_infer:
        srcimg = cv2.imread(imgpath, 1)
        boxes, scores, class_ids = yolov5_detector.detect(srcimg, anchors)

        if expect_specs:
            passed, verdict = verify_results(yolov5_detector.classNames, class_ids, scores,
                                              expect_specs, min_confidence)
            print(verdict)
        else:
            passed = True

        if boxes is not None:
            dstimg = srcimg.copy()
            yolov5_detector.draw_detections(dstimg, boxes, scores, class_ids)

            # save result image
            cv2.imwrite(respath, dstimg)
            print("Success to save result", respath)
        else:
            print("Nothing detected!")

        return passed


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--imgPath', type=str, default='../images/bus.jpg', help="image path")
    parser.add_argument('--cocoClassPath', type=str, default='../models/coco.names', help="coco classes path")
    parser.add_argument('--staticModelPath', type=str, default='../models/f32_model/yolov5s_relu.onnx', help="static onnx filepath")
    parser.add_argument('--objectThreshold', default=0.25, type=float, help='class confidence')
    parser.add_argument('--nmsThreshold', default=0.45, type=float, help='nms iou thresh')
    parser.add_argument('--resPath', type=str, default='./Result.jpg', help="result path")
    parser.add_argument('--calibrationPath', type=str, default='../images', help="calibration path for quantization")
    parser.add_argument('--action', type=str, default='infer', help="action: infer, quant-int8 or quant-fp16")
    parser.add_argument('--modelFormat', type=str, default='onnx', help="model format: onnx, lir or lir-compiled")
    parser.add_argument("--quantOnly", action="store_true", default=False, help="only quantize the model")
    parser.add_argument("--saveLirs", action="store_true", default=False, help="save quantized and compiled lir models")
    parser.add_argument("--forceInt8Output", action="store_true", default=False,
                        help="force int8 output when quantizing to int8; outputs are auto-dequantized at inference")
    parser.add_argument("--per-channel", action="store_true", default=False,
                        help="use per-channel quantization for convolution weights")
    parser.add_argument("--asymmetric-activation", action="store_true", default=False,
                        help="use asymmetric activation quantization for convolution ops")
    parser.add_argument('--expect', type=str, default=None,
                        help='expected class:count, comma-separated (e.g. --expect bus,person:3)')
    parser.add_argument('--minConfidence', type=float, default=0.5,
                        help='minimum confidence threshold for expected classes')
    parser.add_argument('--no-offload-copy', action='store_false', dest='offload_copy',
                        help='Disable offload copy during compilation')
    parser.add_argument('--no-exhaustive-tune', action='store_false', dest='exhaustive_tune', default=True, help='Disable exhaustive tuning during compilation')
    add_pipeline_args(parser)
    args = parser.parse_args()
    monitor_stage_memory(args)

    validate_args(args)

    arg_names = [
        "imgPath", "cocoClassPath", "staticModelPath", "objectThreshold", "nmsThreshold",
        "resPath", "calibrationPath", "action", "modelFormat", "minConfidence",
    ]
    optional_arg_names = ["expect"]
    flag_specs = ["quantOnly", "saveLirs", "forceInt8Output", ("per_channel", "--per-channel"),
                  ("asymmetric_activation", "--asymmetric-activation"),
                  ("offload_copy", "--no-offload-copy", False), ("exhaustive_tune", "--no-exhaustive-tune", False)]
    script_path = os.path.abspath(__file__)

    if should_split_quant_compile(args):
        run_split_quant_compile_pipeline(args, script_path, arg_names, optional_arg_names, flag_specs)
        sys.exit(0)
    if should_split_compile_infer(args):
        run_split_compile_infer_pipeline(args, script_path, arg_names, optional_arg_names, flag_specs)
        sys.exit(0)
    if should_spawn_worker_child(args):
        run_worker_child(args, script_path, arg_names, optional_arg_names, flag_specs)
        sys.exit(0)

    anchors = [
        [[10.0, 13.0], [16.0, 30.0], [33.0, 23.0]],
        [[30.0, 61.0], [62.0, 45.0], [59.0, 119.0]],
        [[116.0, 90.0], [156.0, 198.0], [373.0, 326.0]]
    ]
    print("using anchors:", anchors)
    print("image:", args.imgPath)
    print("model:", args.staticModelPath)
    print("objconf threshold:", args.objectThreshold)
    print("nms threshold:", args.nmsThreshold)
    if args.quantOnly:
        print("quant only!")

    expect_specs = parse_expect(args.expect) if args.expect else None
    if expect_specs:
        print("expect specs:", expect_specs)
    stage = args.pipelineStage
    quantonly = True if stage == "quant-save" else args.quantOnly
    savelirs = True if stage in ("quant-save", "compile-save") else args.saveLirs
    action = "infer" if stage == "compile-save" else args.action
    skip_infer = stage in ("quant-save", "compile-save")  or not args.offload_copy
    passed = yolov5_Static(args.imgPath, args.cocoClassPath, args.staticModelPath, args.calibrationPath, action,
                  args.modelFormat, quantonly, savelirs, args.forceInt8Output,
                  args.objectThreshold, args.nmsThreshold, args.resPath, anchors,
                  expect_specs, args.minConfidence,
                  per_channel_ops={"convolution"} if args.per_channel else set(),
                  asymmetric_activation_ops={"convolution"} if args.asymmetric_activation else set(),
                  output_prefix=args.outputPrefix,
                  save_uncompiled_lir=stage != "compile-save",
                  save_compiled_lir=stage != "quant-save",
                  skip_infer=skip_infer,
                  offload_copy=args.offload_copy,
                  exhaustive_tune=args.exhaustive_tune)
    if args.quantOnly or skip_infer:
        sys.exit(0)
    sys.exit(0 if passed else 1)
