






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


UpperCamelCase__						:      List[Any]								=					"""1.5.0"""

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





def   SCREAMING_SNAKE_CASE__						(   snake_case_  )   ->  Union[str, Any]:


	"""simple docstring"""



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

		a		=			version.parse(snake_case_  )
		if parsed_optimum_version < version.parse(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]'''  )
	a		=			[
	    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}""",
	]
	a		=			subprocess.Popen(''' '''.join(snake_case_  ),  stdout=subprocess.PIPE,  shell=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   SCREAMING_SNAKE_CASE__						(   snake_case_  )   ->  Tuple:


	"""simple docstring"""



	a		=			args.output if args.output.is_file() else args.output.joinpath('''model.onnx'''  )
	if not args.output.parent.exists():
		args.output.parent.mkdir(parents=snake_case_  )

	# Allocate the model
	a		=			FeaturesManager.get_model_from_feature(
	    args.feature,  args.model,  framework=args.framework,  cache_dir=args.cache_dir  )

	a	, a		=			FeaturesManager.check_supported_model_or_raise(snake_case_,  feature=args.feature  )
	a		=			model_onnx_config(model.config  )

	if model_kind in ENCODER_DECODER_MODELS:
		a		=			model.get_encoder()
		a		=			model.get_decoder()

		a		=			onnx_config.get_encoder_config(encoder_model.config  )
		a		=			onnx_config.get_decoder_config(
		    encoder_model.config,  decoder_model.config,  feature=args.feature  )

		if args.opset is None:
			a		=			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."""  )

		a		=			AutoFeatureExtractor.from_pretrained(args.model  )

		a	, a		=			export(
		    snake_case_,  snake_case_,  snake_case_,  args.opset,  args.output.parent.joinpath('''encoder_model.onnx'''  ),  )

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

		a		=			AutoTokenizer.from_pretrained(args.model  )

		a	, a		=			export(
		    snake_case_,  snake_case_,  snake_case_,  args.opset,  args.output.parent.joinpath('''decoder_model.onnx'''  ),  )

		validate_model_outputs(
		    snake_case_,  snake_case_,  snake_case_,  args.output.parent.joinpath('''decoder_model.onnx'''  ),  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":
			a		=			get_preprocessor(args.model  )
		elif args.preprocessor == "tokenizer":
			a		=			AutoTokenizer.from_pretrained(args.model  )
		elif args.preprocessor == "image_processor":
			a		=			AutoImageProcessor.from_pretrained(args.model  )
		elif args.preprocessor == "feature_extractor":
			a		=			AutoFeatureExtractor.from_pretrained(args.model  )
		elif args.preprocessor == "processor":
			a		=			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:
			a		=			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."""  )

		a	, a		=			export(
		    snake_case_,  snake_case_,  snake_case_,  args.opset,  args.output,  )

		if args.atol is None:
			a		=			onnx_config.atol_for_validation

		validate_model_outputs(snake_case_,  snake_case_,  snake_case_,  args.output,  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.''',  snake_case_,  )





