Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Microsoft ❤️Python

Microsoft ❤️Python

This my keynote presentation given at PyConf++ 2020 Russia Online. I demonstrate a few different scanarios of using Python in Microsoft Azure, including Azure Notebooks, Cognitive Services, Bot Framework, Azure Functions and Storage. During the session, we togehter build an interactive virtual science art exhibit in the form of a telegram chatbot. The bot may still be available for you to try at @PeopleBlenderBot in Telegram.

Dmitri Soshnikov

March 27, 2020
Tweet

More Decks by Dmitri Soshnikov

Other Decks in Programming

Transcript

  1. import mPyPl as mp images = ( mp.get_files('images',ext='.jpg') | mp.as_field('filename')

    | mp.apply('filename','image’, lambda x: imread(x)) | mp.apply('filename','date', get_date) | mp.apply(['image','date'],'result’, lambda x: imprint(x[0],x[1])) | mp.select_field('result') | mp.as_list)
  2. def affine_transform(img,attrs): mc_x = (attrs['mouth_left']['x’]+ attrs['mouth_right']['x'])/2.0 mc_y = (attrs['mouth_left']['y’]+ attrs['mouth_right']['y'])/2.0

    tr = cv2.getAffineTransform(np.float32([( attrs['pupil_left']['x’], attrs['pupil_left'][‘y’], (attrs['pupil_right']['x’], attrs['pupil_right']['y']), (mc_x,mc_y)]), target_triangle) return cv2.warpAffine(img,tr,(size,size))
  3. $ pip install botbuilder-core $ cookiecutter https://github.com/microsoft/botbuilder- python/releases/download/Templates/echo.zip $ pip

    install -r requirements.txt $ python app.py async def on_message_activity(self, turn_context: TurnContext): await turn_context.send_activity(f"You said '{ turn_context.activity.text }'")
  4. $ func init coportrait –python $ cd coportrait $ func

    new /-name pdraw /-template "HTTP trigger“ $ func start
  5. def main(req:func.HttpRequest) > func.HttpResponse: logging.info('Execution begins…') name = req.params.get('name') if

    name: return func.HttpResponse(f"Hello {name}!") else: return func.HttpResponse( “Need name query parameter", status_code=400) { "scriptFile": "/_init/_.py", "bindings": [ { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ]}, { "type": "http", "direction": "out", "name": "$return" }]}
  6. blob = BlockBlobService(account_name=acct_name, account_key=acct_key) body = req.get_body() sec_p = int((end_date-datetime.datetime.now()).total_seconds())

    name = f"{sec_p:09d}-"+time.strftime('%Y%m%d-%H%M%S') blob.create_blob_from_bytes("cin",name,body) img = imdecode(body)
  7. cogface = cf.FaceClient(endpoint,CognitiveServicesCredentials(key)) res = cogface.face.detect_with_stream(io.BytesIO(body), return_face_landmarks=True) if res is

    not None and len(res)>0: tr = affine_transform(img,res[0].face_landmarks.as_dict()) _,body = cv2.imencode('.jpg',tr) blob.create_blob_from_bytes("cmapped",name,body.tobytes())
  8. imgs = [ imdecode(blob.get_blob_to_bytes("cmapped",x.name).content) for x in itertools.islice(blob.list_blobs("cmapped"),10) ] imgs

    = np.array(imgs).astype(np.float32)/255.0 res = (np.average(imgs,axis=0)*255.0).astype(np.uint8) b = cv2.imencode('.jpg',res)[1] r = blob.create_blob_from_bytes("out",f"{name}.jpg",b.tobytes()) return func.HttpResponse(f"https://{act}.blob.core.windows.net/out/{name}.jpg")
  9. $ func azure functionapp publish <name> az functionapp create /-resource-group

    <group> /-os-type Linux /-consumption-plan-location westeurope /-runtime python /-runtime-version 3.7 /-functions-version 2 /-name <APP_NAME> /-storage-account <STORAGE_NAME>
  10. api_url="https://coportrait.azurewebsites.net/api/pdraw?code=..." async def on_message_activity(self, turn_context: TurnContext): a = tc.activity if

    a.attachments is not None and len(a.attachments)>0: url = a.attachments[0].content_url r = requests.get(url) res = requests.post(api_url,data=r.content) url = res.text message = MessageFactory.attachment( CardFactory.hero_card( HeroCard(title="Here is your cognitive portrait", images=[CardImage(url=url)]))) await tc.send_activity(message) else: await tc.send_activity(f"Please attach a photograph")
  11. $ func azure functionapp publish <name> az functionapp create /-resource-group

    <group> /-os-type Linux /-consumption-plan-location westeurope /-runtime python /-runtime-version 3.7 /-functions-version 2 /-name <APP_NAME> /-storage-account <STORAGE_NAME>