Spaces:
Sleeping
Sleeping
File size: 8,609 Bytes
771015e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
{
"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": [
"<IPython.core.display.HTML object>"
],
"text/html": [
"<div><iframe src=\"https://487a5d21908977ea69.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
]
},
"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
}
]
}
]
} |