Azure AI services - Content safety - Text Analysis with Azure AI Content Safety:
#pip install azure-ai-contentsafety
import
os
from azure.ai.contentsafety import ContentSafetyClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
def
analyze_text():
key = "6IblsP7u6dukqD3iQCxQcaOWDADIJQQJ99BAACYeBjFXJ3w3AAAHACOGqVgn"; #"CONTENT_SAFETY_KEY"
endpoint = "https://contentsafety1.cognitiveservices.azure.com/"; #"CONTENT_SAFETY_ENDPOINT"
# Create an Azure AI Content Safety client
client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
# Contruct request
request = AnalyzeTextOptions(text = "Hi, How are you!. you are ugly. I hate you.")
# Analyze text
try:
response = client.analyze_text(request)
except HttpResponseError as e:
print("Analyze text failed.")
if e.error:
print(f"Error
code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
hate_result = next(item for item in response.categories_analysis if item.category == TextCategory.HATE)
self_harm_result = next(item for item in response.categories_analysis if item.category == TextCategory.SELF_HARM)
sexual_result = next(item for item in response.categories_analysis if item.category == TextCategory.SEXUAL)
violence_result = next(item for item in response.categories_analysis if item.category == TextCategory.VIOLENCE)
if
hate_result:
print(f"Hate
severity: {hate_result.severity}")
if self_harm_result:
print(f"SelfHarm
severity: {self_harm_result.severity}")
if sexual_result:
print(f"Sexual
severity: {sexual_result.severity}")
if violence_result:
print(f"Violence
severity: {violence_result.severity}")
if __name__ == "__main__":
analyze_text()
OutPut:
from azure.ai.contentsafety import ContentSafetyClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
key = "6IblsP7u6dukqD3iQCxQcaOWDADIJQQJ99BAACYeBjFXJ3w3AAAHACOGqVgn"; #"CONTENT_SAFETY_KEY"
except HttpResponseError as e:
if e.error:
print(f"Error message: {e.error.message}")
raise
print(e)
raise
self_harm_result = next(item for item in response.categories_analysis if item.category == TextCategory.SELF_HARM)
sexual_result = next(item for item in response.categories_analysis if item.category == TextCategory.SEXUAL)
violence_result = next(item for item in response.categories_analysis if item.category == TextCategory.VIOLENCE)
if self_harm_result:
if sexual_result:
if violence_result:
No comments:
Post a Comment