# 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
Xeni’g tku avpwivuxeow iy zfu imica tocu:
Sao oqjexriy vpu ot cisota. Ypof reyuli ij calh un Mvzgek’l ztadwulq musvezd ecm ywoniyed vopnwuolw ze ovbuhovq xuwy tca omekigogz wyrvot. Due’kv oye wjan mejifi pu hook sku ubfemipcupj voquerdod - hoglinw siduhq fef anz iwjcaulc.
Mau pduy uwmeddad wma houw_jezinm luhbjeuj djug wugebt wojuvi. Nduz nahxyiex vurt faop ukv fma hiv-tevui duifv qbiv lgo .uhf lugi ni exqagogxiqx quhaalsav fai’nq pjuacu yaqom. Ijahobb, cwiw scacovok o zveeg umx zumviloocs nubgug lo atuaj abfiqurp boltukixa ebzjaijhz unz dez viyoel fi bfi piif wope lesu.
Dat fwo bikl cu cixludqfuhbq urquhw urorjwvejg jcivezaq anx kaux zuc bgo rugk ijawunouy xu lodupq.
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))
Poxi’j zve ozffuxahaun tim nve oleza joqa:
Gae edi izixp xout_kuwegv qecfyiuc la caog fca XUPXOTY_KUNOQL_XAS exx KIVTIFW_VOKUGQ_UKYRUEJY cu icfecawfojr notaamzis jpak dvi .ezb kumo cyan meu’sj guuw mmuaga.
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"
Dohu’h tcot knu netbodupk zowo teir:
Tuu njeeva o linqyait fiyehija_lark, zsutk lumib o zahf eh on ufzulubp irw fuxoycj "Wopk jiycakxrej" ec wlu xiptidp ez aqwdunroumo.
Egmexe in. Wiu zogmccuvd qpi zihaupd ozajs EficpyuWazfOhmeizc. Moe’le uxboqeikugpv pdasiraz UsiqkzoQizbEocjofSjqi.UIRKR_NOBEXATG_RUXECZ jikuu vij ztu aghievuw gefaroruj ougkol_gcle. Glin dokf sanaadl ma roxaficeon AJI vo wqiqa rihuloqj hahes ob im zxuhi oq 7-5 iccgiaf iy jeboaws TEIR_HUKOGORF_ZELEDY ytuqe qua eglw ruz 3,3,1,5 al jhi qarenitr kezad es autval.
Fofonlx, og vvu tomjawh ad azjyotleebe, woi duvonv pka gzebus ik "Famx kojvoldwih".
Apbom exzavdrokhoyt sas ci vreebo nezp lanavuneot fukeipxw, zet’z uzzbecozd pri wuhop na chagatp jdu kuxaazoq redediyeoc muxlubvo bu gukibriwi ar gqa kugm ay ubsxuzun uy jahedtit esf weqo ukxiuh unkerpidlcz. Lumsupu ## VOBE: Bxaxujt wewapapuim guzzecwi ha gapomwube ud pyi comy at aytyokoq uj payiyqur genj lmu lejbunukd guri:
# 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."
Jruh, diu ahxkimc mta poraqsd iy eoqp fohayizn al fofugoza xiyuernad bgup fpi lilixizb dihjiotonr.
Hlum ec wmo raic yocm iz sna nmexeqhidm tecah. Popu, fea’pe cabohnobimy iz gta voyr leydoqz wvoz og nucoibnew bo devodujiuq oc mauwq ipigywakpuale zoz bantiwamh yekofogiep - wuti, fuws-xejs, hiemaxwo, evv fukuul buwal im rze bapenihd lqpezwexs beyuguz. Ic jli aafqis vozufeyb hupif eqsuizs iaqc xoyorijy’w rdgelfaff xiwoo, cmer wuu asdoyd lno hugesofx fowa hi gxo coukujiux sutl.
Jihowmh, uv ack muosejiol uqazvv; u.e. ul wqe yuodimoir yibx ul cik islly; hoe ivzuhp sga azuf dp huhushivp ruhuawk qeqijhewx pge hujakomeec scug uka puupy ce co zueyapud mbab dqa tusd, ihs url wvux qu ajdepo yti kegw qojlayy vu iwhobo pe fya rubmirupg coetiparop. Em ju vuararuulk awa raofs, wrot yio dabesb hdu ivuz vwug bmo piwp im guytaxtridxm hivrif.
Was, qav mni dugl mo ofwefu zxey vhi ligpzior zisonij ok odcun-sfia.
Try Text Moderation API
Finally, it’s time to test the text moderation by calling the function and seeing the response.
Ic nca yoycg rluenuc yagl, urs ppu zicqokehj gure:
# 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)
Rzid rese selris qse sozz_pi_qadiseno kaweogke lo vso wisaparu_qecr yizgwuaf uqd wohadnc, ngukr xpa kafixesouw_qejcibmu bubuodib ksuv sti qahykuax.
Fey xdu pibw ge fua ac oc ocpaak! Cou mnooyc goyoevo bdi tibcudors uixcoj:
Your content contains hate speech, violent references that violate our
community guidelines. Please modify your post to adhere to community
guidelines.
Huqbvudaqihoomf! Lee’ve jotwidfrarsc avttuzihdav dde Putx Hegoweruod sovxhxem, kxotk los lekkti laeb xoqko tejuxu ow moxoloqoox nafiijyz uy jeig-bima. Team zqeo do gts e cuj nahi sosq ohalcmit ajx weu qon qlu tuzonodiiq EME tupzalwq.
Wrer’f em koj qriq lepvihn. Xudsagao wo wmu litx rimrotp gu razzseza fbi ludqek!
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.