ememzyvisuals commited on
Commit
89cbf60
·
verified ·
1 Parent(s): ebf3b27

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +7 -0
  2. app.py +139 -0
  3. 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,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io, json, logging, os, time, uuid, asyncio
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"
14
+ ORG_NAME = "wolethereader"
15
+ TGT_LANG = "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 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
+
31
+ EXTERNAL_ACCESS_TOKEN = os.environ.get("EXTERNAL_ACCESS_TOKEN")
32
+
33
+ async def verify_org_token(creds: HTTPAuthorizationCredentials = Depends(security)):
34
+ token = creds.credentials
35
+
36
+ if EXTERNAL_ACCESS_TOKEN and token == EXTERNAL_ACCESS_TOKEN:
37
+ log_event("auth_external_token_used")
38
+ return "external-collaborator"
39
+
40
+ now = time.time()
41
+ cached = _token_cache.get(token)
42
+ if cached and cached[1] > now:
43
+ return cached[0]
44
+ try:
45
+ info = hf_api.whoami(token=token)
46
+ except Exception:
47
+ log_event("auth_failed_invalid_token")
48
+ raise HTTPException(status_code=401, detail="Invalid or expired Hugging Face token")
49
+ username = info.get("name", "unknown")
50
+ user_orgs = [o.get("name") for o in info.get("orgs", [])]
51
+ if ORG_NAME not in user_orgs:
52
+ log_event("auth_failed_not_org_member", user=username, orgs=user_orgs)
53
+ raise HTTPException(status_code=403, detail=f"Token does not belong to a member of '{ORG_NAME}'")
54
+ _token_cache[token] = (username, now + TOKEN_CACHE_TTL)
55
+ return username
56
+
57
+ # ---------- Rate limiting ----------
58
+ _rate_state = defaultdict(deque)
59
+ RATE_LIMIT_PER_MIN = 30
60
+
61
+ def check_rate_limit(username: str):
62
+ now = time.time()
63
+ q = _rate_state[username]
64
+ while q and q[0] < now - 60:
65
+ q.popleft()
66
+ if len(q) >= RATE_LIMIT_PER_MIN:
67
+ raise HTTPException(status_code=429, detail="Rate limit exceeded, try again shortly")
68
+ q.append(now)
69
+
70
+ # ---------- Model ----------
71
+ tokenizer = None
72
+ model = None
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)
79
+ model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
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
+ source_lang: str
88
+ max_new_tokens: int = 128
89
+
90
+ @app.get("/")
91
+ def root():
92
+ return {"status": "ok", "languages": sorted(VALID_LANGS), "engine": MODEL_ID}
93
+
94
+ @app.get("/health")
95
+ def health():
96
+ return {"status": "ok" if model is not None else "loading"}
97
+
98
+ @app.post("/translate")
99
+ async def translate(req: TranslateRequest, username: str = Depends(verify_org_token)):
100
+ check_rate_limit(username)
101
+
102
+ if req.source_lang not in VALID_LANGS:
103
+ raise HTTPException(status_code=400, detail=f"source_lang must be one of {sorted(VALID_LANGS)}")
104
+ if not req.text or not req.text.strip():
105
+ raise HTTPException(status_code=400, detail="text must not be empty")
106
+ if len(req.text) > MAX_TEXT_CHARS:
107
+ raise HTTPException(status_code=400, detail=f"text exceeds {MAX_TEXT_CHARS} character limit")
108
+
109
+ request_id = str(uuid.uuid4())
110
+ start = time.time()
111
+
112
+ tokenizer.src_lang = LANG_CODES[req.source_lang]
113
+ inputs = tokenizer(req.text, return_tensors="pt", truncation=True, max_length=128).to(model.device)
114
+ tgt_id = tokenizer.convert_tokens_to_ids(TGT_LANG)
115
+ with torch.no_grad():
116
+ out = model.generate(
117
+ **inputs,
118
+ forced_bos_token_id=tgt_id,
119
+ max_new_tokens=req.max_new_tokens,
120
+ max_length=None,
121
+ )
122
+ translated = tokenizer.decode(out[0], skip_special_tokens=True)
123
+ elapsed_s = round(time.time() - start, 2)
124
+
125
+ log_event("translate_ok", request_id=request_id, user=username,
126
+ source_lang=req.source_lang, elapsed_s=elapsed_s)
127
+
128
+ return {
129
+ "request_id": request_id,
130
+ "source_lang": req.source_lang,
131
+ "target_lang": "en",
132
+ "translated_text": translated,
133
+ "elapsed_s": elapsed_s,
134
+ }
135
+
136
+ @app.exception_handler(HTTPException)
137
+ async def http_exception_handler(request: Request, exc: HTTPException):
138
+ log_event("request_error", path=str(request.url.path), status_code=exc.status_code, detail=exc.detail)
139
+ 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