


'''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	:   Optional[int]   		=					logging.getLogger(__name__)





@require_tensorboard
class _snake_case (			unittest.TestCase ):
							"""simple docstring"""





							def 		__SCREAMING_SNAKE_CASE( self						)  ->Optional[int]:



											"""simple docstring"""







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







							def 		__SCREAMING_SNAKE_CASE( self						)  ->str:



											"""simple docstring"""







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







							def 		__SCREAMING_SNAKE_CASE( self						)  ->List[Any]:



											"""simple docstring"""







											__lowerCamelCase		:   Any           =       "test_project_with_log"
											with tempfile.TemporaryDirectory() as dirpath:
															__lowerCamelCase		:   Tuple           =       Accelerator(log_with="tensorboard"      ,					project_dir=__A						)
															accelerator.init_trackers(__A						)
															__lowerCamelCase		:   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
															__lowerCamelCase		:   List[Any]           =       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:
																			__lowerCamelCase		:   List[Any]           =       f.read()
															__lowerCamelCase		:   Optional[int]           =       False
															while data:
																			__lowerCamelCase		:   List[Any]           =       struct.unpack("Q"      ,					data[:8]						)

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







							def 		__SCREAMING_SNAKE_CASE( self						)  ->Optional[int]:



											"""simple docstring"""







											with self.assertRaisesRegex(__A      ,					"Logging with `tensorboard` requires a `logging_dir`"						):
															__lowerCamelCase		:   Dict           =       Accelerator(log_with="tensorboard"						)
											with tempfile.TemporaryDirectory() as dirpath:
															__lowerCamelCase		:   List[Any]           =       Accelerator(log_with="tensorboard"      ,					project_dir=__A						)







							def 		__SCREAMING_SNAKE_CASE( self						)  ->Optional[int]:



											"""simple docstring"""







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





@require_wandb
@mock.patch.dict(os.environ     , {'''WANDB_MODE''': '''offline'''} )
class _snake_case (			a__     , a__ ):
							"""simple docstring"""





							def 		__SCREAMING_SNAKE_CASE( self						)  ->List[Any]:



											"""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 		__SCREAMING_SNAKE_CASE( __A      ,					__A      ,					__A = True						)  ->Dict:



											"""simple docstring"""







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



											"""simple docstring"""







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

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

											# Actual logging
											__lowerCamelCase		:   List[str]           =       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				,    lowercase				,    lowercase     )      ->Optional[Any]:






				'''simple docstring'''

				__lowerCamelCase		:   Optional[Any]           =       run_name
				__lowerCamelCase		:   Tuple           =       OfflineExperiment(project_name=lowercase				,    offline_directory=lowercase     )
				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 _snake_case (			unittest.TestCase ):
							"""simple docstring"""





							@staticmethod
							def 		__SCREAMING_SNAKE_CASE( __A      ,					__A      ,					__A = False						)  ->Any:



											"""simple docstring"""







											for log in log_list:
															__lowerCamelCase		:   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 		__SCREAMING_SNAKE_CASE( self						)  ->List[str]:



											"""simple docstring"""







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



											"""simple docstring"""







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





							__a				       =  [
							    '''total_loss''',
							    '''iteration''',
							    '''my_text''',
							    '''learning_rate''',
							    '''num_iterations''',
							    '''some_boolean''',
							    '''some_string''',
							]

							__a				       =  '''my_custom_tracker'''
							__a				       =  False







							def __init__( self      ,					__A						)  ->Dict:



											"""simple docstring"""







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







							@property
							def 		__SCREAMING_SNAKE_CASE( self						)  ->Optional[Any]:



											"""simple docstring"""







											return self.writer







							def 		__SCREAMING_SNAKE_CASE( self      ,					__A						)  ->List[Any]:



											"""simple docstring"""







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







							def 		__SCREAMING_SNAKE_CASE( self      ,					__A      ,					__A						)  ->Union[str, Any]:



											"""simple docstring"""







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







							def 		__SCREAMING_SNAKE_CASE( self						)  ->str:



											"""simple docstring"""







											self.f.close()





class _snake_case (			unittest.TestCase ):
							"""simple docstring"""





							def 		__SCREAMING_SNAKE_CASE( self						)  ->str:



											"""simple docstring"""







											with tempfile.TemporaryDirectory() as d:
															__lowerCamelCase		:   str           =       MyCustomTracker(__A						)
															__lowerCamelCase		:   int           =       Accelerator(log_with=__A						)
															__lowerCamelCase		:   Union[str, 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:
																			__lowerCamelCase		:   Any           =       csv.DictReader(__A						)
																			__lowerCamelCase		:   str           =       next(__A						)
																			__lowerCamelCase		:   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 		__SCREAMING_SNAKE_CASE( self						)  ->Dict:



											"""simple docstring"""







											with tempfile.TemporaryDirectory() as d:
															__lowerCamelCase		:   Optional[int]           =       MyCustomTracker(__A						)
															__lowerCamelCase		:   Union[str, Any]           =       Accelerator(log_with=__A						)
															accelerator.init_trackers("Some name"						)
															__lowerCamelCase		:   Optional[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:
																			__lowerCamelCase		:   List[Any]           =       csv.DictReader(__A						)
																			__lowerCamelCase		:   Optional[int]           =       next(__A						)
																			__lowerCamelCase		:   str           =       {
																			    "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 requests

try:
				from django.contrib.auth import authenticate, login
				from django.shortcuts import redirect, render
except ImportError:
				__lowercase	:   Dict   		=					print





def 				a_							(    lowercase     )      ->Any:






				'''simple docstring'''

				__lowerCamelCase		:   str           =       "secretKey"
				__lowerCamelCase		:   Optional[Any]           =       "https://www.google.com/recaptcha/api/siteverify"

				# when method is not POST, direct user to login page
				if request.method != "POST":
								return render(lowercase				,    "login.html"     )

				# from the frontend, get username, password, and client_key
				__lowerCamelCase		:   str           =       request.POST.get("username"     )
				__lowerCamelCase		:   Dict           =       request.POST.get("password"     )
				__lowerCamelCase		:   List[str]           =       request.POST.get("g-recaptcha-response"     )

				# post recaptcha response to Google's recaptcha api
				__lowerCamelCase		:   str           =       requests.post(lowercase				,    data={"secret": secret_key, "response": client_key}     )
				# if the recaptcha api verified our keys
				if response.json().get("success"				,    lowercase     ):
								# authenticate the user
								__lowerCamelCase		:   List[Any]           =       authenticate(lowercase				,    username=lowercase				,    password=lowercase     )
								if user_in_database:
												login(lowercase				,    lowercase     )
												return redirect("/your-webpage"     )
				return render(lowercase				,    "login.html"     )





