Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- Dockerfile +7 -0
- app.py +143 -0
- requirements.txt +7 -0
Dockerfile
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
WORKDIR /app
|
| 3 |
+
COPY requirements.txt .
|
| 4 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 5 |
+
COPY app.py .
|
| 6 |
+
EXPOSE 7860
|
| 7 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json, os, time, uuid
|
| 2 |
+
from collections import defaultdict, deque
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from fastapi import FastAPI, HTTPException, Depends, Request
|
| 6 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 7 |
+
from fastapi.responses import JSONResponse
|
| 8 |
+
from huggingface_hub import HfApi
|
| 9 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
|
| 12 |
+
# ---------- Config ----------
|
| 13 |
+
MODEL_ID = "wolethereader/STORM-OS-MT-3B-BIDIRECTIONAL"
|
| 14 |
+
ORG_NAME = "wolethereader"
|
| 15 |
+
EN = "eng_Latn"
|
| 16 |
+
LANG_CODES = {"yo": "yor_Latn", "ha": "hau_Latn", "ig": "ibo_Latn", "pcm": "pcm_Latn"}
|
| 17 |
+
VALID_LANGS = set(LANG_CODES.keys())
|
| 18 |
+
MAX_TEXT_CHARS = 2000
|
| 19 |
+
|
| 20 |
+
app = FastAPI(title="STORM-OS Bidirectional MT API")
|
| 21 |
+
|
| 22 |
+
def log_event(event, **fields):
|
| 23 |
+
print(json.dumps({"event": event, "ts": time.time(), **fields}))
|
| 24 |
+
|
| 25 |
+
# ---------- Auth: HF token AND must belong to the org ----------
|
| 26 |
+
security = HTTPBearer()
|
| 27 |
+
hf_api = HfApi()
|
| 28 |
+
_token_cache = {}
|
| 29 |
+
TOKEN_CACHE_TTL = 300
|
| 30 |
+
EXTERNAL_ACCESS_TOKEN = os.environ.get("EXTERNAL_ACCESS_TOKEN")
|
| 31 |
+
|
| 32 |
+
async def verify_org_token(creds: HTTPAuthorizationCredentials = Depends(security)):
|
| 33 |
+
token = creds.credentials
|
| 34 |
+
|
| 35 |
+
if EXTERNAL_ACCESS_TOKEN and token == EXTERNAL_ACCESS_TOKEN:
|
| 36 |
+
log_event("auth_external_token_used")
|
| 37 |
+
return "external-collaborator"
|
| 38 |
+
|
| 39 |
+
now = time.time()
|
| 40 |
+
cached = _token_cache.get(token)
|
| 41 |
+
if cached and cached[1] > now:
|
| 42 |
+
return cached[0]
|
| 43 |
+
try:
|
| 44 |
+
info = hf_api.whoami(token=token)
|
| 45 |
+
except Exception:
|
| 46 |
+
log_event("auth_failed_invalid_token")
|
| 47 |
+
raise HTTPException(status_code=401, detail="Invalid or expired Hugging Face token")
|
| 48 |
+
username = info.get("name", "unknown")
|
| 49 |
+
user_orgs = [o.get("name") for o in info.get("orgs", [])]
|
| 50 |
+
if ORG_NAME not in user_orgs:
|
| 51 |
+
log_event("auth_failed_not_org_member", user=username, orgs=user_orgs)
|
| 52 |
+
raise HTTPException(status_code=403, detail=f"Token does not belong to a member of '{ORG_NAME}'")
|
| 53 |
+
_token_cache[token] = (username, now + TOKEN_CACHE_TTL)
|
| 54 |
+
return username
|
| 55 |
+
|
| 56 |
+
# ---------- Rate limiting ----------
|
| 57 |
+
_rate_state = defaultdict(deque)
|
| 58 |
+
RATE_LIMIT_PER_MIN = 30
|
| 59 |
+
|
| 60 |
+
def check_rate_limit(username: str):
|
| 61 |
+
now = time.time()
|
| 62 |
+
q = _rate_state[username]
|
| 63 |
+
while q and q[0] < now - 60:
|
| 64 |
+
q.popleft()
|
| 65 |
+
if len(q) >= RATE_LIMIT_PER_MIN:
|
| 66 |
+
raise HTTPException(status_code=429, detail="Rate limit exceeded, try again shortly")
|
| 67 |
+
q.append(now)
|
| 68 |
+
|
| 69 |
+
# ---------- Model ----------
|
| 70 |
+
tokenizer = None
|
| 71 |
+
model = None
|
| 72 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") # repo is private
|
| 73 |
+
|
| 74 |
+
@app.on_event("startup")
|
| 75 |
+
async def startup():
|
| 76 |
+
global tokenizer, model
|
| 77 |
+
log_event("loading_model", model=MODEL_ID)
|
| 78 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
|
| 79 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16, token=HF_TOKEN)
|
| 80 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 81 |
+
model.to(device)
|
| 82 |
+
model.eval()
|
| 83 |
+
log_event("model_loaded_ok", device=device)
|
| 84 |
+
|
| 85 |
+
class TranslateRequest(BaseModel):
|
| 86 |
+
text: str
|
| 87 |
+
direction: str # "forward" (local -> English) or "reverse" (English -> local)
|
| 88 |
+
lang: str # the local language code, regardless of direction
|
| 89 |
+
max_new_tokens: int = 128
|
| 90 |
+
|
| 91 |
+
@app.get("/")
|
| 92 |
+
def root():
|
| 93 |
+
return {"status": "ok", "languages": sorted(VALID_LANGS), "directions": ["forward", "reverse"], "engine": MODEL_ID}
|
| 94 |
+
|
| 95 |
+
@app.get("/health")
|
| 96 |
+
def health():
|
| 97 |
+
return {"status": "ok" if model is not None else "loading"}
|
| 98 |
+
|
| 99 |
+
@app.post("/translate")
|
| 100 |
+
async def translate(req: TranslateRequest, username: str = Depends(verify_org_token)):
|
| 101 |
+
check_rate_limit(username)
|
| 102 |
+
|
| 103 |
+
if req.lang not in VALID_LANGS:
|
| 104 |
+
raise HTTPException(status_code=400, detail=f"lang must be one of {sorted(VALID_LANGS)}")
|
| 105 |
+
if req.direction not in ("forward", "reverse"):
|
| 106 |
+
raise HTTPException(status_code=400, detail="direction must be 'forward' or 'reverse'")
|
| 107 |
+
if not req.text or not req.text.strip():
|
| 108 |
+
raise HTTPException(status_code=400, detail="text must not be empty")
|
| 109 |
+
if len(req.text) > MAX_TEXT_CHARS:
|
| 110 |
+
raise HTTPException(status_code=400, detail=f"text exceeds {MAX_TEXT_CHARS} character limit")
|
| 111 |
+
|
| 112 |
+
request_id = str(uuid.uuid4())
|
| 113 |
+
start = time.time()
|
| 114 |
+
|
| 115 |
+
if req.direction == "forward":
|
| 116 |
+
src_lang, tgt_lang = LANG_CODES[req.lang], EN
|
| 117 |
+
else:
|
| 118 |
+
src_lang, tgt_lang = EN, LANG_CODES[req.lang]
|
| 119 |
+
|
| 120 |
+
tokenizer.src_lang = src_lang
|
| 121 |
+
inputs = tokenizer(req.text, return_tensors="pt", truncation=True, max_length=128).to(model.device)
|
| 122 |
+
tgt_id = tokenizer.convert_tokens_to_ids(tgt_lang)
|
| 123 |
+
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
out = model.generate(**inputs, forced_bos_token_id=tgt_id, max_new_tokens=req.max_new_tokens, max_length=None)
|
| 126 |
+
|
| 127 |
+
translated = tokenizer.decode(out[0], skip_special_tokens=True)
|
| 128 |
+
elapsed_s = round(time.time() - start, 2)
|
| 129 |
+
|
| 130 |
+
log_event("translate_ok", request_id=request_id, user=username, direction=req.direction, lang=req.lang, elapsed_s=elapsed_s)
|
| 131 |
+
|
| 132 |
+
return {
|
| 133 |
+
"request_id": request_id,
|
| 134 |
+
"direction": req.direction,
|
| 135 |
+
"lang": req.lang,
|
| 136 |
+
"translated_text": translated,
|
| 137 |
+
"elapsed_s": elapsed_s,
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
@app.exception_handler(HTTPException)
|
| 141 |
+
async def http_exception_handler(request: Request, exc: HTTPException):
|
| 142 |
+
log_event("request_error", path=str(request.url.path), status_code=exc.status_code, detail=exc.detail)
|
| 143 |
+
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
transformers==5.15.0
|
| 4 |
+
torch
|
| 5 |
+
sentencepiece
|
| 6 |
+
accelerate
|
| 7 |
+
python-multipart
|