Mohameddda commited on
Commit
f9b46ea
·
1 Parent(s): 1c3fe08

fix: pass HF_TOKEN to pipeline calls, add retry for rate limits

Browse files
Files changed (2) hide show
  1. Dockerfile +0 -1
  2. main.py +29 -8
Dockerfile CHANGED
@@ -16,7 +16,6 @@ COPY . .
16
  # Pre-create HF / torch cache dirs writable by appuser
17
  RUN mkdir -p /home/appuser/.cache && chown -R appuser:appuser /home/appuser /app
18
  ENV HF_HOME=/home/appuser/.cache/huggingface
19
- ENV TRANSFORMERS_CACHE=/home/appuser/.cache/huggingface/hub
20
 
21
  USER appuser
22
 
 
16
  # Pre-create HF / torch cache dirs writable by appuser
17
  RUN mkdir -p /home/appuser/.cache && chown -R appuser:appuser /home/appuser /app
18
  ENV HF_HOME=/home/appuser/.cache/huggingface
 
19
 
20
  USER appuser
21
 
main.py CHANGED
@@ -77,20 +77,41 @@ arabic_classifier = None # dedicated Arabic hate-speech model
77
  llm_client: InferenceClient | None = None # HF Inference API client
78
 
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  @asynccontextmanager
81
  async def lifespan(app: FastAPI):
82
  """Load both AI models when the server starts; release on shutdown."""
83
  global toxicity_classifier, arabic_classifier, llm_client
84
 
85
- toxicity_classifier = pipeline(
86
- "text-classification",
87
- model=MODEL_NAME,
88
- tokenizer=MODEL_NAME,
89
  )
90
- arabic_classifier = pipeline(
91
- "text-classification",
92
- model=ARABIC_MODEL_NAME,
93
- tokenizer=ARABIC_MODEL_NAME,
94
  )
95
 
96
  # Set up the LLM client (optional – works without a token at lower rate)
 
77
  llm_client: InferenceClient | None = None # HF Inference API client
78
 
79
 
80
+ def _load_pipeline_with_retry(task: str, model: str, max_retries: int = 5):
81
+ """Load a HF pipeline with exponential backoff for rate-limit errors."""
82
+ import time
83
+
84
+ for attempt in range(1, max_retries + 1):
85
+ try:
86
+ return pipeline(
87
+ task,
88
+ model=model,
89
+ tokenizer=model,
90
+ token=HF_TOKEN,
91
+ )
92
+ except (OSError, ValueError) as exc:
93
+ if "429" in str(exc) and attempt < max_retries:
94
+ wait = 2 ** attempt # 2, 4, 8, 16, 32 s
95
+ logger.warning(
96
+ "Rate-limited loading %s (attempt %d/%d). "
97
+ "Retrying in %ds …",
98
+ model, attempt, max_retries, wait,
99
+ )
100
+ time.sleep(wait)
101
+ else:
102
+ raise
103
+
104
+
105
  @asynccontextmanager
106
  async def lifespan(app: FastAPI):
107
  """Load both AI models when the server starts; release on shutdown."""
108
  global toxicity_classifier, arabic_classifier, llm_client
109
 
110
+ toxicity_classifier = _load_pipeline_with_retry(
111
+ "text-classification", MODEL_NAME,
 
 
112
  )
113
+ arabic_classifier = _load_pipeline_with_retry(
114
+ "text-classification", ARABIC_MODEL_NAME,
 
 
115
  )
116
 
117
  # Set up the LLM client (optional – works without a token at lower rate)