




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__		    =    logging.getLogger(__name__)


@require_tensorboard
class       SCREAMING_SNAKE_CASE_							(					unittest.TestCase      ):



	"""simple docstring"""


	def 				lowerCamelCase__    (				self		:	List[Any]  )  ->					Optional[int]:







						"""simple docstring"""







						__UpperCamelCase				:  Optional[Any]								=			"""test_project_with_config"""
						with tempfile.TemporaryDirectory() as dirpath:
											__UpperCamelCase				:  List[Any]								=			Accelerator(log_with="""tensorboard"""				,    project_dir=lowerCAmelCase  )
											__UpperCamelCase				:  Union[str, Any]								=			{"""num_iterations""": 12, """learning_rate""": 1E-2, """some_boolean""": False, """some_string""": """some_value"""}
											accelerator.init_trackers(lowerCAmelCase				,    lowerCAmelCase  )
											accelerator.end_training()
											for child in Path(F'''{dirpath}/{project_name}'''  ).glob("""*/**"""  ):
																__UpperCamelCase				:  Any								=			list(filter(lambda lowerCAmelCase  : x.is_file()				,    child.iterdir()  )  )[0]
											self.assertNotEqual(str(lowerCAmelCase  )				,    """"""  )






	def 				lowerCamelCase__    (				self		:	Any  )  ->					Optional[int]:







						"""simple docstring"""







						__UpperCamelCase				:  str								=			"""test_project_with_log"""
						with tempfile.TemporaryDirectory() as dirpath:
											__UpperCamelCase				:  Optional[Any]								=			Accelerator(log_with="""tensorboard"""				,    project_dir=lowerCAmelCase  )
											accelerator.init_trackers(lowerCAmelCase  )
											__UpperCamelCase				:  List[str]								=			{"""total_loss""": 0.1, """iteration""": 1, """my_text""": """some_value"""}
											accelerator.log(lowerCAmelCase				,    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				:  Union[str, Any]								=			list(filter(lambda lowerCAmelCase  : x.is_file()				,    Path(F'''{dirpath}/{project_name}'''  ).iterdir()  )  )[0]
											self.assertNotEqual(str(lowerCAmelCase  )				,    """"""  )






	def 				lowerCamelCase__    (				self		:	int  )  ->					Any:







						"""simple docstring"""







						__UpperCamelCase				:  Dict								=			"""test_project_with_log"""
						with tempfile.TemporaryDirectory() as dirpath:
											__UpperCamelCase				:  str								=			Accelerator(log_with="""tensorboard"""				,    project_dir=lowerCAmelCase  )
											accelerator.init_trackers(lowerCAmelCase  )
											__UpperCamelCase				:  List[Any]								=			{"""tensor""": torch.tensor(1  )}
											accelerator.log(lowerCAmelCase				,    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				:  List[Any]								=			list(filter(lambda lowerCAmelCase  : 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(lowerCAmelCase				,    """rb"""  ) as f:
																__UpperCamelCase				:  List[str]								=			f.read()
											__UpperCamelCase				:  List[str]								=			False
											while data:
																__UpperCamelCase				:  List[str]								=			struct.unpack("""Q"""				,    data[:8]  )

																__UpperCamelCase				:  str								=			data[12 : 12 + int(header[0]  )]  # 8+4
																__UpperCamelCase				:  Dict								=			data[12 + int(header[0]  ) + 4 :]
																__UpperCamelCase				:  Tuple								=			event_pba.Event()

																event.ParseFromString(lowerCAmelCase  )
																if event.HasField("""summary"""  ):
																					for value in event.summary.value:
																										if value.simple_value == 1.0 and value.tag == "tensor":
																															__UpperCamelCase				:  List[Any]								=			True
											self.assertTrue(lowerCAmelCase				,    """Converted tensor was not found in the log file!"""  )






	def 				lowerCamelCase__    (				self		:	str  )  ->					Tuple:







						"""simple docstring"""







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






	def 				lowerCamelCase__    (				self		:	Tuple  )  ->					str:







						"""simple docstring"""







						__UpperCamelCase				:  Optional[int]								=			ProjectConfiguration(total_limit=30  )
						with tempfile.TemporaryDirectory() as dirpath:
											__UpperCamelCase				:  Tuple								=			Accelerator(log_with="""tensorboard"""				,    project_dir=lowerCAmelCase				,    project_config=lowerCAmelCase  )






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



	"""simple docstring"""


	def 				lowerCamelCase__    (				self		:	Optional[int]  )  ->					Dict:







						"""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__    (				lowerCAmelCase		:	str				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	bool = True  )  ->					Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  Union[str, Any]								=			RF'''{section} ([\S\s]*?)\n\n'''
						if record:
											__UpperCamelCase				:  Optional[Any]								=			RF'''Record: {pattern}'''
						__UpperCamelCase				:  List[Any]								=			re.findall(lowerCAmelCase				,    lowerCAmelCase  )[0]
						# A config
						if section == "config" or section == "history":
											__UpperCamelCase				:  Dict								=			re.findall(R"""\"([a-zA-Z0-9_.,]+)"""				,    lowerCAmelCase  )
											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]+)\""""				,    lowerCAmelCase  )  )






	@skip
	def 				lowerCamelCase__    (				self		:	Any  )  ->					List[str]:







						"""simple docstring"""







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

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

						# Actual logging
						__UpperCamelCase				:  Any								=			self.parse_log(lowerCAmelCase				,    """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      :		Optional[int]		,  snake_case      :		str		,  snake_case      :		str							)    ->	Optional[Any]:
					__UpperCamelCase				:  Dict								=			run_name
					__UpperCamelCase				:  Optional[int]								=			OfflineExperiment(project_name=snake_case		,  offline_directory=snake_case							)
					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(_UpperCamelCase  ,     '__init__'  ,     _UpperCamelCase      )
