

import subprocess
import sys
import warnings
from argparse import ArgumentParser
from pathlib import Path

from packaging import version

from .. import AutoFeatureExtractor, AutoImageProcessor, AutoProcessor, AutoTokenizer
from ..utils import logging
from ..utils.import_utils import is_optimum_available
from .convert import export, validate_model_outputs
from .features import FeaturesManager
from .utils import get_preprocessor


_lowerCAmelCase     :			int    ="""1.5.0"""

_lowerCAmelCase     :			Optional[Any]    =["""vision-encoder-decoder"""]



def  _A  (			SCREAMING_SNAKE_CASE			):
	if is_optimum_available():
		from optimum.version import __version__ as optimum_version

		UpperCAmelCase__:  Optional[int]		       =   version.parse(SCREAMING_SNAKE_CASE			)
		if parsed_optimum_version < version.parse(SCREAMING_SNAKE_CASE			):
			raise RuntimeError(
			    f"transformers.onnx requires optimum >= {MIN_OPTIMUM_VERSION} but {optimum_version} is installed. You "
			    "can upgrade optimum by running: pip install -U optimum[exporters]"			)
	else:
		raise RuntimeError(
		    "transformers.onnx requires optimum to run, you can install the library by running: pip install "
		    "optimum[exporters]"			)
	UpperCAmelCase__:  Any		       =   [
	    sys.executable,
	    "-m",
	    "optimum.exporters.onnx",
	    f"--model {args.model}",
	    f"--task {args.feature}",
	    f"--framework {args.framework}" if args.framework is not None else "",
	    f"{args.output}",
	]
	UpperCAmelCase__:  str		       =   subprocess.Popen(" ".join(SCREAMING_SNAKE_CASE			)  ,stdout=subprocess.PIPE  ,shell=SCREAMING_SNAKE_CASE			)
	proc.wait()

	logger.info(
	    "The export was done by optimum.exporters.onnx. We recommend using to use this package directly in future, as "
	    "transformers.onnx is deprecated, and will be removed in v5. You can find more information here: "
	    "https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."			)



