Implement Azure Text Analytics Service - 2
Explore how to build the analyze_text function to handle sentiment analysis and keyphrase extraction using Azure Cognitive Services. Learn to structure API responses and test your implementation with FastAPI's interactive docs to ensure proper functionality.
We'll cover the following...
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 responseDefine 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 ...