def   SCREAMING_SNAKE_CASE__						(   )   ->  Tuple:


	"""simple docstring"""



	a		=			ArgumentParser('''Hugging Face Transformers ONNX exporter'''  )
	parser.add_argument(
	    '''-m''',  '''--model''',  type=snake_case_,  required=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=snake_case_,  default=snake_case_,  help='''ONNX opset version to export the model with.'''  )
	parser.add_argument(
	    '''--atol''',  type=snake_case_,  default=snake_case_,  help='''Absolute difference tolerance when validating the model.'''  )
	parser.add_argument(
	    '''--framework''',  type=snake_case_,  choices=['''pt''', '''tf'''],  default=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=snake_case_,  help='''Path indicating where to store generated ONNX model.'''  )
	parser.add_argument('''--cache_dir''',  type=snake_case_,  default=snake_case_,  help='''Path indicating where to store cache.'''  )
	parser.add_argument(
	    '''--preprocessor''',  type=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.'''
	    ),  )

	a		=			parser.parse_args()
	if args.export_with_transformers or not is_optimum_available():
		export_with_transformers(snake_case_  )
	else:
		export_with_optimum(snake_case_  )


if __name__ == "__main__":
				UpperCamelCase__						:      Optional[Any]								=					logging.get_logger("""transformers.onnx""")  # pylint: disable=invalid-name
				logger.setLevel(logging.INFO)
				main()













import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
				import sqlitea

				import sqlalchemy


UpperCamelCase__						:      Tuple								=					datasets.utils.logging.get_logger(__name__)







@dataclass
class 				lowerCamelCase_     (	datasets.BuilderConfig     ):
							SCREAMING_SNAKE_CASE_						     =			None
							SCREAMING_SNAKE_CASE_						     =			None
							SCREAMING_SNAKE_CASE_						     =			None
							SCREAMING_SNAKE_CASE_						     =			True
							SCREAMING_SNAKE_CASE_						     =			None
							SCREAMING_SNAKE_CASE_						     =			None
							SCREAMING_SNAKE_CASE_						     =			None
							SCREAMING_SNAKE_CASE_						     =			1_00_00
							SCREAMING_SNAKE_CASE_						     =			None
							def  SCREAMING_SNAKE_CASE_ (						self		:					Optional[Any]					):





								'''simple docstring'''



								if self.sql is None:
									raise ValueError('''sql must be specified'''					)
								if self.con is None:
									raise ValueError('''con must be specified'''					)
							def  SCREAMING_SNAKE_CASE_ (						self		:					Any							,__lowerCamelCase		:					dict							,__lowerCamelCase		:					Optional[datasets.Features] = None							,):





								'''simple docstring'''



								a		=			config_kwargs.copy()
								# We need to stringify the Selectable object to make its hash deterministic

								# The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
								a		=			config_kwargs['''sql''']
								if not isinstance(__lowerCamelCase							,__lowerCamelCase					):
									if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
										import sqlalchemy

										if isinstance(__lowerCamelCase							,sqlalchemy.sql.Selectable					):
											a		=			sqlalchemy.create_engine(config_kwargs['''con'''].split('''://'''					)[0] + '''://'''					)
											a		=			str(sql.compile(dialect=engine.dialect					)					)
											a		=			sql_str
										else:
											raise TypeError(
											    F"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(__lowerCamelCase					)}: {sql}"""					)
									else:
										raise TypeError(
										    F"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(__lowerCamelCase					)}: {sql}"""					)
								a		=			config_kwargs['''con''']
								if not isinstance(__lowerCamelCase							,__lowerCamelCase					):
									a		=			id(__lowerCamelCase					)
									logger.info(
									    F"""SQL connection 'con' of type {type(__lowerCamelCase					)} couldn't be hashed properly. To enable hashing, specify 'con' as URI string instead."""					)

								return super().create_config_id(__lowerCamelCase							,custom_features=__lowerCamelCase					)




							@property
							def  SCREAMING_SNAKE_CASE_ (						self		:					Dict					):





								'''simple docstring'''



								a		=			{
								    '''index_col''': self.index_col,
								    '''columns''': self.columns,
								    '''params''': self.params,
								    '''coerce_float''': self.coerce_float,
								    '''parse_dates''': self.parse_dates,
								}
								return pd_read_sql_kwargs







class 				lowerCamelCase_     (	datasets.ArrowBasedBuilder     ):
							SCREAMING_SNAKE_CASE_						     =			SqlConfig
							def  SCREAMING_SNAKE_CASE_ (						self		:					Optional[Any]					):





								'''simple docstring'''



								return datasets.DatasetInfo(features=self.config.features					)
							def  SCREAMING_SNAKE_CASE_ (						self		:					Union[str, Any]							,__lowerCamelCase		:					int					):





								'''simple docstring'''



								return [datasets.SplitGenerator(name=datasets.Split.TRAIN							,gen_kwargs={}					)]
							def  SCREAMING_SNAKE_CASE_ (						self		:					Tuple							,__lowerCamelCase		:					pa.Table					):





								'''simple docstring'''



								if self.config.features is not None:
									a		=			self.config.features.arrow_schema
									if all(not require_storage_cast(__lowerCamelCase					) for feature in self.config.features.values()					):
										# cheaper cast
										a		=			pa.Table.from_arrays([pa_table[field.name] for field in schema]							,schema=__lowerCamelCase					)
									else:
										# more expensive cast; allows str <-> int/float or str to Audio for example
										a		=			table_cast(__lowerCamelCase							,__lowerCamelCase					)
								return pa_table




							def  SCREAMING_SNAKE_CASE_ (						self		:					str					):





								'''simple docstring'''



								a		=			self.config.chunksize
								a		=			pd.read_sql(
								    self.config.sql							,self.config.con							,chunksize=__lowerCamelCase							,**self.config.pd_read_sql_kwargs					)
								a		=			[sql_reader] if chunksize is None else sql_reader
								for chunk_idx, df in enumerate(__lowerCamelCase					):
									a		=			pa.Table.from_pandas(__lowerCamelCase					)
									yield chunk_idx, self._cast_table(__lowerCamelCase					)





