Best Python code snippet using tempest_python
FERManager.py
Source:FERManager.py  
...40        # Checks if the given net is subclass of CNNetwork41        assert issubclass(type(network), CNNetwork)42        self._nn_dict[network.get_name()] = network43        return44    def get_network_by_name(self, model_name=None):45        """46        This method loads the stored network by its name from the neural network list47        model_name: The name of the neural network to load48        INPUT:49        - model_name: The name of the network to load50        RETURN:51        - The specified network in the network list52        """53        assert model_name is not None54        return self._nn_dict[model_name]55    def code_to_emotion(self, code):56        """57        This method converts the emotion number to the appropriate emotion name58        INPUT:59        - code: The integer code of the emotion60        RETURN:61        - The string name of the respective emotion code, otherwise None62        """63        emotion_names = {0: "Angry/Disgust",64                         1: "Fear",65                         2: "Happy",66                         3: "Sad",67                         4: "Surprise",68                         5: "Neutral"}69        if code >=0 and code <=5:70            return emotion_names.get(code)71        return None72    def start_training(self, network_type):73        """74        This method executes the training and validation process of the models75        INPUT:76        - network_type: The type of the network to train77        """78        self.enable_gpu_support()   # Enables the GPU support when it's available79        if network_type not in self._nn_dict:80            raise ValueError("The given network could not be found in the neural network list!!!.")81        network = self.get_network_by_name(network_type)82        # Checks if the log folder for the VGG16 network exists83        if network.get_name() == 'vgg16':84            if os.path.exists(self._log_dir + "vgg16") == False:85                os.makedirs(self._log_dir + "/vgg16/train/")86        # Checks if the log folder for the Inception-v3 network exists87        if network.get_name() == 'inception-v3':88            if os.path.exists(self._log_dir + "inception_v3") == False:89                os.makedirs(self._log_dir + "/inception_v3/train/")90        print("Training of the "+network_type+" network starts...")91        network.build(self._num_emotions)92        network.training(augmentation=True, early_stopping=True, decay_rate=0.5)  # Decays 50% the learning rate93        return94    def predict(self, dataset_path, network=None):95        """96        This method classifies an unknown image97        INPUT:98        - dataset_path: The path of the dataset99        - network: The network to predict100        """101        assert network is not None102        image_list = os.listdir(dataset_path)103        print("Prediction using the", network,"model...")104        vgg16 = None105        test_model_dir = ""106        inception_resnet_v2 = None107        # Checks for the VGG16 network108        if network == 'vgg16':109            vgg16 = self.get_network_by_name(network)110            test_model_dir = "./logs/vgg16/train/"111        # Checks for the Inception-v3 network112        elif network == 'inception-v3':113            inception_resnet_v2 = self.get_network_by_name(network)114            test_model_dir = "./logs/inception_v3/train/"115        else:116            print("No specified network for testing found!!!")117            return118        # Checks if the test directory contains a test checkpoint119        if os.listdir(test_model_dir):120            file = [file for file in os.listdir(test_model_dir)]121            test_model = load_model(test_model_dir + str(file[0]))122        else:123            print("No saved models available, prediction cannot proceed!!!")124            return125        emotion_predictions = []126        # Predicts the unknown images127        for img_file in image_list:128            # Reads every image from the folder, converts it to grayscale129            img_orig = cv2.imread(dataset_path + img_file)130            img_gray = cv2.imread(dataset_path + img_file, 0)131            predictions = []; calc_predictions = []; y_label = []132            if vgg16:133                predictions = vgg16.predict(img_gray, test_model)134            elif inception_resnet_v2:135                predictions = inception_resnet_v2.predict(img_gray, test_model)136            # print(predictions)137            print("Image file: ", img_file, ":")138            for code, percent in enumerate(predictions):139                emotion = self.code_to_emotion(code)    # Converts the code to the emotion name140                # Checks for which emotion/percentage to print141                if code == 0: print(emotion + ":\t%1.2f%%" % (np.float(percent)))142                elif code == 1: print(emotion + ":\t\t\t%1.2f%%" % (np.float(percent)))143                elif code == 2: print(emotion + ":\t\t\t%1.2f%%" % (np.float(percent)))144                elif code == 3: print(emotion + ":\t\t\t%1.2f%%" % (np.float(percent)))145                elif code == 4: print(emotion + ":\t\t%1.2f%%" % (np.float(percent)))146                elif code == 5: print(emotion + ":\t\t%1.2f%%" % (np.float(percent)))147                else: print("Invalid Code!!!")148                calc_predictions.append(percent)149            highest = self.code_to_emotion(np.argmax(calc_predictions))150            print("Highest:", highest, "\n")151            emotion_predictions.append(highest)152            cv2.imshow(highest, img_orig)153            cv2.waitKey(0)154            cv2.destroyAllWindows()155        self.plot_statistics(emotion_predictions)  # Plots the statistics of the prediction156        return157    # TODO: Implementation of the testing process158    def test(self, network=None):159        """160        This method uses the test set to evaluate the given network161        INPUT:162        - dataset_path: The path of the dataset163        - network: The network to predict164        """165        assert network is not None166        self.enable_gpu_support()  # Enables the GPU support if it's available167        print("Testing using the", network, "model...")168        vgg16 = None169        test_model_dir = ""170        inception_resnet_v2 = None171        # Checks for the VGG16 network172        if network == 'vgg16':173            vgg16 = self.get_network_by_name(network)174            test_model_dir = "./logs/vgg16/train/"175        # Checks for the Inception-v3 network176        elif network == 'inception-v3':177            inception_resnet_v2 = self.get_network_by_name(network)178            test_model_dir = "./logs/inception_v3/train/"179        else:180            print("No specified network for testing found!!!")181            return182        # Checks if the test directory contains a test checkpoint183        if os.listdir(test_model_dir):184            file = [file for file in os.listdir(test_model_dir)]185            test_model = load_model(test_model_dir + str(file[0]))186        else:187            print("No saved models available, prediction cannot proceed!!!")188            return189        result = []190        if vgg16:191            result = vgg16.testing(self._num_emotions, test_model)...test_getNetworkByName.py
Source:test_getNetworkByName.py  
...20            raise21        else:22            try:23                for item in range(0, no_of_api_calls):24                    response = self.get_network_by_name(25                        ncm_url, params_from_inputfile.get_anchor(0)26                    )27                    logfile.log_debug(28                        "Received Response Code: " + str(response.status_code)29                    )30                    logfile.log_debug("Received Response Text: " + str(response.text))31                    # logfile.log_debug("Received Response Header SessionId: " + response.headers.get('SessionId'))32                    self.get_network_by_name_assertion_check(33                        logfile,34                        response,35                        params_from_inputfile.get_response_code(0, item),36                        params_from_inputfile.get_response_text(0, item),37                    )38            except HTTPError as http_err:39                logfile.log_debug(utils.printException())40                logfile.log_debug(41                    "Error - HTTP error occurred: '{0}' ".format(http_err)42                )43                raise44            except Exception as err:45                logfile.log_debug(utils.printException())46                logfile.log_debug("Error - other error occurred: '{0}' ".format(err))47                raise48    @classmethod49    def get_network_by_name(self, ncm_url, anchor):50        headers = {"accept": "application/json"}51        response = requests.get(ncm_url + anchor, headers=headers)52        return response53    @classmethod54    def get_network_by_name_assertion_check(55        self, logfile, response, responseCode=None, responseText=None56    ):57        msgResCode = "Response Code does not match, expected: {0}, actual: {1}".format(58            responseCode, response.status_code59        )60        utils.logAssert(response.status_code == responseCode, msgResCode, logfile)61        if responseText:62            if type(responseText) == str:63                msgText = "Response Text does not contain expected string, expected: {0}, actual: {1}".format(...loader.py
Source:loader.py  
1import importlib2__all__ = [3    'get_network_by_name',4]5def get_network_by_name(name, input_shape):6    module = importlib.import_module('badukai.networks.' + name)7    constructor = getattr(module, 'layers')...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
