diff --git "a/movie_rating_bot.ipynb" "b/movie_rating_bot.ipynb"
new file mode 100644--- /dev/null
+++ "b/movie_rating_bot.ipynb"
@@ -0,0 +1,683 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# AI影评家: 用 Hugging Face 模型打造一个电影评分机器人"
+ ],
+ "metadata": {
+ "id": "HfyrRL-19ioh"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "随着人工智能和大模型 ChatGPT 的持续火爆,越来越多的个人和创业者都想并且可以通过自己创建人工智能 APP 来探索这个新兴领域的机会。只要你有一个想法,你就可以通过各种开放社区和资源实现一些简单功能,满足特定领域或者用户的需求。\n",
+ "\n",
+ "试想现在有一部新的电影刚刚上线了,我们和朋友在家热烈的讨论着这部新的电影,这些都是非常有价值的电影评价的信息,不过估计这个时候很少有人会特地去登陆自己的豆瓣账号再去发表这些刚刚的评论,如果有一个电影评论机器人可以自动收集这些评论并且根据评论打分,然后自动上传到制定的电影评论网站呢?再比如,我们在某个餐厅吃饭,我们只用对着手机说几句话,我们的评分就自动上传到大众点评呢?我们来试试如何实现这样一个小小的机器人吧!\n",
+ "\n",
+ "在本教程中,我们将探索如何使用 Hugging Face 资源来 Finetune 一个模型且构建一个电影评分机器人。我们将向大家展示如何整合这些资源,让你的聊天机器人具备总结评论并给出评分的功能。我们会用通俗易懂的语言引导你完成这个有趣的项目!\n",
+ "\n",
+ "\n",
+ "为了可以简单的说明实现的步骤,我们简化这个【电影打分机器人】的实现方法:\n",
+ "\n",
+ "1. APP 直接收集来自 `input` 的 `text` 作为输入,有兴趣的小伙伴们可以研究一下如何接入到语音,[Whisper to ChatGPT](https://huggingface.co/spaces/Eriberto/whisper-to-chatGPT) 是一个很有好的例子。\n",
+ "1. APP 不会实现自动上传评价到特定网站。"
+ ],
+ "metadata": {
+ "id": "CxM9vlfl-T50"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "rDV8tiQ3u5by"
+ },
+ "source": [
+ "# 第一步:训练电影评价打分模型"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "OiosmvO4u5b4"
+ },
+ "source": [
+ "首先我们需要一个可以看懂评论且给评论打分的模型,这个例子选用的是利用数据集 [IMDb](https://huggingface.co/datasets/imdb) 微调 [DistilBERT](https://huggingface.co/distilbert-base-uncased),微调后的模型可以预测一个电影的评论是正面的还是负面的且给出评分(五分满分)。\n",
+ "\n",
+ "\n",
+ "\n",
+ "当然大家可以根据各自的需求找到不同的数据集来 Finetune 模型,也可以使用不同的基础模型,Hugging Face 上提供了很多可选项。\n",
+ "\n",
+ "本任务使用或间接使用了下面模型的架构:\n",
+ "\n",
+ "\n",
+ "\n",
+ "[ALBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/albert), [BART](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bart), [BERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bert), [BigBird](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/big_bird), [BigBird-Pegasus](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bigbird_pegasus), [BLOOM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/bloom), [CamemBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/camembert), [CANINE](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/canine), [ConvBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/convbert), [CTRL](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/ctrl), [Data2VecText](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/data2vec-text), [DeBERTa](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deberta), [DeBERTa-v2](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/deberta-v2), [DistilBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/distilbert), [ELECTRA](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/electra), [ERNIE](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/ernie), [ErnieM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/ernie_m), [ESM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/esm), [FlauBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/flaubert), [FNet](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/fnet), [Funnel Transformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/funnel), [GPT-Sw3](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt-sw3), [OpenAI GPT-2](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt2), [GPT Neo](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gpt_neo), [GPT-J](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/gptj), [I-BERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/ibert), [LayoutLM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/layoutlm), [LayoutLMv2](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/layoutlmv2), [LayoutLMv3](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/layoutlmv3), [LED](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/led), [LiLT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/lilt), [Longformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/longformer), [LUKE](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/luke), [MarkupLM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/markuplm), [mBART](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/mbart), [Megatron-BERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/megatron-bert), [MobileBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/mobilebert), [MPNet](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/mpnet), [MVP](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/mvp), [Nezha](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/nezha), [Nyströmformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/nystromformer), [OpenAI GPT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/openai-gpt), [OPT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/opt), [Perceiver](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/perceiver), [PLBart](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/plbart), [QDQBert](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/qdqbert), [Reformer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/reformer), [RemBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/rembert), [RoBERTa](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/roberta), [RoBERTa-PreLayerNorm](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/roberta-prelayernorm), [RoCBert](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/roc_bert), [RoFormer](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/roformer), [SqueezeBERT](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/squeezebert), [TAPAS](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/tapas), [Transformer-XL](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/transfo-xl), [XLM](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlm), [XLM-RoBERTa](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlm-roberta), [XLM-RoBERTa-XL](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlm-roberta-xl), [XLNet](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xlnet), [X-MOD](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/xmod), [YOSO](https://huggingface.co/docs/transformers/main/en/tasks/../model_doc/yoso)\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "PRgfxOvdu5br"
+ },
+ "outputs": [],
+ "source": [
+ "# Transformers installation\n",
+ "! pip install transformers datasets evaluate\n",
+ "# To install from source instead of the last release, comment the command above and uncomment the following one.\n",
+ "# ! pip install git+https://github.com/huggingface/transformers.git"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "在使用本示例前请安装如下库文件:\n",
+ "\n",
+ "```bash\n",
+ "pip install transformers datasets evaluate\n",
+ "```\n",
+ "\n",
+ "我们建议登陆Hugging Face账户进行操作,这样就可以方便的上传和分享自己创建的模型。当有弹框时请输入个人的 token 。根据下图找到我们自己的Hugging Face Tokens。"
+ ],
+ "metadata": {
+ "id": "DtKi5oYmCMrV"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ ""
+ ],
+ "metadata": {
+ "id": "DkPsHUdk0F8g"
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "iRztP5cOu5b-"
+ },
+ "outputs": [],
+ "source": [
+ "from huggingface_hub import notebook_login\n",
+ "\n",
+ "notebook_login()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "6-F7lWUYu5b_"
+ },
+ "source": [
+ "## 加载 IMDb 数据集"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "sgW2d_5Zu5cA"
+ },
+ "source": [
+ "开始从 Datasets 库中加载 IMDb 数据集 🤗 :"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "YsMgkkA8u5cA"
+ },
+ "outputs": [],
+ "source": [
+ "from datasets import load_dataset\n",
+ "\n",
+ "imdb = load_dataset(\"imdb\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "DC0D4-7Ru5cB"
+ },
+ "source": [
+ "检查一下数据是否载入成功:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "VA9aJyiku5cD"
+ },
+ "outputs": [],
+ "source": [
+ "imdb[\"test\"][0]\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "iBK_Lq0vu5cE"
+ },
+ "source": [
+ "在这个数据集中有两个字段: \n",
+ "\n",
+ "- `text`: 电影评论。\n",
+ "- `label`: 0或者1。`0` 代表负面评价 or `1` 代表正面评价。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "y1bKI-7au5cE"
+ },
+ "source": [
+ "## 输入数据预处理"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "kkClPcA7u5cE"
+ },
+ "source": [
+ "这一步是加载 DistilBERT tokenizer,并创建一个预处理函数来预处理 `text`,且保证输入不会大于 DistilBERT 的最长输入要求:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "SLkQRevSu5cF"
+ },
+ "outputs": [],
+ "source": [
+ "from transformers import AutoTokenizer\n",
+ "\n",
+ "tokenizer = AutoTokenizer.from_pretrained(\"distilbert-base-uncased\")\n",
+ "def preprocess_function(examples):\n",
+ " return tokenizer(examples[\"text\"], truncation=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "6sM2-vELu5cG"
+ },
+ "source": [
+ "使用 🤗 Datasets [map](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.map) 函数把预处理函数应用到整个数据集中。 我们还可以使用 `batched=True` 来加速 `map`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "GB3HyacSu5cG"
+ },
+ "outputs": [],
+ "source": [
+ "tokenized_imdb = imdb.map(preprocess_function, batched=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "MwOm7OY_u5cG"
+ },
+ "source": [
+ "使用 [DataCollatorWithPadding](https://huggingface.co/docs/transformers/main/en/main_classes/data_collator#transformers.DataCollatorWithPadding) 来生成数据包,这样动态的填充数据包到最大长度能够更加节省资源。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "umTF2J8Iu5cG"
+ },
+ "outputs": [],
+ "source": [
+ "from transformers import DataCollatorWithPadding\n",
+ "\n",
+ "data_collator = DataCollatorWithPadding(tokenizer=tokenizer)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "4ICgPGUWu5cH"
+ },
+ "source": [
+ "## 模型评测函数"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "PCMIwOuQu5cH"
+ },
+ "source": [
+ "选择一个合适的测评指标是至关重要的。大家可以直接调用库函数 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) 里的各种测评指标。在这个例子中,我们使用了[accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy),了解更多请查看 [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "Eqp5GCzDu5cH"
+ },
+ "outputs": [],
+ "source": [
+ "import evaluate\n",
+ "\n",
+ "accuracy = evaluate.load(\"accuracy\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "1puiLkQ-u5cH"
+ },
+ "source": [
+ "这里我们需要定义一个可以[计算](https://huggingface.co/docs/evaluate/main/en/package_reference/main_classes#evaluate.EvaluationModule.compute)指标的函数:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "3eI27sDFu5cI"
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\n",
+ "\n",
+ "\n",
+ "def compute_metrics(eval_pred):\n",
+ " predictions, labels = eval_pred\n",
+ " predictions = np.argmax(predictions, axis=1)\n",
+ " return accuracy.compute(predictions=predictions, references=labels)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "N-y8aSc9u5cL"
+ },
+ "source": [
+ "## 训练模型"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "qQVig66Su5cM"
+ },
+ "source": [
+ "\n",
+ "在开始训练前,需要定义一个id到标签和标签到id的 `map` :"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "81s3H078u5cM"
+ },
+ "outputs": [],
+ "source": [
+ "id2label = {0: \"NEGATIVE\", 1: \"POSITIVE\"}\n",
+ "label2id = {\"NEGATIVE\": 0, \"POSITIVE\": 1}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "PxGg8Cchu5cM"
+ },
+ "source": [
+ "\n",
+ "\n",
+ "如果不熟悉如何使用 [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) 来训练模型, 可以查看更详细的[教程](https://huggingface.co/docs/transformers/main/en/tasks/../training#train-with-pytorch-trainer)!\n",
+ "\n",
+ "\n",
+ "\n",
+ "好了,一切已经准备就绪!我们可以使用 [AutoModelForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoModelForSequenceClassification) 加载 DistilBERT 模型:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "SMJufg4ju5cM"
+ },
+ "outputs": [],
+ "source": [
+ "from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer\n",
+ "\n",
+ "model = AutoModelForSequenceClassification.from_pretrained(\n",
+ " \"distilbert-base-uncased\", num_labels=2, id2label=id2label, label2id=label2id\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "A2fnoVSNu5cN"
+ },
+ "source": [
+ "接下来只有三步需要完成:\n",
+ "\n",
+ "1. 在 [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) 中定义模型超参,只有 `output_dir` 参数是必须的。我们可以设置 `push_to_hub=True` 来直接上传训练好的模型(如果已经登陆了Hugging Face)。在每一个训练段,[Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) 都会评测模型的 accuracy 和保存此节点。\n",
+ "2. 传入超参数,模型,数据集和评测函数到 [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer)。\n",
+ "3. 调用 [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train) 来微调模型。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "G0dAij3mu5cN"
+ },
+ "outputs": [],
+ "source": [
+ "training_args = TrainingArguments(\n",
+ " output_dir=\"my_awesome_model\",\n",
+ " learning_rate=2e-5,\n",
+ " per_device_train_batch_size=16,\n",
+ " per_device_eval_batch_size=16,\n",
+ " num_train_epochs=2,\n",
+ " weight_decay=0.01,\n",
+ " evaluation_strategy=\"epoch\",\n",
+ " save_strategy=\"epoch\",\n",
+ " load_best_model_at_end=True,\n",
+ " push_to_hub=True,\n",
+ ")\n",
+ "\n",
+ "trainer = Trainer(\n",
+ " model=model,\n",
+ " args=training_args,\n",
+ " train_dataset=tokenized_imdb[\"train\"],\n",
+ " eval_dataset=tokenized_imdb[\"test\"],\n",
+ " tokenizer=tokenizer,\n",
+ " data_collator=data_collator,\n",
+ " compute_metrics=compute_metrics,\n",
+ ")\n",
+ "\n",
+ "trainer.train()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "_HVfRl1Su5cN"
+ },
+ "source": [
+ "\n",
+ "训练结束后大家就可以通过 [push_to_hub()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.push_to_hub) 上传模型到Hugging Face 上了,这样所有人都可以看见并且使用你的模型了。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 第二步:模型上传到 Hugging Face"
+ ],
+ "metadata": {
+ "id": "VBw-IMUwG_AD"
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "6QOnSkKeu5cN"
+ },
+ "outputs": [],
+ "source": [
+ "trainer.push_to_hub()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "0JytCvmAu5cO"
+ },
+ "source": [
+ "\n",
+ "\n",
+ "大家可以在 [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)\n",
+ "或者 [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb) 查看更加详细的关于如何微调模型的教程。\n",
+ "\n",
+ ""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "HDBB-FMDu5cO"
+ },
+ "source": [
+ "# 第三步:创建自己的 APP"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "UNo4x35ou5cO"
+ },
+ "source": [
+ "恭喜大家已经获得了自己的模型!下面我们可以在 Hugging Face 中创建一个自己的 APP 了。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## 创建新的 Space"
+ ],
+ "metadata": {
+ "id": "qxmwNjSqKb4s"
+ }
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "! pip install gradio torch"
+ ],
+ "metadata": {
+ "id": "MK6-8gmbMvp3"
+ },
+ "execution_count": null,
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "在 Spaces 主页上点击 `Create new Space` 。\n",
+ "\n",
+ "## APP 逻辑\n",
+ "\n",
+ "在 `app.py` 文件中接入以下代码:"
+ ],
+ "metadata": {
+ "id": "M3avatgoKyuV"
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "pSX08YF5u5cO"
+ },
+ "outputs": [],
+ "source": [
+ "import gradio as gr\n",
+ "from transformers import pipeline\n",
+ "import torch\n",
+ "\n",
+ "id2label = {0: \"NEGATIVE\", 1: \"POSITIVE\"}\n",
+ "label2id = {\"NEGATIVE\": 0, \"POSITIVE\": 1}\n",
+ "\n",
+ "# 导入 HuggingFace 模型 我们刚刚训练好而且上传成功的模型 chjun/my_awesome_model\n",
+ "classifier = pipeline(\"sentiment-analysis\", model=\"chjun/my_awesome_model\")\n",
+ "\n",
+ "# input:输入文本\n",
+ "def predict(inputs):\n",
+ " label_score = classifier(inputs)\n",
+ " scaled = 0\n",
+ " if label_score[0][\"label\"] == \"NEGATIVE\":\n",
+ " scaled = 1 - label_score[0][\"score\"]\n",
+ " else:\n",
+ " scaled = label_score[0][\"score\"]\n",
+ "\n",
+ " # 解码返回值得到输出\n",
+ " return round(scaled * 5)\n",
+ "\n",
+ "with gr.Blocks() as demo:\n",
+ " review = gr.Textbox(label=\"用户评论。注:此模型只使用了英文数据 Finetune\")\n",
+ " output = gr.Textbox(label=\"颗星\")\n",
+ " submit_btn = gr.Button(\"提交\")\n",
+ " submit_btn.click(fn=predict, inputs=review, outputs=output, api_name=\"predict\") \n",
+ "\n",
+ "demo.launch(debug=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "成功运行后,大家应该可以看见下面类似的界面:\n",
+ ""
+ ],
+ "metadata": {
+ "id": "ifkEBBh24RlE"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "t3CTVSSLu5cO"
+ },
+ "source": [
+ "注意,我们需要把必须的库文件放在 `requirements.txt` 中,例如这个 APP 需要:\n",
+ "\n",
+ " gradio\n",
+ " torch\n",
+ " transformers"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "另外,由于我们在示范中只跑了2个epoch,所以最终模型 accuracy 不高。大家可以根据自己的情况调整超参和训练时长。"
+ ],
+ "metadata": {
+ "id": "CF4LoLkKpQiX"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## 上传到 Space\n",
+ "\n",
+ " $git add app.py\n",
+ " $git commit -m \"Add application file\"\n",
+ " $git push"
+ ],
+ "metadata": {
+ "id": "Jdt8D2Tqcwa-"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 第四步: 完成机器人开发\n",
+ "\n",
+ "现在,你已经创建了一个能够根据电影评论给电影打分的机器人。当你向机器人提问时,它会使用Hugging Face的模型进行情感分析,根据情感分析结果给出一个评分。\n",
+ "\n",
+ "[chjun/movie_rating_bot](https://huggingface.co/spaces/chjun/movie_rating_bot) 是根据以上教程完成的一个机器人 APP,大家也可以直接复制这一个 Space 在此基础上更改开发。\n",
+ "\n",
+ "点击`submit`,与你的AI伙伴互动吧!这个项目仅仅是一个起点,你可以根据自己的需求和兴趣进一步完善这个聊天机器人,使其具备更多有趣的功能。"
+ ],
+ "metadata": {
+ "id": "UoyaGDX6dbjz"
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# 第五步:接入 BaixingAI 机器人广场\n",
+ "\n",
+ "还有更激动人心的一步,我们可以把机器人接口根据 [BaixingAI 机器人广场需求](https://huggingface.co/spaces/baixing/hackathon_test/blob/main/bot-api.md) 扩展,让我们自己创建的机器人可以去和其他机器人交流对话,以下是代码示范:\n",
+ "\n",
+ "更多详情请参考 Hugging Face [baixing Spaces](https://huggingface.co/baixing)。"
+ ],
+ "metadata": {
+ "id": "J9CupPB_-0qa"
+ }
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "import gradio as gr\n",
+ "from transformers import pipeline\n",
+ "import torch\n",
+ "\n",
+ "# 导入 HuggingFace 模型 我们刚刚训练好而且上传成功的模型 chjun/my_awesome_model\n",
+ "classifier = pipeline(\"sentiment-analysis\", model=\"chjun/my_awesome_model\")\n",
+ "\n",
+ "# input:输入文本\n",
+ "def predict(user_review, qid, uid):\n",
+ " label_score = classifier(user_review)\n",
+ " scaled = 0\n",
+ " if label_score[0][\"label\"] == \"NEGATIVE\":\n",
+ " scaled = 1 - label_score[0][\"score\"]\n",
+ " else:\n",
+ " scaled = label_score[0][\"score\"]\n",
+ "\n",
+ " # 解码返回值得到输出\n",
+ " return str(round(scaled * 5))\n",
+ "\n",
+ "# user_review: 用户评价\n",
+ "# qid:当前消���的唯一标识。例如 `'bxqid-cManAtRMszw...'`。由平台生成并传递给机器人,以便机器人区分单个问题(写日志、追踪调试、异步回调等)。同步调用可忽略。 \n",
+ "# uid:用户的唯一标识。例如`'bxuid-Aj8Spso8Xsp...'`。由平台生成并传递给机器人,以便机器人区分用户。可被用于实现多轮对话的功能。 \n",
+ "demo = gr.Interface(\n",
+ " fn=predict,\n",
+ " inputs=[\"text\",\"text\",\"text\"],\n",
+ " outputs=\"text\",\n",
+ " )\n",
+ "\n",
+ "demo.launch()"
+ ],
+ "metadata": {
+ "id": "S9n2e4Rs_8xB"
+ },
+ "execution_count": null,
+ "outputs": []
+ }
+ ],
+ "metadata": {
+ "colab": {
+ "provenance": [],
+ "private_outputs": true
+ },
+ "language_info": {
+ "name": "python"
+ },
+ "kernelspec": {
+ "name": "python3",
+ "display_name": "Python 3"
+ },
+ "gpuClass": "standard",
+ "accelerator": "GPU"
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
\ No newline at end of file