...
/Implement Azure Text Analytics Service - 2
Implement Azure Text Analytics Service - 2
Create your REST API using the Azure Text Analytics Service.
We'll cover the following...
Define the analyze_text()
function
In the previous lesson, we have already created the structure of the API
. We are only left with writing the function that will handle the POST
route. Let us see the code now.
from fastapi import FastAPI from pydantic import BaseModel import utils app = FastAPI() # headers = { # "Ocp-Apim-Subscription-Key": <SUBSCRIPTION_KEY>, # "Content-Type": "application/json", # "Accept": "application/json" # } class Model(BaseModel): text_to_analyze: list @ app.post("/") def analyze_text(text: Model): response = {"sentiment": [], "keyphrases": []} no_of_text = len(text.text_to_analyze) for i in range(no_of_text): document = {"documents": [{"id": i+1, "language": "en", "text": text.text_to_analyze[i]}]} sentiment = utils.call_text_analytics_api(headers, document, endpoint='sentiment') keyphrases = utils.call_text_analytics_api(headers, document, endpoint='keyPhrases') response["sentiment"].append(sentiment["documents"][0]) response["keyphrases"].append(keyphrases["documents"][0]) return response
Define the analyze_text() function
Explanation
-
All the code is the same. We will only understand the function
analyze_text()
. -
On line 18, we define the structure of the response. The structure of the response is going to be: ...