Skip to content

Instantly share code, notes, and snippets.

@chenxizhang
Created August 17, 2023 23:53
Show Gist options
  • Save chenxizhang/9277e453064baef66b139313e950a19a to your computer and use it in GitHub Desktop.
Save chenxizhang/9277e453064baef66b139313e950a19a to your computer and use it in GitHub Desktop.
This is a simplest web app, people can upload an image and get prediction by azure custom vision serivce
from flask import Flask, render_template, request
from dotenv import load_dotenv
import os
import requests
app = Flask(__name__)
load_dotenv()
def classify_image(image_data):
endpoint = "https://japaneast.api.cognitive.microsoft.com/customvision/v3.0/Prediction/44bd0c2b-20c3-43d9-9805-2f5de1476c3b/classify/iterations/Iteration2/image"
headers = {
"Prediction-Key": os.getenv("PredictionKey"),
"Content-Type": "application/octet-stream",
}
response = requests.post(endpoint, headers=headers, data=image_data)
return response.json()
@app.route("/", methods=["GET", "POST"])
def home():
if request.method == "POST":
# get the uploaded file and read its contents
file = request.files["file"]
image_data = file.read()
# classify the image and get the top 2 tags
result = classify_image(image_data)
tags = [f"{x['tagName']}: {x['probability']:.2%}" for x in result["predictions"][:2]]
# render the results template with the tags
return render_template("results.html", tags=tags)
# render the home page template
return render_template('home.html')
if __name__ == "__main__":
app.run(debug=True)
@chenxizhang
Copy link
Author

To run the app, you need to install below dependencies.

pip install flask python-dotenv requests

@chenxizhang
Copy link
Author

chenxizhang commented Aug 17, 2023

Create a templates folder in the root, and create two html files.

home.html

<!DOCTYPE html>
<html>
  <head>
    <title>Image Classifier</title>
  </head>
  <body>
    <h1>Image Classifier</h1>
    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="Upload">
    </form>
  </body>
</html>

results.html

<!DOCTYPE html>
<html>
  <head>
    <title>Image Classifier Results</title>
  </head>
  <body>
    <h1>Image Classifier Results</h1>
    <p>Top 2 tags:</p>
    <ul>
      {% for tag in tags %}
      <li>{{ tag }}</li>
      {% endfor %}
    </ul>
    <a href="/">Try again</a>
  </body>
</html>

@chenxizhang
Copy link
Author

Create a .env file in the root, put the below content in the file.

PredictionKey=Yourkey

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment