
'''simple docstring'''
import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
						from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
						lowerCAmelCase :  Union[str, Any]      =      True
						from torch.cuda.amp import autocast


lowerCAmelCase :  str      =      logging.getLogger(__name__)


@dataclass
class        SCREAMING_SNAKE_CASE__	:
				lowerCAmelCase_			       =				field(
				    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""})
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}				,    )
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""})
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """Whether to log verbose messages or not."""}				,    )







def 						A_(			A		:						ModelArguments						,			A		:						TrainingArguments):
							logging.basicConfig(
							    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'						,			datefmt='%m/%d/%Y %H:%M:%S'						,			handlers=[logging.StreamHandler(sys.stdout)]						,			)
							UpperCamelCase					       =			logging.WARNING
							if model_args.verbose_logging:
														UpperCamelCase					       =			logging.DEBUG
							elif trainer_utils.is_main_process(training_args.local_rank):
														UpperCamelCase					       =			logging.INFO
							logger.setLevel(A)


@dataclass
class        SCREAMING_SNAKE_CASE__	:
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """The name of the dataset to use (via the datasets library)."""})
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""})
				lowerCAmelCase_			       =				field(
				    default="""train"""				,    metadata={
				        """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
				    }				,    )
				lowerCAmelCase_			       =				field(
				    default="""validation"""				,    metadata={
				        """help""": (
				            """The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"""
				        )
				    }				,    )
				lowerCAmelCase_			       =				field(
				    default="""text"""				,    metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to 'text'"""}				,    )
				lowerCAmelCase_			       =				field(
				    default="""file"""				,    metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""}				,    )
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""}				,    )
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}				,    )
				lowerCAmelCase_			       =				field(
				    default="""librispeech"""				,    metadata={
				        """help""": (
				            """Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"""
				            """ 'buckwalter'."""
				        )
				    }				,    )
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""})
				lowerCAmelCase_			       =				field(
				    default=snake_case_				,    metadata={"""help""": """The number of processes to use for the preprocessing."""}				,    )


@dataclass
class        SCREAMING_SNAKE_CASE__	:
				lowerCAmelCase_			       =				False
				lowerCAmelCase_			       =				None
				lowerCAmelCase_			       =				"|"
				lowerCAmelCase_			       =				field(default_factory=snake_case_)
				lowerCAmelCase_			       =				field(default_factory=snake_case_)
				lowerCAmelCase_			       =				None







				@classmethod
				def 		UpperCAmelCase_  (    cls		,							A_			)->						Union[str, Any]:







											'''simple docstring'''






											if name == "librispeech":
																		return cls()
											if name == "timit":
																		return cls(
																		    do_lower_case=A_		,							translation_table=str.maketrans({'-': ' '}			)		,							)
											if name == "buckwalter":
																		UpperCamelCase					       =			{
																		    '-': ' ',  # sometimes used to represent pauses
																		    '^': 'v',  # fixing "tha" in arabic_speech_corpus dataset
																		}
																		return cls(
																		    vocab_file=pathlib.Path(A_			).parent.joinpath('vocab/buckwalter.json'			)		,							word_delimiter_token='/'		,							translation_table=str.maketrans(A_			)		,							words_to_remove={'sil'}		,							untransliterator=arabic.buckwalter.untransliterate		,							)
											raise ValueError(F'''Unsupported orthography: \'{name}\'.'''			)







				def 		UpperCAmelCase_  (    self		,							A_			)->						str:







											'''simple docstring'''






											if len(self.translation_table			) > 0:
																		UpperCamelCase					       =			text.translate(self.translation_table			)
											if len(self.words_to_remove			) == 0:
																		UpperCamelCase					       =			' '.join(text.split()			)  # clean up whitespaces
											else:
																		UpperCamelCase					       =			' '.join(w for w in text.split() if w not in self.words_to_remove			)  # and clean up whilespaces
											return text







				def 		UpperCAmelCase_  (    self		,							A_			)->						WavaVecaProcessor:







											'''simple docstring'''






											UpperCamelCase					       =			WavaVecaFeatureExtractor.from_pretrained(
											    model_args.model_name_or_path		,							cache_dir=model_args.cache_dir			)
											if self.vocab_file:
																		UpperCamelCase					       =			WavaVecaCTCTokenizer(
																		    self.vocab_file		,							cache_dir=model_args.cache_dir		,							do_lower_case=self.do_lower_case		,							word_delimiter_token=self.word_delimiter_token		,							)
											else:
																		UpperCamelCase					       =			WavaVecaCTCTokenizer.from_pretrained(
																		    model_args.model_name_or_path		,							cache_dir=model_args.cache_dir		,							do_lower_case=self.do_lower_case		,							word_delimiter_token=self.word_delimiter_token		,							)
											return WavaVecaProcessor(A_		,							A_			)


