This is the second part in the article series "Python Flask App and Azure Cognitive Services Read API". In the first article [
Render HTML Page And File Transfer Between Client And Server] which you can access by clicking
Here. we were able to build a HTML Page and a basic Python Flask app which enables the user to upload and download a file. In this article we are taking the file uploaded by the user and calling the Read API to get the analyzed results form the API as JSON string.
Before we Start
Before we start working on code we need a subscription key and endpoint to call Read API. If you don't know how to get it, follow the
official documentation for step by step guidance on how to create single service resource of Computer Vision.
We also need to install request module for POST request to call Read API and python-csv module to create and save csv files. For this installation we can use pip install. The following code does this.
- pip install requests
- pip install python-csv
Integrating Read API
First set the subscription key and endpoint to variables which you get from the Azure portal.
- endpoint = "https://xxxxxxxxx.cognitiveservices.azure.com/"
- subscription_key = "xxxxxxxxxxxxxxxxxxxxxxxxxx"
We need to import json and csv modules for manipulating with JSON & CSV file types. Also requests and time modules for POST request to Read API and sleep function respectively. The following is the updated import statements.
- from flask import Flask,request, render_template,send_from_directory,redirect
- import json
- import os
- import requests
- import time
- import csv
Now use the below function get JSON which is taking the file as input and analyzed JSON string as output after calling the Read API.
- def getJSON(image_data):
- text_recognition_url = endpoint + "/vision/v3.0/read/analyze"
- headers = {'Ocp-Apim-Subscription-Key': subscription_key,
- 'Content-Type': 'application/octet-stream'}
- response = requests.post(
- text_recognition_url, headers=headers, data=image_data)
- response.raise_for_status()
- operation_url = response.headers["Operation-Location"]
- analysis = {}
- poll = True
- while (poll):
- response_final = requests.get(
- response.headers["Operation-Location"], headers=headers)
- analysis = response_final.json()
- if ("analyzeResult" in analysis):
- poll = False
- if ("status" in analysis and analysis['status'] == 'failed'):
- poll = False
- return analysis;
Now we write a saveAsCSV function which takes table/row as input and appends to a file (here output.csv). If you like to clear and rewrite the file replace a+ with w+. The + is optional, if + is used the file will be created if it does not exist.
CSV is actually an abbreviation for comma separated values, each column is separated by comma and rows by space. It can be opened with any text editors or office sheet editors like MS Excel.
- def saveAsCSV(table):
- with open("output.csv", 'a+', newline='') as file:
- writer = csv.writer(file)
- writer.writerows(table)
We now need to update the upload_file function which we created in the previous article. Replace the return redirect statement of third if (ie: under if file: ) as below,
- analysis=getJSON(file)
- row=[]
- table=[]
- for page in analysis['analyzeResult']['readResults']:
- for word in page['lines']:
- row.append(word['text'])
- table.append(row)
- row=[]
- saveAsCSV(table)
- return redirect('/uploads/'+'output.csv')
Explanation
We call the getJSON function and pass the file to read (here file variable) as argument. Then set the response to a variable (here we set to analysis). And declare and set row and table variables as empty lists. Here we use the row list to store a row and table list to store these rows ie; table is of type list of lists. An item in analysis
'analyzeResult
' list corresponds to a page and the ['lines'] inside this item corresponds to each sentence identified. The ['text'] inside this gives the text of a sentence , ['boundingBox'] gives the 8 coordinates of the sentence and ['words'] gives information related to each word. Here in our use case we need only the ['text']. We append this to the row for each sentence. We append each row to table for each page and set the row to empty. Now we call the saveAsCSV function we already defined by passing the 'table' variable.We are now done with the changes needed server side. Some changes are needed in the client side; i.e., in home.html here for accepting the return file.
Yep! We are now done with the application. Our Flask application should be able to upload your pdf/image and return the csv file containing the text. The CSV file will have each sentence in each column and each page in each row.
Deploy to Azure
Now you can deploy this app to Azure as a free web app. For that you want to install Azure CLI from
here. (There are other methods but I would recommend to follow this.) Download and install the same and check if it's successfully installed by the command,
The version should be 2.0.80 or higher.
Now login to Azure in CLI using the following command,
This will open a browser window to enter login credentials and after successful login CLI will display the subscription info as a JSON String.
Now you are ready to deploy your app. You can do the same with following command,
- az webapp up --sku F1 -n <YourAppName>
F1 refers to free tier and you should replace <YourAppName> with your app name. You can give any name to your app but it should be unique across Azure and you can use all lower case alphabets, numbers & special character '-'. There is a best practice that is followed by most developers in naming the app, that is starting with the company name. There are additional optional arguments like location that can be included. You can check the documentation for more info on this.
This process takes 5-20 minutes depending on the file size and bandwidth. After successful deployment you will see a JSON string with details of application.
Yep! Your app is now deployed as a Python app to App Service on Linux in Azure and available over internet for users. Now to browse to the deployed application in your web browser using the URL http://<YourAppName>.azurewebsites.net.
If you have made any changes and would like to update it on Azure you can do it using the below command,
Congrats... We are now done with building a Python Flask App which is integrated with Read API and published it on Azure.
The code below is the final code in app.py and home.html as of now.
app.py
- from flask import Flask,request, render_template,send_from_directory,redirect
- import json
- import os
- import requests
- import time
- import csv
-
- endpoint = "https://xxxxxx.cognitiveservices.azure.com/"
- subscription_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
- dirname = os.path.dirname(__file__)
- app = Flask(__name__)
-
- def saveAsCSV(table):
- with open("output.csv", 'a+', newline='') as file:
- writer = csv.writer(file)
- writer.writerows(table)
-
- def getJSON(image_data):
- text_recognition_url = endpoint + "/vision/v3.0/read/analyze"
- headers = {'Ocp-Apim-Subscription-Key': subscription_key,
- 'Content-Type': 'application/octet-stream'}
- response = requests.post(
- text_recognition_url, headers=headers, data=image_data)
- response.raise_for_status()
- operation_url = response.headers["Operation-Location"]
- analysis = {}
- poll = True
- while (poll):
- response_final = requests.get(
- response.headers["Operation-Location"], headers=headers)
- analysis = response_final.json()
- if ("analyzeResult" in analysis):
- poll = False
- if ("status" in analysis and analysis['status'] == 'failed'):
- poll = False
- return analysis;
-
- @app.route('/uploads/<filename>')
- def uploaded_file(filename):
- return send_from_directory(dirname,
- filename)
- @app.route('/')
- def home():
- return render_template('home.html')
-
- @app.route('/uploader', methods=['POST'])
- def upload_file():
- if 'file' not in request.files:
- return redirect(request.url)
- file = request.files['file']
- if file.filename == '':
- return redirect(request.url)
- if file:
- analysis=getJSON(file)
- row=[]
- table=[]
- for page in analysis['analyzeResult']['readResults']:
- for word in page['lines']:
- row.append(word['text'])
- table.append(row)
- row=[]
- saveAsCSV(table)
- return redirect('/uploads/'+'output.csv')
- return ''
-
- if __name__ == '__main__':
- app.run(debug=True)
home.html
- <html>
- <body>
- <form id="fileUploadForm" method='post' enctype='multipart/form-data' action='/uploader'>
- <input type="file" name="file" id="fileSelect">
- <button type="submit" id="btnSubmit">Upload</button>
- </form>
- </body>
- </html>
In the next article we will see how we can send an html table instead of the CSV file and how we can return multiple values as JSON string from server to client using AJAX and JQuery.