How to use list_mappings method in tempest

Best Python code snippet using tempest_python

recipe_adaptation.py

Source:recipe_adaptation.py Github

copy

Full Screen

1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""4Created on Tue Mar 24 17:29:00 20205@author: Andrea Morales Garzón6Adaptation of recipes 7This file pre-processes the ingredients of the recipe, and looks for a mapping to the database.8The properties of the food are consulted to see if there is an incompatibility9with the restriction, and a new mapping is made that allows to map the ingredient10to one of those that are allowed.11 12"""13from gensim.models import KeyedVectors14from gensim.models.phrases import Phraser15from gensim.parsing.preprocessing import preprocess_string, remove_stopwords, stem_text16import gensim17import pandas as pd18import numpy as np19from fjaccard import fjaccard_extended20import ast21import random22import json23# load language models24CUSTOM_FILTERS = [remove_stopwords, stem_text]25CUSTOM_FILTERS_2 = [remove_stopwords]26modelo_guardado = KeyedVectors.load("../models/v2/modelo3")27bigram_loaded = Phraser.load("../models/v2/my_bigram_model.pkl")28df_idiet = pd.read_excel("../data/inglesa-labeled_reducida_vegan_terminada.xlsx")29def funcc(tex):30 x = 'Yes'31 return x32df_idiet['no_restriction'] = df_idiet['Main food description'].apply(funcc)33#%%34# apply word embedding text preprocessing to the food to get their representation35def preprocess_recipe(text_recipe, create_tokens = True, main_ingredient = False):36 if main_ingredient:37 pos = text_recipe.find(',')38 if pos != -1:39 text_recipe = text_recipe[0:(pos+1)]40 41 if create_tokens:42 tokens = list(gensim.utils.tokenize(text_recipe, lower=True))43 44 else:45 tokens = text_recipe46 47 tokens = preprocess_string(" ".join(tokens), [remove_stopwords, stem_text]) 48 sentenc = list(bigram_loaded[tokens])49 50 return sentenc51#%%52# Function to mapping ingredient to food database53def get_DB_equivalent(idiet_item_list, bd_names_ , bd_names_mapping , model, number_instances = False):54 55 # get similarity between ingredient and dataset foods56 vector_similarity = np.zeros(len(bd_names_mapping))57 for i,item in enumerate(bd_names_mapping):58 s = fjaccard_extended(idiet_item_list, item, modelo_guardado)59 vector_similarity[i] = s60 # identify the most accurate61 sorted_list = np.argsort(vector_similarity)62 # get the bestx mappings (in this case we obtain 10)63 if number_instances == True:64 most_similar = [ bd_names_[sorted_list[i]] for i in range(10) ]65 value_most_similar = [ vector_similarity[sorted_list[i]] for i in range(10) ]66 67 # inf distance value is infinity or very high, we consider there is no similar ingredient in the database68 for i,value in enumerate(value_most_similar):69 if value == np.Infinity:70 most_similar[i] = 'No matches'71 if value > 44.0:72 most_similar[i] = 'No matches'73 else:74 most_similar = bd_names_[sorted_list[0]]75 value_most_similar = vector_similarity[sorted_list[0]] 76 if value_most_similar == np.Infinity:77 most_similar = 'No matches'78 alternatives = [ bd_names_[sorted_list[i]] for i in range(10) ]79 print(alternatives)80 return most_similar, value_most_similar, alternatives81#%%82def get_accurate_mapping(i,model,bigram,db,nutritional_data,bd_names_processed):83 ingredient_processed = preprocess_recipe(i)84 print(ingredient_processed)85 mapping_idiet, value_mapping, alternatives_ = get_DB_equivalent(ingredient_processed,bd_names_=db,bd_names_mapping=bd_names_processed,model=model,number_instances=False)86 mapping = nutritional_data[nutritional_data['Main food description'] == mapping_idiet]87 88 return mapping, mapping_idiet, value_mapping, alternatives_ 89#%%90def get_adapted_recipe(recipe,model,bigram,db,nutritional_data,restriction):91 92 # preprocessing recipe data93 bd_names_processed = [preprocess_recipe(x) for x in db]94 95 96 list_recipe_ingredients = []97 # get recipe ingredients98 recipe_ingredients = recipe['ingredients']99 100 for i in recipe_ingredients:101 print("......")102 print(i)103 104 # for each ingredient in recipe, we search for the most accurate mapping105 mapping, mapping_idiet, value_mapping, others= get_accurate_mapping(i,model,bigram,db,nutritional_data,bd_names_processed)106 modified_action = 'no'107 adapted_ing = ""108 109 if mapping_idiet != 'No matches':110 111 mapping = mapping.iloc[0]112 if mapping[restriction] == "No" and value_mapping <0.9:113 print("entra")114 modified_db = nutritional_data[nutritional_data[restriction] == "Yes"]115 bd_names_mod = list(modified_db['Main food description'])116 bd_names_mod_processed = [preprocess_recipe(x) for x in bd_names_mod] 117 mapping, adapted_ing, value_mapping, others = get_accurate_mapping(i,model,bigram,bd_names_mod,modified_db,bd_names_mod_processed)118 modified_action = 'yes'119 120 if value_mapping > 0.9:121 value_mapping = None122 else:123 value_mapping = None124 125 list_recipe_ingredients.append({'name':i, 'modified':modified_action,'adapted':adapted_ing, 'others':others})126 return list_recipe_ingredients127 128#%% 129# ejemplo130usda_ingredients = pd.read_excel("../data/inglesa-labeled_reducida_vegan_terminada.xlsx")131bd_names = list(usda_ingredients['Main food description'])132df_rcp = pd.read_csv('../data/RAW_recipes-foodcom-kaggle.csv')133dict_rcp = df_rcp.to_dict('records')134##135random.seed(12345)136xx = random.sample(dict_rcp,20)137#%%138 139# order results (used for preference type of adaptations)140 141def ordenar(list_mappings,nutrient):142 list_mappings = list_mappings[2:5]143 print(len(list_mappings))144 valores_nutricionales = np.zeros(len(list_mappings))145 for i,map_ in enumerate(list_mappings):146 print(map_)147 item = usda_ingredients[usda_ingredients['Main food description'] == map_].iloc[0]148 print(item['Main food description'])149 if item[nutrient] == 'Tr':150 valores_nutricionales[i] = 0151 elif item[nutrient] != 'N':152 valores_nutricionales[i] = item[nutrient]153 print(valores_nutricionales[i])154 else: 155 valores_nutricionales[i] = np.nan156 157 print(valores_nutricionales)158 159 mean_value = np.nanmean(valores_nutricionales)160 valores_nutricionales = np.where(valores_nutricionales==np.nan, mean_value, valores_nutricionales) 161 print(mean_value)162 sorted_list = np.argsort(valores_nutricionales)163 print(sorted_list)164 res_ordenado = [list_mappings[i] for i in sorted_list ]165 return res_ordenado166 167 168list_prueba = ['Allspice, ground','Lime juice cordial, diluted','Langoustine, boiled'] 169r_list = ordenar(list_prueba, 'Energy (kcal) (kcal)') 170#%%171def get_recipe_adaptation(recipe_,adaptation_type='no_restriction', kind='preferences', order=False):172 173 print(recipe_['name'])174 print(recipe_['ingredients'])175 rp_ = {"id":recipe_176 ['id'],'name':recipe_["name"],"ingredients":ast.literal_eval(recipe_["ingredients"]), "steps":ast.literal_eval(recipe_['steps']), 'description':recipe_['description'], 'type':kind}177 x = get_adapted_recipe(recipe=rp_,model=modelo_guardado,bigram=bigram_loaded,db=bd_names,nutritional_data=usda_ingredients,restriction=adaptation_type)178 179 180 if order:181 for i,element in enumerate(x):182 x[i]['others'] = ordenar(element['others'],'Energy (kcal) (kcal)')183 184 185 rp_['ingredients'] = x186 187 188 189 with open('../res/'+kind+'/data_recipe_'+rp_['name']+'.json', 'w') as fp:190 json.dump(rp_, fp)191 192 print("--")193 194 195#%%196for i in list(xx):197 print("-------------------------------------")198 get_recipe_adaptation(i,adaptation_type='no_restriction', kind='light',order=True)199 ...

Full Screen

Full Screen

3_list_of_depths.py

Source:3_list_of_depths.py Github

copy

Full Screen

1class Node:2 def __init__(self, value:int, children:list=[]):3 self.value = value4 self.children = children5class LlNode:6 def __init__(self, value:int, next_node=None):7 self.value = value8 self.next = next_node9def create_tree(array:list) -> Node:10 if not array:11 return None12 mid_index = len(array)//213 14 left_child = create_tree(array[:mid_index])15 right_child = create_tree(array[mid_index+1:])16 r = Node(array[mid_index], [left_child, right_child])17 return r18def print_link_list(node:LlNode):19 while node:20 print(node.value)21 node = node.next22def find_depths(tree_root:Node) -> list:23 list_mapping = []24 queue = []25 queue.append(tree_root)26 level_counter = 027 while len(queue) > 0:28 next_queue = []29 list_mapping.append(LlNode(None))30 while len(queue) > 0:31 r = queue.pop()32 33 next_queue.extend([i for i in r.children if i])34 35 ll_element = LlNode(r.value)36 ll_element.next = list_mapping[level_counter].next37 list_mapping[level_counter].next = ll_element38 39 level_counter += 140 queue = next_queue41 return list_mapping42 43 44def main():45 46 values = [0,1,2,3,4,5,6,7,8,9]47 tree_root = create_tree(values)48 list_mappings = find_depths(tree_root)49 50 for i in list_mappings:51 print("list")52 print_link_list(i)53if __name__ == '__main__':...

Full Screen

Full Screen

dict_to_xml.py

Source:dict_to_xml.py Github

copy

Full Screen

1from xml.dom.minidom import Document2class DictToXML(object):3 default_list_item_name = "item"4 def __init__(self, structure, list_mappings={}):5 self.doc = Document()6 if len(structure) == 1:7 rootName = str(list(structure.keys())[0])8 self.root = self.doc.createElement(rootName)9 self.list_mappings = list_mappings10 self.doc.appendChild(self.root)11 self.build(self.root, structure[rootName])12 def build(self, father, structure):13 if type(structure) == dict:14 for k in structure:15 tag = self.doc.createElement(k)16 father.appendChild(tag)17 self.build(tag, structure[k])18 elif type(structure) == list:19 tag_name = self.default_list_item_name20 if father.tagName in self.list_mappings:21 tag_name = self.list_mappings[father.tagName]22 for l in structure:23 tag = self.doc.createElement(tag_name)24 self.build(tag, l)25 father.appendChild(tag)26 else:27 data = str(structure)28 tag = self.doc.createTextNode(data)29 father.appendChild(tag)30 def display(self):31 print(self.doc.toprettyxml(indent=" "))32 def get_string(self):...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tempest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful