{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "toc_visible": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "source": [ "# Full Implementation Notebook\n", "\n", "This notebook contain the\n", "complete working code where the Hugging Face text-to-text pipeline is\n", "integrated with Gradio." ], "metadata": { "id": "pHjELrmOIZi8" } }, { "cell_type": "markdown", "source": [ "## Code" ], "metadata": { "id": "ondE_4z0IcAd" } }, { "cell_type": "markdown", "source": [ "### Libraries\n", "\n", "Start by installing and importing necessary libraries" ], "metadata": { "id": "fwkJqEkZIlcO" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "WQVTT-lNINjq" }, "outputs": [], "source": [ "!pip install gradio\n", "!pip install transformers" ] }, { "cell_type": "code", "source": [ "import gradio as gr # Gradio library to create an interactive interface\n", "from transformers import pipeline # Transformers libraries which imports pipeline to use Hugging-Face models\n", "import pandas as pd # Pandas library for data manipulation and analysis\n", "import matplotlib.pylab as plt # Matplot library for the interactive visualizations" ], "metadata": { "id": "UGSX08P-InwG" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Initialize Sentiment Analyzers and Define Function\n", "\n", "In this project, Two pre-trained sentiment analysis models will be used, One is for analysizng English text, and the other one if for Arabic text, Also the function that will be used by the Gradio\n" ], "metadata": { "id": "eui-QVCNI0CX" } }, { "cell_type": "code", "source": [ "# Initialize the analyzers\n", "\n", "# Loads a pretrained model for the Arabic language\n", "arabic_analyzer = pipeline('sentiment-analysis', model='CAMeL-Lab/bert-base-arabic-camelbert-da-sentiment')\n", "\n", "# Loads a pretrained model for the English language\n", "english_analyzer = pipeline('sentiment-analysis', model='distilbert-base-uncased-finetuned-sst-2-english')" ], "metadata": { "id": "j-A9yOTAI42S" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# Define function\n", "\n", "def sentiment_analysis(language,file):\n", " # Select the appropriate analyzer\n", " if language == \"Arabic\":\n", " analyzer = arabic_analyzer\n", " else:\n", " analyzer = english_analyzer\n", "\n", " results = []\n", "\n", " # Read the sentences from the uploaded file\n", " with open (file.name,'r') as fn:\n", " sentences = fn.readlines()\n", "\n", " # Perform sentiment analysis on each sentence\n", " for sentence in sentences:\n", " result = analyzer(sentence)\n", " result = result[0]\n", "\n", " results.append({\n", " \"Sentence\": sentence,\n", " \"Label\": result['label'],\n", " \"Score\": f\"{result['score'] *100:.2f}%\"\n", " })\n", " # Convert the results into a DataFrame\n", " df = pd.DataFrame(results)\n", " # Ensure every label is lower, if not this will cause a logic error\n", " # English labels are Upper but Arabic labels are lower\n", " df['Label'] = df['Label'].str.lower()\n", " # Take the \"Label\" column values\n", " label_value = df['Label'].value_counts()\n", "\n", " # Pre-Define the plot parameters\n", " labels = ['Positive','Neutral','Negative']\n", " counts = [label_value.get('positive',0),\n", " label_value.get('neutral',0),\n", " label_value.get('negative',0)]\n", " colors=['green','gray','red']\n", "\n", " # Create a bar plot\n", " plt.bar(labels,counts,color=colors)\n", " plt.title('Sentiment-Analysis')\n", " plt.xlabel(\"Labels\")\n", " plt.ylabel(\"No. of sentences\")\n", "\n", "\n", " return df,plt" ], "metadata": { "id": "1eTYcvvDJagw" }, "execution_count": 62, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Build The Gradio Interface\n", "\n", "Here, The Gradio interface is set up using the following components:\n", "\n", "**A file uploader:** Allows user to upload a text file which contains the sentences to be analyzed\n", "\n", "**Dropdown Menu**: Allows user to choose in which language the sentences will be analyzed\n", "\n", "**DataFrame Output:** Displays program's output in a structured table format\n", "\n", "**Title and Description:** Provides clear title and description for the interface" ], "metadata": { "id": "d8ayqK8jO5I8" } }, { "cell_type": "code", "source": [ "# Set up the Gradio interface\n", "\n", "demo = gr.Interface(\n", " fn=sentiment_analysis,\n", " inputs=[gr.Dropdown(choices=[\"Arabic\",\"English\"],\n", " label=\"Select a Language\",\n", " value=\"Arabic\"),\n", " gr.File(label=\"Upload a file\")],\n", " outputs=[gr.DataFrame(label=\"Results\"),\n", " gr.Plot(label=\"Bar plot\")],\n", " title=\"Sentiment-Analysis\",\n", " description=\"Gradio interface that allows users to Choose what language the sentences will be and upload a text file containing the sentences to be analyzed, the sentences will be classified and results will be in a formatted table along with a plot sentiment distribution\"\n", ")\n", "\n", "demo.launch(debug=True)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 660 }, "id": "l3Dc5RWOO7i_", "outputId": "4a321589-f0c0-453c-bba6-079fa79adb8d" }, "execution_count": 65, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Setting queue=True in a Colab notebook requires sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n", "\n", "Colab notebook detected. This cell will run indefinitely so that you can see errors and logs. To turn off, set debug=False in launch().\n", "Running on public URL: https://487a5d21908977ea69.gradio.live\n", "\n", "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "" ], "text/html": [ "
" ] }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "Keyboard interruption in main thread... closing server.\n", "Killing tunnel 127.0.0.1:7860 <> https://487a5d21908977ea69.gradio.live\n" ] }, { "output_type": "execute_result", "data": { "text/plain": [] }, "metadata": {}, "execution_count": 65 } ] } ] }