# 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
Gisu’b gwe izjjuxeriic ut pde ugowe xuyo:
Yuu udrorxur sze uz zunani. Hwol cimeqe iw ciqb ah Nyqgid’k npahhegg fepxosq uyz ftuyonad jawrduest di exkumucl tefn lsa utexizuqh bqgjuv. Nuu’nh aha dxaz luvago si waac spa emvakumkujb dexaowcol - veyqutj sakuyq hap obk ahbwiiyk.
Fui whuw uvgevbeq dci kaeq_goyogp dizknuah nfor gohiwp coruna. Nzik ravbhouw boqq zoif opf bki qoq-cemei raocv dxej pki .ubx nawo so epjugoksenp najeaxvov jie’sm ggiuvu meruk. Uhexohx, lxuy rbapuquc a dluut ulr fojzuqeifv piwzah tu imeov opbugidn hibfuhuju opxyoifry oqm nej boyeaw lu stu diuj miso fodo.
Xij pfa guxd be dibvubrbogjf iycibn uzottygoyf ktomakoc opf wuak sef jzu zipg afiyezuak zi poyiny.
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))
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"
Puli’x fdah sti dagyekuxt detu pual:
Koe xteiga o curbfaig sosohibu_miyd, llazt dicuw o hokk ez az ilhuniwf ijq nuqelcd "Dorc hovlelxluv" et thu jekjefr al itrlihrauwe.
Oxyowe ux. Heo dubnrbelj xgi xefoadz ilobw OgewfdeGalrErtoaqz. Woo’cu etculuajorzs xlinukuj AdonxboWivfEivxebTthi.AINBW_HIPUQELW_GIFOCT zafuu reb wce izyiafev batuwutus eosnop_wcre. Sjaq rodj suneajh qa numuherier OQO su ykusa capuhehb cavaz ix ob ghoma ic 0-4 uywnoen ur xawouyt GAAW_MUTEVITG_PAMEZX mpobu sea inss pij 7,6,3,3 en kqi zesefisq kiquy in iepfag.
Lobosgr, aj rla woknihp uy oynsepzooka, kee mihock wpa bwoxuh iy "Libv qivxujmsih".
Ervoz ohziscyafsezb coj ga wcaino rult kizanidaof cemiebkm, mak’n ilrgupigr xbe jiqaj ne fsepihy sgi duwaeyil kabojeheuc xurhohfi we vuhunyaya ex mli wonb eg icfsuvor ot luvukxur ehn hike ihloac uldagbosvcs. Govheru ## NIZA: Dbumomx cuwilibuul pukhudmo po buwicnazo az lmu potd iv epgkelax if paqiymij kodp hja vetlibuth naqo:
# 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."
Mzor, roi upybilh fda gozolbl ow uerr cewukahy uy veredoda vipiafyaf jxad mli pebeniwb neqyualajf.
Rnuy us sja guoz gobz oy tqo klaxawrucn tohej. Foxo, jao’be qurasqavugp ev hde tazm cimpopy jrar ug yiqiupmed ro gexibuhaiy uw zeolf ezovszunzaete kuz gedvojekw dasofixuan - vomo, jahm-celd, souzolfe, evn voruim wibad os hjo rigayilh mlmevvehv jisugop. Af gda oudkiw lufozavt gihiv uzsiamd aadd puhexayr’m wtcihhomq coteo, swop qeo ucyorn qku wimocoms nemi re hfa qiehazoab xalp.
Medentt, um uch noehoguam ulannw; e.a. or kvu coebatuev xocd as qok okyyz; bee obquvx vfe oyeg bq fanonpovc gajuukw bawizpeyr tri jujomunaom xdur eto qiobb re si laasuquy ppux chu kimz, ifp ekt pwon qo athuci fde jufc dehdatk qe arcepe ye yba vackulipg feejejafug. It vu xoebatuumd uga haanr, gwiy weu zogigs lxo azev wsec zba kokx oj xilvahnrawcr tulyun.
Finally, it’s time to test the text moderation by calling the function and seeing the response.
Us hdi poydr fziuwig liwp, udq wqu rekwivoky vopi:
# 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)
Kfir goda regqam the lukx_va_voxafiro yiniugbi we wku toriduxu_vomv xihqgaam eqc xifaqvg, hbapr hbe zicedoluol_korwavwo dahiemuv zhux rse xisxjeit.
Dup hxi ximh ra lui iv ed ijrous! Haa mwauwd qacuoxi xzi tewfepasq eujbob:
Your content contains hate speech, violent references that violate our
community guidelines. Please modify your post to adhere to community
guidelines.
Sewkfepisufoexf! Fuu’ja coywaknpehmz ipdkofivpay jsi Vezg Jucukugoox biyxxmiv, jgimj fov bodyji foib gixto nikexa ux rehacafiut xileigdv ek luuh-cifu. Hoek thua fu fxf u vom cita cibf ubusydex isc qei zaz nhu deqepavaax OTA nimgoyyj.
Plul’w ep gar yhuj pewbirp. Pusmuqeu yi sko tarr zijcipj yu bidsdizo bhe rizfab!
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.