"""
Module used to convert, package, deconvert, and unpack language models using the encoding and decoding standards of Sapiens Technology®️.
The models are converted into secure formats with or without encryption, thus allowing them to be deployed internally as protected submodels.
Any copying, editing, or sharing of this code is strictly prohibited. Public posts or comments about this technology or how it works are also not authorized by Sapiens Technology®️.
Violation of these rules will result in legal action taken by our team of lawyers.
"""
# --------------------------> A SAPIENS TECHNOLOGY®️ PRODUCTION) <--------------------------
class Submodels:
	def __init__(self, show_errors=True, display_error_point=False):
		try:
			self.__show_errors = bool(show_errors) if type(show_errors) in (bool, int, float) else True
			self.__display_error_point = bool(display_error_point) if type(display_error_point) in (bool, int, float) else False
			try:
				from warnings import filterwarnings
				from logging import getLogger, ERROR, disable, CRITICAL
				from os import environ
				from dotenv import load_dotenv
				filterwarnings('ignore')
				filterwarnings('ignore', category=UserWarning, module='torch.distributed')
				getLogger('torch.distributed.elastic.multiprocessing.redirects').setLevel(ERROR)
				environ['DISABLE_MODEL_SOURCE_CHECK'] = 'True'
				load_dotenv()
				disable(CRITICAL)
			except: pass
			from traceback import print_exc
			self.__print_exc = print_exc
			self.__is_submodel = False
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in Submodels.__init__: '+str(error)
					print(error_message)
					try: self.__print_exc() if self.__display_error_point or self.show_error_details else None
					except: pass
			except: pass
	def __get_system_temp_directory(self):
		try:
			from tempfile import gettempdir
			return gettempdir()
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in Submodels.__get_system_temp_directory: '+str(error)
					print(error_message)
					try: self.__print_exc() if self.__display_error_point or self.show_error_details else None
					except: pass
			except: pass
			return './'
	def __get_file_name_base64(self, file_path=''):
		try:
			from base64 import b64encode
			from os.path import basename
			file_name = basename(file_path)
			file_name_bytes = file_name.encode('utf-8')
			file_name_base64_bytes = b64encode(file_name_bytes)
			file_name_base64 = file_name_base64_bytes.decode('utf-8')
			return file_name_base64
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in Submodels.__get_file_name_base64: '+str(error)
					print(error_message)
					try: self.__print_exc() if self.__display_error_point or self.show_error_details else None
					except: pass
			except: pass
			return 'temp'
	def convert(self, model_path='', progress=True):
		try:
			conversion_result = False
			model_path = str(model_path).strip()
			progress = bool(progress) if type(progress) in (bool, int, float) else True
			self.__is_submodel = True
			conversion_result = self.pack(model_path=model_path, progress=progress, encrypt=True)
			self.__is_submodel = False
			return conversion_result
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in Submodels.convert: '+str(error)
					print(error_message)
					try: self.__print_exc() if self.__display_error_point or self.show_error_details else None
					except: pass
				self.__is_submodel = False
			except: pass
			return False
	def unconvert(self, model_path='', progress=True):
		try:
			unconversion_result = False
			model_path = str(model_path).strip()
			progress = bool(progress) if type(progress) in (bool, int, float) else True
			unconversion_result = self.unpack(model_path=model_path, progress=progress)
			return unconversion_result
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in Submodels.unconvert: '+str(error)
					print(error_message)
					try: self.__print_exc() if self.__display_error_point or self.show_error_details else None
					except: pass
			except: pass
			return False
	def pack(self, model_path='', progress=True, encrypt=False):
		try:
			pack_result = False
			model_path = str(model_path).strip()
			progress = bool(progress) if type(progress) in (bool, int, float) else True
			encrypt = bool(encrypt) if type(encrypt) in (bool, int, float) else False
			from os import path
			from utilities_nlp import UtilitiesNLP as SapiensUtilities
			sapiens_utilities = SapiensUtilities(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
			def _get_name_from_path(path_string=''):
				normalized_path = path.normpath(path_string)
				base_name = path.basename(normalized_path)
				if path.isfile(normalized_path): return path.splitext(base_name)[0]
				return base_name
			def _get_parent_directory(path_string=''):
				absolute_path = path.abspath(path_string)
				if path.isfile(absolute_path): return path.dirname(absolute_path)
				if path.isdir(absolute_path): return path.dirname(absolute_path)
				return path.dirname(absolute_path)
			directory_path = _get_parent_directory(path_string=model_path)
			if self.__is_submodel: extension = '.submodel' if encrypt else '.sapiens'
			else: extension = '.SAPI' if encrypt else '.sapiens'
			file_path = _get_name_from_path(path_string=model_path)+extension
			file_path = path.join(directory_path, file_path)
			pack_result = sapiens_utilities.compactModel(model_path=model_path, file_path=file_path, progress=progress)
			if pack_result and encrypt:
				from scn import SCN as SapiensSCN
				pack_result = SapiensSCN(show_errors=self.__show_errors).fileToEncryptedHEX(file_path=file_path, progress=progress)
			return pack_result
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in Submodels.pack: '+str(error)
					print(error_message)
					try: self.__print_exc() if self.__display_error_point or self.show_error_details else None
					except: pass
			except: pass
			return False
	def unpack(self, model_path='', progress=True):
		try:
			result_path = ''
			model_path = str(model_path).strip()
			progress = bool(progress) if type(progress) in (bool, int, float) else True
			from os import path
			from pathlib import Path
			from utilities_nlp import UtilitiesNLP as SapiensUtilities
			sapiens_utilities = SapiensUtilities(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
			temporary_directory = self.__get_system_temp_directory()
			file_path = self.__get_file_name_base64(file_path=model_path)
			file_path = path.join(temporary_directory, file_path)
			if Path(file_path).exists(): return file_path
			if model_path.endswith(('.SAPI', '.submodel')):
				from scn import SCN as SapiensSCN
				unpack_result = SapiensSCN(show_errors=self.__show_errors).encryptedHEXToFile(file_path=model_path, progress=progress)
				if not unpack_result: return result_path
			if sapiens_utilities.decompactModel(file_path=model_path, model_path=file_path, progress=progress) and Path(file_path).exists(): result_path = file_path
			return result_path
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in Submodels.unpack: '+str(error)
					print(error_message)
					try: self.__print_exc() if self.__display_error_point or self.show_error_details else None
					except: pass
			except: pass
			return ''
	def deleteModel(self, model_path=''):
		try:
			deletion_result = False
			model_path = str(model_path).strip()
			from os import path
			from pathlib import Path
			temporary_directory = self.__get_system_temp_directory()
			file_path = self.__get_file_name_base64(file_path=model_path)
			file_path = path.join(temporary_directory, file_path)
			def _delete_path(target_path=''):
				from os import path
				from os import remove
				from shutil import rmtree
				if path.isdir(target_path): rmtree(target_path)
				elif path.isfile(target_path): remove(target_path)
				return not Path(target_path).exists()
			if Path(file_path).exists() and _delete_path(target_path=file_path): deletion_result = _delete_path(target_path=model_path)
			elif Path(model_path).exists(): deletion_result = _delete_path(target_path=model_path)
			return deletion_result
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in Submodels.deleteModel: '+str(error)
					print(error_message)
					try: self.__print_exc() if self.__display_error_point or self.show_error_details else None
					except: pass
			except: pass
			return False
"""
Module used to convert, package, deconvert, and unpack language models using the encoding and decoding standards of Sapiens Technology®️.
The models are converted into secure formats with or without encryption, thus allowing them to be deployed internally as protected submodels.
Any copying, editing, or sharing of this code is strictly prohibited. Public posts or comments about this technology or how it works are also not authorized by Sapiens Technology®️.
Violation of these rules will result in legal action taken by our team of lawyers.
"""
# --------------------------> A SAPIENS TECHNOLOGY®️ PRODUCTION) <--------------------------