def  _A  (			SCREAMING_SNAKE_CASE			):
	UpperCAmelCase__:  Optional[int]		       =   args.output if args.output.is_file() else args.output.joinpath("model.onnx"			)
	if not args.output.parent.exists():
		args.output.parent.mkdir(parents=SCREAMING_SNAKE_CASE			)

	# Allocate the model
	UpperCAmelCase__:  int		       =   FeaturesManager.get_model_from_feature(
	    args.feature  ,args.model  ,framework=args.framework  ,cache_dir=args.cache_dir			)

	UpperCAmelCase__       ,	UpperCAmelCase__:  List[str]		       =   FeaturesManager.check_supported_model_or_raise(SCREAMING_SNAKE_CASE  ,feature=args.feature			)
	UpperCAmelCase__:  str		       =   model_onnx_config(model.config			)

	if model_kind in ENCODER_DECODER_MODELS:
		UpperCAmelCase__:  List[str]		       =   model.get_encoder()
		UpperCAmelCase__:  Optional[int]		       =   model.get_decoder()

		UpperCAmelCase__:  List[str]		       =   onnx_config.get_encoder_config(encoder_model.config			)
		UpperCAmelCase__:  Any		       =   onnx_config.get_decoder_config(
		    encoder_model.config  ,decoder_model.config  ,feature=args.feature			)

		if args.opset is None:
			UpperCAmelCase__:  Tuple		       =   max(encoder_onnx_config.default_onnx_opset  ,decoder_onnx_config.default_onnx_opset			)

		if args.opset < min(encoder_onnx_config.default_onnx_opset  ,decoder_onnx_config.default_onnx_opset			):
			raise ValueError(
			    f"Opset {args.opset} is not sufficient to export {model_kind}. At least "
			    f" {min(encoder_onnx_config.default_onnx_opset  ,decoder_onnx_config.default_onnx_opset			)} is required."			)

		UpperCAmelCase__:  str		       =   AutoFeatureExtractor.from_pretrained(args.model			)

		UpperCAmelCase__       ,	UpperCAmelCase__:  Tuple		       =   export(
		    SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,args.opset  ,args.output.parent.joinpath("encoder_model.onnx"			)  ,)

		validate_model_outputs(
		    SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,args.output.parent.joinpath("encoder_model.onnx"			)  ,SCREAMING_SNAKE_CASE  ,args.atol if args.atol else encoder_onnx_config.atol_for_validation  ,)

		UpperCAmelCase__:  Dict		       =   AutoTokenizer.from_pretrained(args.model			)

		UpperCAmelCase__       ,	UpperCAmelCase__:  str		       =   export(
		    SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,args.opset  ,args.output.parent.joinpath("decoder_model.onnx"			)  ,)

		validate_model_outputs(
		    SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,args.output.parent.joinpath("decoder_model.onnx"			)  ,SCREAMING_SNAKE_CASE  ,args.atol if args.atol else decoder_onnx_config.atol_for_validation  ,)
		logger.info(
		    f"All good, model saved at: {args.output.parent.joinpath('encoder_model.onnx'			).as_posix()},"
		    f" {args.output.parent.joinpath('decoder_model.onnx'			).as_posix()}"			)

	else:
		# Instantiate the appropriate preprocessor
		if args.preprocessor == "auto":
			UpperCAmelCase__:  str		       =   get_preprocessor(args.model			)
		elif args.preprocessor == "tokenizer":
			UpperCAmelCase__:  Any		       =   AutoTokenizer.from_pretrained(args.model			)
		elif args.preprocessor == "image_processor":
			UpperCAmelCase__:  Optional[int]		       =   AutoImageProcessor.from_pretrained(args.model			)
		elif args.preprocessor == "feature_extractor":
			UpperCAmelCase__:  int		       =   AutoFeatureExtractor.from_pretrained(args.model			)
		elif args.preprocessor == "processor":
			UpperCAmelCase__:  Optional[int]		       =   AutoProcessor.from_pretrained(args.model			)
		else:
			raise ValueError(f"Unknown preprocessor type '{args.preprocessor}'"			)

		# Ensure the requested opset is sufficient
		if args.opset is None:
			UpperCAmelCase__:  List[str]		       =   onnx_config.default_onnx_opset

		if args.opset < onnx_config.default_onnx_opset:
			raise ValueError(
			    f"Opset {args.opset} is not sufficient to export {model_kind}. "
			    f"At least  {onnx_config.default_onnx_opset} is required."			)

		UpperCAmelCase__       ,	UpperCAmelCase__:  Tuple		       =   export(
		    SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,args.opset  ,args.output  ,)

		if args.atol is None:
			UpperCAmelCase__:  List[Any]		       =   onnx_config.atol_for_validation

		validate_model_outputs(SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,args.output  ,SCREAMING_SNAKE_CASE  ,args.atol			)
		logger.info(f"All good, model saved at: {args.output.as_posix()}"			)
		warnings.warn(
		    "The export was done by transformers.onnx which is deprecated and will be removed in v5. We recommend"
		    " using optimum.exporters.onnx in future. You can find more information here:"
		    " https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."  ,SCREAMING_SNAKE_CASE  ,)



def  _A  (			):
	UpperCAmelCase__:  str		       =   ArgumentParser("Hugging Face Transformers ONNX exporter"			)
	parser.add_argument(
	    "-m"  ,"--model"  ,type=SCREAMING_SNAKE_CASE  ,required=SCREAMING_SNAKE_CASE  ,help="Model ID on huggingface.co or path on disk to load model from."			)
	parser.add_argument(
	    "--feature"  ,default="default"  ,help="The type of features to export the model with."  ,)
	parser.add_argument("--opset"  ,type=SCREAMING_SNAKE_CASE  ,default=SCREAMING_SNAKE_CASE  ,help="ONNX opset version to export the model with."			)
	parser.add_argument(
	    "--atol"  ,type=SCREAMING_SNAKE_CASE  ,default=SCREAMING_SNAKE_CASE  ,help="Absolute difference tolerance when validating the model."			)
	parser.add_argument(
	    "--framework"  ,type=SCREAMING_SNAKE_CASE  ,choices=["pt", "tf"]  ,default=SCREAMING_SNAKE_CASE  ,help=(
	        "The framework to use for the ONNX export."
	        " If not provided, will attempt to use the local checkpoint's original framework"
	        " or what is available in the environment."
	    )  ,)
	parser.add_argument("output"  ,type=SCREAMING_SNAKE_CASE  ,help="Path indicating where to store generated ONNX model."			)
	parser.add_argument("--cache_dir"  ,type=SCREAMING_SNAKE_CASE  ,default=SCREAMING_SNAKE_CASE  ,help="Path indicating where to store cache."			)
	parser.add_argument(
	    "--preprocessor"  ,type=SCREAMING_SNAKE_CASE  ,choices=["auto", "tokenizer", "feature_extractor", "image_processor", "processor"]  ,default="auto"  ,help="Which type of preprocessor to use. 'auto' tries to automatically detect it."  ,)
	parser.add_argument(
	    "--export_with_transformers"  ,action="store_true"  ,help=(
	        "Whether to use transformers.onnx instead of optimum.exporters.onnx to perform the ONNX export. It can be "
	        "useful when exporting a model supported in transformers but not in optimum, otherwise it is not "
	        "recommended."
	    )  ,)

	UpperCAmelCase__:  Optional[int]		       =   parser.parse_args()
	if args.export_with_transformers or not is_optimum_available():
		export_with_transformers(SCREAMING_SNAKE_CASE			)
	else:
		export_with_optimum(SCREAMING_SNAKE_CASE			)


