Best Python code snippet using localstack_python
inference.py
Source:inference.py
1import imp, sys2import numpy as np3import os4import pickle5import torch6import io7import boto38import json9from torchvision import transforms10from PIL import Image11from six import BytesIO12str_labels = ["FP", "GOOD", "VG", "VG-EX", "EX", "EX-MT", "NM", "NM-MT", "MINT", "GEM-MT"]13 14def train(hyperparameters, input_data_config, channel_input_dirs, output_data_dir,15 num_gpus, num_cpus, hosts, current_host, **kwargs):16 pass17def test(ctx, net, val_data):18 pass19def model_fn(model_dir):20 """Creates pytorch model specified via model_dir.21 22 Args:23 model_dir (str): path to model root dir. 24 """25 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")26 model = torch.load(open(os.path.join(model_dir, 'model/model.pth'), "rb")).to(device)27 print('[INFO] model loaded:')28 print(model.eval())29 return model 30def predict_fn(input_object, model):31 """ Uses Image library to load image and transfrom into float numbers for model prediction.32 33 Args:34 input_object (Image): image loaded using PIL.Image35 model (Object): unpickled model provided using model_fn36 """37 transformer = transforms.Compose([38 transforms.Resize((255, 255)),39 transforms.ToTensor(),40 transforms.Normalize(mean=[0.485, 0.456, 0.406],41 std=[0.229, 0.224, 0.225]),42 ])43 print("[INFO] Running model inference on image: {}".format(input_object))44 X = transformer(input_object)45 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')46 model.to(device)47 model.eval()48 with torch.no_grad():49 logits = model(X[None, ...].to(device))50 print("[INFO]: The prediction logits are: {}".format(logits))51 pred = logits.argmax(dim=1)52 return str_labels[pred]53def input_fn(request_body, request_content_type):54 """ Loads input from request content and returns image specified in request_body as PIL.Image.55 56 Args:57 request_body (bytes): serialized dictionary with two required key: "bucket" and "key" which specify an image to predict.58 request_content_type (str): type of content59 60 """61 print('[INFO] request_body: {}'.format(request_body))62 data = json.loads(request_body.decode())63 s3 = boto3.resource('s3')64 bucket = s3.Bucket(data['bucket'])65 object = bucket.Object(data['key'])66 response = object.get()67 file_stream = response['Body']68 image = Image.open(file_stream)69 70 #print('[INFO] Got Image of shape {} with scale {}'.format(image.shape, image.max()))71 return image72def output_fn(prediction, content_type):73 """Outputs result of prediction.74 75 Args:76 prediction (str): Label predicted by predict_fn77 content_type (str): type of content78 """79 print('[INFO] prediction: {}'.format(prediction))80 return {'statusCode': 200, 'body': '{}'.format(prediction) }81if __name__ == "__main__":82 """83 Test script - please run this at the root directory of model/, i.e., ./model/..84 """85 86 test_model_dir = "./"87 test_request_body = json.dumps({'bucket': 'ccbd-mint-cv-model', 'key': 'test_data.jpeg'}).encode('utf-8')88 test_request_content_type = "test_type" 89 test_response_content_type = "test_type"90 91 # Deserialize the Invoke request body into an object we can perform prediction on92 input_object = input_fn(test_request_body, test_request_content_type)93 test_model = model_fn(test_model_dir)94 95 # Perform prediction on the deserialized object, with the loaded model96 prediction = predict_fn(input_object, test_model)97 # Serialize the prediction result into the desired response content type98 output = output_fn(prediction, test_response_content_type)99 ...
test_GeniosSite.py
Source:test_GeniosSite.py
...14 if actual_response:15 assert actual_response == BASE_URL16 else:17 assert False18def test_response_content_type():19 headers = site.get_response_headers()20 content_type = headers["Content-Type"]21 assert content_type == "text/html; charset=UTF-8"22def test_site_connection_type():23 headers = site.get_response_headers()24 connection_type = headers["Connection"]25 assert connection_type == "Upgrade, Keep-Alive"26def test_site_link_lists():27 actual_links = site.get_site_link_lists()28 expected_links = csv_manipulation(SITE_LIST).read_csv_lines()29 if len(actual_links) == len(expected_links):30 check_link_list = zip(sorted(actual_links), sorted(expected_links))31 for actual, expected in check_link_list:32 assert actual == expected33 else:34 assert False35def test_all_cubes_types():36 cube_name = csv_manipulation(CUBE_TYPES).read_csv_specific_column(0)37 cube_link = csv_manipulation(CUBE_TYPES).read_csv_specific_column(1)38 expected_cube_types = dict(zip(cube_name, cube_link))39 actual_cube_types = site.get_all_cubes_types()40 if len(actual_cube_types) == len(expected_cube_types):41 for key in actual_cube_types.keys():42 assert actual_cube_types[key] == expected_cube_types[key]43 else:44 assert False45if __name__ == '__main__':46 # test_response_content_type()47 # test_site_connection_type()48 # test_site_link_lists()...
renderers_test.py
Source:renderers_test.py
1# -*- coding: utf-8 -*-2from h import renderers3def test_response_content_type(pyramid_request):4 renderer = renderers.CSV({})5 renderer({}, {'request': pyramid_request})6 assert pyramid_request.response.content_type == 'text/csv'7def test_render_simple_csv(pyramid_request):8 renderer = renderers.CSV({})9 sys = {'request': pyramid_request}10 value = {'header': ['One', 'Two'],11 'rows': [[1, 2], [3, 4]]}12 assert renderer(value, sys) == "One,Two\r\n1,2\r\n3,4\r\n"13def test_render_unicode_csv(pyramid_request):14 renderer = renderers.CSV({})15 sys = {'request': pyramid_request}16 value = {'header': [u'Ó', u'Ä'],17 'rows': [[u'ñ', u'ã'], [u'ïº', u'Óª']]}...
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!!