class       SCREAMING_SNAKE_CASE_							(					unittest.TestCase      ):



	"""simple docstring"""


	@staticmethod
	def 				lowerCamelCase__    (				lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	bool = False  )  ->					Optional[int]:







						"""simple docstring"""







						for log in log_list:
											__UpperCamelCase				:  Dict								=			json.loads(lowerCAmelCase  )["""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		:	int  )  ->					int:







						"""simple docstring"""







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






	def 				lowerCamelCase__    (				self		:	str  )  ->					List[Any]:







						"""simple docstring"""







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






class       SCREAMING_SNAKE_CASE_							(					_UpperCamelCase      ):



	"""simple docstring"""


	__magic_name__      :					Optional[int]			  =		[
	    'total_loss',
	    'iteration',
	    'my_text',
	    'learning_rate',
	    'num_iterations',
	    'some_boolean',
	    'some_string',
	]

	__magic_name__      :					int			  =		'my_custom_tracker'
	__magic_name__      :					Tuple			  =		False






	def __init__(				self		:	Union[str, Any]				,    lowerCAmelCase		:	str  )  ->					str:







						"""simple docstring"""







						__UpperCamelCase				:  Optional[Any]								=			open(F'''{dir}/log.csv'''				,    """w+"""  )
						__UpperCamelCase				:  Optional[int]								=			csv.DictWriter(self.f				,    fieldnames=self._col_names  )
						self.writer.writeheader()






	@property
	def 				lowerCamelCase__    (				self		:	List[Any]  )  ->					Any:







						"""simple docstring"""







						return self.writer






	def 				lowerCamelCase__    (				self		:	int				,    lowerCAmelCase		:	dict  )  ->					Optional[Any]:







						"""simple docstring"""







						logger.info("""Call init"""  )
						self.writer.writerow(lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Tuple				,    lowerCAmelCase		:	dict				,    lowerCAmelCase		:	Optional[int]  )  ->					Any:







						"""simple docstring"""







						logger.info("""Call log"""  )
						self.writer.writerow(lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Optional[Any]  )  ->					List[Any]:







						"""simple docstring"""







						self.f.close()






class       SCREAMING_SNAKE_CASE_							(					unittest.TestCase      ):



	"""simple docstring"""


	def 				lowerCamelCase__    (				self		:	int  )  ->					str:







						"""simple docstring"""







						with tempfile.TemporaryDirectory() as d:
											__UpperCamelCase				:  Optional[int]								=			MyCustomTracker(lowerCAmelCase  )
											__UpperCamelCase				:  int								=			Accelerator(log_with=lowerCAmelCase  )
											__UpperCamelCase				:  Optional[Any]								=			{"""num_iterations""": 12, """learning_rate""": 1E-2, """some_boolean""": False, """some_string""": """some_value"""}
											accelerator.init_trackers("""Some name"""				,    lowerCAmelCase  )
											accelerator.end_training()
											with open(F'''{d}/log.csv'''				,    """r"""  ) as f:
																__UpperCamelCase				:  int								=			csv.DictReader(lowerCAmelCase  )
																__UpperCamelCase				:  Dict								=			next(lowerCAmelCase  )
																__UpperCamelCase				:  str								=			{
																    """total_loss""": """""",
																    """iteration""": """""",
																    """my_text""": """""",
																    """learning_rate""": """0.01""",
																    """num_iterations""": """12""",
																    """some_boolean""": """False""",
																    """some_string""": """some_value""",
																}
																self.assertDictEqual(lowerCAmelCase				,    lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	List[str]  )  ->					List[str]:







						"""simple docstring"""







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












import os





def 							A__   ()    ->	int:
					__UpperCamelCase				:  int								=			os.path.dirname(os.path.realpath(snake_case							)							)
					__UpperCamelCase				:  List[str]								=			os.path.join(snake_case		,  """triangle.txt"""							)

					with open(snake_case							) as in_file:
										__UpperCamelCase				:  Optional[Any]								=			[[int(snake_case							) for i in line.split()] for line in in_file]

					while len(snake_case							) != 1:
										__UpperCamelCase				:  Union[str, Any]								=			triangle.pop()
										__UpperCamelCase				:  List[str]								=			triangle[-1]
										for j in range(len(snake_case							) - 1							):
															curr_row[j] += max(last_row[j]		,  last_row[j + 1]							)
					return triangle[0][0]


if __name__ == "__main__":
	print(solution())






