Spaces:
Sleeping

howard9963 commited on
Commit
7361439
·
verified ·
1 Parent(s): e5d897c

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +28 -0
  2. repuirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Body
2
+ from transformers import AutoTokenizer
3
+
4
+ # 從 Hugging Face Space 的 Secret 環境變數取得 API_KEY
5
+ EXPECTED_API_KEY = os.environ.get("API_KEY", "")
6
+
7
+ # 初始化 CKIP 模型 (使用 Hugging Face 提供的預訓練模型)
8
+ tokenizer = AutoTokenizer.from_pretrained("ckiplab/bert-base-chinese-ws")
9
+
10
+ class TextInput(BaseModel):
11
+ text: str
12
+
13
+ app = FastAPI(title="CKIP Word Segmentation API")
14
+
15
+ @app.get("/")
16
+ def root():
17
+ return {"message": "CKIP Tokenizer API is running!"}
18
+
19
+ @app.post("/tokenize")
20
+ def tokenize(input_text: TextInput, x_api_key: str = Header(default=None)):
21
+ # 驗證 API Key
22
+ if not EXPECTED_API_KEY:
23
+ raise HTTPException(status_code=500, detail="Server missing API_KEY config")
24
+ if x_api_key != EXPECTED_API_KEY:
25
+ raise HTTPException(status_code=401, detail="Unauthorized: Invalid API Key")
26
+
27
+ tokens = tokenizer.tokenize(text)
28
+ return {"tokens": tokens}
repuirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ transformers
4
+ torch