





'''simple docstring'''

import csv
import json
import logging
import os
import re
import subprocess
import tempfile
import unittest
import zipfile
from pathlib import Path
from typing import Optional
from unittest import mock

import torch

# We use TF to parse the logs
from accelerate import Accelerator
from accelerate.test_utils.testing import (
    MockingTestCase,
    TempDirTestCase,
    require_comet_ml,
    require_tensorboard,
    require_wandb,
    skip,
)
from accelerate.tracking import CometMLTracker, GeneralTracker
from accelerate.utils import ProjectConfiguration, is_comet_ml_available, is_tensorboard_available


if is_comet_ml_available():
			from comet_ml import OfflineExperiment

if is_tensorboard_available():
			import struct

			import tensorboard.compat.proto.event_pba as event_pba

lowerCAmelCase__	:					int	     =       logging.getLogger(__name__)


@require_tensorboard
class 			SCREAMING_SNAKE_CASE__	(					unittest.TestCase						):







					"""simple docstring"""






					def 						lowerCamelCase_					(					self    :	List[str]						):







							"""simple docstring"""
							__UpperCAmelCase     :				int					   =			"test_project_with_config"
							with tempfile.TemporaryDirectory() as dirpath:
									__UpperCAmelCase     :				List[Any]					   =			Accelerator(log_with="tensorboard"						,     project_dir=_A						)
									__UpperCAmelCase     :				Union[str, Any]					   =			{"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
									accelerator.init_trackers(_A						,     _A						)
									accelerator.end_training()
									for child in Path(f"{dirpath}/{project_name}"						).glob("*/**"						):
											__UpperCAmelCase     :				str					   =			list(filter(lambda UpperCAmelCase_						: x.is_file()						,     child.iterdir()						)						)[0]
									self.assertNotEqual(str(_A						)						,     ""						)
					def 						lowerCamelCase_					(					self    :	List[str]						):







							"""simple docstring"""
							__UpperCAmelCase     :				Tuple					   =			"test_project_with_log"
							with tempfile.TemporaryDirectory() as dirpath:
									__UpperCAmelCase     :				int					   =			Accelerator(log_with="tensorboard"						,     project_dir=_A						)
									accelerator.init_trackers(_A						)
									__UpperCAmelCase     :				Optional[int]					   =			{"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
									accelerator.log(_A						,     step=0						)
									accelerator.end_training()
									# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
									# Names are randomly generated each time
									__UpperCAmelCase     :				Tuple					   =			list(filter(lambda UpperCAmelCase_						: x.is_file()						,     Path(f"{dirpath}/{project_name}"						).iterdir()						)						)[0]
									self.assertNotEqual(str(_A						)						,     ""						)
					def 						lowerCamelCase_					(					self    :	Any						):







							"""simple docstring"""
							__UpperCAmelCase     :				List[Any]					   =			"test_project_with_log"
							with tempfile.TemporaryDirectory() as dirpath:
									__UpperCAmelCase     :				Union[str, Any]					   =			Accelerator(log_with="tensorboard"						,     project_dir=_A						)
									accelerator.init_trackers(_A						)
									__UpperCAmelCase     :				Optional[Any]					   =			{"tensor": torch.tensor(1						)}
									accelerator.log(_A						,     step=0						)
									accelerator.end_training()
									# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
									# Names are randomly generated each time
									__UpperCAmelCase     :				Optional[Any]					   =			list(filter(lambda UpperCAmelCase_						: x.is_file()						,     Path(f"{dirpath}/{project_name}"						).iterdir()						)						)[0]
									# Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
									with open(_A						,     "rb"						) as f:
											__UpperCAmelCase     :				int					   =			f.read()
									__UpperCAmelCase     :				Dict					   =			False
									while data:
											__UpperCAmelCase     :				Dict					   =			struct.unpack("Q"						,     data[:8]						)

											__UpperCAmelCase     :				List[Any]					   =			data[12 : 12 + int(header[0]						)]  # 8+4
											__UpperCAmelCase     :				Dict					   =			data[12 + int(header[0]						) + 4 :]
											__UpperCAmelCase     :				Union[str, Any]					   =			event_pba.Event()

											event.ParseFromString(_A						)
											if event.HasField("summary"						):
													for value in event.summary.value:
															if value.simple_value == 1.0 and value.tag == "tensor":
																	__UpperCAmelCase     :				Optional[int]					   =			True
									self.assertTrue(_A						,     "Converted tensor was not found in the log file!"						)
					def 						lowerCamelCase_					(					self    :	List[str]						):







							"""simple docstring"""
							with self.assertRaisesRegex(_A						,     "Logging with `tensorboard` requires a `logging_dir`"						):
									__UpperCAmelCase     :				int					   =			Accelerator(log_with="tensorboard"						)
							with tempfile.TemporaryDirectory() as dirpath:
									__UpperCAmelCase     :				List[Any]					   =			Accelerator(log_with="tensorboard"						,     project_dir=_A						)






					def 						lowerCamelCase_					(					self    :	Optional[Any]						):







							"""simple docstring"""
							__UpperCAmelCase     :				Dict					   =			ProjectConfiguration(total_limit=30						)
							with tempfile.TemporaryDirectory() as dirpath:
									__UpperCAmelCase     :				int					   =			Accelerator(log_with="tensorboard"						,     project_dir=_A						,     project_config=_A						)






@require_wandb
@mock.patch.dict(os.environ				,{'''WANDB_MODE''': '''offline'''}						)
class 			SCREAMING_SNAKE_CASE__	(					A_				,A_						):







					"""simple docstring"""






					def 						lowerCamelCase_					(					self    :	int						):







							"""simple docstring"""
							super().setUp()
							# wandb let's us override where logs are stored to via the WANDB_DIR env var
							self.add_mocks(mock.patch.dict(os.environ						,     {"WANDB_DIR": self.tmpdir}						)						)
					@staticmethod
					def 						lowerCamelCase_					(					UpperCAmelCase_    :	str						,     UpperCAmelCase_    :	str						,     UpperCAmelCase_    :	bool = True						):







							"""simple docstring"""
							__UpperCAmelCase     :				Any					   =			Rf"{section} ([\S\s]*?)\n\n"
							if record:
									__UpperCAmelCase     :				str					   =			Rf"Record: {pattern}"
							__UpperCAmelCase     :				str					   =			re.findall(_A						,     _A						)[0]
							# A config
							if section == "config" or section == "history":
									__UpperCAmelCase     :				Dict					   =			re.findall(R"\"([a-zA-Z0-9_.,]+)"						,     _A						)
									return {key: val for key, val in zip(cleaned_record[0::2]						,     cleaned_record[1::2]						)}
							# Everything else
							else:
									return dict(re.findall(R"(\w+): \"([^\s]+)\""						,     _A						)						)






					@skip
					def 						lowerCamelCase_					(					self    :	Optional[int]						):







							"""simple docstring"""
							__UpperCAmelCase     :				List[Any]					   =			"test_project_with_config"
							__UpperCAmelCase     :				Tuple					   =			Accelerator(log_with="wandb"						)
							__UpperCAmelCase     :				Optional[Any]					   =			{"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
							__UpperCAmelCase     :				str					   =			{"wandb": {"tags": ["my_tag"]}}
							accelerator.init_trackers(_A						,     _A						,     _A						)
							__UpperCAmelCase     :				Tuple					   =			{"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
							accelerator.log(_A						,     step=0						)
							accelerator.end_training()
							# The latest offline log is stored at wandb/latest-run/*.wandb
							for child in Path(f"{self.tmpdir}/wandb/latest-run"						).glob("*"						):
									if child.is_file() and child.suffix == ".wandb":
											__UpperCAmelCase     :				Optional[Any]					   =			subprocess.check_output(
											    ["wandb", "sync", "--view", "--verbose", str(_A						)]						,     env=os.environ.copy()						).decode("utf8"						,     "ignore"						)
											break

        # Check HPS through careful parsing and cleaning
							__UpperCAmelCase     :				Optional[Any]					   =			self.parse_log(_A						,     "config"						)
							self.assertEqual(logged_items["num_iterations"]						,     "12"						)
							self.assertEqual(logged_items["learning_rate"]						,     "0.01"						)
							self.assertEqual(logged_items["some_boolean"]						,     "false"						)
							self.assertEqual(logged_items["some_string"]						,     "some_value"						)
							self.assertEqual(logged_items["some_string"]						,     "some_value"						)

							# Run tags
							__UpperCAmelCase     :				Dict					   =			self.parse_log(_A						,     "run"						,     _A						)
							self.assertEqual(logged_items["tags"]						,     "my_tag"						)

							# Actual logging
							__UpperCAmelCase     :				List[Any]					   =			self.parse_log(_A						,     "history"						)
							self.assertEqual(logged_items["total_loss"]						,     "0.1"						)
							self.assertEqual(logged_items["iteration"]						,     "1"						)
							self.assertEqual(logged_items["my_text"]						,     "some_value"						)
							self.assertEqual(logged_items["_step"]						,     "0"						)






def 		__UpperCamelCase		(       self,    _UpperCAmelCase,    _UpperCAmelCase   ):
		__UpperCAmelCase     :				Optional[Any]					   =			run_name
		__UpperCAmelCase     :				Any					   =			OfflineExperiment(project_name=A__,    offline_directory=A__   )
		logger.info(F"Initialized offline CometML project {self.run_name}"   )
		logger.info("Make sure to log any initial configurations with `self.store_init_configuration` before training!"   )


@require_comet_ml
@mock.patch.object(A_				,'''__init__'''				,A_						)
class 			SCREAMING_SNAKE_CASE__	(					unittest.TestCase						):







					"""simple docstring"""






					@staticmethod
					def 						lowerCamelCase_					(					UpperCAmelCase_    :	Tuple						,     UpperCAmelCase_    :	str						,     UpperCAmelCase_    :	bool = False						):







							"""simple docstring"""
							for log in log_list:
									__UpperCAmelCase     :				int					   =			json.loads(_A						)["payload"]
									if is_param and "param" in j.keys():
											if j["param"]["paramName"] == key:
													return j["param"]["paramValue"]
									if "log_other" in j.keys():
											if j["log_other"]["key"] == key:
													return j["log_other"]["val"]
									if "metric" in j.keys():
											if j["metric"]["metricName"] == key:
													return j["metric"]["metricValue"]
					def 						lowerCamelCase_					(					self    :	str						):







							"""simple docstring"""
							with tempfile.TemporaryDirectory() as d:
									__UpperCAmelCase     :				Union[str, Any]					   =			CometMLTracker("test_project_with_config"						,     _A						)
									__UpperCAmelCase     :				Optional[int]					   =			Accelerator(log_with=_A						)
									__UpperCAmelCase     :				Optional[int]					   =			{"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
									accelerator.init_trackers(_A						,     _A						)
									accelerator.end_training()
									__UpperCAmelCase     :				Tuple					   =			os.listdir(_A						)[0]  # Comet is nice, it's just a zip file here
									# We parse the raw logs
									__UpperCAmelCase     :				Tuple					   =			os.path.join(_A						,     _A						)
									__UpperCAmelCase     :				Optional[Any]					   =			zipfile.ZipFile(_A						,     "r"						)
									__UpperCAmelCase     :				Dict					   =			archive.open("messages.json"						).read().decode("utf-8"						)
							__UpperCAmelCase     :				str					   =			log.split("\n"						)[:-1]
							self.assertEqual(self.get_value_from_key(_A						,     "num_iterations"						,     _A						)						,     12						)
							self.assertEqual(self.get_value_from_key(_A						,     "learning_rate"						,     _A						)						,     0.01						)
							self.assertEqual(self.get_value_from_key(_A						,     "some_boolean"						,     _A						)						,     _A						)
							self.assertEqual(self.get_value_from_key(_A						,     "some_string"						,     _A						)						,     "some_value"						)






					def 						lowerCamelCase_					(					self    :	Dict						):







							"""simple docstring"""
							with tempfile.TemporaryDirectory() as d:
									__UpperCAmelCase     :				str					   =			CometMLTracker("test_project_with_config"						,     _A						)
									__UpperCAmelCase     :				int					   =			Accelerator(log_with=_A						)
									accelerator.init_trackers(_A						)
									__UpperCAmelCase     :				str					   =			{"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
									accelerator.log(_A						,     step=0						)
									accelerator.end_training()
									__UpperCAmelCase     :				Optional[int]					   =			os.listdir(_A						)[0]  # Comet is nice, it's just a zip file here
									# We parse the raw logs
									__UpperCAmelCase     :				List[str]					   =			os.path.join(_A						,     _A						)
									__UpperCAmelCase     :				int					   =			zipfile.ZipFile(_A						,     "r"						)
									__UpperCAmelCase     :				List[str]					   =			archive.open("messages.json"						).read().decode("utf-8"						)
							__UpperCAmelCase     :				List[str]					   =			log.split("\n"						)[:-1]
							self.assertEqual(self.get_value_from_key(_A						,     "curr_step"						,     _A						)						,     0						)
							self.assertEqual(self.get_value_from_key(_A						,     "total_loss"						)						,     0.1						)
							self.assertEqual(self.get_value_from_key(_A						,     "iteration"						)						,     1						)
							self.assertEqual(self.get_value_from_key(_A						,     "my_text"						)						,     "some_value"						)






class 			SCREAMING_SNAKE_CASE__	(					A_						):







					"""simple docstring"""






					SCREAMING_SNAKE_CASE				=     [
					    "total_loss",
					    "iteration",
					    "my_text",
					    "learning_rate",
					    "num_iterations",
					    "some_boolean",
					    "some_string",
					]

					SCREAMING_SNAKE_CASE				=     "my_custom_tracker"
					SCREAMING_SNAKE_CASE				=     False
					def __init__(					self    :	str						,     UpperCAmelCase_    :	str						):







							"""simple docstring"""
							__UpperCAmelCase     :				Optional[int]					   =			open(f"{dir}/log.csv"						,     "w+"						)
							__UpperCAmelCase     :				Optional[Any]					   =			csv.DictWriter(self.f						,     fieldnames=self._col_names						)
							self.writer.writeheader()
					@property
					def 						lowerCamelCase_					(					self    :	List[Any]						):







							"""simple docstring"""
							return self.writer
					def 						lowerCamelCase_					(					self    :	Any						,     UpperCAmelCase_    :	dict						):







							"""simple docstring"""
							logger.info("Call init"						)
							self.writer.writerow(_A						)
					def 						lowerCamelCase_					(					self    :	List[Any]						,     UpperCAmelCase_    :	dict						,     UpperCAmelCase_    :	Optional[int]						):







							"""simple docstring"""
							logger.info("Call log"						)
							self.writer.writerow(_A						)






					def 						lowerCamelCase_					(					self    :	int						):







							"""simple docstring"""
							self.f.close()






class 			SCREAMING_SNAKE_CASE__	(					unittest.TestCase						):







					"""simple docstring"""






					def 						lowerCamelCase_					(					self    :	List[str]						):







							"""simple docstring"""
							with tempfile.TemporaryDirectory() as d:
									__UpperCAmelCase     :				List[str]					   =			MyCustomTracker(_A						)
									__UpperCAmelCase     :				int					   =			Accelerator(log_with=_A						)
									__UpperCAmelCase     :				List[str]					   =			{"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
									accelerator.init_trackers("Some name"						,     _A						)
									accelerator.end_training()
									with open(f"{d}/log.csv"						,     "r"						) as f:
											__UpperCAmelCase     :				Union[str, Any]					   =			csv.DictReader(_A						)
											__UpperCAmelCase     :				List[Any]					   =			next(_A						)
											__UpperCAmelCase     :				Union[str, Any]					   =			{
											    "total_loss": "",
											    "iteration": "",
											    "my_text": "",
											    "learning_rate": "0.01",
											    "num_iterations": "12",
											    "some_boolean": "False",
											    "some_string": "some_value",
											}
											self.assertDictEqual(_A						,     _A						)






					def 						lowerCamelCase_					(					self    :	List[Any]						):







							"""simple docstring"""
							with tempfile.TemporaryDirectory() as d:
									__UpperCAmelCase     :				Dict					   =			MyCustomTracker(_A						)
									__UpperCAmelCase     :				Dict					   =			Accelerator(log_with=_A						)
									accelerator.init_trackers("Some name"						)
									__UpperCAmelCase     :				Any					   =			{"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
									accelerator.log(_A						,     step=0						)
									accelerator.end_training()
									with open(f"{d}/log.csv"						,     "r"						) as f:
											__UpperCAmelCase     :				Optional[Any]					   =			csv.DictReader(_A						)
											__UpperCAmelCase     :				Union[str, Any]					   =			next(_A						)
											__UpperCAmelCase     :				List[str]					   =			{
											    "total_loss": "0.1",
											    "iteration": "1",
											    "my_text": "some_value",
											    "learning_rate": "",
											    "num_iterations": "",
											    "some_boolean": "",
											    "some_string": "",
											}
											self.assertDictEqual(_A						,     _A						)






from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


_A  					= logging.get_logger(__name__)







class      lowerCamelCase		(  A_  ):
     UpperCAmelCase__				:							int           =		["input_values", "attention_mask"]





     def __init__(self      :    Tuple				,    _A      :    Optional[Any]=1				,    _A      :    Dict=1_6_0_0_0				,    _A      :    int=0.0				,    _A      :    List[str]=False				,    _A      :    Optional[int]=True				,    **_A      :    List[Any]				,    )						->						str:
         super().__init__(feature_size=_A				,    sampling_rate=_A				,    padding_value=_A				,    **_A   )
         snake_case      =					return_attention_mask
         snake_case      =					do_normalize





     @staticmethod
     def 		UpperCAmelCase(_A      :    List[np.ndarray]				,    _A      :    List[np.ndarray]				,    _A      :    float = 0.0   )						->						List[np.ndarray]:
         if attention_mask is not None:
             snake_case      =					np.array(_A				,    np.intaa   )
             snake_case      =					[]

             for vector, length in zip(_A				,    attention_mask.sum(-1   )   ):
                 snake_case      =					(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7   )
                 if length < normed_slice.shape[0]:
                     snake_case      =					padding_value

                 normed_input_values.append(_A   )
         else:
             snake_case      =					[(x - x.mean()) / np.sqrt(x.var() + 1E-7   ) for x in input_values]

         return normed_input_values





     def __call__(self      :    Optional[Any]				,    _A      :    Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]				,    _A      :    Union[bool, str, PaddingStrategy] = False				,    _A      :    Optional[int] = None				,    _A      :    bool = False				,    _A      :    Optional[int] = None				,    _A      :    Optional[bool] = None				,    _A      :    Optional[Union[str, TensorType]] = None				,    _A      :    Optional[int] = None				,    **_A      :    List[Any]				,    )						->						BatchFeature:

         if sampling_rate is not None:
             if sampling_rate != self.sampling_rate:
                 raise ValueError(
                     f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
                     f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'
                     f' {self.sampling_rate} and not {sampling_rate}.'   )
         else:
             logger.warning(
                 "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
                 "Failing to do so can result in silent errors that might be hard to debug."   )

         snake_case      =					isinstance(_A				,    np.ndarray   ) and len(raw_speech.shape   ) > 1
         if is_batched_numpy and len(raw_speech.shape   ) > 2:
             raise ValueError(f'Only mono-channel audio is supported for input to {self}'   )
         snake_case      =					is_batched_numpy or (
             isinstance(_A				,    (list, tuple)   ) and (isinstance(raw_speech[0]				,    (np.ndarray, tuple, list)   ))
         )

         # always return batch
         if not is_batched:
             snake_case      =					[raw_speech]

         # convert into correct format for padding
         snake_case      =					BatchFeature({"input_values": raw_speech}   )

         snake_case      =					self.pad(
             _A				,    padding=_A				,    max_length=_A				,    truncation=_A				,    pad_to_multiple_of=_A				,    return_attention_mask=_A				,    )

         # convert input values to correct format
         snake_case      =					padded_inputs["input_values"]
         if not isinstance(input_values[0]				,    np.ndarray   ):
             snake_case      =					[np.asarray(_A				,    dtype=np.floataa   ) for array in input_values]
         elif (
             not isinstance(_A				,    np.ndarray   )
             and isinstance(input_values[0]				,    np.ndarray   )
             and input_values[0].dtype is np.dtype(np.floataa   )
         ):
             snake_case      =					[array.astype(np.floataa   ) for array in input_values]
         elif isinstance(_A				,    np.ndarray   ) and input_values.dtype is np.dtype(np.floataa   ):
             snake_case      =					input_values.astype(np.floataa   )

         # convert attention_mask to correct format
         snake_case      =					padded_inputs.get("attention_mask"   )
         if attention_mask is not None:
             snake_case      =					[np.asarray(_A				,    dtype=np.intaa   ) for array in attention_mask]

         # zero-mean and unit-variance normalization
         if self.do_normalize:
             snake_case      =					(
                 attention_mask
                 if self._get_padding_strategies(_A				,    max_length=_A   ) is not PaddingStrategy.DO_NOT_PAD
                 else None
             )
             snake_case      =					self.zero_mean_unit_var_norm(
                 padded_inputs["input_values"]				,    attention_mask=_A				,    padding_value=self.padding_value   )

         if return_tensors is not None:
             snake_case      =					padded_inputs.convert_to_tensors(_A   )

         return padded_inputs

