所有文章 > 如何集成API > 使用 FastAPI、Docker 和 Hugging Face Transformers 的文本分类 API
使用 FastAPI、Docker 和 Hugging Face Transformers 的文本分类 API

使用 FastAPI、Docker 和 Hugging Face Transformers 的文本分类 API

Docker

文本分类是自然语言处理中的基本任务之一。它是指将文本分类为多个预定义的标签。它通常是使用机器学习算法和自然语言处理技术完成的。

现实世界中有许多文本分类的使用案例,例如客户评论的情绪分析、电子邮件垃圾邮件过滤、文档分类、主题建模和意图检测。

随着机器学习和人工智能领域的进步,这些文本分类任务已经通过Hugging Face上的多个预训练模型得以实现。因此,我们无需从头开始。我们可以从数千个已可用的模型中挑选,并使用它们来对文本进行分类。

我将指导您完成使用 FastAPI、Docker 和 Hugging Face 转换器构建端到端文本分类 API 的过程。这是一个 MLOps 案例研究,涵盖了从创建用于文本分类的 FastAPI 端点到使用 Docker 容器化 API 的所有内容。因此,让我们从对本案例研究中使用的技术堆栈的基本了解开始。

什么是 Hugging Face?

Hugging Face 是一个面向机器学习工程师的协作平台,他们可以在其中上传预训练模型、部署机器学习应用程序以及执行更多操作。该平台上有数千个与机器学习、深度学习、计算机视觉、自然语言处理和语音识别相关的预训练模型,可以通过 Hugging Face transformers 库使用。

什么是 FastAPI?

API 代表应用程序编程接口。它是两个或多个计算机程序或组件使用一组规则和协议相互通信的一种方式。API 可用于访问应用程序的功能、从数据库中检索数据或执行其他任务。

FastAPI 是一个现代的高性能 Web 框架,用于使用 Python 构建 API。学习起来非常快速和直观,您只需几行代码即可实现很多功能。

什么是 Docker?

Docker是一组平台即服务产品,它使用操作系统级别的虚拟化来以称为容器的软件包交付软件。Docker容器是一个便携的计算环境。它是一个完整的软件包,包含应用程序的代码、依赖项和配置。Docker容器镜像是一个轻量级、独立、可执行的软件包,包含运行应用程序所需的一切,即代码、运行时、系统工具、系统库和设置。因此,无论在哪台机器上,应用程序都作为一个单独的实体运行,并且每次运行都完全相同。

现在我们已经对这些工具和框架有了基本的了解,让我们直接进入API的构建。我们将使用FastAPI开发一个RESTful API,该API利用预训练的Hugging Face Transformer模型来执行文本分类(情感分析)。该API将使用Docker进行容器化。

第 1 步:从 Hugging Face 中选择文本分类模型

访问 https://huggingface.co/models 的 Hugging Face 平台。在自然语言处理下选择文本分类,它将显示超过 50,000 个模型可供选择。我们可以根据项目的目的或我们试图解决的问题来选择我们选择的任何模型。在这里,我们将选择 Twitter-roBERTa-base 进行情绪分析模型,这是一个基于 RoBERTa 的模型,在 2018 年 1 月至 2021 年 12 月期间对 ~124M 条推文进行了训练,并使用 TweetEval 基准对推文分类进行了微调以进行情绪分析。

第 2 步:安装 Docker Desktop

要在本地计算机上运行 Docker 容器,您需要安装 Docker Desktop。您可以根据您的操作系统从 https://www.docker.com/products/docker-desktop/ 下载安装程序,然后运行可执行文件将其安装到您的计算机上。

Docker 桌面

第 3 步:初始化 Docker 容器

创建一个名为text-classification-api的新目录,用于存放文本分类API。打开命令提示符,并导航到text-classification-api目录。运行以下命令以初始化Docker容器。

docker init

系统会向您提出几个问题。请将应用程序平台选择为Python,版本和端口保持默认设置,并输入运行应用程序的命令。

uvicorn 'main:app' --host=0.0.0.0 --port=8000

它将为您的项目创建以下默认配置文件:

  • .dockerignore
  • Dockerfile
  • compose.yaml
  • README.Docker.md

应用程序的基本结构现已准备就绪。

.dockerignore 指定在构建 Docker 镜像时应从 Docker 构建上下文中排除哪些文件和目录,以防止镜像中包含不必要的文件。

