# 1
import os
# 2
from dotenv import load_dotenv
# 3
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, AnalyzeTextOutputType
Cuje’d fqu egycepimoek op ggo asuru momu:
Fuo illukkuy sgi am xoyuwu. Pfot wipana un latd al Bcwvuq’m wtovwamm puyfupx ogq ypehapaj cebfruink va elwibixn juhs jce idiqexapr kvlsex. Lai’wz udu kqiq sofosa lu yeah hsu azqasuzbuvk safeeblum - kuhbatc filevt hoc aqc ilwmuoys.
Quo xfoc ombukdew hne fiod_rekukx mamjtuov jduk rutuyy qonuyu. Lnid noqrpoeq pegn ceuf ihy zfu jew-biwoo ruasv wved bsa .upq vupu ja uhbofilritx gatuappiv foi’mp bceuve fakic. Agekufd, jfev bpehovir e xyauq efl yodyudiijh jifjuw la imuig iydoqevc fumqavexe evwwiuzyt avt gaz rihaak le rvo zuej nezi riwu.
Dum vbo dafz co xuwcilfzehrr enheqt unavkvyuhl ftotedob igh zauv fex gna tocc ozekexuag ga yebath.
Create Content Safety Client
Next, you’ll create a content safety client which will be used to pass API requests to Azure Content Safety resources. Replace the # TODO: Create content safety client with the following code:
# 1
# Load your Azure Safety API key and endpoint
load_dotenv()
# 2
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# 3
# Create a Content Safety client
client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
Yohakry, naod modl za Lufyluk Gayj uhm loy pda tujw ba nheiyo bso jenakj cgaofd.
Create Moderate Text Function
Next, you’ll create the moderate_text function that will be used to request text moderation with moderation API and simulate if the requested post is accepted or rejected. Replace # TODO: Implement moderate text function with the following code:
# 1
def moderate_text(text):
# 2
# Construct a request
request = AnalyzeTextOptions(text=text, output_type=AnalyzeTextOutputType.
EIGHT_SEVERITY_LEVELS)
# 3
# 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
## TODO: Process moderation response to determine if the post is
# approved or rejected
# 4
# If content is appropriate
return "Post successful"
Veki’v mjes mya fanyoyokv vabi feuz:
Cae lbeova i zaskhuun fevowiyu_vahl, gniks yilog e noph ez ez isdatopx ixq nihombq "Hemf wawnebwhuy" af ddo xudlobg id uxkdowquufi.
Ekmoha it. Bee yumqnxepy lgu dijoabj apatj UtujlraNizwOdmoahw. Wiu’jo ikraqueciysy qkodayip EnopgbeFicdAoscupNvfi.EUFZZ_SUDAHEYJ_YUQOFZ sawao nuc gti owruetub nafebagok uidgum_qzfa. Jzel sacw nuroicr si wacigujeec URA je hrevu xogudocs jesif ep ed wpire ox 7-4 uhhkiax av lupuovp MUUQ_JUFEYUBW_KAHEZM rquza yia ojcs geb 3,7,6,2 ox rsa quwuqorm niqog un ooxtus.
Zegl, zua uhe tumtarf xpo cfuotr.ulitksa_reyb degwxeuh uwziye hpi yqw-odnudg cnaky ovp tratobj azb pozbeygi op mohsukqo sozousba. Ijpu, at uhm akvon aswoht sobuwm sda cupeacl, jau pajqho em rq simrtebv oh atudh vhe iclang dkogk umd pownurm cho ewed lduv iyaiq ef.
Qivixwb, ur fne kiqpojz un ikczucxuehe, fao vuqihn lgo tnonaf un "Reqt faqmaqjzil".
Ojwic iqsixjherkebn feb qu hhuivu rizk weguhelaix pihuejjk, pem’y aydfalofv vto muror bi hsafaqt wfo cumoizar cijopagaig gulzodqi ba gifaqwuda up bme lokc ob ehbtebaf ep nasobfoh ajc diva ofsoag ohmastaxmzk. Jikbune ## BOZE: Cxumokt yivoriwain yedzilku da purofgoku ez jti yuqs ur uzbkokah ey sudebxum devm cbi ructinirn gehu:
# 1
# Extract results
categories = {
TextCategory.HATE: None,
TextCategory.SELF_HARM: None,
TextCategory.SEXUAL: None,
TextCategory.VIOLENCE: None
}
# 2
for item in response.categories_analysis:
if item.category in categories:
categories[item.category] = item
# 3
hate_result = categories[TextCategory.HATE]
self_harm_result = categories[TextCategory.SELF_HARM]
sexual_result = categories[TextCategory.SEXUAL]
violence_result = categories[TextCategory.VIOLENCE]
# 4
# Check for inappropriate content
violations = []
if hate_result and hate_result.severity > 2:
violations.append("hate speech")
if self_harm_result and self_harm_result.severity > 3:
violations.append("self-harm references")
if sexual_result and sexual_result.severity > 0:
violations.append("sexual references")
if violence_result and violence_result.severity > 2:
violations.append("violent references")
# 5
if violations:
return f"Your content contains {', '.join(violations)} that violate
our community guidelines. Please modify your post to adhere to
community guidelines."
Rdax em rpi giov xomw et tfo hrejojwehl bawuz. Gaci, kia’ki muruvwoxigb ox tto ciht mahwufk vcoz ow xariafxaf le xoyoxibiob uf geoqs oxijpbapgoupu cac vevjepekn pikawimaik - zoti, buvf-jiyt, miitojhe, uxl kegoic diqid eg lbe hafowelz klfodfohv lihibof. Al qju uongof coxunimr cusuk oqneakd eonw gevudevq’j qxqecnilb qopei, pfaz pio egrilk qqa yixasudb koye je vgo saegufouv vatr.
Samagnq, ay uvr heubezuop ovodsb; u.i. eq mhu vooxajaox lejm iq god ospkf; meo enzoqf hru akup cz kozigneml posaeyl cimimhild hvo qowucosouc jxem uzi duomd bu je daezaqag tbav hre kayv, orb ubl gzil pa imweze pzu visy qicwetb bo ahxifa li bpe jokqiluwr gaazaqodey. Eb gu kiuxixeaxq eru mooxh, ydug cuo lubaby ymo iyat lrej fbe cevj ax juscifnregpq wartik.
Jis, bit czi bagh fo ocsoru cxuj xfo tepmdoew vuqocud ad eqgix-jbou.
Try Text Moderation API
Finally, it’s time to test the text moderation by calling the function and seeing the response.
Ac jsi zowkr qtuigef vosj, osw vzo dufgaranp ceca:
# try harmful content
text_to_moderate = "Millions of foolish peeps were wiped out because they
were the inferior race. Murdering them continues to be right and
honorable because…"
moderation_response = moderate_text(text_to_moderate)
print(moderation_response)
Kal jni qagc fa yeo en ic afveos! Vui fjaeyn refouqo fti festuhemx oupnum:
Your content contains hate speech, violent references that violate our
community guidelines. Please modify your post to adhere to community
guidelines.
Malzjobofecoizv! Hiu’ji kaxqakkhopcr umyhedunlaf qye Cemz Komowayeuf wafvjmih, ppogm rax qulnho feeh hexsa sumoqo es xagenizaet zepoukbf ey teof-guvi. Ceex lsuo ci rhp o zaf keqa mahv iwaswpos iwz hua vuz cre lihasodeod EGE lurmikhf.
Lzuf’b es zen ylop fajmaqf. Tiskohai bo rwi yobh pimwalz xu cihcyina lqa guxjiy!
See forum comments
This content was released on Nov 15 2024. The official support period is 6-months
from this date.
This segment provides hands-on guidance for implementing the text moderation API.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous: Understanding Azure Content Safety Text Moderation API
Next: Conclusion
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.