@dataclass
class        SCREAMING_SNAKE_CASE__	:
				lowerCAmelCase_			       =				42
				lowerCAmelCase_			       =				True
				lowerCAmelCase_			       =				None
				lowerCAmelCase_			       =				None
				lowerCAmelCase_			       =				None
				lowerCAmelCase_			       =				None







				def __call__(    self		,							A_			)->						Dict[str, torch.Tensor]:







											'''simple docstring'''






											UpperCamelCase					       =			[{'input_values': feature['input_values']} for feature in features]
											UpperCamelCase					       =			[{'input_ids': feature['labels']} for feature in features]

											UpperCamelCase					       =			self.processor.pad(
											    A_		,							padding=self.padding		,							max_length=self.max_length		,							pad_to_multiple_of=self.pad_to_multiple_of		,							return_tensors='pt'		,							)
											UpperCamelCase					       =			self.processor.pad(
											    labels=A_		,							padding=self.padding		,							max_length=self.max_length_labels		,							pad_to_multiple_of=self.pad_to_multiple_of_labels		,							return_tensors='pt'		,							)

											# replace padding with -100 to ignore loss correctly
											UpperCamelCase					       =			labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1			)		,							-100			)

											UpperCamelCase					       =			labels

											return batch


class        SCREAMING_SNAKE_CASE__	(			snake_case_):







				def 		UpperCAmelCase_  (    self		,							A_		,							A_			)->						torch.Tensor:







											'''simple docstring'''






											model.train()
											UpperCamelCase					       =			self._prepare_inputs(A_			)

											if self.use_amp:
																		with autocast():
																									UpperCamelCase					       =			self.compute_loss(A_		,							A_			)
											else:
																		UpperCamelCase					       =			self.compute_loss(A_		,							A_			)

											if self.args.n_gpu > 1:
																		if model.module.config.ctc_loss_reduction == "mean":
																									UpperCamelCase					       =			loss.mean()
																		elif model.module.config.ctc_loss_reduction == "sum":
																									UpperCamelCase					       =			loss.sum() / (inputs['labels'] >= 0).sum()
																		else:
																									raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'''			)

											if self.args.gradient_accumulation_steps > 1:
																		UpperCamelCase					       =			loss / self.args.gradient_accumulation_steps

											if self.use_amp:
																		self.scaler.scale(A_			).backward()
											elif self.use_apex:
																		with amp.scale_loss(A_		,							self.optimizer			) as scaled_loss:
																									scaled_loss.backward()
											elif self.deepspeed:
																		self.deepspeed.backward(A_			)
											else:
																		loss.backward()

											return loss.detach()







def 						A_(			):
							# See all possible arguments in src/transformers/training_args.py
							# or by passing the --help flag to this script.
							# We now keep distinct sets of args, for a cleaner separation of concerns.

							UpperCamelCase					       =			HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))

							UpperCamelCase       ,     UpperCamelCase       ,     UpperCamelCase					       =			parser.parse_args_into_dataclasses()
							configure_logger(A						,			A)

							UpperCamelCase					       =			Orthography.from_name(data_args.orthography.lower())
							UpperCamelCase					       =			orthography.create_processor(A)
							UpperCamelCase					       =			WavaVecaForCTC.from_pretrained(
							    model_args.model_name_or_path						,			cache_dir=model_args.cache_dir						,			gradient_checkpointing=training_args.gradient_checkpointing						,			vocab_size=len(processor.tokenizer)						,			)

							UpperCamelCase					       =			datasets.load_dataset(
							    data_args.dataset_name						,			data_args.dataset_config_name						,			split=data_args.train_split_name)
							UpperCamelCase					       =			datasets.load_dataset(
							    data_args.dataset_name						,			data_args.dataset_config_name						,			split=data_args.validation_split_name)

							UpperCamelCase					       =			datasets.load_metric('wer')
							UpperCamelCase					       =			processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
							UpperCamelCase					       =			''.join(t for t in processor.tokenizer.get_vocab().keys() if len(A) == 1)
							UpperCamelCase					       =			re.compile(  # remove characters not in vocabulary
							    rf'''[^\s{re.escape(A)}]'''						,			flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0						,			)
							UpperCamelCase					       =			[]

							def prepare_example(A		:						Optional[Any]):  # TODO(elgeish) make use of multiprocessing?
														UpperCamelCase       ,     UpperCamelCase					       =			librosa.load(example[data_args.speech_file_column]						,			sr=A)
														if data_args.max_duration_in_seconds is not None:
																					UpperCamelCase					       =			len(example['speech']) / example['sampling_rate']
														# Normalize and clean up text; order matters!
														UpperCamelCase					       =			orthography.preprocess_for_training(example[data_args.target_text_column])
														UpperCamelCase					       =			vocabulary_text_cleaner.sub(''						,			A)
														if updated_text != example[data_args.target_text_column]:
																					text_updates.append((example[data_args.target_text_column], updated_text))
																					UpperCamelCase					       =			updated_text
														return example

							UpperCamelCase					       =			train_dataset.map(A						,			remove_columns=[data_args.speech_file_column])
							UpperCamelCase					       =			val_dataset.map(A						,			remove_columns=[data_args.speech_file_column])

							if data_args.max_duration_in_seconds is not None:

														def filter_by_max_duration(A		:						Tuple):
																					return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

														UpperCamelCase					       =			len(A)
														UpperCamelCase					       =			len(A)
														UpperCamelCase					       =			train_dataset.filter(A						,			remove_columns=['duration_in_seconds'])
														UpperCamelCase					       =			val_dataset.filter(A						,			remove_columns=['duration_in_seconds'])
														if len(A) > old_train_size:
																					logger.warning(
																					    f'''Filtered out {len(A) - old_train_size} train example(s) longer than'''
																					    f''' {data_args.max_duration_in_seconds} second(s).''')
														if len(A) > old_val_size:
																					logger.warning(
																					    f'''Filtered out {len(A) - old_val_size} validation example(s) longer than'''
																					    f''' {data_args.max_duration_in_seconds} second(s).''')
							logger.info(f'''Split sizes: {len(A)} train and {len(A)} validation.''')

							logger.warning(f'''Updated {len(A)} transcript(s) using \'{data_args.orthography}\' orthography rules.''')
							if logger.isEnabledFor(logging.DEBUG):
														for original_text, updated_text in text_updates:
																					logger.debug(f'''Updated text: "{original_text}" -> "{updated_text}"''')
							UpperCamelCase					       =			None

							def prepare_dataset(A		:						Optional[Any]):
														# check that all files have the correct sampling rate
														assert (
														    len(set(batch['sampling_rate'])) == 1
														), f'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'''

														UpperCamelCase					       =			processor(
														    audio=batch['speech']						,			text=batch[data_args.target_text_column]						,			sampling_rate=batch['sampling_rate'][0])
														batch.update(A)
														return batch

							UpperCamelCase					       =			train_dataset.map(
							    A						,			batch_size=training_args.per_device_train_batch_size						,			batched=A						,			num_proc=data_args.preprocessing_num_workers						,			)
							UpperCamelCase					       =			val_dataset.map(
							    A						,			batch_size=training_args.per_device_train_batch_size						,			batched=A						,			num_proc=data_args.preprocessing_num_workers						,			)

							UpperCamelCase					       =			DataCollatorCTCWithPadding(processor=A						,			padding=A)

							def compute_metrics(A		:						Optional[Any]):
														UpperCamelCase					       =			pred.predictions
														UpperCamelCase					       =			np.argmax(A						,			axis=-1)

														UpperCamelCase					       =			processor.tokenizer.pad_token_id

														UpperCamelCase					       =			processor.batch_decode(A)
														# we do not want to group tokens when computing the metrics
														UpperCamelCase					       =			processor.batch_decode(pred.label_ids						,			group_tokens=A)
														if logger.isEnabledFor(logging.DEBUG):
																					for reference, predicted in zip(A						,			A):
																												logger.debug(f'''reference: "{reference}"''')
																												logger.debug(f'''predicted: "{predicted}"''')
																												if orthography.untransliterator is not None:
																																			logger.debug(f'''reference (untransliterated): "{orthography.untransliterator(A)}"''')
																																			logger.debug(f'''predicted (untransliterated): "{orthography.untransliterator(A)}"''')

														UpperCamelCase					       =			wer_metric.compute(predictions=A						,			references=A)

														return {"wer": wer}

							if model_args.freeze_feature_extractor:
														model.freeze_feature_extractor()

							UpperCamelCase					       =			CTCTrainer(
							    model=A						,			data_collator=A						,			args=A						,			compute_metrics=A						,			train_dataset=A						,			eval_dataset=A						,			tokenizer=processor.feature_extractor						,			)

							trainer.train()


