



'''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

A			:   List[str]			=      logging.getLogger(__name__)





@require_tensorboard
class 							lowerCAmelCase_		(	unittest.TestCase						):





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       snake_case   :							List[Any]						  ="test_project_with_config"
       with tempfile.TemporaryDirectory() as dirpath:
          snake_case   :							Optional[int]						  =Accelerator(log_with='''tensorboard''',    project_dir=_A     )
          snake_case   :							Tuple						  ={"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('''*/**'''     ):
             snake_case   :							Any						  =list(filter(lambda _snake_case     : x.is_file(),    child.iterdir()     )     )[0]
          self.assertNotEqual(str(_A     ),    ''''''     )





    def 					__snake_case       (    self    :    int     ):



       '''simple docstring'''







       snake_case   :							List[str]						  ="test_project_with_log"
       with tempfile.TemporaryDirectory() as dirpath:
          snake_case   :							Dict						  =Accelerator(log_with='''tensorboard''',    project_dir=_A     )
          accelerator.init_trackers(_A     )
          snake_case   :							List[Any]						  ={"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
          snake_case   :							int						  =list(filter(lambda _snake_case     : x.is_file(),    Path(f'''{dirpath}/{project_name}'''     ).iterdir()     )     )[0]
          self.assertNotEqual(str(_A     ),    ''''''     )





    def 					__snake_case       (    self    :    int     ):



       '''simple docstring'''







       snake_case   :							Optional[Any]						  ="test_project_with_log"
       with tempfile.TemporaryDirectory() as dirpath:
          snake_case   :							Optional[int]						  =Accelerator(log_with='''tensorboard''',    project_dir=_A     )
          accelerator.init_trackers(_A     )
          snake_case   :							Union[str, 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
          snake_case   :							List[Any]						  =list(filter(lambda _snake_case     : 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:
             snake_case   :							Any						  =f.read()
          snake_case   :							Union[str, Any]						  =False
          while data:
             snake_case   :							Tuple						  =struct.unpack('''Q''',    data[:8]     )

             snake_case   :							Optional[Any]						  =data[12 : 12 + int(header[0]     )]  # 8+4
             snake_case   :							List[Any]						  =data[12 + int(header[0]     ) + 4 :]
             snake_case   :							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":
                      snake_case   :							Tuple						  =True
          self.assertTrue(_A,    '''Converted tensor was not found in the log file!'''     )





    def 					__snake_case       (    self    :    List[Any]     ):



       '''simple docstring'''







       with self.assertRaisesRegex(_A,    '''Logging with `tensorboard` requires a `logging_dir`'''     ):
          snake_case   :							Dict						  =Accelerator(log_with='''tensorboard'''     )
       with tempfile.TemporaryDirectory() as dirpath:
          snake_case   :							Tuple						  =Accelerator(log_with='''tensorboard''',    project_dir=_A     )






    def 					__snake_case       (    self    :    str     ):



       '''simple docstring'''







       snake_case   :							int						  =ProjectConfiguration(total_limit=30     )
       with tempfile.TemporaryDirectory() as dirpath:
          snake_case   :							Dict						  =Accelerator(log_with='''tensorboard''',    project_dir=_A,    project_config=_A     )





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





    def 					__snake_case       (    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 					__snake_case       (    _snake_case    :    str,    _snake_case    :    str,    _snake_case    :    bool = True     ):



       '''simple docstring'''







       snake_case   :							Union[str, Any]						  =rf'''{section} ([\S\s]*?)\n\n'''
       if record:
          snake_case   :							int						  =rf'''Record: {pattern}'''
       snake_case   :							Optional[int]						  =re.findall(_A,    _A     )[0]
       # A config
       if section == "config" or section == "history":
          snake_case   :							List[Any]						  =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 					__snake_case       (    self    :    Tuple     ):



       '''simple docstring'''







       snake_case   :							str						  ="test_project_with_config"
       snake_case   :							List[str]						  =Accelerator(log_with='''wandb'''     )
       snake_case   :							Optional[int]						  ={"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
       snake_case   :							Dict						  ={"wandb": {"tags": ["my_tag"]}}
       accelerator.init_trackers(_A,    _A,    _A     )
       snake_case   :							List[str]						  ={"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":
             snake_case   :							Tuple						  =subprocess.check_output(
                 ['''wandb''', '''sync''', '''--view''', '''--verbose''', str(_A     )],    env=os.environ.copy()     ).decode('''utf8''',    '''ignore'''     )
             break

        # Check HPS through careful parsing and cleaning
       snake_case   :							Tuple						  =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
       snake_case   :							Optional[int]						  =self.parse_log(_A,    '''run''',    _A     )
       self.assertEqual(logged_items['''tags'''],    '''my_tag'''     )

       # Actual logging
       snake_case   :							Optional[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 		_a   (  self					,						lowerCamelCase_					,						lowerCamelCase_							):
   snake_case   :							List[str]						  =run_name
   snake_case   :							Any						  =OfflineExperiment(project_name=lowerCamelCase_					,						offline_directory=lowerCamelCase_							)
   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 							lowerCAmelCase_		(	unittest.TestCase						):





    @staticmethod
    def 					__snake_case       (    _snake_case    :    List[str],    _snake_case    :    str,    _snake_case    :    bool = False     ):



       '''simple docstring'''







       for log in log_list:
          snake_case   :							Union[str, Any]						  =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 					__snake_case       (    self    :    Any     ):



       '''simple docstring'''







       with tempfile.TemporaryDirectory() as d:
          snake_case   :							Any						  =CometMLTracker('''test_project_with_config''',    _A     )
          snake_case   :							int						  =Accelerator(log_with=_A     )
          snake_case   :							Any						  ={"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
          accelerator.init_trackers(_A,    _A     )
          accelerator.end_training()
          snake_case   :							Union[str, Any]						  =os.listdir(_A     )[0]  # Comet is nice, it's just a zip file here
          # We parse the raw logs
          snake_case   :							Optional[Any]						  =os.path.join(_A,    _A     )
          snake_case   :							Optional[int]						  =zipfile.ZipFile(_A,    '''r'''     )
          snake_case   :							Optional[int]						  =archive.open('''messages.json'''     ).read().decode('''utf-8'''     )
       snake_case   :							List[Any]						  =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 					__snake_case       (    self    :    List[str]     ):



       '''simple docstring'''







       with tempfile.TemporaryDirectory() as d:
          snake_case   :							str						  =CometMLTracker('''test_project_with_config''',    _A     )
          snake_case   :							Any						  =Accelerator(log_with=_A     )
          accelerator.init_trackers(_A     )
          snake_case   :							Tuple						  ={"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
          accelerator.log(_A,    step=0     )
          accelerator.end_training()
          snake_case   :							Any						  =os.listdir(_A     )[0]  # Comet is nice, it's just a zip file here
          # We parse the raw logs
          snake_case   :							Any						  =os.path.join(_A,    _A     )
          snake_case   :							Any						  =zipfile.ZipFile(_A,    '''r'''     )
          snake_case   :							List[str]						  =archive.open('''messages.json'''     ).read().decode('''utf-8'''     )
       snake_case   :							Optional[int]						  =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 							lowerCAmelCase_		(	A__						):
    __UpperCAmelCase							=	[
        'total_loss',
        'iteration',
        'my_text',
        'learning_rate',
        'num_iterations',
        'some_boolean',
        'some_string',
    ]

    __UpperCAmelCase							=	'my_custom_tracker'
    __UpperCAmelCase							=	False





    def __init__(    self    :    str,    _snake_case    :    str     ):



       '''simple docstring'''







       snake_case   :							Dict						  =open(f'''{dir}/log.csv''',    '''w+'''     )
       snake_case   :							Dict						  =csv.DictWriter(self.f,    fieldnames=self._col_names     )
       self.writer.writeheader()





    @property
    def 					__snake_case       (    self    :    List[str]     ):



       '''simple docstring'''







       return self.writer





    def 					__snake_case       (    self    :    Dict,    _snake_case    :    dict     ):



       '''simple docstring'''







       logger.info('''Call init'''     )
       self.writer.writerow(_A     )





    def 					__snake_case       (    self    :    List[str],    _snake_case    :    dict,    _snake_case    :    Optional[int]     ):



       '''simple docstring'''







       logger.info('''Call log'''     )
       self.writer.writerow(_A     )






    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       self.f.close()





class 							lowerCAmelCase_		(	unittest.TestCase						):





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       with tempfile.TemporaryDirectory() as d:
          snake_case   :							Tuple						  =MyCustomTracker(_A     )
          snake_case   :							List[str]						  =Accelerator(log_with=_A     )
          snake_case   :							Any						  ={"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:
             snake_case   :							str						  =csv.DictReader(_A     )
             snake_case   :							int						  =next(_A     )
             snake_case   :							List[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 					__snake_case       (    self    :    Optional[Any]     ):



       '''simple docstring'''







       with tempfile.TemporaryDirectory() as d:
          snake_case   :							str						  =MyCustomTracker(_A     )
          snake_case   :							Tuple						  =Accelerator(log_with=_A     )
          accelerator.init_trackers('''Some name'''     )
          snake_case   :							List[str]						  ={"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:
             snake_case   :							Optional[Any]						  =csv.DictReader(_A     )
             snake_case   :							Dict						  =next(_A     )
             snake_case   :							Optional[Any]						  ={
                 "total_loss": "0.1",
                 "iteration": "1",
                 "my_text": "some_value",
                 "learning_rate": "",
                 "num_iterations": "",
                 "some_boolean": "",
                 "some_string": "",
             }
             self.assertDictEqual(_A,    _A     )










'''simple docstring'''





from __future__ import annotations

import random
import string





class 							lowerCAmelCase_		:





    def __init__(    self    :    Union[str, Any],    _snake_case    :    str | None = None     ):



       '''simple docstring'''







       snake_case   :							Optional[int]						  =passcode or self.__passcode_creator()
       snake_case   :							List[str]						  =self.__make_key_list()
       snake_case   :							Dict						  =self.__make_shift_key()





    def __str__(    self    :    List[Any]     ):



       '''simple docstring'''







       return "".join(self.__passcode     )





    def 					__snake_case       (    self    :    int,    _snake_case    :    list[int]     ):



       '''simple docstring'''







       for i in range(1,    len(_snake_case     ),    2     ):
          iterlist[i] *= -1
       return iterlist





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       snake_case   :							int						  =string.ascii_letters + string.digits
       snake_case   :							Union[str, Any]						  =[random.choice(_snake_case     ) for _ in range(random.randint(10,    20     )     )]
       return password





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       snake_case   :							Dict						  =(
           string.ascii_letters + string.digits + string.punctuation + ''' \t\n'''
       )

       snake_case   :							Any						  =[]

       # creates points known as breakpoints to break the key_list_options at those
       # points and pivot each substring
       snake_case   :							Optional[int]						  =sorted(set(self.__passcode     )     )
       snake_case   :							list[str]						  =[]

       # algorithm for creating a new shuffled list, keys_l, out of key_list_options
       for i in key_list_options:
          temp_list.extend(_snake_case     )

          # checking breakpoints at which to pivot temporary sublist and add it into
          # keys_l
          if i in breakpoints or i == key_list_options[-1]:
             keys_l.extend(temp_list[::-1]     )
             temp_list.clear()

        # returning a shuffled keys_l to prevent brute force guessing of shift key
       return keys_l





    def 					__snake_case       (    self    :    Union[str, Any]     ):



       '''simple docstring'''







       snake_case   :							str						  =sum(self.__neg_pos([ord(_snake_case     ) for x in self.__passcode]     )     )
       return num if num > 0 else len(self.__passcode     )





    def 					__snake_case       (    self    :    Optional[int],    _snake_case    :    str     ):



       '''simple docstring'''







       snake_case   :							List[Any]						  =''''''

       # decoding shift like Caesar cipher algorithm implementing negative shift or
       # reverse shift or left shift
       for i in encoded_message:
          snake_case   :							Optional[int]						  =self.__key_list.index(_snake_case     )
          decoded_message += self.__key_list[
              (position - self.__shift_key) % -len(self.__key_list     )
          ]

       return decoded_message






    def 					__snake_case       (    self    :    Union[str, Any],    _snake_case    :    str     ):



       '''simple docstring'''







       snake_case   :							int						  =''''''

       # encoding shift like Caesar cipher algorithm implementing positive shift or
       # forward shift or right shift
       for i in plaintext:
          snake_case   :							int						  =self.__key_list.index(_snake_case     )
          encoded_message += self.__key_list[
              (position + self.__shift_key) % len(self.__key_list     )
          ]

       return encoded_message




def 		_a   (  lowerCamelCase_ = "Hello, this is a modified Caesar cipher"							):
   snake_case   :							List[Any]						  =ShuffledShiftCipher()
   return cipa.decrypt(cipa.encrypt(lowerCamelCase_							)							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()





