{ "cells": [ { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/emmanuelkoupoh/Documents/Github/LP_NLP/venv/lib/python3.9/site-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "from transformers import AutoModelForSequenceClassification\n", "from transformers import TFAutoModelForSequenceClassification\n", "from transformers import AutoTokenizer, AutoConfig\n", "import numpy as np\n", "from scipy.special import softmax\n", "import gradio as gr" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Requirements\n", "model_path = f\"test_trainer/checkpoint-1000/\"\n", "tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')\n", "config = AutoConfig.from_pretrained(model_path)\n", "model = AutoModelForSequenceClassification.from_pretrained(model_path)\n", "\n", "# Preprocess text (username and link placeholders)\n", "def preprocess(text):\n", " new_text = []\n", " for t in text.split(\" \"):\n", " t = '@user' if t.startswith('@') and len(t) > 1 else t\n", " t = 'http' if t.startswith('http') else t\n", " new_text.append(t)\n", " return \" \".join(new_text)\n", "\n", "\n", "def sentiment_analysis(text):\n", " text = preprocess(text)\n", "\n", " # PyTorch-based models\n", " encoded_input = tokenizer(text, return_tensors='pt')\n", " output = model(**encoded_input)\n", " scores_ = output[0][0].detach().numpy()\n", " scores_ = softmax(scores_)\n", " \n", " # Format output dict of scores\n", " labels = ['Negative', 'Neutral', 'Positive']\n", " scores = {l:float(s) for (l,s) in zip(labels, scores_) }\n", " \n", " return scores\n", "\n", "demo = gr.Interface(\n", " fn=sentiment_analysis, \n", " inputs=gr.Textbox(placeholder=\"Write your tweet here...\"), \n", " outputs=\"label\", \n", " interpretation=\"default\",\n", " examples=[[\"This is wonderful!\"]])\n", "\n", "demo.launch()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3.9.6 ('venv': venv)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6 (default, Aug 5 2022, 15:21:02) \n[Clang 14.0.0 (clang-1400.0.29.102)]" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "1ab24538aa0da4b2d8c48eaca591ff7ffc54671225fb0511b432fd9e26a098ba" } } }, "nbformat": 4, "nbformat_minor": 2 }