1+ import logging
2+ import cv2
3+ import numpy as np
4+ import json
5+ import os
6+ import base64
7+ import logging
8+ import azure .functions as func
9+
10+
11+ def main (req : func .HttpRequest ) -> func .HttpResponse :
12+ logging .info ('Python HTTP trigger function processed a request.' )
13+
14+ try :
15+ body = json .dumps (req .get_json ())
16+ except ValueError :
17+ return func .HttpResponse (
18+ "Invalid body" ,
19+ status_code = 400
20+ )
21+
22+ if body :
23+ logging .info (body )
24+ result = compose_response (body )
25+ return func .HttpResponse (result , mimetype = "application/json" )
26+ else :
27+ return func .HttpResponse (
28+ "Invalid body" ,
29+ status_code = 400
30+ )
31+
32+
33+ def compose_response (json_data ):
34+ values = json .loads (json_data )['values' ]
35+
36+ # Prepare the Output before the loop
37+ results = {}
38+ results ["values" ] = []
39+
40+ for value in values :
41+ output_record = transform_value (value )
42+ if output_record != None :
43+ results ["values" ].append (output_record )
44+ return json .dumps (results , ensure_ascii = False )
45+
46+ ## Perform an operation on a record
47+ def transform_value (value ):
48+ try :
49+ recordId = value ['recordId' ]
50+ except AssertionError as error :
51+ return None
52+
53+ # Validate the inputs
54+ try :
55+ assert ('data' in value ), "'data' field is required."
56+ data = value ['data' ]
57+ base64String = data ["image" ]["data" ]
58+ base64Bytes = base64String .encode ('utf-8' )
59+ inputBytes = base64 .b64decode (base64Bytes )
60+ jpg_as_np = np .frombuffer (inputBytes , dtype = np .uint8 )
61+ originalImage = cv2 .imdecode (jpg_as_np , flags = 1 )
62+ slices = []
63+ for line in data ["layoutText" ]["lines" ]:
64+ slicedImage = originalImage [line ["boundingBox" ][0 ]["x" ]:line ["boundingBox" ][0 ]["y" ], line ["boundingBox" ][3 ]["x" ]:line ["boundingBox" ][3 ]["y" ]]
65+ if (slicedImage .size > 0 ):
66+ is_success , im_buf_arr = cv2 .imencode (".jpg" , slicedImage )
67+ byte_im = im_buf_arr .tobytes ()
68+ base64Bytes = base64 .b64encode (byte_im )
69+ base64String = base64Bytes .decode ('utf-8' )
70+ aslice = { "$type" : "file" ,
71+ "data" : base64String
72+ }
73+ slices .append (aslice )
74+
75+
76+ except AssertionError as error :
77+ return (
78+ {
79+ "recordId" : recordId ,
80+ "errors" : [ { "message" : "Error:" + error .args [0 ] } ]
81+ })
82+
83+
84+
85+ return ({
86+ "recordId" : recordId ,
87+ "data" : {
88+ "slices" : slices
89+ }
90+ })
0 commit comments