





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

lowercase_         =			logging.getLogger(__name__)


@require_tensorboard
class  a_					(    unittest.TestCase	):

    '''simple docstring'''


    def       snake_case_(		self	)		->       Union[str, Any]:
        _SCREAMING_SNAKE_CASE     =      """test_project_with_config"""
        with tempfile.TemporaryDirectory() as dirpath:
            _SCREAMING_SNAKE_CASE     =      Accelerator(log_with="""tensorboard"""			,		project_dir=A	)
            _SCREAMING_SNAKE_CASE     =      {"""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("""*/**"""	):
                _SCREAMING_SNAKE_CASE     =      list(filter(lambda A	: x.is_file()			,		child.iterdir()	)	)[0]
            self.assertNotEqual(str(A	)			,		""""""	)


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


    def       snake_case_(		self	)		->       int:
        _SCREAMING_SNAKE_CASE     =      """test_project_with_log"""
        with tempfile.TemporaryDirectory() as dirpath:
            _SCREAMING_SNAKE_CASE     =      Accelerator(log_with="""tensorboard"""			,		project_dir=A	)
            accelerator.init_trackers(A	)
            _SCREAMING_SNAKE_CASE     =      {"""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
            _SCREAMING_SNAKE_CASE     =      list(filter(lambda A	: 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:
                _SCREAMING_SNAKE_CASE     =      f.read()
            _SCREAMING_SNAKE_CASE     =      False
            while data:
                _SCREAMING_SNAKE_CASE     =      struct.unpack("""Q"""			,		data[:8]	)

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


    def       snake_case_(		self	)		->       List[str]:
        with self.assertRaisesRegex(A			,		"""Logging with `tensorboard` requires a `logging_dir`"""	):
            _SCREAMING_SNAKE_CASE     =      Accelerator(log_with="""tensorboard"""	)
        with tempfile.TemporaryDirectory() as dirpath:
            _SCREAMING_SNAKE_CASE     =      Accelerator(log_with="""tensorboard"""			,		project_dir=A	)





    def       snake_case_(		self	)		->       str:
        _SCREAMING_SNAKE_CASE     =      ProjectConfiguration(total_limit=30	)
        with tempfile.TemporaryDirectory() as dirpath:
            _SCREAMING_SNAKE_CASE     =      Accelerator(log_with="""tensorboard"""			,		project_dir=A			,		project_config=A	)




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

    '''simple docstring'''


    def       snake_case_(		self	)		->       int:
        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_(		A			,		A			,		A = True	)		->       List[Any]:
        _SCREAMING_SNAKE_CASE     =      Rf'{section} ([\S\s]*?)\n\n'
        if record:
            _SCREAMING_SNAKE_CASE     =      Rf'Record: {pattern}'
        _SCREAMING_SNAKE_CASE     =      re.findall(A			,		A	)[0]
        # A config
        if section == "config" or section == "history":
            _SCREAMING_SNAKE_CASE     =      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	)		->       Optional[Any]:
        _SCREAMING_SNAKE_CASE     =      """test_project_with_config"""
        _SCREAMING_SNAKE_CASE     =      Accelerator(log_with="""wandb"""	)
        _SCREAMING_SNAKE_CASE     =      {"""num_iterations""": 12, """learning_rate""": 1e-2, """some_boolean""": False, """some_string""": """some_value"""}
        _SCREAMING_SNAKE_CASE     =      {"""wandb""": {"""tags""": ["""my_tag"""]}}
        accelerator.init_trackers(A			,		A			,		A	)
        _SCREAMING_SNAKE_CASE     =      {"""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":
                _SCREAMING_SNAKE_CASE     =      subprocess.check_output(
                    ["""wandb""", """sync""", """--view""", """--verbose""", str(A	)]			,		env=os.environ.copy()	).decode("""utf8"""			,		"""ignore"""	)
                break

        # Check HPS through careful parsing and cleaning
        _SCREAMING_SNAKE_CASE     =      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
        _SCREAMING_SNAKE_CASE     =      self.parse_log(A			,		"""run"""			,		A	)
        self.assertEqual(logged_items["""tags"""]			,		"""my_tag"""	)

        # Actual logging
        _SCREAMING_SNAKE_CASE     =      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 lowerCamelCase						(					self			:   int ,	__lowerCamelCase			:   str ,	__lowerCamelCase			:   str   )						->Optional[int]:
    _SCREAMING_SNAKE_CASE     =      run_name
    _SCREAMING_SNAKE_CASE     =      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(snake_case_				,   '''__init__'''				,   snake_case_	)
class  a_					(    unittest.TestCase	):

    '''simple docstring'''


    @staticmethod
    def       snake_case_(		A			,		A			,		A = False	)		->       int:
        for log in log_list:
            _SCREAMING_SNAKE_CASE     =      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	)		->       Dict:
        with tempfile.TemporaryDirectory() as d:
            _SCREAMING_SNAKE_CASE     =      CometMLTracker("""test_project_with_config"""			,		A	)
            _SCREAMING_SNAKE_CASE     =      Accelerator(log_with=A	)
            _SCREAMING_SNAKE_CASE     =      {"""num_iterations""": 12, """learning_rate""": 1e-2, """some_boolean""": False, """some_string""": """some_value"""}
            accelerator.init_trackers(A			,		A	)
            accelerator.end_training()
            _SCREAMING_SNAKE_CASE     =      os.listdir(A	)[0]  # Comet is nice, it's just a zip file here
            # We parse the raw logs
            _SCREAMING_SNAKE_CASE     =      os.path.join(A			,		A	)
            _SCREAMING_SNAKE_CASE     =      zipfile.ZipFile(A			,		"""r"""	)
            _SCREAMING_SNAKE_CASE     =      archive.open("""messages.json"""	).read().decode("""utf-8"""	)
        _SCREAMING_SNAKE_CASE     =      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	)		->       Union[str, Any]:
        with tempfile.TemporaryDirectory() as d:
            _SCREAMING_SNAKE_CASE     =      CometMLTracker("""test_project_with_config"""			,		A	)
            _SCREAMING_SNAKE_CASE     =      Accelerator(log_with=A	)
            accelerator.init_trackers(A	)
            _SCREAMING_SNAKE_CASE     =      {"""total_loss""": 0.1, """iteration""": 1, """my_text""": """some_value"""}
            accelerator.log(A			,		step=0	)
            accelerator.end_training()
            _SCREAMING_SNAKE_CASE     =      os.listdir(A	)[0]  # Comet is nice, it's just a zip file here
            # We parse the raw logs
            _SCREAMING_SNAKE_CASE     =      os.path.join(A			,		A	)
            _SCREAMING_SNAKE_CASE     =      zipfile.ZipFile(A			,		"""r"""	)
            _SCREAMING_SNAKE_CASE     =      archive.open("""messages.json"""	).read().decode("""utf-8"""	)
        _SCREAMING_SNAKE_CASE     =      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  a_					(    snake_case_	):

    '''simple docstring'''
    UpperCamelCase			   =			[
        '''total_loss''',
        '''iteration''',
        '''my_text''',
        '''learning_rate''',
        '''num_iterations''',
        '''some_boolean''',
        '''some_string''',
    ]

    UpperCamelCase			   =			'''my_custom_tracker'''
    UpperCamelCase			   =			False


    def __init__(		self			,		A	)		->       Dict:
        _SCREAMING_SNAKE_CASE     =      open(f'{dir}/log.csv'			,		"""w+"""	)
        _SCREAMING_SNAKE_CASE     =      csv.DictWriter(self.f			,		fieldnames=self._col_names	)
        self.writer.writeheader()


    @property
    def       snake_case_(		self	)		->       Dict:
        return self.writer


    def       snake_case_(		self			,		A	)		->       str:
        logger.info("""Call init"""	)
        self.writer.writerow(A	)


    def       snake_case_(		self			,		A			,		A	)		->       List[str]:
        logger.info("""Call log"""	)
        self.writer.writerow(A	)





    def       snake_case_(		self	)		->       str:
        self.f.close()




class  a_					(    unittest.TestCase	):

    '''simple docstring'''


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










'''simple docstring'''

import os
import sys
import time

from . import transposition_cipher as trans_cipher





def lowerCamelCase						(					)						->None:
    _SCREAMING_SNAKE_CASE     =      """Prehistoric Men.txt"""
    _SCREAMING_SNAKE_CASE     =      """Output.txt"""
    _SCREAMING_SNAKE_CASE     =      int(input("""Enter key: """   )   )
    _SCREAMING_SNAKE_CASE     =      input("""Encrypt/Decrypt [e/d]: """   )

    if not os.path.exists(__lowerCamelCase   ):
        print(F'File {input_file} does not exist. Quitting...'   )
        sys.exit()
    if os.path.exists(__lowerCamelCase   ):
        print(F'Overwrite {output_file}? [y/n]'   )
        _SCREAMING_SNAKE_CASE     =      input("""> """   )
        if not response.lower().startswith("""y"""   ):
            sys.exit()

    _SCREAMING_SNAKE_CASE     =      time.time()
    if mode.lower().startswith("""e"""   ):
        with open(__lowerCamelCase   ) as f:
            _SCREAMING_SNAKE_CASE     =      f.read()
        _SCREAMING_SNAKE_CASE     =      trans_cipher.encrypt_message(__lowerCamelCase ,	__lowerCamelCase   )
    elif mode.lower().startswith("""d"""   ):
        with open(__lowerCamelCase   ) as f:
            _SCREAMING_SNAKE_CASE     =      f.read()
        _SCREAMING_SNAKE_CASE     =      trans_cipher.decrypt_message(__lowerCamelCase ,	__lowerCamelCase   )

    with open(__lowerCamelCase ,	"""w"""   ) as output_obj:
        output_obj.write(__lowerCamelCase   )

    _SCREAMING_SNAKE_CASE     =      round(time.time() - start_time ,	2   )
    print(("""Done (""", total_time, """seconds )""")   )


if __name__ == "__main__":
      main()



