
什么是GPT-4?完整指南
文本分類是自然語言處理中的基本任務之一。它是指將文本分類為多個預定義的標簽。它通常是使用機器學習算法和自然語言處理技術完成的。
現實世界中有許多文本分類的使用案例,例如客戶評論的情緒分析、電子郵件垃圾郵件過濾、文檔分類、主題建模和意圖檢測。
隨著機器學習和人工智能領域的進步,這些文本分類任務已經通過Hugging Face上的多個預訓練模型得以實現。因此,我們無需從頭開始。我們可以從數千個已可用的模型中挑選,并使用它們來對文本進行分類。
我將指導您完成使用 FastAPI、Docker 和 Hugging Face 轉換器構建端到端文本分類 API 的過程。這是一個 MLOps 案例研究,涵蓋了從創建用于文本分類的 FastAPI 端點到使用 Docker 容器化 API 的所有內容。因此,讓我們從對本案例研究中使用的技術堆棧的基本了解開始。
Hugging Face 是一個面向機器學習工程師的協作平臺,他們可以在其中上傳預訓練模型、部署機器學習應用程序以及執行更多操作。該平臺上有數千個與機器學習、深度學習、計算機視覺、自然語言處理和語音識別相關的預訓練模型,可以通過 Hugging Face transformers 庫使用。
API 代表應用程序編程接口。它是兩個或多個計算機程序或組件使用一組規則和協議相互通信的一種方式。API 可用于訪問應用程序的功能、從數據庫中檢索數據或執行其他任務。
FastAPI 是一個現代的高性能 Web 框架,用于使用 Python 構建 API。學習起來非常快速和直觀,您只需幾行代碼即可實現很多功能。
Docker是一組平臺即服務產品,它使用操作系統級別的虛擬化來以稱為容器的軟件包交付軟件。Docker容器是一個便攜的計算環境。它是一個完整的軟件包,包含應用程序的代碼、依賴項和配置。Docker容器鏡像是一個輕量級、獨立、可執行的軟件包,包含運行應用程序所需的一切,即代碼、運行時、系統工具、系統庫和設置。因此,無論在哪臺機器上,應用程序都作為一個單獨的實體運行,并且每次運行都完全相同。
現在我們已經對這些工具和框架有了基本的了解,讓我們直接進入API的構建。我們將使用FastAPI開發一個RESTful API,該API利用預訓練的Hugging Face Transformer模型來執行文本分類(情感分析)。該API將使用Docker進行容器化。
訪問 https://huggingface.co/models 的 Hugging Face 平臺。在自然語言處理下選擇文本分類,它將顯示超過 50,000 個模型可供選擇。我們可以根據項目的目的或我們試圖解決的問題來選擇我們選擇的任何模型。在這里,我們將選擇 Twitter-roBERTa-base 進行情緒分析模型,這是一個基于 RoBERTa 的模型,在 2018 年 1 月至 2021 年 12 月期間對 ~124M 條推文進行了訓練,并使用 TweetEval 基準對推文分類進行了微調以進行情緒分析。
要在本地計算機上運行 Docker 容器,您需要安裝 Docker Desktop。您可以根據您的操作系統從 https://www.docker.com/products/docker-desktop/ 下載安裝程序,然后運行可執行文件將其安裝到您的計算機上。
創建一個名為text-classification-api的新目錄,用于存放文本分類API。打開命令提示符,并導航到text-classification-api目錄。運行以下命令以初始化Docker容器。
docker init
系統會向您提出幾個問題。請將應用程序平臺選擇為Python,版本和端口保持默認設置,并輸入運行應用程序的命令。
uvicorn 'main:app' --host=0.0.0.0 --port=8000
它將為您的項目創建以下默認配置文件:
應用程序的基本結構現已準備就緒。
.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
設置虛擬環境是 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
API端點是由API公開的一個特定URL。它代表客戶端應用程序和托管API的服務器之間的交互點。每個端點通常對應于API提供的特定功能或資源,并定義了客戶端可以執行的操作以及它們可以使用的數據格式。當客戶端應用程序向特定的API端點發出HTTP請求時,服務器會處理該請求并返回響應,通常以指定的數據格式(如JSON,即JavaScript對象表示法)返回。
我們將使用FastAPI開發一個包含GET和POST兩個端點的API。GET端點是API的入口點,它向客戶端返回一個歡迎消息。POST端點接受包含文本字段的JSON輸入,并返回文本的情感傾向。我們將把選定的Hugging Face Transformers模型集成到這個API中。
創建 main.py 作為您的主應用程序文件。它將包含應用程序的所有代碼,包括端點。
編寫以下代碼以使用歡迎終端節點初始化 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
運行以下命令以在本地計算機上構建 Docker 鏡像。
docker build -t api_image
運行以下命令以容器化您的 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會返回文本的情感傾向,如正面、負面或中性。
我們將修改main.py文件以添加POST端點。我們將使用Hugging Face的庫來加載預訓練模型。我們需要確保API高效地處理模型加載,可能使用FastAPI的背景任務或啟動事件。transformers
讓我們一步一步來。
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
我們將使用 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
文檔非常重要,這樣我們的 API 才能被其他開發人員輕松理解和使用。
FastAPI具有自動文檔功能(Swagger UI或ReDoc)。此外,我們可以為API創建一個README.md
文件。該文件應包含有關如何構建和運行Docker容器以及如何與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 Face :https://huggingface.co/spaces/aminaj/Text-Classification-API
GitHub :https://github.com/aminajavaid30/Text-Classification-API