
前言
當你嘗試按照官方指引部署 Hugging Face Spaces 時:
git init
git add app.py requirements.txt
git commit -m "Initial commit"
git remote add origin https://huggingface.co/spaces/YOUR_USERNAME/mcp-sentiment
git push -u origin main
你可能會遇到各種錯誤。本指南將帶你逐步解決這些問題,並成功部署到 Hugging Face Spaces。
為什麼原始指令無法運作?
自 2023 年 10 月 1 日起,Hugging Face 停止支援密碼身分驗證,因此當你使用 HTTPS URL 推送時,會收到以下錯誤訊息:
remote: Password authentication in git is no longer supported.
You must use a user access token or an SSH key instead.
第一步:建立 Hugging Face Space
- 前往 huggingface.co/spaces
- 點選「Create new Space」
- 填寫以下資訊:
- Owner: 選擇你的使用者名稱或組織
- Space name: 輸入名稱(例如:mcp-sentiment)
- License: 選擇授權條款
- Space SDK: 選擇 Gradio
- Hardware: 選擇 CPU basic(免費)
- Visibility: 選擇 Public 或 Private
第二步:準備專案檔案
建立 requirements.txt
gradio[mcp]
textblob
注意: 由於 conda 無法理解 Python extras 語法(方括號部分),以下指令會失敗:
conda install "gradio[mcp]" textblob # ❌ 無法運作
如果使用 conda,建議採用混合方式:
conda create -n llmtools python=3.11
conda activate llmtools
conda install -c conda-forge textblob
pip install "gradio[mcp]"
建立 app.py
import json
import gradio as gr
from textblob import TextBlob
def sentiment_analysis(text: str) -> str:
"""
Analyze the sentiment of the given text.
Args:
text (str): The text to analyze
Returns:
str: A JSON string containing polarity, subjectivity, and assessment
"""
blob = TextBlob(text)
sentiment = blob.sentiment
result = {
"polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive)
"subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective)
"assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
}
return json.dumps(result)
# Create the Gradio interface
demo = gr.Interface(
fn=sentiment_analysis,
inputs=gr.Textbox(placeholder="Enter text to analyze..."),
outputs=gr.Textbox(), # Changed from gr.JSON() to gr.Textbox()
title="Text Sentiment Analysis",
description="Analyze the sentiment of text using TextBlob"
)
# Launch the interface and MCP server
if __name__ == "__main__":
demo.launch(mcp_server=True)
第三步
初始化儲存庫
git init
git add app.py requirements.txt
設定 Git 身分(必要步驟)
git config --global user.name "你的名字"
git config --global user.email "你的郵箱@example.com"
如果忽略這個步驟,就會收到錯誤:
Author identity unknown
*** Please tell me who you are.
第一次提交
git commit -m "Initial commit"