if __name__ == "__main__":
						main()









from __future__ import annotations

from pathlib import Path







def 				A			(		__UpperCAmelCase							,					__UpperCAmelCase	)       ->       int:



						'''simple docstring'''






						return pointa[0] * pointa[1] - pointa[1] * pointa[0]







def 				A			(		__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase	)       ->       bool:



						'''simple docstring'''






						UpperCAmelCase_     							=     (xa, ya)
						UpperCAmelCase_     							=     (xa - xa, ya - ya)
						UpperCAmelCase_     							=     (xa - xa, ya - ya)
						UpperCAmelCase_     							=     -vector_product(__UpperCAmelCase							,					__UpperCAmelCase	) / vector_product(
						    __UpperCAmelCase							,					__UpperCAmelCase	)
						UpperCAmelCase_     							=     +vector_product(__UpperCAmelCase							,					__UpperCAmelCase	) / vector_product(
						    __UpperCAmelCase							,					__UpperCAmelCase	)

						return a > 0 and b > 0 and a + b < 1







def 				A			(		__UpperCAmelCase = "p102_triangles.txt"	)       ->       int:



						'''simple docstring'''






						UpperCAmelCase_     							=     Path(__UpperCAmelCase	).parent.joinpath(__UpperCAmelCase	).read_text(encoding='''utf-8'''	)

						UpperCAmelCase_     							=     []
						for line in data.strip().split('''\n'''	):
												triangles.append([int(__UpperCAmelCase	) for number in line.split(''','''	)]	)

						UpperCAmelCase_     							=     0
						UpperCAmelCase_     							=     42

						for triangle in triangles:
												ret += contains_origin(*__UpperCAmelCase	)

						return ret


if __name__ == "__main__":
							print(f"{solution() = }")





