"""
The "Schizophrenic Artificial Intelligence" is a module used to invoke the Frankenstein and its submodels,
as well as other models of various distinct architectures, through the categorization of the loaded models and the user's inputs.
In this way, it selects the most appropriate and compatible model for each type of situation and returns the corresponding outputs,
derived from the inference of the current input converted into the output of the computed tokens.
"""
# --------------------------> A SAPIENS TECHNOLOGY®️ PRODUCTION) <--------------------------
class SchizophrenicArtificialIntelligence:
	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
			from sapiens_loader import DataLoader, SapiensLoader
			self.__DataLoader = DataLoader
			self.__SapiensLoader = SapiensLoader
			self.__data_loader = None
			self.__sapiens_architecture = None
			self.device = None
			self.end_tag = '<|end|>'
			self.max_tokens = None
			self.temperature = 0.5
			self.top_k = 0
			self.top_p = 1.0
			self.delay = 0.0
			self.messages = []
			self.task_names = []
			self.language = ''
			self.creativity = 0.5
			self.humor = 0.5
			self.formality = 0.5
			self.political_spectrum = 0.5
			self.reasoning = 0.0
			self.reflection = False
			self.tools = []
			self.training_id = 0
			self.username = ''
			self.range_size = 3
			self.precision = 0.8
			self.tokens_tolerance = 0.5
			self.length_tolerance = 0.5
			self.__semantic_comparison = False
			self.__is_frankenstein = False
			self.system = ''
			self.__original_path = ''
			self.__extraction_path = ''
			self.__model_path = ''
			self.__OUTPUT = {'answer': '', 'answer_for_files': '', 'files': [], 'sources': [], 'javascript_charts': [], 'artifacts': [], 'next_token': '', 'str_cost': '0.0000000000', 'tool_call': []}
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.__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 __is_apple_mps_processor(self):
		try:
			from torch import backends
			if hasattr(backends, 'mps') and backends.mps.is_available(): return True
			return False
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.__is_apple_mps_processor: '+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 __find_file_in_directory(self, directory_path='', file_name=''):
		try:
			directory_path, file_name = str(directory_path).strip(), str(file_name).strip()
			def _normalize_directory_path(directory_path=''):
				from os.path import isfile
				from os.path import dirname
				if isfile(directory_path): return dirname(directory_path)
				return directory_path
			directory_path = _normalize_directory_path(directory_path=directory_path)
			from os import walk
			from os.path import basename
			for current_directory, directory_names, file_names in walk(directory_path):
				for current_file in file_names:
					if basename(current_file).endswith(file_name): return True
			return False
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.__find_file_in_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 False
	def __find_file_by_name(self, directory_path='', text=''):
		try:
			directory_path, text = str(directory_path).strip(), str(text).strip()
			from os import walk
			from os.path import join
			for root_directory, directory_names, file_names in walk(directory_path):
				for file_name in file_names:
					if text in file_name: return join(root_directory, file_name)
			return './'
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.__find_file_by_name: '+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 __read_json_file(self, file_path=''):
		try:
			file_path = str(file_path).strip()
			if not file_path.lower().endswith('.json'): return {}
			from json import load
			with open(file_path, 'r', encoding='utf-8') as file: return load(file)
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.__read_json_file: '+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 __complete_messages(self, messages=[], stream=False):
	    try:
	        complete_messages = self.__OUTPUT
	        messages = list(messages) if type(messages) in (tuple, list, dict) else []
	        stream = bool(stream) if type(stream) in (bool, int, float) else False
	        if messages:
	            prompt_template, assistant = '', 'assistant'
	            if len(messages) < 2: prompt_template = str(messages[-1].get('content', '?')).strip()
	            else:
	                end_tag, system_tags = self.end_tag if self.end_tag else '', ('system', 'model', 'instruction')
	                assistant = str(messages[-2].get('role', '')).strip() if len(messages) > 1 else 'assistant'
	                if assistant.lower() in system_tags: assistant = 'assistant'
	                for message in messages:
	                    role = str(message.get('role', '')).strip()
	                    content = str(message.get('content', '')).strip()
	                    if role and content and (role == assistant or role.lower() in system_tags): prompt_template += f'{role}:\n{content}{end_tag}\n'
	                    elif role and content: prompt_template += f'{role}:\n{content}\n'
	            prompt_template = prompt_template.strip()
	            prompt_template += f'\n{assistant}:\n'
	            def _get_stream(prompt_template='', complete_messages={}):
	                inference_function = self.inference(prompt=prompt_template, stream=True)
	                for token in inference_function:
	                    complete_messages['answer'] += token
	                    complete_messages['next_token'] = token
	                    yield complete_messages
	            def _get_string(prompt_template='', complete_messages={}):
	                inference_function = self.inference(prompt=prompt_template, stream=False)
	                complete_messages['answer'] = inference_function
	                token = inference_function.split(chr(32))[-1].rstrip()
	                complete_messages['next_token'] = token
	                return complete_messages
	            if stream: complete_messages = _get_stream(prompt_template=prompt_template, complete_messages=complete_messages)
	            else: complete_messages = _get_string(prompt_template=prompt_template, complete_messages=complete_messages)
	        return complete_messages
	    except Exception as error:
	        try:
	            if self.__show_errors:
	                error_message = 'ERROR in SchizophrenicArtificialIntelligence.__complete_messages: '+str(error)
	                print(error_message)
	                try: self.__print_exc() if self.__display_error_point else None
	                except: pass
	        except: pass
	        return self.__OUTPUT
	def loadModel(self, model_path='', progress=True):
		try:
			loaded_model = False
			self.__original_path = str(model_path).strip()
			submodel = self.__find_file_in_directory(directory_path=model_path, file_name='.submodel')
			SAPI = self.__find_file_in_directory(directory_path=model_path, file_name='.SAPI')
			sapiens = self.__find_file_in_directory(directory_path=model_path, file_name='.sapiens')
			if submodel: model_path = self.__find_file_by_name(directory_path=model_path, text='.submodel')
			elif SAPI: model_path = self.__find_file_by_name(directory_path=model_path, text='.SAPI')
			elif sapiens: model_path = self.__find_file_by_name(directory_path=model_path, text='.sapiens')
			self.__original_path = model_path
			data_loader = self.__DataLoader(self.__SapiensLoader(show_errors=False, display_error_point=False), show_errors=False, display_error_point=False)
			if type(model_path) == type(data_loader):
				self.__data_loader = model_path
				self.__data_loader.open()
				model_path = self.__data_loader.output
				self.__extraction_path = self.__data_loader.output
			model_path, file_path = str(model_path).strip(), ''
			progress = bool(progress) if type(progress) in (bool, int, float) else True
			if not self.__data_loader:
				self.__data_loader = self.__DataLoader(sapiens_loader=self.__SapiensLoader(model_path=model_path, show_errors=self.__show_errors, display_error_point=self.__display_error_point), show_errors=self.__show_errors, display_error_point=self.__display_error_point)
				self.__data_loader.open()
				model_path = self.__data_loader.output
				self.__extraction_path = self.__data_loader.output
			def _get_existing_directory(model_path=''):
				from os.path import exists, dirname, isfile
				if exists(model_path): return dirname(model_path) if isfile(model_path) else model_path
				return dirname(model_path)
			model_path, use_cpu = _get_existing_directory(model_path=model_path), False
			def _frankenstein_files(): return True if self.__find_file_in_directory(directory_path=model_path, file_name='frankenstein.json') else False
			def _transformer_files():
				transformer_files = ['tokenizer_config.json', 'generation_config.json', 'preprocessor_config.json', 'config.json', 'model_args.json', 'training_args.json', 'args.json', 'special_tokens_map.json']
				for transformer_file in transformer_files:
					if self.__find_file_in_directory(directory_path=model_path, file_name=transformer_file): return True
				return False
			if self.__find_file_in_directory(directory_path=model_path, file_name='sapiens.json'):
				file_path = self.__find_file_by_name(directory_path=model_path, text='sapiens.json')
				json_file_read = self.__read_json_file(file_path=file_path)
				sub_architecture = json_file_read['sub_architecture'] if 'sub_architecture' in json_file_read else ''
				if sub_architecture == 'hur': file_path, use_cpu = self.__find_file_by_name(directory_path=model_path, text='.hurlm'), True
				elif sub_architecture == 'cpu': file_path = self.__find_file_by_name(directory_path=model_path, text='.cpu')
				elif sub_architecture == 'scn':
					scn_architecture = self.__read_json_file(file_path=file_path)['scn_architecture']
					if scn_architecture == 'level_1': file_path = self.__find_file_by_name(directory_path=model_path, text='.scnnet')
					elif scn_architecture == 'level_2': file_path = self.__find_file_by_name(directory_path=model_path, text='.scnet')
					elif scn_architecture == 'level_3': file_path = self.__find_file_by_name(directory_path=model_path, text='.scn02')
				elif sub_architecture == 'mgt': file_path = self.__find_file_by_name(directory_path=model_path, text='.mini')
				from sapiens_model import SapiensArchitecture
				self.__sapiens_architecture = SapiensArchitecture(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
				if hasattr(self.__sapiens_architecture, 'device'): self.__sapiens_architecture.device = 'cpu' if use_cpu and self.__is_apple_mps_processor() else self.device
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.scnnet'): file_path = self.__find_file_by_name(directory_path=model_path, text='.scnnet')
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.scnet'): file_path = self.__find_file_by_name(directory_path=model_path, text='.scnet')
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.scn02'): file_path = self.__find_file_by_name(directory_path=model_path, text='.scn02')
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.mini'): file_path = self.__find_file_by_name(directory_path=model_path, text='.mini')
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.cpu'): file_path = self.__find_file_by_name(directory_path=model_path, text='.cpu')
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.hurlm'): file_path, use_cpu = self.__find_file_by_name(directory_path=model_path, text='.hurlm'), True
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.gpt'):
				file_path = self.__find_file_by_name(directory_path=model_path, text='.gpt')
				from torch import load
				try: checkpoint = load(file_path, map_location=self.device) if self.device else load(file_path)
				except: checkpoint = load(file_path)
				architecture_type = str(checkpoint.get('architecture_type', 'gpt_model')).lower().strip()
				if architecture_type == 'gpt_model':
					try:
						from sapiens_gpt import SapiensGPT as SapiensModel
						self.__sapiens_architecture = SapiensModel(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
					except:
						from gptmodel import GPTModel as SapiensModel
						self.__sapiens_architecture = SapiensModel()
				elif architecture_type == 'hur_model':
					from hurmodel import HurModel as SapiensModel
					self.__sapiens_architecture, use_cpu = SapiensModel(), True
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.bert'):
				file_path = self.__find_file_by_name(directory_path=model_path, text='.bert')
				from sapiens_bert import SapiensBERT as SapiensModel
				self.__sapiens_architecture = SapiensModel(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
			elif _frankenstein_files() and (self.__find_file_in_directory(directory_path=model_path, file_name='.ben') or self.__find_file_in_directory(directory_path=model_path, file_name='.hur') or _transformer_files()):
				from FRANKENSTEIN_MODEL import FRANKENSTEIN
				self.__sapiens_architecture = FRANKENSTEIN(show_errors=self.__show_errors, display_error_point=self.__display_error_point, progress=progress)
				if self.__sapiens_architecture: self.__is_frankenstein = True
			elif self.__find_file_in_directory(directory_path=model_path, file_name='.ben') or self.__find_file_in_directory(directory_path=model_path, file_name='.hur') or _transformer_files():
				from sapiens_transformers.inference import SapiensModel
				self.__sapiens_architecture, loaded_model = SapiensModel(model_path=model_path, show_errors=self.__show_errors), True
			else:
				from semantic_comparison import SemanticComparison as SapiensModel
				self.__sapiens_architecture, loaded_model, self.__semantic_comparison = SapiensModel(display_error_point=self.__display_error_point), True, True
			if not self.__sapiens_architecture:
				from sapiens_model import SapiensArchitecture
				self.__sapiens_architecture = SapiensArchitecture(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
				if hasattr(self.__sapiens_architecture, 'device'): self.__sapiens_architecture.device = 'cpu' if use_cpu and self.__is_apple_mps_processor() else self.device
			loaded_model = True if self.__sapiens_architecture else False
			if file_path: model_path = file_path
			self.__model_path = model_path
			if hasattr(self.__sapiens_architecture, 'loadModel') and callable(getattr(self.__sapiens_architecture, 'loadModel')): loaded_model = self.__sapiens_architecture.loadModel(model_path=model_path, progress=progress)
			elif hasattr(self.__sapiens_architecture, 'loadFrankenstein') and callable(getattr(self.__sapiens_architecture, 'loadFrankenstein')): loaded_model = self.__sapiens_architecture.loadFrankenstein(model_path=model_path)
			return loaded_model
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.loadModel: '+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 inference(self, prompt='', file_path='', stream=False):
		try:
			inference_dictionary = self.__OUTPUT
			prompt, file_path = str(prompt).strip(), str(file_path).strip()
			stream = bool(stream) if type(stream) in (bool, int, float) else False
			if not prompt: prompt = '?'
			inference_result = ''
			is_frankenstein = hasattr(self.__sapiens_architecture, 'loadFrankenstein') and callable(getattr(self.__sapiens_architecture, 'loadFrankenstein'))
			self.__is_frankenstein = self.__is_frankenstein and is_frankenstein
			if not self.__is_frankenstein and self.max_tokens is None: self.max_tokens = 500
			if hasattr(self.__sapiens_architecture, 'inference') and callable(getattr(self.__sapiens_architecture, 'inference')):
				if self.__is_frankenstein:
					def _entity_invokes_frankenstein(INPUT=''):
						from utilities_nlp import UtilitiesNLP as EntityUtilities
						entity_utilities = EntityUtilities(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
						requested_tasks = entity_utilities.getTasks(prompt=INPUT)
						return requested_tasks
					message = {'role': 'user', 'content': prompt, 'file_paths': [file_path]} if file_path else {'role': 'user', 'content': prompt}
					if type(self.messages) != list: self.messages = []
					if self.system:
						role, system_content = '', ''
						first_message = self.messages[0] if self.messages else {}
						if first_message and type(first_message) == dict:
							role = str(first_message.get('role', '')).lower().strip()
							if role == 'system': system_content = str(first_message.get('content', '')).strip()
						system_content = f'{self.system}\n\n{system_content}'.strip()
						if role == 'system' and len(system_content) > 0 and len(self.messages) > 0: self.messages[0]['content'] = system_content
						elif len(system_content) > 0: self.messages = [{'role': 'system', 'content': system_content}]+self.messages
					last_message = self.messages[-1] if self.messages else {}
					if last_message and type(last_message) == dict:
						role = str(last_message.get('role', '')).lower().strip()
						if role == 'user':
							content = str(last_message.get('content', '')).strip()
							prompt = f'{content}\n\n{prompt}'.strip()
							if not self.task_names: self.task_names = _entity_invokes_frankenstein(prompt=prompt)
							message = {'role': role, 'content': prompt}
							if file_path:
								file_paths = last_message.get('file_paths', [])
								if not file_paths:
									file_paths = str(last_message.get('file_path', '')).strip()
									if file_paths: file_paths = [file_paths]
								file_paths.append(file_path)
								message['file_paths'] = file_paths
						else: self.messages.append(message)
					else: self.messages.append(message)
					try:
						if not self.task_names: self.task_names = _entity_invokes_frankenstein(prompt=prompt)
						return self.__sapiens_architecture.inference(messages=self.messages, max_tokens=self.max_tokens, stream=stream, task_names=self.task_names, language=self.language, temperature=self.temperature, creativity=self.creativity, humor=self.humor, formality=self.formality, political_spectrum=self.political_spectrum, reasoning=self.reasoning, reflection=self.reflection, tools=self.tools)
					except: return self.__sapiens_architecture.inference(messages=self.messages, stream=stream)
				else:
					if file_path:
						try: inference_result = self.__sapiens_architecture.inference(prompt=prompt, file_path=file_path, stream=stream)
						except: inference_result = self.__sapiens_architecture.inference(prompt=prompt, stream=stream)
					else: inference_result = self.__sapiens_architecture.inference(prompt=prompt, stream=stream)
			elif hasattr(self.__sapiens_architecture, 'predict') and callable(getattr(self.__sapiens_architecture, 'predict')):
				if self.__semantic_comparison:
					try: answer = self.__sapiens_architecture.predict(training_id=self.training_id, prompt=prompt, username=self.username, range_size=self.range_size, precision=self.precision, tokens_tolerance=self.tokens_tolerance, length_tolerance=self.length_tolerance)
					except: answer = self.__sapiens_architecture.predict(prompt=prompt)
					if stream:
						def _get_tokens(answer=''):
							tokens = answer.split(chr(32))
							for token in tokens: yield token
							return ''
						inference_result = _get_tokens(answer=answer)
					else: inference_result = answer
				try: inference_result = self.__sapiens_architecture.predict(prompt=prompt, max_tokens=self.max_tokens, temperature=self.temperature, top_k=self.top_k, top_p=self.top_p, stream=stream)
				except: inference_result = self.__sapiens_architecture.predict(prompt=prompt, stream=stream)
			elif hasattr(self.__sapiens_architecture, 'generate_text') and callable(getattr(self.__sapiens_architecture, 'generate_text')):
				if file_path:
					from utilities_nlp import UtilitiesNLP as EntityUtilities
					entity_utilities = EntityUtilities(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
					file_category = entity_utilities.getFileCategory(file_path=file_path)
					def _multimodality(file_path=''):
						from INFINITE_CONTEXT_WINDOW import InfiniteContextWindow as SAPIENS_INFINITE_CONTEXT_WINDOW
						return SAPIENS_INFINITE_CONTEXT_WINDOW(show_errors=self.__show_errors, display_error_point=self.__display_error_point).interpreter(file_path=file_path)
					multimodality = _multimodality(file_path=file_path)
					if not multimodality and file_category == 'IMAGE_FILE': self.__sapiens_architecture.add_image(path=file_path)
					elif not multimodality and file_category == 'AUDIO_FILE': self.__sapiens_architecture.add_audio(path=file_path)
					elif not multimodality and file_category == 'VIDEO_FILE': self.__sapiens_architecture.add_video(path=file_path)
					else: prompt = rf'{multimodality}\n\n{prompt}'.strip()
					try: inference_result = self.__sapiens_architecture.generate_text(system=self.system, prompt=prompt, temperature=self.temperature, max_new_tokens=self.max_tokens, stream=stream)
					except: inference_result = self.__sapiens_architecture.generate_text(system=self.system, prompt=rf'{_multimodality(file_path=file_path)}\n\n{prompt}'.strip(), temperature=self.temperature, max_new_tokens=self.max_tokens, stream=stream)
				else: inference_result = self.__sapiens_architecture.generate_text(system=self.system, prompt=prompt, temperature=self.temperature, max_new_tokens=self.max_tokens, stream=stream)
			if stream:
				def _get_tokens(answer=''):
					for token in inference_result:
						inference_dictionary['next_token'] = token
						inference_dictionary['answer'] += token
						yield inference_dictionary
					return ''
				return _get_tokens(answer=inference_result)
			else:
				inference_dictionary['answer'] = str(inference_result).strip()
				return inference_dictionary
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.inference: '+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 self.__OUTPUT
	def completeMessages(self, messages=[], stream=False):
		try:
			complete_messages = self.__OUTPUT
			messages = list(messages) if type(messages) in (tuple, list, dict) else []
			stream = bool(stream) if type(stream) in (bool, int, float) else False
			if hasattr(self.__sapiens_architecture, 'completeMessages') and callable(getattr(self.__sapiens_architecture, 'completeMessages')):
				inference_function = self.__sapiens_architecture.completeMessages(messages=messages, stream=stream)
				if stream:
					def _get_stream(complete_messages={}, inference_function=''):
						for complete_message in inference_function:
							complete_messages['answer'] += complete_message['answer']
							complete_messages['next_token'] = complete_message['next_token']
							yield complete_messages
					complete_messages = _get_stream(complete_messages=complete_messages, inference_function=inference_function)
				else:
					complete_messages['answer'] = inference_function['answer']
					complete_messages['next_token'] = inference_function['next_token']
			elif hasattr(self.__sapiens_architecture, 'generate_text') and callable(getattr(self.__sapiens_architecture, 'generate_text')):
				last_message, file_path = messages[-1], ''
				file_path = last_message.get('file_path', '') if 'file_path' in last_message else ''
				if not file_path: file_path = last_message.get('file_paths', []) if 'file_paths' in last_message else []
				if type(file_path) == list and len(file_path) > 0: file_path = file_path[0]
				file_path = str(file_path).strip()
				if file_path:
					from utilities_nlp import UtilitiesNLP as EntityUtilities
					entity_utilities = EntityUtilities(show_errors=self.__show_errors, display_error_point=self.__display_error_point)
					file_category = entity_utilities.getFileCategory(file_path=file_path)
					def _multimodality(file_path=''):
						from INFINITE_CONTEXT_WINDOW import InfiniteContextWindow as SAPIENS_INFINITE_CONTEXT_WINDOW
						return SAPIENS_INFINITE_CONTEXT_WINDOW(show_errors=self.__show_errors, display_error_point=self.__display_error_point).interpreter(file_path=file_path)
					multimodality = _multimodality(file_path=file_path)
					if not multimodality and file_category == 'IMAGE_FILE': self.__sapiens_architecture.add_image(path=file_path)
					elif not multimodality and file_category == 'AUDIO_FILE': self.__sapiens_architecture.add_audio(path=file_path)
					elif not multimodality and file_category == 'VIDEO_FILE': self.__sapiens_architecture.add_video(path=file_path)
					else:
						prompt = str(last_message.get('content', '?')).strip()
						messages[-1]['content'] = rf'{multimodality}\n\n{prompt}'
					try: tokens_generator = self.__sapiens_architecture.generate_text(system=self.system, messages=messages, temperature=self.temperature, max_new_tokens=self.max_tokens, stream=stream)
					except: tokens_generator = self.__sapiens_architecture.generate_text(messages=messages, stream=stream)
				else: tokens_generator = self.__sapiens_architecture.generate_text(system=self.system, messages=messages, temperature=self.temperature, max_new_tokens=self.max_tokens, stream=stream)
				if stream:
					def _get_stream(complete_messages={}, inference_function=''):
						for token in inference_function:
							complete_messages['answer'] += token
							complete_messages['next_token'] = token
							yield complete_messages
					complete_messages = _get_stream(complete_messages=complete_messages, inference_function=tokens_generator)
				else:
					def _get_string(complete_messages={}, inference_function=''):
						complete_messages['answer'] = inference_function
						return complete_messages
					complete_messages = _get_string(complete_messages=complete_messages, inference_function=tokens_generator)
			elif hasattr(self.__sapiens_architecture, 'loadFrankenstein') and callable(getattr(self.__sapiens_architecture, 'loadFrankenstein')):
				try:
					if self.system:
						role, system_content = '', ''
						first_message = messages[0] if messages else {}
						if first_message and type(first_message) == dict:
							role = str(first_message.get('role', '')).lower().strip()
							if role == 'system': system_content = str(first_message.get('content', '')).strip()
						system_content = f'{self.system}\n\n{system_content}'.strip()
						if role == 'system' and len(system_content) > 0 and len(messages) > 0: messages[0]['content'] = system_content
						elif len(system_content) > 0: messages = [{'role': 'system', 'content': system_content}]+messages
					if len(self.messages) > len(messages): messages = self.messages
					complete_messages = self.__sapiens_architecture.inference(messages=messages, max_tokens=self.max_tokens, stream=stream, task_names=self.task_names, language=self.language, temperature=self.temperature, creativity=self.creativity, humor=self.humor, formality=self.formality, political_spectrum=self.political_spectrum, reasoning=self.reasoning, reflection=self.reflection, tools=self.tools)
				except: complete_messages = self.__sapiens_architecture.inference(messages=messages, stream=stream)
			else: complete_messages = self.__complete_messages(messages=messages, stream=stream)
			return complete_messages
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.completeMessages: '+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 self.__OUTPUT
	def printInference(self, prompt='', file_path='', stream=True):
		try:
			prompt, file_path = str(prompt).strip(), str(file_path).strip()
			stream = bool(stream) if type(stream) in (bool, int, float) else False
			if not prompt: prompt = '?'
			if hasattr(self.__sapiens_architecture, 'printInference') and callable(getattr(self.__sapiens_architecture, 'printInference')):
				if file_path:
					try: self.__sapiens_architecture.printInference(prompt=prompt, file_path=file_path, stream=stream)
					except: self.__sapiens_architecture.printInference(prompt=prompt, stream=stream)
				else: self.__sapiens_architecture.printInference(prompt=prompt, stream=stream)
			elif hasattr(self.__sapiens_architecture, 'print_predict') and callable(getattr(self.__sapiens_architecture, 'print_predict')):
				try: self.__sapiens_architecture.print_predict(prompt=prompt, max_tokens=self.max_tokens, temperature=self.temperature, top_k=self.top_k, top_p=self.top_p, stream=stream)
				except: self.__sapiens_architecture.print_predict(prompt=prompt, stream=stream)
			else:
				generated_tokens = self.inference(prompt=prompt, file_path=file_path, stream=stream)
				if stream:
					first_token = True
					from time import sleep
					for dictionary in generated_tokens:
						token = dictionary.get('next_token', '')
						if not token: continue
						if first_token:
							print(token.lstrip(), end='', flush=True)
							first_token = False
						else: print(token, end='', flush=True)
						sleep(self.delay)
					print()
				else: print(generated_tokens['answer'])
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.printInference: '+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 printCompleteMessages(self, messages=[], stream=True):
		try:
			messages = list(messages) if type(messages) in (tuple, list, dict) else []
			stream = bool(stream) if type(stream) in (bool, int, float) else False
			if hasattr(self.__sapiens_architecture, 'printCompleteMessages') and callable(getattr(self.__sapiens_architecture, 'printCompleteMessages')): self.__sapiens_architecture.printCompleteMessages(messages=messages, stream=stream)
			else:
				generated_tokens = self.completeMessages(messages=messages, stream=stream)
				if stream:
					first_token = True
					from time import sleep
					for dictionary in generated_tokens:
						token = dictionary.get('next_token', '')
						if not token: continue
						if first_token:
							print(token.lstrip(), end='', flush=True)
							first_token = False
						else: print(token, end='', flush=True)
						sleep(self.delay)
					print()
				else: print(generated_tokens['answer'])
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.printCompleteMessages: '+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 close(self):
		try:
			try:
				if self.__data_loader and self.__original_path and self.__extraction_path:
					if self.__is_frankenstein and self.__original_path != self.__extraction_path: self.__data_loader.close()
					elif self.__original_path.endswith(('.SAPI', '.submodel', 'sapiens')):
						from tempfile import gettempdir
						extraction_path = gettempdir()
						if extraction_path in self.__extraction_path:
							def _get_parent_directory(model_path=''):
								from os import path as os_path
								return os_path.dirname(os_path.abspath(model_path))
							directory_path = _get_parent_directory(model_path=self.__data_loader.output)
							if directory_path == extraction_path: directory_path = self.__extraction_path
							if directory_path != extraction_path:
								from shutil import rmtree
								from os.path import exists
								if exists(directory_path): rmtree(directory_path)
				if hasattr(self.__sapiens_architecture, 'close') and callable(getattr(self.__sapiens_architecture, 'close')): self.__sapiens_architecture.close()
				del self.__sapiens_architecture
			except: pass
			return True
		except Exception as error:
			try:
				if self.__show_errors or self.show_error:
					error_message = 'ERROR in SchizophrenicArtificialIntelligence.close: '+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
"""
The "Schizophrenic Artificial Intelligence" is a module used to invoke the Frankenstein and its submodels,
as well as other models of various distinct architectures, through the categorization of the loaded models and the user's inputs.
In this way, it selects the most appropriate and compatible model for each type of situation and returns the corresponding outputs,
derived from the inference of the current input converted into the output of the computed tokens.
"""
# --------------------------> A SAPIENS TECHNOLOGY®️ PRODUCTION) <--------------------------
