Get startedGet started for free

Handle textual request data

Another requirement in the content moderation system is to take into account user comments' sentiment. The system needs to identify specific problematic phrases to help moderators review potentially inappropriate content.

You'll create an endpoint that analyzes text coming from users and extracts standardized moderation flags.

This exercise is part of the course

Deploying AI into Production with FastAPI

View Course

Exercise instructions

  • Turn the incoming text into lowercase in the analyze_comment() function to make it case-insensitive.
  • Extract problem keywords in found_issues from the processed text using the problem_keywords list.
  • Return a JSON response with the following keys - issues (list of keywords), issue_count (integer), and the original_text (string).

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

@app.post("/analyze_comment")
def analyze_comment(text: str):
    problem_keywords = ["spam", "hate", "offensive", "abuse"]
    
    # Convert the input text to lowercase
    text_lower = ____
    # Extract matching flags using list comprehension
    found_issues = [____ for ____ in problem_keywords if keyword in text_lower]
    # Return the dictionary with required keys
    return {
        "____": found_issues,
        "____": len(found_issues),
        "____": text
    }
Edit and Run Code