def UploadCsv(event, context, ACCESS_KEY, SECRET_KEY, BUCKET_NAME): try: content_type_header = event['headers']['content-type'] body = base64.b64decode(event['body']) username = decoder.MultipartDecoder( body, content_type_header).parts[1].content.decode('utf-8') print('username----', username) csv_file_name = 'dataset.csv' csv_file = decoder.MultipartDecoder( body, content_type_header).parts[2].content.decode('utf-8') csv_file_path = f'/tmp/{csv_file_name}' print("csv_File------ ", csv_file) f = open(csv_file_path, "w") f.write(csv_file) f.close() print('created csv file') df = pd.read_csv(csv_file_path, names=['data', 'categories']) df.fillna('No value', inplace=True) codes, index = pd.factorize(df['categories']) df['labels'] = codes df = df.drop(['categories'], axis=1) df.to_csv(csv_file_path, index=False, header=False) print('created clean csv') S3_FILE_NAME = f'{username}/{csv_file_name}' upload_to_s3(csv_file_path, BUCKET_NAME, S3_FILE_NAME, ACCESS_KEY, SECRET_KEY) print('uploaded to s3') os.remove(csv_file_path) print('removed file') return tuple(index) except Exception as e: print(repr(e))
def face_swap(event, context): try: content_type_header = event['headers']['content-type'] # print(event['body']) body = base64.b64decode(event["body"]) picture = decoder.MultipartDecoder(body, content_type_header).parts[0] picture1 = decoder.MultipartDecoder(body, content_type_header).parts[1] image_bytes = picture.content image_bytes1 = picture1.content print("Start Swapping the faces") image = Image.open(io.BytesIO(image_bytes)) image1 = Image.open(io.BytesIO(image_bytes1)) print("Image Shape:", image.size) np_image, np_image1, = np.array(image), np.array(image1) swapped_image = face_swap_func(np_image, np_image1) pil_image = Image.fromarray(swapped_image) res_image = get_response_image(pil_image) img = get_response_image(image) img1 = get_response_image(image1) # res_image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQQEhMSExMWFRUWGBkYFxgWFxUTFxYZHhcWHR4VFxkYHiggGB8mIRcXIT0iJzUrLi4uFyAzODMsNygtLysBCgoKDg0OGxAQGy0mHyUrLS8tNy0tMDUtLy0rLS0tLS0tLS0tLS0rLS0tLTAvLS0rLS0tLS0rLS8tLS0rLy0tLf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QIse0ShSOpADoQDY+D0j9JE7f9teHrpUw1DC1XFVWpZqjJTADgrmyjMTa97aekov/WJbCU9lmmoSjVaqKlyWYmpUbKVtYfvT/SJSrv6JhefZPWL7Vqljr2FY2Jvb9phhp9/rNnn5k3Z3vOy8U2LFIVsyPSyl+z0apTbMGytw7MC1ufhNJ2V7ccFUIWvSrUL/ABWFZB6p3v8ALFEYpJalE8my9p0cVTWtQqJVptwZCGHl4EdOInrl0EREBERAREQEREBERAREQEREBERAREQEREBERAT8v+1/A1G2rinzZ7sosTqoyLZR1FunU6c5+oJg3tp2M9HG/iONPEAEHoyIiMpHkFPqekDKcHh8rqzG1iCfCeunhi1R2XvXv3uF7+B/5pJNVBGoB89Z5sQijgAPLSVmMpR+MOYkG97n9B/vPIcKx4C89racJ8UyYjCGuf8Ap1w703xgLaFaZKA3UG7WPS5F+HTj022Zj7CtjPSw1XEvYDEFQg55aZqDMel2Zv6fGadJCIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgJm/tzw2bBUag+CsAfJkf+4WaRKj7VsL2my8T1XI4/lqKT9rwPztTedGIbxn0NOmq0hLoacqc4GdtCkXIReLEKPM6D9YQ/VO4uF7HZ2DQ8RQpk+bKGP3Jk7OvD0giqg4KAB5AWnZJCIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgJG7zYPt8JiaQFy9Goo8yhA+9pJRA/HxM6XM/SW83sxwOOZquVqFVjdnokLmPVkYFSTzNgT1kLgvYrhFWoKtWrVY+4b9mKemhyqe+b666aDQa3gYGZP7h4E4jaODpDnWRj+Wme0b/KjTTMF7CqY/fY12H/10lpH6szy/bq7k4PZtzh6X7QizVXOeoRppmPujQaLYacIFiiIkhERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQERED/9k=" message = 'here is my message' response = { 'Status': 'Success', 'message': message, 'img': img, 'img1': img1, 'swapped_image': res_image } # img_bytes = image.tobytes() # bytes_encoded = base64.b64encode(img_bytes) return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, # "body": response, "isBase64Encoded":"true" "body": json.dumps(response) } except Exception as e: traceback.print_exc() return { "statusCode": 500, "headers": { 'Content-Type': 'multipart/form-data', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({"error": repr(e)}) }
def get_images_from_event(event, max_files=1): try: pic_details = [] content_type_key = "Content-Type" if event["headers"].get(content_type_key.lower()): content_type_key = content_type_key.lower() content_type_header = event["headers"][content_type_key] body = base64.b64decode(event["body"]) if type(event["body"]) is str: event["body"] = bytes(event["body"], "utf-8") pictures = decoder.MultipartDecoder(body, content_type_header) for part in pictures.parts: filename = get_picture_filename(part).replace('"', "") pic_details.append((part, filename)) logger.info(f"len: {len(pic_details)}") return pic_details[0:max_files] except Exception as e: logger.exception(e) raise e
def post_cb(self, request, context): from requests_toolbelt.multipart import decoder multipart_data = decoder.MultipartDecoder( request.body, request.headers["content-type"]) part = multipart_data.parts[0] self.content[self.relpath(request.path)] = part.content
def handler(event, context): body = event['body-json'] # 람다 생성 확인용 코드 if body == "test": return {'statusCode': 200, 'body': "함수가 정상적으로 배포 되었습니다."} body = base64.b64decode(body) boundary = body.split(b'\r\n')[0] boundary = boundary.decode('utf-8') content_type = f"multipart/form-data; boundary={boundary}" multipart_data = decoder.MultipartDecoder(body, content_type) img = multipart_to_input(multipart_data) result = inference_model(img) return { 'statusCode': 200, 'body': json.dumps( f"{result[0][1]}&{result[0][2]}&{result[1][1]}&{result[1][2]}&{result[2][1]}&{result[2][2]}&{result[3][1]}&{result[3][2]}&{result[4][1]}&{result[4][2]}" ) }
def get_multipart_filename(self, content_type, request): """Return filename for given multipart request.""" body = request.body multipart_data = decoder.MultipartDecoder(body, content_type) multipart_dict = {} filename_array = [self.filename, request.method] for part in multipart_data.parts: content_disposition = part.headers.get( 'Content-Disposition'.encode(), None ) decoded_cd = content_disposition.decode("utf-8") multipart_name = self.get_multipart_name(decoded_cd) multipart_dict[multipart_name] = part.text.replace(' ', '-') ordered_dict = collections.OrderedDict( sorted(multipart_dict.items()) ) for key, value in ordered_dict.items(): filename_array.append(key + '=' + value) filename = '--'.join(filename_array) return filename
def classify_image(event, context): try: content_type_header = event['headers']['content-type'] print(event['body']) body = base64.b64decode(event['body']) print('BODY LOADED') picture = decoder.MultipartDecoder(body, content_type_header).parts[0] prediction = get_prediction(image_bytes=picture.content) print("The prediction is {}".format(prediction)) #filename = picture.headers[b'Content-Disposition'].decoder().split(';')[2].split('=')[1] return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True }, "body": json.dumps({"predicted": prediction}) } except Exception as e: print(repr(e)) return { "statusCode": 500, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True }, "body": json.dumps({"predicted": prediction}) }
def parse_multipart_req(body, content_type): """ Parse multipart-encoded form data """ req = {} # convert to bytes if needed if isinstance(body, str): body = bytes(body, "utf-8") multipart_data = decoder.MultipartDecoder(body, content_type) for part in multipart_data.parts: content_disposition = part.headers.get(b"Content-Disposition", b"") content_disposition = content_disposition.decode("utf-8") search_field = PATTERN.search(content_disposition) if search_field: if search_field.group(0) == "image": img_io = io.BytesIO(part.content) img_io.seek(0) req["image"] = img_io elif search_field.group(0) == "url": url = part.content.decode("utf-8") img_io = io.BytesIO(urlopen(url).read()) req["url"] = img_io elif search_field.group(0) == "bbox": req["bbox"] = json.loads(part.content.decode("utf-8")) else: logger.debug("Bad field name in form-data") return req
def parse_email(content_type, body): multipart_string = base64.b64decode(body) parts = decoder.MultipartDecoder(multipart_string, content_type).parts for part in parts: if 'name="email"' in str(part.headers[b'Content-Disposition']): return part.text return None
def classify_image(event, context): """Take input image from API and classify it.""" print("Executing classify_image") try: # Get image from the request print("requesting") print(event) content_type_header = event['headers']['Content-Type'] print("content_type_header loaded") body = base64.b64decode(event['body']) print('Body loaded') # Obtain the final picture that will be used by the model picture = decoder.MultipartDecoder(body, content_type_header).parts[0] print('Picture obtained') # print("picture",dir(picture)) # Get predictions prediction = get_prediction(image_bytes=picture.content) prediction_name = class_name[prediction] print(f'Prediction: {prediction}\tPrediction Name: {prediction_name}') return { 'statusCode': 200, 'body': json.dumps({ 'predicted': prediction, 'predicted name': prediction_name }) } except Exception as e: print(repr(e)) return {'statusCode': 500, 'body': json.dumps({'error': repr(e)})}
def main_handler(event, context): try: content_type_header = event['headers']['content-type'] print('content_type header: ' + content_type_header) #print('Event Body: ' + event["body"]) body = base64.b64decode(event["body"]) #print('Image content Loaded') picture = decoder.MultipartDecoder(body, content_type_header).parts[0] print(f'MultipartDecoder processed') img = Image.open(io.BytesIO(picture.content)) print(f'Input image data loaded') lr, hr_restore, hr = get_sample_images(real_image=img, upscale_factor=2) print( f'lr shape: {lr.shape}, hr_restore shape: {hr_restore.shape}, hr shape: {hr.shape}' ) lrSize = lr.shape[1] hrSize = hr.shape[1] lr = lr.unsqueeze(0) sr = g_model(lr) # create SR image sr, lr = sr.squeeze(0), lr.squeeze(0) lr_np = tensor2np(lr) hr_restore_np = tensor2np(hr_restore) sr_np = tensor2np(sr) sr_np_norm = np.uint8(sr_np * 255) print(f'SR image created') return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({ 'lrSize': lrSize, 'hrSize': hrSize, 'lrImg': img_to_base64(lr_np), 'hrRestoredImg': img_to_base64(hr_restore_np), 'srImg': img_to_base64(sr_np_norm) }) } except Exception as e: print(repr(e)) return { "statusCode": 500, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({"error": repr(e)}) }
def get_image_from_event(event): content_type_header = event["headers"]["content-type"] body = base64.b64decode(event["body"]) logger.info("Body Loaded") picture = decoder.MultipartDecoder(body, content_type_header).parts[0] filename = get_picture_filename(picture).replace('"', "") return picture, filename
def lambdaHandler(event, context): headers = event['headers'] content_type = headers['Content-Type'] if 'Content-Type' in headers else headers['content-type'] # This code can only handle base64 encoded # Need to work on Non-base64 encoded case isBase64 = event['isBase64Encoded'] # In the CDK, if the binaryMediaTypes: ['multipart/form-data'] specified on the API level, it is base64 encoded, otherwise, it is not body = base64.b64decode(event['body']) form_data = decoder.MultipartDecoder(body, content_type).parts part = form_data[0] # print(part.headers) # print(part.content) key = f'F-{int(time.time())}.jpg' client = boto3.client('s3') def get_presigned_url(): client.put_object(Body = part.content, Bucket = bucket, Key = key) # ExpiresIn - time in second return client.generate_presigned_url('get_object', Params = { 'Bucket': bucket, 'Key': key }, ExpiresIn = 60 * 60 * 24) presigned_url = get_presigned_url() return { 'statusCode': 200, 'headers': { 'Access-Control-Allow-Origin': '*', 'content-type': 'application/json' }, 'body': json.dumps(presigned_url) }
async def format_files(r, encode=False): if encode: pass else: decoded = decoder.MultipartDecoder(await r.content, r.mimetype) dump = {} for part in decoded.parts: header = part.headers[b"Content-Disposition"].decode("utf-8") mimetype = part.headers.get(b"Content-Type", None) filename = None for section in [h.strip() for h in header.split(";")]: split = section.split("=") if len(split) > 1: key = split[0] value = split[1] value = value[1:-1] if key == "filename": filename = value elif key == "name": formname = value if mimetype is None: dump[formname] = part.content else: dump[formname] = { "filename": filename, "content": part.content, "content-type": mimetype.decode("utf-8"), } return dump
def WadoRs(self, wado_url: Text, accept_header: Text = None) -> bytes: """Performs the request, parses the multipart response, and returns content. Args: wado_url: URL for the WADO request. accept_header: Value of the Accept header to use. If set to None, no Accept header will be used. Returns: The content of the first (and only) part as a string. Raises: UnexpectedResponseError: If the response status was not success or the number of parts in the multipart response is different from 1. """ resp, content = self._InvokeHttpRequest( wado_url, 'GET', headers={'Accept': accept_header} if accept_header is not None else {}) if 200 <= resp.status >= 299: raise UnexpectedResponseError( 'WadoRs error. Response Status: %d,\nURL: %s,\nContent: %s.' % (resp.status, wado_url, content)) multipart_data = decoder.MultipartDecoder(content, resp['content-type']) num_parts = len(multipart_data.parts) if num_parts != 1: raise UnexpectedResponseError( 'WadoRs multipart response expected to have a single part.' ' Actual: %d.\nURL: %s' % (num_parts, wado_url)) return multipart_data.parts[0].content
def text_classification(event,context): try: print('event-------',event) content_type_header = event['headers']['content-type'] body = base64.b64decode(event['body']) print('body-------',body) print('body loaded') print(content_type_header) decoded = decoder.MultipartDecoder(body,content_type_header) function_usage =( decoded.parts[0].content).decode('utf-8') if function_usage == 'text_classify_test': prediction = predict_class(S3_BUCKET,decoded,ACCESS_KEY,SECRET_KEY,min_len=5) return { 'statusCode': 200, 'headers':{ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True }, 'body': json.dumps({'status': '1', 'result': str(prediction) }) } except Exception as e: print(repr(e)) return { 'statusCode': 500, 'headers':{ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True }, 'body': json.dumps({ 'error': repr(e) }) }
def parse_multipart_data(body_dec, content_type): """Parser for transforming multipart form data into readable key value pairs Args: body_dec (byte), content_type (str) Returns: Parsed Form Data (list): List of key value pairs describing each form data """ items = [] for part in decoder.MultipartDecoder(body_dec, content_type).parts: disposition = part.headers[b'Content-Disposition'] params = {} for dispPart in str(disposition).split(';'): kv = dispPart.split('=', 2) params[str(kv[0]).strip()] = str(kv[1]).strip( '\"\'\t \r\n') if len(kv) > 1 else str(kv[0]).strip() type = part.headers[b'Content-Type'].decode( "utf-8") if b'Content-Type' in part.headers else None items.append({"content": part.content, "type": type, "params": params}) return items
def classify_image (event, context): try: content_type_header = event['headers']['content-type'] print(event['body']) body = base64.b64decode(event["body"]) picture = decoder.MultipartDecoder(body, content_type_header).parts[0] prediction = get_prediction(image_bytes=picture.content) print (prediction) filename = picture.headers[b'Content-Disposition'].decode().split(';')[1].split('=')[1] if len(filename) < 4: filename = picture.headers[b'Content-Disposition'].decode().split(';')[2].split('=')[1] return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({'file': filename.replace('"', ''), 'predicted': [prediction, classes[prediction] ]}) } except Exception as e: print(repr(e)) return { "statusCode": 500, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({"error": repr(e)}) }
def classifyHandler(event, context): content_type_header = event['headers']['Content-Type'] body = event['body'].encode() rawBytes = decoder.MultipartDecoder(body, content_type_header).parts[0].content # # TODO: why do rawBytes look off? why are they unable to be opened as image? # rawIO = BytesIO(rawBytes) # image = Image.open(rawBytes) # # image = np.array(image) # # image = tf.image.convert_image_dtype(image, tf.float32) # # image = tf.image.resize(image, (224,224)) # # image = np.expand_dims(image, axis=0) # # prediction = model.predict_classes(image)[0] # # prediction = class_dict['prediction'] response = { 'statusCode': 200, 'body': json.dumps({ 'sample_bytes': str(rawBytes)[:10000], 'request_body': str(event['body'][:10000]) }) } return response
def deserialize(self, data, headers, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for deserialized object, or string of class name. :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance if response_type == "file": return self.__deserialize_file(data, headers) if response_type == "multipart": return decoder.MultipartDecoder(data, headers['Content-Type'], 'UTF-8') # fetch data from response object if six.PY3: data = data.decode('utf8') try: data = json.loads(data) except: pass return self.__deserialize(data, response_type)
def _postData(cls, mediaType, body): if mediaType and mediaType.mimeType() == 'multipart/form-data': try: multipart_data = decoder.MultipartDecoder(body, str(mediaType)) except ImproperBodyPartContentException: return {} params = [] default_type = None for part in multipart_data.parts: if 'Content-Disposition' not in part.headers: continue if default_type is None: default_type = part.headers.get('Content-Type') _, pdict = cgi.parse_header( part.headers['Content-Disposition']) p = dict(name=pdict.get('name'), contentType=part.headers.get('Content-Type', default_type)) if pdict.get('filename'): p['fileName'] = pdict.get('filename') if 'text/' in p['contentType']: p['value'] = part.content else: p['value'] = b64encode(part.content) params.append(p) return dict(mimeType=str(mediaType), params=params, comment='') return {}
def classify_image(event, context): """Classify image using api. Function is called from this template python: handler.py Args: event: Dictionary containing API inputs context: Dictionary Returns: dictionary: API response Raises: Exception: Returning API repsonse 500 """ try: content_type_header = event['headers']['content-type'] # print(event['body']) body = base64.b64decode(event["body"]) print('BODY LOADED') picture = decoder.MultipartDecoder(body, content_type_header).parts[0] prediction = get_prediction(image_bytes=picture.content) print(prediction) prediction_label = imagenet1000_classidx_to_label(prediction) filename = (picture.headers[b'Content-Disposition'].decode().split(';') [1].split('=')[1]) if len(filename) < 4: filename = (picture.headers[b'Content-Disposition'].decode().split( ';')[2].split('=')[1]) return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True }, "body": json.dumps({ 'file': filename.replace('"', ''), 'predicted': f"{prediction}, {prediction_label}" }) } except Exception as e: print(repr(e)) return { "statusCode": 500, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True }, "body": json.dumps({"error": repr(e)}) }
def _upload_artifacts_callback(self, request): # TODO We should authorise the artifacts first if ( "JOB-TOKEN" not in request.headers or request.headers["JOB-TOKEN"] != self.token ): return (403, {}, json.dumps({"message": "403 Forbidden"})) if self.status != "running": return ( 403, {}, json.dumps({"message": "403 Forbidden - Job is not running"}), ) if self.file_data is not None: return ( 400, {}, json.dumps( {"message": '400 (Bad request) "Already uploaded" not given'} ), ) from requests_toolbelt.multipart import decoder payload = {} for part in decoder.MultipartDecoder( request.body, request.headers["Content-Type"] ).parts: header = ( part.headers[b"Content-Disposition"].decode(part.encoding).split("; ") ) assert header[0] == "form-data" header = {h.split("=")[0]: h.split("=")[1][1:-1] for h in header[1:]} assert header["name"] not in payload if header["name"] == "file": assert len(header) == 2 payload[header["name"]] = (header["filename"], part.content) else: assert len(header) == 1 payload[header["name"]] = part.text file_name, file_data = payload["file"] if "artifact_type" in payload or "artifact_format" in payload: raise NotImplementedError("Not sure what this does") if "expire_in" in payload: pass # TODO I think this should update the job's underlying job_info object # https://gitlab.com/gitlab-org/gitlab-ce/blob/78b3eea7d248c6d3c48b615c9df24a95cb5fd1d8/lib/api/runner.rb#L292 self.upload_artifacts(file_name, file_data) headers = {} response = self.as_dict() return (201, headers, json.dumps(response))
def version_4(event): content_type_header = event['headers']['content-type'] postdata = base64.b64decode(event['body']).decode('iso-8859-1') lst = [] for part in decoder.MultipartDecoder(postdata.encode('utf-8'), content_type_header).parts: lst.append(part.text) upload_to_s3(lst, "image.jpeg")
def classify_image(event, context): try: if (event['httpMethod'] == 'OPTIONS'): return { "statusCode": 200, "headers": { 'Access-control-Allow-origin': '*', 'Access-control-Allow-credentials': True, 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, DELETE', 'Access-Control-Allow-Headers': '*', }, "body": json.dumps({'foo': 'bar'}) } content_type_header = event['headers']['content-type'] #print(event['body']) body = base64.b64decode(event["body"]) print('BODY LOADED') picture = decoder.MultipartDecoder(body, content_type_header).parts[0] face_tensor, probs = extract_align_faces(image_bytes=picture.content) prediction = get_prediction(face_tensor) print("Get Prediction returned:", prediction, type(prediction), class_names[int(prediction)]) predicted_val = class_names[int(prediction)] predicted_str = f'{predicted_val}' content_disp = picture.headers[b'Content-Disposition'].decode().split( ';') filename = content_disp[1].split('=')[1] if len(filename) < 4: filename = content_disp[2].split('=')[1] return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-control-Allow-origin': '*', 'Access-control-Allow-credentials': True }, "body": json.dumps({ 'file': filename.replace('"', ''), 'predicted': predicted_str, 'class': int(prediction) }) } except Exception as e: print("classify_image Exception", repr(e)) return { "statusCode": 500, "headers": { 'Content-Type': 'application/json', 'Access-control-Allow-origin': '*', "Access-control-Allow-credentials": True }, "body": json.dumps({"error": repr(e)}) }
def unwrap_multipart_response(response: Response): """ :param response: :return: """ content = response.content.decode("utf-8") boundary = content.split("\r")[0][2:] content_type = f"multipart/form-data; boundary={boundary}" return decoder.MultipartDecoder(response.content, content_type)
def face_swap_handler(event, context): try: content_type_header = event['headers']['content-type'] body = base64.b64decode(event["body"]) print('content_type header: ' + content_type_header) print('Event Body: ' + event["body"]) #json_body = json.loads(event["body"]) picture1 = decoder.MultipartDecoder(body, content_type_header).parts[0] picture2 = decoder.MultipartDecoder(body, content_type_header).parts[1] im1 = np.frombuffer(picture1.content, dtype=np.uint8) im2 = np.frombuffer(picture2.content, dtype=np.uint8) print('Body Loaded') #picture = decoder.MultipartDecoder(body, content_type_header).parts[0] #print(f'MultipartDecoder processed') swapped_face = fsp.face_swap(im1, im2, PREDICTOR_PATH_68) return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({ 'file': 'swap', 'swapface': img_to_base64(swapped_face) }) } except Exception as e: print(repr(e)) return { "statusCode": 500, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({"error": repr(e)}) }
def face_align(event, context): try: content_type_header = event["headers"]["content-type"] body = base64.b64decode(event["body"]) # if type(event["body"]) is str: # event["body"] = bytes(event["body"], "utf-8") pictures = decoder.MultipartDecoder(body, content_type_header) print(len(pictures.parts)) for picture in pictures.parts: im_ndarray = cv2.imdecode(np.frombuffer(picture.content, np.uint8), -1) print("image_decoded") err, aligned = FD.faceAligner(im_ndarray) print(aligned) filename = picture.headers[b'content-Disposition'].decode().split(';')[1].split('=')[1] if len(filename) < 4: filename = picture.headers[b'content-Disposition'].decode().split(';')[2].split('=')[1] fields = {"face-aligned": base64.b64encode(aligned).decode("utf-8")} return { "statusCode": 200, "headers": { 'content-type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps(fields), } except ValueError as ve: return { "statusCode": 422, "headers": { 'content-type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({"error": repr(ve)}), } except Exception as e: print(repr(e)) return { 'statusCode': 500, "headers": { 'content-type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({"error": repr(e)}) }
def classify_image(event, context): """Take input image from API and classify it.""" try: # Get image from the request if 'Content-Type' in event['headers']: content_type_header = event['headers']['Content-Type'] else: content_type_header = event['headers']['content-type'] body = base64.b64decode(event['body']) print('Body loaded') # Obtain the final picture that will be used by the model picture = decoder.MultipartDecoder(body, content_type_header).parts[0] print('Picture obtained') # Get predictions prediction = get_prediction(image_bytes=picture.content) prediction_name = imagenet_class_names[prediction] print(f'Prediction: {prediction}\tPrediction Name: {prediction_name}') filename = picture.headers[b'Content-Disposition'].decode().split( ';')[1].split('=')[1] if len(filename) < 4: filename = picture.headers[b'Content-Disposition'].decode().split( ';')[2].split('=')[1] return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True }, 'body': json.dumps({ 'file': filename.replace('"', ''), 'predicted': prediction, 'predicted_name': prediction_name, }) } except Exception as e: print(repr(e)) return { 'statusCode': 500, 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True }, 'body': json.dumps({'error': repr(e)}) }
def face_rec(event,context): try: print(event) print(context) content_type_header = event['headers']['content-type'] print(event['body']) body = base64.b64decode(event["body"]) print("BODY LOADED...") picture = decoder.MultipartDecoder(body, content_type_header).parts[0] prediction = get_prediction(image_bytes = picture.content) label = labels[str(prediction)] print(prediction,label) filename = picture.headers[b'Content-Disposition'].decode().split(';')[1].split('=')[1] if len(filename) < 4: filename = picture.headers[b'Content-Disposition'].decode().split(';')[2].split('=')[1] print('filename: '+filename.replace('"','')) return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({'status': 'Predicted' ,'predicted': prediction, 'label': label}) } except ValueError as v: print(v) return { "statusCode": 200, "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Credentials": True }, "body": json.dumps({'status': str(v) ,'predicted': '', 'label': ''}) } except Exception as e: print(repr(e)) return { "statuscode" : 500, "headers" : { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin' : '*', 'Access-Control-Allow-Credentials' : True }, "body": json.dumps({"error": str(repr(e))}) }