if __name__ == "__main__":
					_lowerCAmelCase     :			int    =logging.get_logger("""transformers.onnx""")  # pylint: disable=invalid-name
					logger.setLevel(logging.INFO)
					main()


import json
import os
import random
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
					from PIL import Image

					from transformers import FlavaImageProcessor, FlavaProcessor
					from transformers.models.flava.image_processing_flava import (
					    FLAVA_CODEBOOK_MEAN,
					    FLAVA_CODEBOOK_STD,
					    FLAVA_IMAGE_MEAN,
					    FLAVA_IMAGE_STD,
					)

@require_vision
class __UpperCamelCase    (							unittest.TestCase		):






					'''simple docstring'''



					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  Optional[int]		       =   tempfile.mkdtemp()

						# fmt: off
						UpperCAmelCase__:  Optional[Any]		       =   ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"]
						# fmt: on
						UpperCAmelCase__:  str		       =   os.path.join(self.tmpdirname							,			VOCAB_FILES_NAMES["vocab_file"]	)

						with open(self.vocab_file							,			"w"							,			encoding="utf-8"	) as fp:
							fp.write("".join([x + "\n" for x in vocab_tokens]	)	)

						UpperCAmelCase__:  Tuple		       =   {
						    "image_mean": FLAVA_IMAGE_MEAN,
						    "image_std": FLAVA_IMAGE_STD,
						    "do_normalize": True,
						    "do_resize": True,
						    "size": 2_2_4,
						    "do_center_crop": True,
						    "crop_size": 2_2_4,
						    "input_size_patches": 1_4,
						    "total_mask_patches": 7_5,
						    "mask_group_max_patches": None,
						    "mask_group_min_patches": 1_6,
						    "mask_group_min_aspect_ratio": 0.3,
						    "mask_group_max_aspect_ratio": None,
						    "codebook_do_resize": True,
						    "codebook_size": 1_1_2,
						    "codebook_do_center_crop": True,
						    "codebook_crop_size": 1_1_2,
						    "codebook_do_map_pixels": True,
						    "codebook_do_normalize": True,
						    "codebook_image_mean": FLAVA_CODEBOOK_MEAN,
						    "codebook_image_std": FLAVA_CODEBOOK_STD,
						}

						UpperCAmelCase__:  Tuple		       =   os.path.join(self.tmpdirname							,			lowerCamelCase__	)
						with open(self.image_processor_file							,			"w"							,			encoding="utf-8"	) as fp:
							json.dump(lowerCamelCase__							,			lowerCamelCase__	)





					def       _UpperCAmelCase						(							self							,			**lowerCamelCase__	):
						return BertTokenizer.from_pretrained(self.tmpdirname							,			**lowerCamelCase__	)





					def       _UpperCAmelCase						(							self							,			**lowerCamelCase__	):
						return BertTokenizerFast.from_pretrained(self.tmpdirname							,			**lowerCamelCase__	)





					def       _UpperCAmelCase						(							self							,			**lowerCamelCase__	):
						return FlavaImageProcessor.from_pretrained(self.tmpdirname							,			**lowerCamelCase__	)





					def       _UpperCAmelCase						(							self	):
						shutil.rmtree(self.tmpdirname	)





					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  Dict		       =   [np.random.randint(2_5_5							,			size=(3, 3_0, 4_0_0)							,			dtype=np.uinta	)]

						UpperCAmelCase__:  Any		       =   [Image.fromarray(np.moveaxis(lowerCamelCase__							,			0							,			-1	)	) for x in image_inputs]

						return image_inputs





					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  int		       =   self.get_tokenizer()
						UpperCAmelCase__:  Any		       =   self.get_rust_tokenizer()
						UpperCAmelCase__:  List[Any]		       =   self.get_image_processor()

						UpperCAmelCase__:  Tuple		       =   FlavaProcessor(tokenizer=lowerCamelCase__							,			image_processor=lowerCamelCase__	)
						processor_slow.save_pretrained(self.tmpdirname	)
						UpperCAmelCase__:  Dict		       =   FlavaProcessor.from_pretrained(self.tmpdirname							,			use_fast=lowerCamelCase__	)

						UpperCAmelCase__:  Union[str, Any]		       =   FlavaProcessor(tokenizer=lowerCamelCase__							,			image_processor=lowerCamelCase__	)
						processor_fast.save_pretrained(self.tmpdirname	)
						UpperCAmelCase__:  int		       =   FlavaProcessor.from_pretrained(self.tmpdirname	)

						self.assertEqual(processor_slow.tokenizer.get_vocab()							,			tokenizer_slow.get_vocab()	)
						self.assertEqual(processor_fast.tokenizer.get_vocab()							,			tokenizer_fast.get_vocab()	)
						self.assertEqual(tokenizer_slow.get_vocab()							,			tokenizer_fast.get_vocab()	)
						self.assertIsInstance(processor_slow.tokenizer							,			lowerCamelCase__	)
						self.assertIsInstance(processor_fast.tokenizer							,			lowerCamelCase__	)

						self.assertEqual(processor_slow.image_processor.to_json_string()							,			image_processor.to_json_string()	)
						self.assertEqual(processor_fast.image_processor.to_json_string()							,			image_processor.to_json_string()	)
						self.assertIsInstance(processor_slow.image_processor							,			lowerCamelCase__	)
						self.assertIsInstance(processor_fast.image_processor							,			lowerCamelCase__	)





					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  Any		       =   FlavaProcessor(tokenizer=self.get_tokenizer()							,			image_processor=self.get_image_processor()	)
						processor.save_pretrained(self.tmpdirname	)

						UpperCAmelCase__:  Any		       =   self.get_tokenizer(bos_token="(BOS)"							,			eos_token="(EOS)"	)
						UpperCAmelCase__:  str		       =   self.get_image_processor(do_normalize=lowerCamelCase__							,			padding_value=1.0	)

						UpperCAmelCase__:  str		       =   FlavaProcessor.from_pretrained(
						    self.tmpdirname							,			bos_token="(BOS)"							,			eos_token="(EOS)"							,			do_normalize=lowerCamelCase__							,			padding_value=1.0	)

						self.assertEqual(processor.tokenizer.get_vocab()							,			tokenizer_add_kwargs.get_vocab()	)
						self.assertIsInstance(processor.tokenizer							,			lowerCamelCase__	)

						self.assertEqual(processor.image_processor.to_json_string()							,			image_processor_add_kwargs.to_json_string()	)
						self.assertIsInstance(processor.image_processor							,			lowerCamelCase__	)





					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  int		       =   self.get_image_processor()
						UpperCAmelCase__:  Optional[Any]		       =   self.get_tokenizer()

						UpperCAmelCase__:  Optional[Any]		       =   FlavaProcessor(tokenizer=lowerCamelCase__							,			image_processor=lowerCamelCase__	)

						UpperCAmelCase__:  Optional[int]		       =   self.prepare_image_inputs()

						UpperCAmelCase__:  Tuple		       =   image_processor(lowerCamelCase__							,			return_tensors="np"	)
						UpperCAmelCase__:  str		       =   processor(images=lowerCamelCase__							,			return_tensors="np"	)

						for key in input_feat_extract.keys():
							self.assertAlmostEqual(input_feat_extract[key].sum()							,			input_processor[key].sum()							,			delta=1e-2	)

						# With rest of the args
						random.seed(1_2_3_4	)
						UpperCAmelCase__:  Optional[int]		       =   image_processor(
						    lowerCamelCase__							,			return_image_mask=lowerCamelCase__							,			return_codebook_pixels=lowerCamelCase__							,			return_tensors="np"	)
						random.seed(1_2_3_4	)
						UpperCAmelCase__:  Tuple		       =   processor(
						    images=lowerCamelCase__							,			return_image_mask=lowerCamelCase__							,			return_codebook_pixels=lowerCamelCase__							,			return_tensors="np"	)

						for key in input_feat_extract.keys():
							self.assertAlmostEqual(input_feat_extract[key].sum()							,			input_processor[key].sum()							,			delta=1e-2	)





					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  Dict		       =   self.get_image_processor()
						UpperCAmelCase__:  str		       =   self.get_tokenizer()

						UpperCAmelCase__:  List[str]		       =   FlavaProcessor(tokenizer=lowerCamelCase__							,			image_processor=lowerCamelCase__	)

						UpperCAmelCase__:  Union[str, Any]		       =   "lower newer"

						UpperCAmelCase__:  Optional[Any]		       =   processor(text=lowerCamelCase__	)

						UpperCAmelCase__:  Optional[Any]		       =   tokenizer(lowerCamelCase__	)

						for key in encoded_tok.keys():
							self.assertListEqual(encoded_tok[key]							,			encoded_processor[key]	)





					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  List[Any]		       =   self.get_image_processor()
						UpperCAmelCase__:  int		       =   self.get_tokenizer()

						UpperCAmelCase__:  str		       =   FlavaProcessor(tokenizer=lowerCamelCase__							,			image_processor=lowerCamelCase__	)

						UpperCAmelCase__:  Any		       =   "lower newer"
						UpperCAmelCase__:  Any		       =   self.prepare_image_inputs()

						UpperCAmelCase__:  Optional[int]		       =   processor(text=lowerCamelCase__							,			images=lowerCamelCase__	)

						self.assertListEqual(list(inputs.keys()	)							,			["input_ids", "token_type_ids", "attention_mask", "pixel_values"]	)

						# add extra args
						UpperCAmelCase__:  str		       =   processor(text=lowerCamelCase__							,			images=lowerCamelCase__							,			return_codebook_pixels=lowerCamelCase__							,			return_image_mask=lowerCamelCase__	)

						self.assertListEqual(
						    list(inputs.keys()	)							,			[
						        "input_ids",
						        "token_type_ids",
						        "attention_mask",
						        "pixel_values",
						        "codebook_pixel_values",
						        "bool_masked_pos",
						    ]							,			)

						# test if it raises when no input is passed
						with pytest.raises(lowerCamelCase__	):
							processor()





					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  Optional[Any]		       =   self.get_image_processor()
						UpperCAmelCase__:  List[Any]		       =   self.get_tokenizer()

						UpperCAmelCase__:  Any		       =   FlavaProcessor(tokenizer=lowerCamelCase__							,			image_processor=lowerCamelCase__	)

						UpperCAmelCase__:  List[Any]		       =   [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

						UpperCAmelCase__:  str		       =   processor.batch_decode(lowerCamelCase__	)
						UpperCAmelCase__:  Dict		       =   tokenizer.batch_decode(lowerCamelCase__	)

						self.assertListEqual(lowerCamelCase__							,			lowerCamelCase__	)





					def       _UpperCAmelCase						(							self	):
						UpperCAmelCase__:  List[str]		       =   self.get_image_processor()
						UpperCAmelCase__:  Dict		       =   self.get_tokenizer()

						UpperCAmelCase__:  Tuple		       =   FlavaProcessor(tokenizer=lowerCamelCase__							,			image_processor=lowerCamelCase__	)

						UpperCAmelCase__:  Optional[Any]		       =   "lower newer"
						UpperCAmelCase__:  Dict		       =   self.prepare_image_inputs()

						UpperCAmelCase__:  int		       =   processor(text=lowerCamelCase__							,			images=lowerCamelCase__	)

						self.assertListEqual(list(inputs.keys()	)							,			processor.model_input_names	)