Spaces:
Running on Zero

File size: 2,070 Bytes
5e0b6f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Download every model the app loads at runtime, at IMAGE BUILD time, so the
container starts fully offline (HF_HUB_OFFLINE=1) and never blocks a visitor on a
download. Instantiates each model the same way the app does (so only the files the
app actually needs are fetched), then runs one inference to prove it works.

Standalone on purpose (no controlplane imports) so Docker can cache this layer
independently of code changes.
"""

from __future__ import annotations

import os
import time

os.environ.pop("HF_HUB_OFFLINE", None)
os.environ.pop("TRANSFORMERS_OFFLINE", None)


def step(label, fn):
    t = time.time()
    fn()
    print(f"[prefetch] {label:45s} {time.time() - t:6.1f}s", flush=True)


def st_models():
    from sentence_transformers import SentenceTransformer

    for name in ("all-MiniLM-L6-v2", "BAAI/bge-small-en-v1.5"):
        SentenceTransformer(name, device="cpu").encode(["prefetch"])


def hf_pipelines():
    from transformers import pipeline

    for task, name in (
        ("text-classification", os.getenv("CP_NLI_MODEL", "cross-encoder/nli-distilroberta-base")),
        ("text-classification", "unitary/toxic-bert"),
        ("text-classification", "s-nlp/roberta_toxicity_classifier"),
    ):
        pipeline(task, model=name, top_k=None, device=-1)("prefetch text", truncation=True)


def detoxify():
    from detoxify import Detoxify

    Detoxify("original").predict(["prefetch text"])


def nltk_data():
    import nltk

    target = os.environ.get("NLTK_DATA")
    for pkg in ("punkt", "punkt_tab"):
        nltk.download(pkg, quiet=True, download_dir=target)


def spacy_model():
    import spacy

    spacy.load("en_core_web_sm")("Prefetch check for Microsoft Azure in Seattle.")


if __name__ == "__main__":
    step("sentence-transformers (MiniLM, bge-small)", st_models)
    step("HF pipelines (NLI, toxic-bert, s-nlp)", hf_pipelines)
    step("Detoxify original checkpoint", detoxify)
    step("NLTK punkt", nltk_data)
    step("spaCy en_core_web_sm", spacy_model)
    print("[prefetch] all models cached", flush=True)