Dockerfile 包含有关构建 Docker 映像的说明。它指定要使用的基础映像、用于安装依赖项的命令、将文件复制到映像中、配置环境以及定义应如何执行应用程序。

compose.yaml 简化了对整个应用程序堆栈的控制,从而可以轻松地在单个易于理解的配置文件中管理服务、网络和卷。然后,您可以使用单个命令从配置文件创建并启动所有服务。

README.Docker.md 是一个 Markdown 文件,其中包含特定于将 Docker 与项目结合使用的文档或说明。此文件对于为开发人员提供有关构建、运行和排查项目的指导至关重要。

以下是自动生成的初始Dockerfile。

# syntax=docker/dockerfile:1

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.com/go/dockerfile-reference/

# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7

ARG PYTHON_VERSION=3.11.9
FROM python:${PYTHON_VERSION}-slim as base

# Prevents Python from writing pyc files.
ENV PYTHONDONTWRITEBYTECODE=1

# Keeps Python from buffering stdout and stderr to avoid situations where
# the application crashes without emitting any logs due to buffering.
ENV PYTHONUNBUFFERED=1

WORKDIR /app

# Create a non-privileged user that the app will run under.
# See https://docs.docker.com/go/dockerfile-user-best-practices/
ARG UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
appuser

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
# Leverage a bind mount to requirements.txt to avoid having to copy them into
# into this layer.
RUN --mount=type=cache,target=/root/.cache/pip \
--mount=type=bind,source=requirements.txt,target=requirements.txt \
python -m pip install -r requirements.txt

# Switch to the non-privileged user to run the application.
USER appuser

# Copy the source code into the container.
COPY . .

# Expose the port that the application listens on.
EXPOSE 8000

# Run the application.
CMD uvicorn 'main:app' --host=0.0.0.0 --port=8000

第 4 步:在本地计算机上创建 Python 虚拟环境

设置虚拟环境是 Python 开发的最佳实践。Python 虚拟环境是一个目录,其中包含特定的 Python 解释器版本以及一组库和程序包。它允许您将 Python 项目的依赖项与其他项目的依赖项隔离开来。

使用以下命令通过 Anaconda Prompt 为您的项目创建虚拟环境:

conda create -n docker_env -y

使用以下命令激活虚拟环境:

conda activate docker_env

在虚拟环境中安装 Python。

conda install python -y

通过检查其版本来确认 Python 是否已正确安装。

python --version

在虚拟环境中安装依赖项

执行以下命令安装 fastapi

pip install fastapi

Uvicorn 是 Python 的 ASGI(异步服务器网关接口)Web 服务器实现。它旨在运行 ASGI 应用程序,这是用 Python 编写异步 Web 应用程序的标准方法。执行以下命令安装 uvicorn。

pip install uvicorn

第 5 步:创建 FastAPI 端点

API端点是由API公开的一个特定URL。它代表客户端应用程序和托管API的服务器之间的交互点。每个端点通常对应于API提供的特定功能或资源,并定义了客户端可以执行的操作以及它们可以使用的数据格式。当客户端应用程序向特定的API端点发出HTTP请求时,服务器会处理该请求并返回响应,通常以指定的数据格式(如JSON,即JavaScript对象表示法)返回。

我们将使用FastAPI开发一个包含GET和POST两个端点的API。GET端点是API的入口点,它向客户端返回一个欢迎消息。POST端点接受包含文本字段的JSON输入,并返回文本的情感倾向。我们将把选定的Hugging Face Transformers模型集成到这个API中。

创建 main.py 作为您的主应用程序文件。它将包含应用程序的所有代码,包括端点。

创建 GET 终端节点 — /

编写以下代码以使用欢迎终端节点初始化 FastAPI 应用程序。

main.py

from fastapi import FastAPI

# Initialize the FastAPI app
app = FastAPI()

# Define the welcome endpoint
@app.get('/')
async def welcome():
return "Welcome to our Text Classification API"

创建 Dependencies 文件 — requirements.txt

创建 requirements.txt 文件,其中包含应用程序的依赖项。

requirements.txt

fastapi
uvicorn

第 6 步:在本地计算机上构建和运行 Docker 容器

构建 Docker 镜像

运行以下命令以在本地计算机上构建 Docker 镜像。

