111
111
972c71f
# cd my-first-ai
# pip install fastapi uvicorn
# fastapi:现代 Python Web 框架,自动生成 API 文档
# uvicorn:高性能 ASGI 服务器,用于运行 FastAPI
# 🚀 今日核心任务(30–50 分钟)
# 步骤 1:创建 API 文件 api.py
# 启动命令:python -m uvicorn api:app --reload --port 8000
# --reload:代码修改后自动重启(开发模式)
# 默认地址:http://localhost:8000
# 步骤 3:测试 API
# 方法 1:打开浏览器访问文档
# 访问:http://localhost:8000/docs
# 你会看到自动生成的交互式 API 文档(Swagger UI)👇
# 点击 /analyze → “Try it out” → 输入:
# {"text": "这个功能真的很棒!"}
# 生成依赖列表
# pip freeze > requirements.txt
import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
from fastapi import FastAPI, HTTPException
from transformers import pipeline
# 初始化 FastAPI 应用
app = FastAPI(title="AI 新闻分类服务", version="1.0")
# 加载模型(只加载一次,启动时完成)
classifier = pipeline(
"text-classification",
model="uer/roberta-base-finetuned-chinanews-chinese"
)
# 定义请求体(可选,但推荐)
from pydantic import BaseModel
class TextInput(BaseModel):
text: str
# 定义 API 接口
@app.post("/analyze")
def analyze_sentiment(input: TextInput):
if len(input.text) > 512:
raise HTTPException(status_code=400, detail="文本过长,请控制在512字以内")
try:
result = classifier(input.text)
label = result[0]['label']
score = round(result[0]['score'], 4)
print("label:", label, "score:", score)
# 统一返回格式
return {
"text": input.text,
"category": label,
"confidence": score
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"模型推理失败: {str(e)}")
# 健康检查接口
@app.get("/health")
def health_check():
return {"status": "ok"}