{ "cells": [ { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "f:\\miniconda3\\envs\\btl\\Lib\\site-packages\\tqdm\\auto.py:21: 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": [ "import matplotlib.pyplot as plt\n", "import gradio as gd\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7860\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import gradio as gr\n", "\n", "def greet(name, intensity):\n", " return \"Hello, \" + name + \"!\" * int(intensity)\n", "\n", "demo = gr.Interface(\n", " fn=greet,\n", " inputs=[\"text\", \"slider\"],\n", " outputs=[\"text\"],\n", ")\n", "\n", "demo.launch()\n" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7904\n", "\n", "Could not create share link. Missing file: f:\\miniconda3\\envs\\btl\\Lib\\site-packages\\gradio\\frpc_windows_amd64_v0.2. \n", "\n", "Please check your internet connection. This can happen if your antivirus software blocks the download of this file. You can install manually by following these steps: \n", "\n", "1. Download this file: https://cdn-media.huggingface.co/frpc-gradio-0.2/frpc_windows_amd64.exe\n", "2. Rename the downloaded file to: frpc_windows_amd64_v0.2\n", "3. Move the file to this location: f:\\miniconda3\\envs\\btl\\Lib\\site-packages\\gradio\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# #setup\n", "# model_path = \"KAITANY/finetuned-roberta-base-sentiment\"\n", "\n", "# tokenizer = AutoTokenizer.from_pretrained(model_path)\n", "# #config = AutoConfig.from_pretrained(model_path)\n", "# model = AutoModelForSequenceClassification.from_pretrained(model_path)\n", "\n", "# def preprocess(text):\n", "# # Preprocess text (username and link placeholders)\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", "# def sentiment_analysis(text):\n", " # text = preprocess(text)\n", "\n", " # # Tokenize the text\n", " # inputs = tokenizer(text, return_tensors=\"pt\", padding=True)\n", "\n", " # # Make a prediction\n", " # with torch.no_grad():\n", " # outputs = model(**inputs)\n", "\n", " # # Get the predicted class probabilities\n", " # scores = torch.softmax(outputs.logits, dim=1).tolist()[0]\n", " # # Map the scores to labels\n", " # labels = ['Negative', 'Neutral', 'Positive']\n", " # scores_dict = {label: score for label, score in zip(labels, scores)}\n", "\n", " # return scores_dict\n", "#demo\n", "aspects = ['General', 'Battery', 'Performance', 'Camera', 'Ser&Acc', 'Others', 'Design', 'Screen', 'Features', 'Price']\n", "aspects_ratio = (np.random.dirichlet(np.ones(10), size=1) * 100).flatten()\n", "\n", "sentiments_ratio = (np.random.dirichlet(np.ones(3), size=1) * 100).flatten()\n", "sentiments = ['Positive', 'Negative', 'Neutral']\n", "\n", "aspects_polarity = []\n", "aspects_polarity_ratio = (np.random.dirichlet(np.ones(30), size=1) * 100).flatten()\n", "for aspect in aspects:\n", " for sentiment in sentiments:\n", " aspects_polarity.append(aspect + '#' + sentiment) \n", "\n", "def sentiment_analysis(text, aspect):\n", "\n", " # Tạo biểu đồ cảm xúc theo aspect\n", " pie_sentiments_of_an_aspect = draw_pie_sentiments_of_an_aspect(aspect)\n", "\n", " #Biểu đồ aspect\n", " pie_of_all_aspect = draw_pie_of_aspect()\n", "\n", " #Biểu đồ aspect#polirity\n", " pie_aspect_polarity = draw_pie_aspect_polarity()\n", " # return [pie_aspect, pie_all_aspect, pie_aspect_polarity]\n", " return pie_sentiments_of_an_aspect, pie_of_all_aspect, pie_aspect_polarity\n", "\n", "def draw_pie_sentiments_of_an_aspect(aspect):\n", " sentiments_ratio = (np.random.dirichlet(np.ones(3), size=1) * 100).flatten()\n", " pie_sentiments_of_an_aspect = plt.figure(figsize=(5,5))\n", " plt.pie(sentiments_ratio, labels=sentiments, autopct='%1.1f%%', startangle=140)\n", " return pie_sentiments_of_an_aspect\n", "\n", "def draw_pie_of_aspect():\n", " pie_aspect = plt.figure(figsize=(5,5))\n", " plt.pie(aspects_ratio, labels=aspects, autopct='%1.1f%%', startangle=140)\n", " return pie_aspect\n", "\n", "def draw_pie_aspect_polarity():\n", " pie_aspect_polarity = plt.figure(figsize=(20, 10))\n", " plt.pie(aspects_polarity_ratio, labels=aspects_polarity, autopct='%1.1f%%', startangle=140)\n", " plt.legend(aspects_polarity, loc='upper right', bbox_to_anchor=(1.5, 1.))\n", " return pie_aspect_polarity\n", "\n", "def submit(comment, aspect):\n", " return sentiment_analysis(comment, aspect)\n", " \n", "title = \"Sentiment Analysis Application\\n\\n\\nThis application assesses if a twitter post relating to vaccination is positive,neutral or negative\"\n", "with gr.Blocks() as demo:\n", " with gr.Row():\n", " text_box = gr.Textbox(placeholder=\"Write your comment here...\", visible=True, label=\"Comment\")\n", " submit_btn = gr.Button(\"Submit\")\n", " with gr.Row():\n", " with gr.Column():\n", " choose_aspect_dropdown = gr.Dropdown(\n", " choices=['General', 'Battery', 'Performance', 'Camera', 'Ser&Acc', 'Others', 'Design', 'Screen', 'Features', 'Price'], \n", " label=\"Choose Aspect\",\n", " value='General'\n", " )\n", " pie_sentiment = gr.Plot()\n", " pie_all_aspect = gr.Plot()\n", " pie_aspect_polarity = gr.Plot(min_width=2000)\n", " # demo.fn(draw_pie_aspect(choose_aspect_dropdown))\n", "\n", " choose_aspect_dropdown.select(\n", " fn = draw_pie_sentiments_of_an_aspect,\n", " inputs = [choose_aspect_dropdown],\n", " outputs = [pie_sentiment],\n", " )\n", "\n", " submit_btn.click(\n", " fn = submit,\n", " inputs = [text_box, choose_aspect_dropdown],\n", " outputs = [pie_sentiment, pie_all_aspect, pie_aspect_polarity],\n", ")\n", "\n", "\n", "# demo = gr.Interface(\n", "# fn=sentiment_analysis,\n", "# inputs=gr.Textbox(placeholder=\"Write your tweet here...\"),\n", "# outputs=gr.Plot(),\n", "# examples=[[\"The Vaccine is harmful!\"],[\"I cant believe people don't vaccinate their kids\"],[\"FDA think just not worth the AE unfortunately\"],[\"For a vaccine given to healthy\"]],\n", "# title=title\n", "# )\n", "\n", "demo.launch(share=True)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7881\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import gradio as gr\n", "\n", "with gr.Blocks() as demo:\n", " error_box = gr.Textbox(label=\"Error\", visible=False)\n", "\n", " name_box = gr.Textbox(label=\"Name\")\n", " age_box = gr.Number(label=\"Age\", minimum=0, maximum=100)\n", " symptoms_box = gr.CheckboxGroup([\"Cough\", \"Fever\", \"Runny Nose\"])\n", " submit_btn = gr.Button(\"Submit\")\n", "\n", " with gr.Column(visible=False) as output_col:\n", " diagnosis_box = gr.Textbox(label=\"Diagnosis\")\n", " patient_summary_box = gr.Textbox(label=\"Patient Summary\")\n", "\n", " def submit(name, age, symptoms):\n", " if len(name) == 0:\n", " return {error_box: gr.Textbox(value=\"Enter name\", visible=True)}\n", " return {\n", " output_col: gr.Column(visible=True),\n", " diagnosis_box: \"covid\" if \"Cough\" in symptoms else \"flu\",\n", " patient_summary_box: f\"{name}, {age} y/o\",\n", " }\n", "\n", " submit_btn.click(\n", " submit,\n", " [name_box, age_box, symptoms_box],\n", " [error_box, diagnosis_box, patient_summary_box, output_col],\n", " )\n", "\n", "demo.launch()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "btl", "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.12.2" } }, "nbformat": 4, "nbformat_minor": 2 }