File size: 2,293 Bytes
bb07b0f
1
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: gender_sentence_custom_interpretation"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import re\n", "\n", "import gradio as gr\n", "\n", "male_words, female_words = [\"he\", \"his\", \"him\"], [\"she\", \"hers\", \"her\"]\n", "\n", "\n", "def gender_of_sentence(sentence):\n", "    male_count = len([word for word in sentence.split() if word.lower() in male_words])\n", "    female_count = len(\n", "        [word for word in sentence.split() if word.lower() in female_words]\n", "    )\n", "    total = max(male_count + female_count, 1)\n", "    return {\"male\": male_count / total, \"female\": female_count / total}\n", "\n", "\n", "# Number of arguments to interpretation function must\n", "# match number of inputs to prediction function\n", "def interpret_gender(sentence):\n", "    result = gender_of_sentence(sentence)\n", "    is_male = result[\"male\"] > result[\"female\"]\n", "    interpretation = []\n", "    for word in re.split(\"( )\", sentence):\n", "        score = 0\n", "        token = word.lower()\n", "        if (is_male and token in male_words) or (not is_male and token in female_words):\n", "            score = 1\n", "        elif (is_male and token in female_words) or (\n", "            not is_male and token in male_words\n", "        ):\n", "            score = -1\n", "        interpretation.append((word, score))\n", "    # Output must be a list of lists containing the same number of elements as inputs\n", "    # Each element corresponds to the interpretation scores for the given input\n", "    return [interpretation]\n", "\n", "\n", "demo = gr.Interface(\n", "    fn=gender_of_sentence,\n", "    inputs=gr.Textbox(value=\"She went to his house to get her keys.\"),\n", "    outputs=\"label\",\n", "    interpretation=interpret_gender,\n", ")\n", "\n", "if __name__ == \"__main__\":\n", "    demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}