File size: 1,127 Bytes
d363f25
 
 
b194439
d363f25
 
 
 
 
 
 
 
 
 
 
00accf7
d363f25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b2bc93
 
 
d363f25
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import os
from fastapi import FastAPI, Header, HTTPException, Body
from transformers import AutoTokenizer
import gradio as gr

# 從環境變數讀取 secret
EXPECTED_API_KEY = os.environ.get("apikey")

# 初始化 tokenizer
tokenizer = AutoTokenizer.from_pretrained("ckiplab/bert-base-chinese-ws")

app = FastAPI(title="CKIP Word Segmentation API")

# ✅ GET 方法:健康檢查
@app.get("/check")
def health_check():
    return {"status": "ok", "message": "API is running"}

# ✅ POST 方法:斷詞
@app.post("/tokenize")
async def tokenize(

    text: str = Body(..., embed=True),

    x_api_key: str = Header(None)

):
    # 驗證 API Key 設定是否存在
    if not EXPECTED_API_KEY:
        raise HTTPException(status_code=500, detail="Server missing API_KEY config")
    # 驗證 API Key 值是否正確
    if x_api_key != EXPECTED_API_KEY:
        raise HTTPException(status_code=401, detail="Invalid API Key")

    tokens = tokenizer.tokenize(text)
    return {"tokens": tokens}
    
with gr.Blocks() as demo:
    print('boot')

if __name__ == "__main__":
    demo.launch()