docker build -t api_image 

运行 Docker 容器

运行以下命令以容器化您的 Docker 镜像。

docker run -p 8000:8000 api_image

带有 GET 终端节点的基本 API 现在可以正常工作了。通过以下 URL 访问它:

http://localhost:8000

通过以下 URL 访问 API 文档:

http://localhost:8000/docs

通过试用与 GET 终端节点进行交互。

哇!太棒了。我们的基本端到端应用程序使用FastAPI端点,并通过Docker进行了容器化,现在已经可以正常运行了。接下来是更有趣的部分。实现POST端点,客户端可以向API发送一些文本,并且API会返回文本的情感倾向,如正面、负面或中性。

第 7 步:创建 POST 端点 — /analyze

我们将修改main.py文件以添加POST端点。我们将使用Hugging Face的库来加载预训练模型。我们需要确保API高效地处理模型加载,可能使用FastAPI的背景任务或启动事件。transformers

让我们一步一步来。

  1. 添加必要的 import 语句。
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ValidationError
from fastapi.encoders import jsonable_encoder

该装饰器允许定义异步上下文管理器,这些对象是可用于以异步方式管理资源或执行设置和关闭操作的对象。

FastAPI是一个用Python构建API的现代Web框架,以其速度、简洁性和自动文档生成而闻名。HTTPException是FastAPI提供的一个异常类,用于引发具有特定状态码和错误消息的HTTP错误。

BaseModel是Pydantic(一个Python数据验证库)提供的一个类,允许您使用类型注释和验证规则定义数据模型。ValidationError是Pydantic提供的一个异常类,用于处理在数据模型实例化或验证过程中引发的验证错误。

jsonable_encoder是 FastAPI 提供的一个实用函数,用于将 Python 对象转换为 JSON 可序列化的表示形式。在将文本发送到服务器之前,我们将使用它来对文本进行编码。

2.应用文本预处理。

