Skip to content

Instantly share code, notes, and snippets.

@riston
Created January 8, 2017 18:55
Show Gist options
  • Select an option

  • Save riston/59cbe7f10d83012dba9b52abf4251812 to your computer and use it in GitHub Desktop.

Select an option

Save riston/59cbe7f10d83012dba9b52abf4251812 to your computer and use it in GitHub Desktop.

Revisions

  1. riston created this gist Jan 8, 2017.
    66 changes: 66 additions & 0 deletions vision-detect.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@

    from io import BytesIO
    import requests
    import dropbox
    import time
    import sys
    import os

    IMG_PATH = "/var/images"
    MS_VISION_BASE_URL = "https://api.projectoxford.ai/vision/v1.0/analyze"
    MS_VISION_API_KEY = os.environ.get("MS_VISION_API_KEY")

    DROPBOX_API_KEY = os.environ.get("DROPBOX_API_KEY")

    def analyse_image(file_data):
    headers = {
    "Content-Type": "application/octet-stream",
    "Ocp-Apim-Subscription-Key": MS_VISION_API_KEY
    }

    params = {
    "visualFeatures": "Categories,Tags,Description,Faces"
    }

    response = requests.post(MS_VISION_BASE_URL,
    params=params, headers=headers, data=file_data)
    return response.json()

    def upload(file_path):
    t_now = time.time()

    try:
    with open(file_path, "rb") as image_file:
    content = image_file.read()
    response = analyse_image(content)
    print(response)

    # Do nothing if no tags in response has been set
    if "tags" not in response:
    return

    # # Get the name
    if "description" in response and "captions" in response["description"]:
    captions = response["description"]["captions"]
    caption = captions[0] if len(captions) > 0 else ["not-set"]
    file_name = "image-%s-%s.jpg" % (caption["text"], t_now)

    # # Search for person tag
    for tag in response["tags"]:
    if tag["name"] == "person" and tag["confidence"] >= 0.85:
    print("We found some person forward this")
    dbx = dropbox.Dropbox(DROPBOX_API_KEY)
    dbx.files_upload(content, "/images/%s" % file_name)

    except Exception as err:
    print("Failed to upload\n%s" % err)
    print(err)

    def main():
    file_path = sys.argv[1:][0]
    print("File full path '%s'" % file_path)

    upload(file_path)

    if __name__ == "__main__":
    main()