在将原始文本发送到模型进行情感分析之前,我们将对其应用必要的预处理步骤,例如删除 URL 和标点符号、将文本转换为小写以及使用 NLTK 库对文本进行词形还原。这可能是一个可选步骤,但它可确保模型返回最适合给定文本的情绪。(在将原始文本发送到模型进行情感分析之前,我们将对其应用必要的预处理步骤,如删除URL和标点符号、将文本转换为小写,并使用NLTK库对文本进行词形还原。这虽然是一个可选步骤,但它可以确保模型为给定文本返回最适当的情感。

# TEXT PREPROCESSING
# --------------------------------------------------------------------
import re
import string
import nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('omw-1.4')
from nltk.stem import WordNetLemmatizer

# Function to remove URLs from text
def remove_urls(text):
return re.sub(r'http[s]?://\S+', '', text)

# Function to remove punctuations from text
def remove_punctuation(text):
regular_punct = string.punctuation
return str(re.sub(r'['+regular_punct+']', '', str(text)))

# Function to convert the text into lower case
def lower_case(text):
return text.lower()

# Function to lemmatize text
def lemmatize(text):
wordnet_lemmatizer = WordNetLemmatizer()

tokens = nltk.word_tokenize(text)
lemma_txt = ''
for w in tokens:
lemma_txt = lemma_txt + wordnet_lemmatizer.lemmatize(w) + ' '

return lemma_txt

def preprocess_text(text):
# Preprocess the input text
text = remove_urls(text)
text = remove_punctuation(text)
text = lower_case(text)
text = lemmatize(text)
return text

3. 加载模型。

# Load the model using FastAPI lifespan event so that the model is loaded at the beginning for efficiency
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load the model from HuggingFace transformers library
from transformers import pipeline
global sentiment_task
sentiment_task = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment-latest", tokenizer="cardiffnlp/twitter-roberta-base-sentiment-latest")
yield
# Clean up the model and release the resources
del sentiment_task

Lifespan Events对于设置需要用于整个应用程序的资源、在请求之间共享的资源以及之后需要清理的资源非常有用。我们将使用它,以便我们可以在应用程序启动时加载一次紧贴面部模型以提高效率,并在应用程序关闭时释放资源。

4. 初始化 FastAPI 应用程序。

# Initialize the FastAPI app
app = FastAPI(lifespan=lifespan)

5. 定义输入数据模型。

# Define the input data model
class TextInput(BaseModel):
text: str

我们希望将输入作为JSON对象发送,因此我们借助Pydantic的BaseModel来定义它。

6. 定义欢迎端点 — /

# Define the welcome endpoint
@app.get('/')
async def welcome():
return "Welcome to our Text Classification API"

7. 定义 POST 端点 — /analyze

# Validate input text length
MAX_TEXT_LENGTH = 1000

# Define the sentiment analysis endpoint
@app.post('/analyze/{text}')
async def classify_text(text_input:TextInput):
try:
# Convert input data to JSON serializable dictionary
text_input_dict = jsonable_encoder(text_input)
# Validate input data using Pydantic model
text_data = TextInput(**text_input_dict) # Convert to Pydantic model

# Validate input text length
if len(text_input.text) > MAX_TEXT_LENGTH:
raise HTTPException(status_code=400, detail="Text length exceeds maximum allowed length")
elif len(text_input.text) == 0:
raise HTTPException(status_code=400, detail="Text cannot be empty")
except ValidationError as e:
# Handle validation error
raise HTTPException(status_code=422, detail=str(e))

try:
# Perform text classification
return sentiment_task(preprocess_text(text_input.text))
except ValueError as ve:
# Handle value error
raise HTTPException(status_code=400, detail=str(ve))
except Exception as e:
# Handle other server errors
raise HTTPException(status_code=500, detail=str(e))

我们将 JSON 格式的输入文本发送到 POST 终端节点。它将使用预先训练的 Hugging Face 模型应用文本分类,并将情绪作为响应返回。在这种情况下,我们的模型会返回 sentiment 标签和分数。

异常处理是任何应用程序工作流中的关键步骤。在这里,我们验证了边缘情况的输入,即空文本或文本长度大于 1000 个字符,以及输入格式中的任何其他验证错误。我们还在验证情绪任务是否存在 ValueError 或任何其他服务器错误。如果出现每个错误,我们将引发适当的 HTTPException

下面是完整的 main.py 文件,其中包含 API 所需的所有代码。

main.py

from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ValidationError
from fastapi.encoders import jsonable_encoder

# TEXT PREPROCESSING
# --------------------------------------------------------------------
import re
import string
import nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('omw-1.4')
from nltk.stem import WordNetLemmatizer

# Function to remove URLs from text
def remove_urls(text):
return re.sub(r'http[s]?://\S+', '', text)

# Function to remove punctuations from text
def remove_punctuation(text):
regular_punct = string.punctuation
return str(re.sub(r'['+regular_punct+']', '', str(text)))

# Function to convert the text into lower case
def lower_case(text):
return text.lower()

# Function to lemmatize text
def lemmatize(text):
wordnet_lemmatizer = WordNetLemmatizer()

tokens = nltk.word_tokenize(text)
lemma_txt = ''
for w in tokens:
lemma_txt = lemma_txt + wordnet_lemmatizer.lemmatize(w) + ' '

return lemma_txt

def preprocess_text(text):
# Preprocess the input text
text = remove_urls(text)
text = remove_punctuation(text)
text = lower_case(text)
text = lemmatize(text)
return text

# Load the model using FastAPI lifespan event so that the model is loaded at the beginning for efficiency
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load the model from HuggingFace transformers library
from transformers import pipeline
global sentiment_task
sentiment_task = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment-latest", tokenizer="cardiffnlp/twitter-roberta-base-sentiment-latest")
yield
# Clean up the model and release the resources
del sentiment_task

# Initialize the FastAPI app
app = FastAPI(lifespan=lifespan)

# Define the input data model
class TextInput(BaseModel):
text: str

# Define the welcome endpoint
@app.get('/')
async def welcome():
return "Welcome to our Text Classification API"

# Validate input text length
MAX_TEXT_LENGTH = 1000

# Define the sentiment analysis endpoint
@app.post('/analyze/{text}')
async def classify_text(text_input:TextInput):
try:
# Convert input data to JSON serializable dictionary
text_input_dict = jsonable_encoder(text_input)
# Validate input data using Pydantic model
text_data = TextInput(**text_input_dict) # Convert to Pydantic model

# Validate input text length
if len(text_input.text) > MAX_TEXT_LENGTH:
raise HTTPException(status_code=400, detail="Text length exceeds maximum allowed length")
elif len(text_input.text) == 0:
raise HTTPException(status_code=400, detail="Text cannot be empty")
except ValidationError as e:
# Handle validation error
raise HTTPException(status_code=422, detail=str(e))

try:
# Perform text classification
return sentiment_task(preprocess_text(text_input.text))
except ValueError as ve:
# Handle value error
raise HTTPException(status_code=400, detail=str(ve))
except Exception as e:
# Handle other server errors
raise HTTPException(status_code=500, detail=str(e))

让我们修改我们的应用程序,创建一个新的镜像,并使用Docker将其容器化,以便查看POST端点的实际运行情况。我们首先需要为额外的依赖项修改requirements.txt文件。

requirements.txt

fastapi
uvicorn
nltk
pydantic
transformers
torch

然后,我们需要修改Dockerfile,因为我们需要指定容器中的可写目录,并为NLTK(自然语言工具包)任务和Hugging Face任务设置这些目录的权限。我们将在Dockerfile中添加以下命令。

# Set the TRANSFORMERS_CACHE environment variable
ENV TRANSFORMERS_CACHE=/tmp/.cache/huggingface

# Create the cache folder with appropriate permissions
RUN mkdir -p $TRANSFORMERS_CACHE && chmod -R 777 $TRANSFORMERS_CACHE

# Set NLTK data directory
ENV NLTK_DATA=/tmp/nltk_data

# Create the NLTK data directory with appropriate permissions
RUN mkdir -p $NLTK_DATA && chmod -R 777 $NLTK_DATA

以下是添加目录权限后修改后的完整 Dockerfile。

Dockerfile 文件

# syntax=docker/dockerfile:1

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.com/go/dockerfile-reference/

# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7

ARG PYTHON_VERSION=3.11.9
FROM python:${PYTHON_VERSION}-slim as base

# Prevents Python from writing pyc files.
ENV PYTHONDONTWRITEBYTECODE=1

# Keeps Python from buffering stdout and stderr to avoid situations where
# the application crashes without emitting any logs due to buffering.
ENV PYTHONUNBUFFERED=1

WORKDIR /app

# Create a non-privileged user that the app will run under.
# See https://docs.docker.com/go/dockerfile-user-best-practices/
ARG UID=10001
RUN adduser \
--disabled-password \
--gecos "" \
--home "/nonexistent" \
--shell "/sbin/nologin" \
--no-create-home \
--uid "${UID}" \
appuser

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
# Leverage a bind mount to requirements.txt to avoid having to copy them into
# into this layer.
RUN --mount=type=cache,target=/root/.cache/pip \
--mount=type=bind,source=requirements.txt,target=requirements.txt \
python -m pip install -r requirements.txt

# Switch to the non-privileged user to run the application.
USER appuser

# Set the TRANSFORMERS_CACHE environment variable
ENV TRANSFORMERS_CACHE=/tmp/.cache/huggingface

# Create the cache folder with appropriate permissions
RUN mkdir -p $TRANSFORMERS_CACHE && chmod -R 777 $TRANSFORMERS_CACHE

# Set NLTK data directory
ENV NLTK_DATA=/tmp/nltk_data

# Create the NLTK data directory with appropriate permissions
RUN mkdir -p $NLTK_DATA && chmod -R 777 $NLTK_DATA

# Copy the source code into the container.
COPY . .

# Expose the port that the application listens on.
EXPOSE 8000

# Run the application.
CMD uvicorn 'main:app' --host=0.0.0.0 --port=8000

我们将再次使用相同的命令创建新的映像和 Docker 容器。在执行此操作之前,请记住从 Docker Desktop 停止以前运行的容器。请记住,这次构建和运行 API 需要一些时间,因为 POST 端点使用 NLTK 库进行文本预处理,并从 Hugging Face Transformers 加载预训练模型。

运行以下命令以构建并运行容器:

docker build -t api_image .
docker run -p 8000:8000 api_image

我们完整的功能 API 现已在本地计算机上启动并运行。让我们通过 Swagger UI 与我们的 POST 端点进行交互。我们将尝试发送一些文本,看看 API 如何对其进行分类。http://localhost:8000/docs

第 8 步:通过 FastAPI TestClient 测试 API

我们将使用 FastAPI TestClient 为我们的文本分类 API 编写自动验证测试。

FastAPI TestClient 是 FastAPI 框架提供的一个实用程序,用于在受控和隔离的环境中测试 API 端点。它允许我们向 FastAPI 应用程序发送 HTTP 请求并以编程方式验证响应,而无需运行单独的服务器或发出实际的网络请求。

我们将使用[此处省略的具体命令或工具]来运行自动化测试。在运行测试之前,我们需要在虚拟环境中安装所有必需的依赖项。运行以下命令在pytestdocker_env中安装所需的软件包。

pip install httpx nltk transformers torch pytest

这是我们验证测试的代码。创建一个新的文件test_main.py用于测试 API。

test_main.py

from fastapi.testclient import TestClient
from main import app
from main import TextInput
from fastapi.encoders import jsonable_encoder

client = TestClient(app)

# Test the welcome endpoint
def test_welcome():
# Test the welcome endpoint
response = client.get("/")
assert response.status_code == 200
assert response.json() == "Welcome to our Text Classification API"

# Test the sentiment analysis endpoint for positive sentiment
def test_positive_sentiment():
with client:
# Define the request payload
# Initialize payload as a TextInput object
payload = TextInput(text="I love this product! It's amazing!")

# Convert TextInput object to JSON-serializable dictionary
payload_dict = jsonable_encoder(payload)

# Send a POST request to the sentiment analysis endpoint
response = client.post("/analyze/{text}", json=payload_dict)

# Assert that the response status code is 200 OK
assert response.status_code == 200

# Assert that the sentiment returned is positive
assert response.json()[0]['label'] == "positive"

# Test the sentiment analysis endpoint for negative sentiment
def test_negative_sentiment():
with client:
# Define the request payload
# Initialize payload as a TextInput object
payload = TextInput(text="I'm really disappointed with this service. It's terrible.")

# Convert TextInput object to JSON-serializable dictionary
payload_dict = jsonable_encoder(payload)

# Send a POST request to the sentiment analysis endpoint
response = client.post("/analyze/{text}", json=payload_dict)

# Assert that the response status code is 200 OK
assert response.status_code == 200

# Assert that the sentiment returned is positive
assert response.json()[0]['label'] == "negative"

# Test the sentiment analysis endpoint for neutral sentiment
def test_neutral_sentiment():
with client:
# Define the request payload
# Initialize payload as a TextInput object
payload = TextInput(text="This is a neutral statement.")

# Convert TextInput object to JSON-serializable dictionary
payload_dict = jsonable_encoder(payload)

# Send a POST request to the sentiment analysis endpoint
response = client.post("/analyze/{text}", json=payload_dict)

# Assert that the response status code is 200 OK
assert response.status_code == 200

# Assert that the sentiment returned is positive
assert response.json()[0]['label'] == "neutral"

执行以下命令以运行这些测试用例。

pytest

第 9 步:API 文档

文档非常重要,这样我们的 API 才能被其他开发人员轻松理解和使用。

FastAPI具有自动文档功能(Swagger UI或ReDoc)。此外,我们可以为API创建一个README.md文件。该文件应包含有关如何构建和运行Docker容器以及如何与API进行交互的说明。

第 10 步:在 Hugging Face Spaces 上部署 API

Hugging Face Spaces是一个易于使用的平台,可以发布各种类型的应用程序并免费托管。我们可以通过创建一个新空间并选择Docker作为选项来轻松地将我们的API部署到Hugging Face Spaces上。它将自动为我们的Docker容器创建一些配置文件。不要修改由空间创建的README.md文件。将您的API文件上传到空间中。请确保将Dockerfile中的端口更改为7860,这是Hugging Face使用的默认端口。或者,您也可以在README.md文件中将此变量设置为您所需的端口(app_port)。

关键要点

本案例研究描述了一个端到端的 MLOps 工作流程,从使用 FastAPI 和 Hugging Face 转换器创建文本分类 API 到使用 Docker 容器化 API 并将其部署到 Hugging Face Spaces 上。

引用

Hugging Facehttps://huggingface.co/spaces/aminaj/Text-Classification-API

GitHubhttps://github.com/aminajavaid30/Text-Classification-API

原文链接:https://medium.com/@aminajavaid30/text-classification-api-with-fastapi-docker-and-hugging-face-transformers-088bc8d8e8c5

#你可能也喜欢这些API文章!