millid 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- millid/__init__.py +35 -0
- millid/batching.py +92 -0
- millid/cli.py +58 -0
- millid/data/scripts.json +1 -0
- millid/encoding.py +165 -0
- millid/registry.py +104 -0
- millid/runtime.py +212 -0
- millid/server.py +87 -0
- millid-0.2.0.dist-info/METADATA +225 -0
- millid-0.2.0.dist-info/RECORD +13 -0
- millid-0.2.0.dist-info/WHEEL +4 -0
- millid-0.2.0.dist-info/entry_points.txt +2 -0
- millid-0.2.0.dist-info/licenses/LICENSE +202 -0
millid/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""MillID (MultiLingual Language IDentifier): the language of a text, for 1,600+ language-script
|
|
2
|
+
pairs, with ONNX Runtime.
|
|
3
|
+
|
|
4
|
+
from millid import MillID
|
|
5
|
+
|
|
6
|
+
model = MillID.from_pretrained("tiny-v1.5") # or large-v1.5, medium-v1, a repo id, a directory
|
|
7
|
+
model.predict("Lave men ou ak savon anvan ou manje.", k=3)
|
|
8
|
+
model.predict(["one text", "another"], k=3) # a list gives a list of answers
|
|
9
|
+
model.identify_document(long_text) # a whole document, in windows
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from millid.batching import MicroBatcher
|
|
13
|
+
from millid.encoding import encode_batch, normalize
|
|
14
|
+
from millid.registry import ModelSpec, Registry, parse_specs
|
|
15
|
+
from millid.runtime import DEFAULT_MODEL, MODELS, DocumentResult, LanguageIdentifier, Prediction, Segment
|
|
16
|
+
|
|
17
|
+
#: The shorter name for LanguageIdentifier.
|
|
18
|
+
MillID = LanguageIdentifier
|
|
19
|
+
|
|
20
|
+
__version__ = "0.2.0"
|
|
21
|
+
__all__ = [
|
|
22
|
+
"DEFAULT_MODEL",
|
|
23
|
+
"MODELS",
|
|
24
|
+
"DocumentResult",
|
|
25
|
+
"LanguageIdentifier",
|
|
26
|
+
"MicroBatcher",
|
|
27
|
+
"MillID",
|
|
28
|
+
"ModelSpec",
|
|
29
|
+
"Prediction",
|
|
30
|
+
"Registry",
|
|
31
|
+
"Segment",
|
|
32
|
+
"encode_batch",
|
|
33
|
+
"normalize",
|
|
34
|
+
"parse_specs",
|
|
35
|
+
]
|
millid/batching.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Many concurrent requests, few model calls.
|
|
2
|
+
|
|
3
|
+
Requests that arrive while a batch is running wait in a queue; the next batch takes them all,
|
|
4
|
+
up to max_batch passages. Each batch runs in a worker thread (ONNX Runtime releases the GIL),
|
|
5
|
+
so the event loop keeps accepting requests. Under load batches grow and the cost per passage
|
|
6
|
+
falls; with one caller a request waits at most max_wait_ms.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from millid.runtime import DocumentResult, LanguageIdentifier, Prediction
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MicroBatcher:
|
|
20
|
+
def __init__(self, identifier: LanguageIdentifier, max_batch: int = 256, max_wait_ms: float = 2.0, parallel: int = 1):
|
|
21
|
+
"""parallel: batches in flight at once. 1 suits a CPU session that already uses every
|
|
22
|
+
core it was given, and a GPU session under a memory cap; more needs the memory for it."""
|
|
23
|
+
self.identifier = identifier
|
|
24
|
+
self.max_batch = max_batch
|
|
25
|
+
self.max_wait = max_wait_ms / 1000
|
|
26
|
+
self.parallel = parallel
|
|
27
|
+
self._executor = ThreadPoolExecutor(max_workers=parallel, thread_name_prefix="millid")
|
|
28
|
+
self._queue: asyncio.Queue | None = None
|
|
29
|
+
self._workers: list[asyncio.Task] = []
|
|
30
|
+
|
|
31
|
+
def _start(self) -> asyncio.Queue:
|
|
32
|
+
if self._queue is None:
|
|
33
|
+
self._queue = asyncio.Queue()
|
|
34
|
+
self._workers = [asyncio.create_task(self._run()) for _ in range(self.parallel)]
|
|
35
|
+
return self._queue
|
|
36
|
+
|
|
37
|
+
async def probabilities(self, texts: list[str]) -> np.ndarray:
|
|
38
|
+
if not texts:
|
|
39
|
+
return self.identifier.probabilities([])
|
|
40
|
+
future = asyncio.get_running_loop().create_future()
|
|
41
|
+
await self._start().put((list(texts), future))
|
|
42
|
+
return await future
|
|
43
|
+
|
|
44
|
+
async def predict(self, texts: list[str], k: int = 3) -> list[list[Prediction]]:
|
|
45
|
+
return self.identifier.top(await self.probabilities(texts), k)
|
|
46
|
+
|
|
47
|
+
async def identify_document(self, text: str, k: int = 3, max_windows: int = 256) -> DocumentResult:
|
|
48
|
+
# Off the event loop: cutting a megabyte of text into windows takes a moment.
|
|
49
|
+
norm, spans = await asyncio.to_thread(self.identifier.document_windows, text, max_windows)
|
|
50
|
+
probs = await self.probabilities([norm[a:b] for a, b in spans])
|
|
51
|
+
return self.identifier.combine(norm, spans, probs, k)
|
|
52
|
+
|
|
53
|
+
async def _run(self) -> None:
|
|
54
|
+
loop = asyncio.get_running_loop()
|
|
55
|
+
queue = self._queue
|
|
56
|
+
while True:
|
|
57
|
+
items = [await queue.get()]
|
|
58
|
+
size = len(items[0][0])
|
|
59
|
+
deadline = loop.time() + self.max_wait
|
|
60
|
+
while size < self.max_batch:
|
|
61
|
+
try:
|
|
62
|
+
item = queue.get_nowait()
|
|
63
|
+
except asyncio.QueueEmpty:
|
|
64
|
+
remaining = deadline - loop.time()
|
|
65
|
+
if remaining <= 0:
|
|
66
|
+
break
|
|
67
|
+
try:
|
|
68
|
+
item = await asyncio.wait_for(queue.get(), remaining)
|
|
69
|
+
except asyncio.TimeoutError:
|
|
70
|
+
break
|
|
71
|
+
items.append(item)
|
|
72
|
+
size += len(item[0])
|
|
73
|
+
texts = [t for batch, _ in items for t in batch]
|
|
74
|
+
try:
|
|
75
|
+
probs = await loop.run_in_executor(self._executor, self.identifier.probabilities, texts)
|
|
76
|
+
except Exception as e: # every waiting request learns why, none hangs
|
|
77
|
+
for _, future in items:
|
|
78
|
+
if not future.done():
|
|
79
|
+
future.set_exception(e)
|
|
80
|
+
continue
|
|
81
|
+
at = 0
|
|
82
|
+
for batch, future in items:
|
|
83
|
+
if not future.done():
|
|
84
|
+
future.set_result(probs[at : at + len(batch)])
|
|
85
|
+
at += len(batch)
|
|
86
|
+
|
|
87
|
+
async def aclose(self) -> None:
|
|
88
|
+
for task in self._workers:
|
|
89
|
+
task.cancel()
|
|
90
|
+
await asyncio.gather(*self._workers, return_exceptions=True)
|
|
91
|
+
self._workers, self._queue = [], None
|
|
92
|
+
self._executor.shutdown(wait=False, cancel_futures=True)
|
millid/cli.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""`millid predict` (also `millid identify`) and `millid serve`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from dataclasses import asdict
|
|
10
|
+
|
|
11
|
+
from millid.runtime import DEFAULT_MODEL
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main(argv: list[str] | None = None) -> None:
|
|
15
|
+
ap = argparse.ArgumentParser(prog="millid", description="MillID language identification (ONNX Runtime).")
|
|
16
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
17
|
+
|
|
18
|
+
ident = sub.add_parser(
|
|
19
|
+
"predict", aliases=["identify"], help="the languages of texts given as arguments or on stdin, one per line"
|
|
20
|
+
)
|
|
21
|
+
ident.add_argument("texts", nargs="*")
|
|
22
|
+
ident.add_argument("--model", default=DEFAULT_MODEL, help="tiny-v1.5, large-v1.5, medium-v1, a repo id or a directory")
|
|
23
|
+
ident.add_argument("--device", default="cpu", choices=["cpu", "cuda", "auto"])
|
|
24
|
+
ident.add_argument("-k", "--k", type=int, default=3)
|
|
25
|
+
ident.add_argument("--document", action="store_true", help="read all the input as one document, in windows")
|
|
26
|
+
|
|
27
|
+
serve = sub.add_parser("serve", help="the HTTP service: POST /identify, GET /models, GET /health")
|
|
28
|
+
serve.add_argument("--models", default=os.environ.get("MILLID_MODELS", "tiny-v1.5=baobabtech/millid-tiny-v1.5@cpu"),
|
|
29
|
+
help="name=ref[@device][#threads],...") # fmt: skip
|
|
30
|
+
serve.add_argument("--default", default=os.environ.get("MILLID_DEFAULT"))
|
|
31
|
+
serve.add_argument("--host", default="127.0.0.1")
|
|
32
|
+
serve.add_argument("--port", type=int, default=8050)
|
|
33
|
+
serve.add_argument("--workers", type=int, default=1, help="processes, each with every model loaded")
|
|
34
|
+
args = ap.parse_args(argv)
|
|
35
|
+
|
|
36
|
+
if args.command in ("predict", "identify"):
|
|
37
|
+
from millid.runtime import LanguageIdentifier
|
|
38
|
+
|
|
39
|
+
texts = args.texts or [line.rstrip("\n") for line in sys.stdin if line.strip()]
|
|
40
|
+
model = LanguageIdentifier.from_pretrained(args.model, device=args.device)
|
|
41
|
+
if args.document:
|
|
42
|
+
print(json.dumps(asdict(model.identify_document("\n".join(texts), args.k)), ensure_ascii=False, indent=2))
|
|
43
|
+
return
|
|
44
|
+
for text, preds in zip(texts, model.predict(texts, args.k), strict=True):
|
|
45
|
+
answers = ", ".join(f"{p.label} {p.probability:.3f}" for p in preds)
|
|
46
|
+
print(f"{answers}\t{text[:80]}")
|
|
47
|
+
return
|
|
48
|
+
|
|
49
|
+
import uvicorn
|
|
50
|
+
|
|
51
|
+
os.environ["MILLID_MODELS"] = args.models
|
|
52
|
+
if args.default:
|
|
53
|
+
os.environ["MILLID_DEFAULT"] = args.default
|
|
54
|
+
uvicorn.run("millid.server:app_from_env", factory=True, host=args.host, port=args.port, workers=args.workers)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
if __name__ == "__main__":
|
|
58
|
+
main()
|
millid/data/scripts.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"unicode_version":"15.0.0","script_buckets":512,"size":1114112,"starts":[0,65,91,97,123,170,171,181,182,186,187,192,215,216,247,248,688,706,710,711,712,722,736,741,748,749,750,751,768,880,885,886,888,890,894,895,896,902,903,904,907,908,909,910,930,931,994,1008,1014,1015,1024,1154,1155,1162,1328,1329,1367,1369,1370,1376,1417,1425,1470,1471,1472,1473,1475,1476,1478,1479,1480,1488,1515,1519,1523,1552,1563,1568,1632,1646,1748,1749,1757,1759,1769,1770,1776,1786,1789,1791,1792,1808,1867,1869,1872,1920,1970,1994,2038,2042,2043,2045,2046,2048,2094,2112,2140,2144,2155,2160,2184,2185,2191,2200,2274,2275,2304,2404,2417,2432,2436,2437,2445,2447,2449,2451,2473,2474,2481,2482,2483,2486,2490,2492,2501,2503,2505,2507,2511,2519,2520,2524,2526,2527,2532,2544,2546,2556,2557,2558,2559,2561,2564,2565,2571,2575,2577,2579,2601,2602,2609,2610,2612,2613,2615,2616,2618,2620,2621,2622,2627,2631,2633,2635,2638,2641,2642,2649,2653,2654,2655,2672,2678,2689,2692,2693,2702,2703,2706,2707,2729,2730,2737,2738,2740,2741,2746,2748,2758,2759,2762,2763,2766,2768,2769,2784,2788,2809,2816,2817,2820,2821,2829,2831,2833,2835,2857,2858,2865,2866,2868,2869,2874,2876,2885,2887,2889,2891,2894,2901,2904,2908,2910,2911,2916,2929,2930,2946,2948,2949,2955,2958,2961,2962,2966,2969,2971,2972,2973,2974,2976,2979,2981,2984,2987,2990,3002,3006,3011,3014,3017,3018,3022,3024,3025,3031,3032,3072,3085,3086,3089,3090,3113,3114,3130,3132,3141,3142,3145,3146,3150,3157,3159,3160,3163,3165,3166,3168,3172,3200,3204,3205,3213,3214,3217,3218,3241,3242,3252,3253,3258,3260,3269,3270,3273,3274,3278,3285,3287,3293,3295,3296,3300,3313,3316,3328,3341,3342,3345,3346,3397,3398,3401,3402,3407,3412,3416,3423,3428,3450,3456,3457,3460,3461,3479,3482,3506,3507,3516,3517,3518,3520,3527,3530,3531,3535,3541,3542,3543,3544,3552,3570,3572,3585,3643,3648,3663,3713,3715,3716,3717,3718,3723,3724,3748,3749,3750,3751,3774,3776,3781,3782,3783,3784,3791,3804,3808,3840,3841,3864,3866,3893,3894,3895,3896,3897,3898,3902,3912,3913,3949,3953,3973,3974,3992,3993,4029,4038,4039,4096,4160,4176,4240,4250,4254,4256,4294,4295,4296,4301,4302,4304,4347,4348,4349,4352,4608,4681,4682,4686,4688,4695,4696,4697,4698,4702,4704,4745,4746,4750,4752,4785,4786,4790,4792,4799,4800,4801,4802,4806,4808,4823,4824,4881,4882,4886,4888,4955,4957,4960,4992,5008,5024,5110,5112,5118,5121,5741,5743,5760,5761,5787,5792,5867,5873,5881,5888,5910,5919,5920,5941,5952,5972,5984,5997,5998,6001,6002,6004,6016,6100,6103,6104,6108,6110,6155,6158,6159,6160,6176,6265,6272,6315,6320,6390,6400,6431,6432,6444,6448,6460,6480,6510,6512,6517,6528,6572,6576,6602,6656,6684,6688,6751,6752,6781,6783,6784,6823,6824,6832,6863,6912,6989,7019,7028,7040,7088,7098,7104,7156,7168,7224,7245,7248,7258,7294,7296,7305,7312,7355,7357,7360,7376,7379,7380,7419,7424,7462,7467,7468,7522,7526,7531,7544,7545,7579,7616,7680,7936,7958,7960,7966,7968,8006,8008,8014,8016,8024,8025,8026,8027,8028,8029,8030,8031,8062,8064,8117,8118,8125,8126,8127,8130,8133,8134,8141,8144,8148,8150,8156,8160,8173,8178,8181,8182,8189,8305,8306,8319,8320,8336,8349,8400,8433,8450,8451,8455,8456,8458,8460,8461,8462,8464,8465,8466,8468,8469,8470,8473,8475,8476,8477,8478,8484,8485,8486,8487,8488,8489,8490,8491,8492,8493,8494,8495,8498,8499,8501,8502,8503,8505,8506,8508,8512,8517,8522,8526,8527,8579,8580,8581,11264,11360,11389,11390,11392,11493,11499,11508,11520,11558,11559,11560,11565,11566,11568,11624,11631,11632,11647,11648,11671,11680,11687,11688,11695,11696,11703,11704,11711,11712,11719,11720,11727,11728,11735,11736,11743,11744,11776,11823,11824,12293,12295,12330,12334,12336,12337,12342,12347,12348,12349,12353,12439,12441,12443,12445,12448,12449,12539,12540,12541,12544,12549,12592,12593,12687,12704,12736,12784,12800,13312,19904,19968,40960,42125,42192,42238,42240,42509,42512,42528,42538,42540,42560,42607,42611,42612,42622,42623,42652,42654,42656,42726,42736,42738,42775,42784,42786,42864,42865,42888,42889,42891,42955,42960,42962,42963,42964,42965,42970,42994,42997,43000,43002,43008,43048,43052,43053,43072,43124,43136,43206,43232,43250,43256,43259,43260,43261,43264,43274,43310,43312,43348,43360,43389,43392,43457,43471,43472,43488,43504,43514,43519,43520,43575,43584,43598,43616,43639,43642,43648,43715,43739,43742,43744,43760,43762,43767,43777,43783,43785,43791,43793,43799,43808,43815,43816,43823,43824,43867,43868,43872,43877,43878,43881,43882,43888,43968,44011,44012,44014,44032,55204,55216,55239,55243,55292,63744,64110,64112,64218,64256,64263,64275,64280,64285,64297,64298,64311,64312,64317,64318,64319,64320,64322,64323,64325,64326,64336,64434,64467,64830,64848,64912,64914,64968,65008,65020,65024,65040,65056,65072,65136,65141,65142,65277,65313,65339,65345,65371,65382,65471,65474,65480,65482,65488,65490,65496,65498,65501,65536,65548,65549,65575,65576,65595,65596,65598,65599,65614,65616,65630,65664,65787,66045,66046,66176,66205,66208,66257,66272,66273,66304,66336,66349,66352,66369,66370,66378,66384,66422,66427,66432,66462,66464,66500,66504,66512,66560,66640,66688,66718,66736,66772,66776,66812,66816,66856,66864,66916,66928,66939,66940,66955,66956,66963,66964,66966,66967,66978,66979,66994,66995,67002,67003,67005,67072,67383,67392,67414,67424,67432,67456,67462,67463,67505,67506,67515,67584,67590,67592,67593,67594,67638,67639,67641,67644,67645,67647,67648,67670,67680,67703,67712,67743,67808,67827,67828,67830,67840,67862,67872,67898,67968,68024,68030,68032,68096,68100,68101,68103,68108,68116,68117,68120,68121,68150,68152,68155,68159,68160,68192,68221,68224,68253,68288,68296,68297,68327,68352,68406,68416,68438,68448,68467,68480,68498,68608,68681,68736,68787,68800,68851,68864,68904,69248,69290,69291,69293,69296,69298,69373,69376,69405,69415,69416,69424,69457,69488,69510,69552,69573,69600,69623,69632,69703,69744,69750,69759,69760,69819,69826,69827,69840,69865,69888,69941,69956,69960,69968,70004,70006,70007,70016,70085,70089,70093,70094,70096,70106,70107,70108,70109,70144,70162,70163,70200,70206,70210,70272,70279,70280,70281,70282,70286,70287,70302,70303,70313,70320,70379,70400,70404,70405,70413,70415,70417,70419,70441,70442,70449,70450,70452,70453,70458,70459,70460,70469,70471,70473,70475,70478,70480,70481,70487,70488,70493,70500,70502,70509,70512,70517,70656,70731,70750,70754,70784,70854,70855,70856,71040,71094,71096,71105,71128,71134,71168,71233,71236,71237,71296,71353,71424,71451,71453,71468,71488,71495,71680,71739,71840,71904,71935,71936,71943,71945,71946,71948,71956,71957,71959,71960,71990,71991,71993,71995,72004,72096,72104,72106,72152,72154,72162,72163,72165,72192,72255,72263,72264,72272,72346,72349,72350,72368,72384,72441,72704,72713,72714,72759,72760,72769,72818,72848,72850,72872,72873,72887,72960,72967,72968,72970,72971,73015,73018,73019,73020,73022,73023,73032,73056,73062,73063,73065,73066,73103,73104,73106,73107,73113,73440,73463,73472,73489,73490,73531,73534,73539,73648,73649,73728,74650,74880,75076,77712,77809,77824,78896,78912,78934,82944,83527,92160,92729,92736,92767,92784,92863,92880,92910,92912,92917,92928,92983,92992,92996,93027,93048,93053,93072,93760,93824,93952,94027,94031,94088,94095,94112,94176,94177,94178,94179,94180,94181,94192,94194,100352,101120,101590,110576,110580,110581,110588,110589,110591,110592,110593,110594,110879,110880,110883,110898,110899,110928,110931,110933,110934,110948,110952,110960,111356,113664,113771,113776,113789,113792,113801,113808,113818,113821,113823,118528,118574,118576,118599,119141,119146,119149,119155,119163,119171,119173,119180,119210,119214,119362,119365,119808,119893,119894,119965,119966,119968,119970,119971,119973,119975,119977,119981,119982,119994,119995,119996,119997,120004,120005,120070,120071,120075,120077,120085,120086,120093,120094,120122,120123,120127,120128,120133,120134,120135,120138,120145,120146,120486,120488,120513,120514,120539,120540,120571,120572,120597,120598,120629,120630,120655,120656,120687,120688,120713,120714,120745,120746,120771,120772,120780,121344,121399,121403,121453,121461,121462,121476,121477,121499,121504,121505,121520,122624,122655,122661,122667,122880,122887,122888,122905,122907,122914,122915,122917,122918,122923,122928,122961,122987,122990,123023,123024,123136,123181,123184,123198,123214,123215,123536,123567,123584,123632,124112,124144,124896,124903,124904,124908,124909,124911,124912,124927,124928,125125,125136,125143,125184,125260,126464,126468,126469,126496,126497,126499,126500,126501,126503,126504,126505,126515,126516,126520,126521,126522,126523,126524,126530,126531,126535,126536,126537,126538,126539,126540,126541,126544,126545,126547,126548,126549,126551,126552,126553,126554,126555,126556,126557,126558,126559,126560,126561,126563,126564,126565,126567,126571,126572,126579,126580,126584,126585,126589,126590,126591,126592,126602,126603,126620,126625,126628,126629,126634,126635,126652,131072,173792,173824,177978,177984,178206,178208,183970,183984,191457,194560,195102,196608,201547,201552,205744,917760,918000],"values":[1,422,1,422,1,454,1,86,1,422,1,422,1,422,1,422,497,1,497,359,497,1,497,1,497,1,497,1,396,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,469,244,1,244,462,1,396,462,1,183,1,183,1,183,1,182,1,182,1,182,1,182,1,182,1,182,1,182,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,236,1,236,49,288,1,487,1,487,1,487,1,411,1,127,1,236,1,49,1,49,1,49,1,49,480,1,480,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,439,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,174,1,174,1,174,1,174,1,174,1,174,1,174,1,174,1,174,1,174,1,174,1,174,1,174,1,174,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,266,1,340,1,340,1,340,1,340,1,340,1,340,1,340,1,340,1,340,1,340,1,340,1,58,1,58,1,58,1,58,1,58,1,58,1,58,1,58,1,58,1,58,1,58,1,58,1,58,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,200,1,200,1,200,1,200,1,200,1,200,1,200,1,200,1,200,1,200,1,200,1,445,1,445,1,207,1,207,1,207,1,207,1,207,1,207,1,207,1,207,1,207,1,207,1,339,1,339,1,339,1,339,1,339,1,339,1,339,1,339,1,339,1,339,1,339,1,100,1,100,1,100,1,257,1,257,1,257,1,257,1,497,257,360,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,330,1,330,1,489,1,489,1,36,1,114,1,114,1,453,1,453,150,1,65,1,74,1,74,1,74,1,106,1,106,1,106,1,200,1,200,1,200,1,200,1,489,1,415,1,415,1,415,1,496,1,496,1,281,1,281,1,454,1,496,1,496,1,496,1,496,1,396,1,136,1,136,1,451,1,451,262,1,175,1,175,1,120,1,462,1,257,1,257,1,339,1,339,1,422,244,462,497,422,244,422,497,422,497,396,422,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,244,1,503,1,503,1,422,1,396,1,269,1,398,1,356,14,269,86,356,14,356,1,269,1,269,356,14,269,1,269,1,443,1,14,1,443,145,356,14,1,356,139,356,281,389,373,23,1,269,1,269,1,139,1,471,422,1,234,422,497,422,469,1,469,1,257,1,257,1,257,1,257,1,257,1,257,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,62,1,396,1,366,1,5,1,5,360,1,366,1,366,421,1,500,1,396,1,500,1,79,1,481,79,1,261,1,360,1,261,1,79,1,350,1,350,426,1,192,1,496,1,496,1,496,1,462,396,1,396,1,462,497,396,217,1,217,1,497,1,422,497,422,497,1,422,1,422,1,422,1,422,1,497,422,497,422,22,1,22,1,342,1,413,1,396,480,1,480,1,480,1,418,1,48,1,360,1,151,1,151,1,100,1,100,1,306,1,306,1,100,1,100,496,1,496,1,385,1,385,1,62,1,62,1,62,1,62,1,62,1,422,1,497,422,244,422,497,1,330,385,1,385,1,360,1,360,1,360,1,350,1,350,1,422,1,183,1,182,1,182,1,182,1,182,1,182,1,182,1,182,49,1,49,1,49,1,49,1,49,1,179,1,396,1,49,1,49,1,123,1,123,1,100,1,100,1,100,1,100,1,100,1,473,1,473,1,473,1,473,1,473,1,473,1,473,1,466,1,3,1,11,1,469,1,427,1,427,316,1,316,1,427,396,1,211,1,427,1,427,1,430,308,394,1,245,1,245,1,128,1,278,1,147,1,147,1,147,1,147,1,147,1,147,1,147,1,147,1,473,1,473,1,473,1,497,1,497,1,497,1,119,1,119,1,119,1,119,1,119,1,119,363,1,450,1,170,1,61,1,61,1,221,1,248,1,90,1,90,1,482,1,482,1,482,1,482,1,482,1,482,1,482,1,427,1,427,1,77,1,77,1,31,1,357,1,357,1,2,1,427,1,427,1,427,1,21,1,41,1,41,1,41,1,49,427,1,427,1,510,1,427,1,115,1,126,1,17,1,17,1,17,115,1,115,1,241,1,234,1,234,1,107,1,107,1,109,1,109,1,109,1,109,1,109,1,179,1,179,1,179,1,484,1,484,1,484,1,484,1,484,1,390,1,345,1,345,1,345,1,345,1,345,1,345,1,345,1,396,345,1,345,1,345,1,345,1,345,1,345,1,396,1,396,1,140,1,140,1,34,1,34,1,228,1,228,1,228,1,430,1,430,1,195,1,29,1,29,1,29,1,250,1,267,1,267,211,1,211,1,211,1,211,1,211,1,211,1,211,1,431,1,431,1,431,1,431,1,365,1,365,1,361,1,361,1,489,203,1,61,1,61,1,61,1,73,1,73,1,73,1,356,1,356,1,356,1,356,1,356,1,356,1,50,1,50,1,50,1,50,1,50,1,77,1,290,1,290,1,290,1,192,1,182,1,182,1,355,1,152,1,152,1,296,1,217,1,212,1,175,1,392,1,392,1,349,1,349,1,349,1,349,1,115,1,364,1,364,1,364,1,416,84,1,427,276,1,216,1,416,276,1,79,1,79,1,79,1,79,500,492,500,79,1,500,1,500,1,79,1,79,1,84,1,504,1,504,1,504,1,504,1,504,1,246,1,246,1,285,1,285,1,285,1,285,1,285,1,396,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,332,1,213,1,213,1,213,1,213,1,213,1,213,1,422,1,422,1,396,1,396,1,396,1,396,1,396,1,497,462,497,1,396,1,170,1,170,1,170,1,271,1,30,1,169,1,62,1,62,1,62,1,62,1,234,1,234,1,59,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,49,1,350,1,350,1,350,1,350,1,350,1,350,1,350,1,350,1,179,1]}
|
millid/encoding.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""The universal text encoding, in NumPy: what the model reads, without PyTorch.
|
|
2
|
+
|
|
3
|
+
The same encoding as `training/millid.py` (tests/test_package.py checks them byte for byte).
|
|
4
|
+
A passage becomes four aligned sequences, one entry per UTF-8 byte, CLS first:
|
|
5
|
+
|
|
6
|
+
ids the byte, shifted by OFFSET
|
|
7
|
+
script the Unicode script of the character the byte belongs to (data/scripts.json)
|
|
8
|
+
charpos 1 a one-byte character, 2 the first byte of a longer one, 3 a continuation byte
|
|
9
|
+
ngrams hashed character 2-, 3- and 4-grams ending at the byte's character
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import random
|
|
16
|
+
import unicodedata
|
|
17
|
+
import zlib
|
|
18
|
+
from importlib.resources import files
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
PAD, CLS, EOS = 0, 1, 2
|
|
23
|
+
OFFSET = 3
|
|
24
|
+
SCRIPT_BUCKETS = 512
|
|
25
|
+
SCRIPT_COMMON = 1
|
|
26
|
+
NGRAM_ORDERS = (2, 3, 4)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def normalize(text: str) -> str:
|
|
30
|
+
"""NFKC, and runs of whitespace as one space."""
|
|
31
|
+
return " ".join(unicodedata.normalize("NFKC", str(text)).split())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def script_from_unicodedata(ch: str) -> int:
|
|
35
|
+
"""How a script id was first defined: a letter or mark's Unicode name, its first word
|
|
36
|
+
hashed. It depends on the running Python's Unicode data, so the encoder reads the ids this
|
|
37
|
+
gave under Unicode 15.0, frozen in data/scripts.json (scripts/freeze_scripts.py)."""
|
|
38
|
+
if unicodedata.category(ch)[0] not in "LM":
|
|
39
|
+
return SCRIPT_COMMON
|
|
40
|
+
word = unicodedata.name(ch, "").split(" ", 1)[0]
|
|
41
|
+
if not word:
|
|
42
|
+
return SCRIPT_COMMON
|
|
43
|
+
return 2 + zlib.crc32(word.encode()) % (SCRIPT_BUCKETS - 2)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_script_table: np.ndarray | None = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def script_table() -> np.ndarray:
|
|
50
|
+
"""The script id of every code point, from the frozen table, built once per process."""
|
|
51
|
+
global _script_table
|
|
52
|
+
if _script_table is None:
|
|
53
|
+
frozen = json.loads(files("millid").joinpath("data", "scripts.json").read_text(encoding="utf-8"))
|
|
54
|
+
starts = np.array(frozen["starts"] + [frozen["size"]], dtype=np.int64)
|
|
55
|
+
_script_table = np.repeat(np.array(frozen["values"], dtype=np.int64), np.diff(starts))
|
|
56
|
+
return _script_table
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def char_script(ch: str) -> int:
|
|
60
|
+
return int(script_table()[ord(ch)])
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
_START = 0x110000
|
|
64
|
+
_PRIME = np.uint64(0x100000001B3)
|
|
65
|
+
_MIX1, _MIX2 = np.uint64(0xBF58476D1CE4E5B9), np.uint64(0x94D049BB133111EB)
|
|
66
|
+
_ORDER_SEED = {n: np.uint64((0x9E3779B97F4A7C15 * n) & 0xFFFFFFFFFFFFFFFF) for n in NGRAM_ORDERS}
|
|
67
|
+
_UTF8_LEAD = np.array([0, 0x00, 0xC0, 0xE0, 0xF0], dtype=np.int64)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _splitmix(x: np.ndarray) -> np.ndarray:
|
|
71
|
+
x = (x ^ (x >> np.uint64(30))) * _MIX1
|
|
72
|
+
x = (x ^ (x >> np.uint64(27))) * _MIX2
|
|
73
|
+
return x ^ (x >> np.uint64(31))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _codepoints(text: str) -> np.ndarray:
|
|
77
|
+
return np.frombuffer(text.encode("utf-32-le", "replace"), dtype=np.uint32)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def utf8_length(text: str) -> int:
|
|
81
|
+
return len(text.encode("utf-8", "replace"))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def encode_batch(
|
|
85
|
+
texts: list[str], max_len: int = 256, ngram_buckets: int = 32768, rng: random.Random | None = None
|
|
86
|
+
) -> dict[str, np.ndarray]:
|
|
87
|
+
"""Passages as the model's input, padded to the longest: ids, script, charpos, ngrams
|
|
88
|
+
(int64) and mask (bool). A passage longer than max_len bytes is cut to its first window
|
|
89
|
+
of whole characters (a random one when rng is given)."""
|
|
90
|
+
texts = [normalize(t) for t in texts]
|
|
91
|
+
b, budget = len(texts), max_len - 1
|
|
92
|
+
joined = "".join(texts)
|
|
93
|
+
cp = _codepoints(joined)
|
|
94
|
+
low = joined.lower()
|
|
95
|
+
low = _codepoints(low) if len(low) == len(joined) else _codepoints("".join(ch.lower()[0] for ch in joined))
|
|
96
|
+
lens = np.fromiter(map(len, texts), dtype=np.int64, count=b)
|
|
97
|
+
first = np.cumsum(lens) - lens
|
|
98
|
+
after = first + lens
|
|
99
|
+
sizes = (1 + (cp >= 0x80) + (cp >= 0x800) + (cp >= 0x10000)).astype(np.int64)
|
|
100
|
+
ends = np.concatenate([[0], np.cumsum(sizes)])
|
|
101
|
+
|
|
102
|
+
lo = first.copy()
|
|
103
|
+
if rng is not None:
|
|
104
|
+
long = np.flatnonzero(ends[after] - ends[first] > budget)
|
|
105
|
+
if len(long):
|
|
106
|
+
last = np.searchsorted(ends, ends[after[long]] - budget, side="left")
|
|
107
|
+
u = np.array([rng.random() for _ in long])
|
|
108
|
+
lo[long] += (u * (last - first[long])).astype(np.int64)
|
|
109
|
+
hi = np.minimum(np.searchsorted(ends, ends[lo] + budget, side="right") - 1, after)
|
|
110
|
+
w = hi - lo
|
|
111
|
+
at = np.repeat(lo - (np.cumsum(w) - w), w) + np.arange(w.sum())
|
|
112
|
+
c = cp[at].astype(np.int64)
|
|
113
|
+
|
|
114
|
+
script = script_table()[c]
|
|
115
|
+
|
|
116
|
+
into = at - np.repeat(first, w)
|
|
117
|
+
grams = np.empty((len(at), len(NGRAM_ORDERS)), dtype=np.int64)
|
|
118
|
+
h = np.zeros(len(at), dtype=np.uint64)
|
|
119
|
+
for n in range(1, max(NGRAM_ORDERS) + 1):
|
|
120
|
+
h = h * _PRIME + np.where(into >= n - 1, low[np.maximum(at - (n - 1), 0)], _START).astype(np.uint64)
|
|
121
|
+
if n in _ORDER_SEED:
|
|
122
|
+
grams[:, NGRAM_ORDERS.index(n)] = (_splitmix(h ^ _ORDER_SEED[n]) % np.uint64(ngram_buckets - 1)).astype(np.int64) + 1
|
|
123
|
+
|
|
124
|
+
s = sizes[at]
|
|
125
|
+
cb, sb = np.repeat(c, s), np.repeat(s, s)
|
|
126
|
+
k = np.arange(len(cb)) - np.repeat(np.cumsum(s) - s, s)
|
|
127
|
+
shifted = cb >> (6 * (sb - 1 - k))
|
|
128
|
+
raw = np.where(k == 0, shifted | _UTF8_LEAD[sb], (shifted & 0x3F) | 0x80)
|
|
129
|
+
charpos = np.where(sb == 1, 1, np.where(k == 0, 2, 3))
|
|
130
|
+
|
|
131
|
+
nb = ends[hi] - ends[lo]
|
|
132
|
+
row = np.repeat(np.arange(b), nb)
|
|
133
|
+
col = 1 + np.arange(len(cb)) - np.repeat(np.cumsum(nb) - nb, nb)
|
|
134
|
+
width = 1 + int(nb.max(initial=0))
|
|
135
|
+
out = {name: np.zeros((b, width), dtype=np.int64) for name in ("ids", "script", "charpos")}
|
|
136
|
+
out["ngrams"] = np.zeros((b, width, len(NGRAM_ORDERS)), dtype=np.int64)
|
|
137
|
+
out["ids"][:, 0], out["script"][:, 0], out["charpos"][:, 0] = CLS, SCRIPT_COMMON, 1
|
|
138
|
+
out["ids"][row, col] = raw + OFFSET
|
|
139
|
+
out["script"][row, col] = np.repeat(script, s)
|
|
140
|
+
out["charpos"][row, col] = charpos
|
|
141
|
+
out["ngrams"][row, col] = np.repeat(grams, s, axis=0)
|
|
142
|
+
out["mask"] = out["ids"] != PAD
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def windows(text: str, max_bytes: int) -> list[tuple[int, int]]:
|
|
147
|
+
"""A long text as consecutive (start, end) character spans of the normalised text, each at
|
|
148
|
+
most max_bytes of UTF-8, cut at spaces where there are any: the whole document, read one
|
|
149
|
+
model-sized piece at a time."""
|
|
150
|
+
spans, start, n = [], 0, len(text)
|
|
151
|
+
while start < n:
|
|
152
|
+
end, used, last_space = start, 0, -1
|
|
153
|
+
while end < n:
|
|
154
|
+
size = utf8_length(text[end])
|
|
155
|
+
if used + size > max_bytes:
|
|
156
|
+
break
|
|
157
|
+
if text[end] == " ":
|
|
158
|
+
last_space = end
|
|
159
|
+
used += size
|
|
160
|
+
end += 1
|
|
161
|
+
if end < n and last_space > start:
|
|
162
|
+
end = last_space
|
|
163
|
+
spans.append((start, end))
|
|
164
|
+
start = end + 1 if end < n and text[end] == " " else end
|
|
165
|
+
return [(a, b) for a, b in spans if b > a]
|
millid/registry.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Several MillID models served side by side, each on its own device, one of them the default.
|
|
2
|
+
|
|
3
|
+
medium-v1=baobabtech/millid-medium-v1@cuda,tiny-v1.5=baobabtech/millid-tiny-v1.5@cpu
|
|
4
|
+
|
|
5
|
+
A spec is name=ref[@device][#threads]: ref a local directory or a Hugging Face repo (with an
|
|
6
|
+
optional :revision), device cpu, cuda or auto.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
from millid.batching import MicroBatcher
|
|
15
|
+
from millid.runtime import LanguageIdentifier
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class ModelSpec:
|
|
20
|
+
name: str
|
|
21
|
+
ref: str
|
|
22
|
+
device: str = "cpu"
|
|
23
|
+
threads: int | None = None
|
|
24
|
+
revision: str | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def parse_specs(text: str) -> list[ModelSpec]:
|
|
28
|
+
specs = []
|
|
29
|
+
for part in filter(None, (p.strip() for p in text.split(","))):
|
|
30
|
+
name, _, rest = part.partition("=")
|
|
31
|
+
if not rest:
|
|
32
|
+
raise ValueError(f"model spec {part!r}: expected name=ref[@device][#threads]")
|
|
33
|
+
rest, _, threads = rest.partition("#")
|
|
34
|
+
ref, _, device = rest.partition("@")
|
|
35
|
+
revision = None
|
|
36
|
+
if ":" in ref and not os.path.isdir(ref) and not ref[1:3] == ":\\":
|
|
37
|
+
ref, _, revision = ref.partition(":")
|
|
38
|
+
if (device or "cpu") not in ("cpu", "cuda", "auto"):
|
|
39
|
+
raise ValueError(f"model spec {part!r}: device must be cpu, cuda or auto")
|
|
40
|
+
specs.append(ModelSpec(name.strip(), ref.strip(), device or "cpu", int(threads) if threads else None, revision))
|
|
41
|
+
if not specs:
|
|
42
|
+
raise ValueError("no model given")
|
|
43
|
+
if len({s.name for s in specs}) != len(specs):
|
|
44
|
+
raise ValueError("two models share a name")
|
|
45
|
+
return specs
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Registry:
|
|
49
|
+
def __init__(
|
|
50
|
+
self, specs: list[ModelSpec], default: str | None = None, max_batch: int = 256, max_wait_ms: float = 2.0,
|
|
51
|
+
token: str | None = None, gpu_mem_limit_mb: int | None = None,
|
|
52
|
+
): # fmt: skip
|
|
53
|
+
self.specs = {s.name: s for s in specs}
|
|
54
|
+
self.default = default or specs[0].name
|
|
55
|
+
if self.default not in self.specs:
|
|
56
|
+
raise ValueError(f"default model {self.default!r} is not one of {sorted(self.specs)}")
|
|
57
|
+
self.max_batch, self.max_wait_ms, self.token = max_batch, max_wait_ms, token
|
|
58
|
+
self.gpu_mem_limit_mb = gpu_mem_limit_mb
|
|
59
|
+
self.models: dict[str, LanguageIdentifier] = {}
|
|
60
|
+
self.batchers: dict[str, MicroBatcher] = {}
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_text(cls, models: str, default: str | None = None, **kwargs) -> Registry:
|
|
64
|
+
return cls(parse_specs(models), default, **kwargs)
|
|
65
|
+
|
|
66
|
+
def load(self) -> Registry:
|
|
67
|
+
"""Load every model now, so the first request does not pay for it."""
|
|
68
|
+
for name, spec in self.specs.items():
|
|
69
|
+
ident = LanguageIdentifier.from_pretrained(
|
|
70
|
+
spec.ref, revision=spec.revision, token=self.token, device=spec.device, threads=spec.threads,
|
|
71
|
+
gpu_mem_limit_mb=self.gpu_mem_limit_mb,
|
|
72
|
+
)
|
|
73
|
+
self.models[name] = ident
|
|
74
|
+
# One batch in flight per model, on the GPU too: measured on a GB10, a second one
|
|
75
|
+
# did not raise throughput and ran out of a 2 GB arena under a burst.
|
|
76
|
+
self.batchers[name] = MicroBatcher(ident, max_batch=self.max_batch, max_wait_ms=self.max_wait_ms, parallel=1)
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
def resolve(self, name: str | None) -> str:
|
|
80
|
+
name = name or self.default
|
|
81
|
+
if name not in self.batchers:
|
|
82
|
+
raise KeyError(f"unknown model {name!r}; available: {sorted(self.batchers)}")
|
|
83
|
+
return name
|
|
84
|
+
|
|
85
|
+
def batcher(self, name: str | None = None) -> MicroBatcher:
|
|
86
|
+
return self.batchers[self.resolve(name)]
|
|
87
|
+
|
|
88
|
+
def describe(self) -> list[dict]:
|
|
89
|
+
return [
|
|
90
|
+
{
|
|
91
|
+
"name": name,
|
|
92
|
+
"source": self.specs[name].ref,
|
|
93
|
+
"device": m.device,
|
|
94
|
+
"labels": len(m.labels),
|
|
95
|
+
"parameters": m.parameters,
|
|
96
|
+
"max_bytes": m.max_len - 1,
|
|
97
|
+
"default": name == self.default,
|
|
98
|
+
}
|
|
99
|
+
for name, m in self.models.items()
|
|
100
|
+
]
|
|
101
|
+
|
|
102
|
+
async def aclose(self) -> None:
|
|
103
|
+
for b in self.batchers.values():
|
|
104
|
+
await b.aclose()
|
millid/runtime.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""MillID with ONNX Runtime: a model directory or Hub repo in, ranked languages out."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from millid.encoding import encode_batch, normalize, utf8_length, windows
|
|
13
|
+
|
|
14
|
+
INPUTS = ("ids", "script", "charpos", "ngrams", "mask")
|
|
15
|
+
#: What a model repo must hold for this runtime; model.safetensors is for PyTorch only.
|
|
16
|
+
FILES = ["onnx/model.onnx", "config.json", "labels.json"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Prediction:
|
|
21
|
+
label: str
|
|
22
|
+
"""ISO 639-3 + script, e.g. eng_Latn"""
|
|
23
|
+
language: str
|
|
24
|
+
"""the language's English name"""
|
|
25
|
+
probability: float
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Segment:
|
|
30
|
+
"""A run of consecutive windows of a document that MillID reads as one language. start and
|
|
31
|
+
end index the normalised text (NFKC, whitespace collapsed)."""
|
|
32
|
+
|
|
33
|
+
start: int
|
|
34
|
+
end: int
|
|
35
|
+
label: str
|
|
36
|
+
language: str
|
|
37
|
+
probability: float
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class DocumentResult:
|
|
42
|
+
languages: list[Prediction]
|
|
43
|
+
"""the document's languages, from the windows' probabilities weighted by their length"""
|
|
44
|
+
segments: list[Segment] = field(default_factory=list)
|
|
45
|
+
windows: int = 0
|
|
46
|
+
characters: int = 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _onnxruntime():
|
|
50
|
+
try:
|
|
51
|
+
import onnxruntime
|
|
52
|
+
except ImportError as e:
|
|
53
|
+
raise ImportError("ONNX Runtime is not installed: pip install 'millid[cpu]' or 'millid[gpu]'") from e
|
|
54
|
+
return onnxruntime
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _providers(device: str, gpu_mem_limit_mb: int | None = None) -> list:
|
|
58
|
+
ort = _onnxruntime()
|
|
59
|
+
available = ort.get_available_providers()
|
|
60
|
+
want_cuda = device == "cuda" or (device == "auto" and "CUDAExecutionProvider" in available)
|
|
61
|
+
if not want_cuda:
|
|
62
|
+
return ["CPUExecutionProvider"]
|
|
63
|
+
if "CUDAExecutionProvider" not in available:
|
|
64
|
+
raise RuntimeError(f"device 'cuda' asked for, but this onnxruntime has only {available}: pip install 'millid[gpu]'")
|
|
65
|
+
if hasattr(ort, "preload_dlls"): # the CUDA and cuDNN libraries installed from pip
|
|
66
|
+
ort.preload_dlls()
|
|
67
|
+
# Grow the arena by what is asked for, not by doubling: the GPU may be shared.
|
|
68
|
+
options = {"arena_extend_strategy": "kSameAsRequested"}
|
|
69
|
+
if gpu_mem_limit_mb:
|
|
70
|
+
options["gpu_mem_limit"] = int(gpu_mem_limit_mb) * 1024 * 1024
|
|
71
|
+
return [("CUDAExecutionProvider", options), "CPUExecutionProvider"]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
#: The released models by short name: what from_pretrained and the CLI accept besides a repo id
|
|
75
|
+
#: or a directory. large v1.5 is the most accurate; tiny v1.5 is 2.9M parameters and runs
|
|
76
|
+
#: anywhere, a browser included.
|
|
77
|
+
MODELS = {
|
|
78
|
+
"tiny-v1.5": "baobabtech/millid-tiny-v1.5",
|
|
79
|
+
"large-v1.5": "baobabtech/millid-large-v1.5",
|
|
80
|
+
"medium-v1": "baobabtech/millid-medium-v1",
|
|
81
|
+
}
|
|
82
|
+
DEFAULT_MODEL = "tiny-v1.5"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class LanguageIdentifier:
|
|
86
|
+
"""One MillID model in ONNX Runtime. `probabilities` is safe to call from several threads
|
|
87
|
+
at once: an InferenceSession's run is thread-safe and releases the GIL."""
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self, model_dir: str | os.PathLike, device: str = "cpu", threads: int | None = None, batch_size: int = 64,
|
|
91
|
+
gpu_mem_limit_mb: int | None = None,
|
|
92
|
+
): # fmt: skip
|
|
93
|
+
ort = _onnxruntime()
|
|
94
|
+
root = Path(model_dir)
|
|
95
|
+
onnx_path = root / "onnx" / "model.onnx"
|
|
96
|
+
if not onnx_path.exists():
|
|
97
|
+
onnx_path = root / "model.onnx"
|
|
98
|
+
config = json.loads((root / "config.json").read_text(encoding="utf-8"))
|
|
99
|
+
meta = json.loads((root / "labels.json").read_text(encoding="utf-8"))
|
|
100
|
+
self.max_len = int(config["model"]["max_len"])
|
|
101
|
+
self.ngram_buckets = int(config["model"]["ngram_buckets"])
|
|
102
|
+
self.parameters = config.get("parameters")
|
|
103
|
+
self.labels: list[str] = meta["labels"]
|
|
104
|
+
self.names: dict[str, str] = meta.get("names", {})
|
|
105
|
+
trained = set(meta.get("trained", self.labels))
|
|
106
|
+
# A label the model never saw a passage of is never an answer.
|
|
107
|
+
self._bias = np.where(np.array([lab in trained for lab in self.labels]), 0.0, -np.inf).astype(np.float32)
|
|
108
|
+
self.batch_size = batch_size
|
|
109
|
+
|
|
110
|
+
options = ort.SessionOptions()
|
|
111
|
+
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
|
112
|
+
if threads:
|
|
113
|
+
options.intra_op_num_threads = threads
|
|
114
|
+
options.inter_op_num_threads = 1
|
|
115
|
+
self.session = ort.InferenceSession(str(onnx_path), options, providers=_providers(device, gpu_mem_limit_mb))
|
|
116
|
+
self.device = "cuda" if self.session.get_providers()[0] == "CUDAExecutionProvider" else "cpu"
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def from_pretrained(
|
|
120
|
+
cls, ref: str = DEFAULT_MODEL, revision: str | None = None, token: str | None = None, **kwargs
|
|
121
|
+
) -> LanguageIdentifier:
|
|
122
|
+
"""A short name (tiny-v1.5, large-v1.5, medium-v1), a Hugging Face repo id, or a local
|
|
123
|
+
directory. A repo is downloaded once, then read from the Hugging Face cache."""
|
|
124
|
+
ref = MODELS.get(ref, ref)
|
|
125
|
+
if Path(ref).is_dir():
|
|
126
|
+
return cls(ref, **kwargs)
|
|
127
|
+
from huggingface_hub import snapshot_download
|
|
128
|
+
|
|
129
|
+
local = snapshot_download(ref, revision=revision, token=token, allow_patterns=FILES)
|
|
130
|
+
return cls(local, **kwargs)
|
|
131
|
+
|
|
132
|
+
def _logits(self, texts: list[str]) -> np.ndarray:
|
|
133
|
+
enc = encode_batch(texts, self.max_len, self.ngram_buckets)
|
|
134
|
+
# Widths in steps of 32 bytes: a handful of shapes rather than hundreds, so the GPU's
|
|
135
|
+
# memory arena reuses its blocks instead of fragmenting. Padding is masked: the answers
|
|
136
|
+
# do not change.
|
|
137
|
+
width = enc["ids"].shape[1]
|
|
138
|
+
padded = min(self.max_len, -(-width // 32) * 32)
|
|
139
|
+
if padded > width:
|
|
140
|
+
extra = padded - width
|
|
141
|
+
enc = {k: np.pad(v, [(0, 0), (0, extra)] + [(0, 0)] * (v.ndim - 2)) for k, v in enc.items()}
|
|
142
|
+
return self.session.run(["logits"], {name: enc[name] for name in INPUTS})[0]
|
|
143
|
+
|
|
144
|
+
def probabilities(self, texts: list[str]) -> np.ndarray:
|
|
145
|
+
"""N x labels. Texts are sorted by length before batching, so a batch is padded only to
|
|
146
|
+
lengths like its own, then put back in order."""
|
|
147
|
+
if not texts:
|
|
148
|
+
return np.zeros((0, len(self.labels)), dtype=np.float32)
|
|
149
|
+
order = np.argsort([utf8_length(t) for t in texts], kind="stable")
|
|
150
|
+
out = np.empty((len(texts), len(self.labels)), dtype=np.float32)
|
|
151
|
+
for i in range(0, len(texts), self.batch_size):
|
|
152
|
+
idx = order[i : i + self.batch_size]
|
|
153
|
+
logits = self._logits([texts[j] for j in idx]) + self._bias
|
|
154
|
+
logits -= logits.max(axis=1, keepdims=True)
|
|
155
|
+
p = np.exp(logits)
|
|
156
|
+
out[idx] = p / p.sum(axis=1, keepdims=True)
|
|
157
|
+
return out
|
|
158
|
+
|
|
159
|
+
def top(self, probs: np.ndarray, k: int) -> list[list[Prediction]]:
|
|
160
|
+
k = max(1, min(k, probs.shape[1]))
|
|
161
|
+
idx = np.argpartition(-probs, k - 1, axis=1)[:, :k]
|
|
162
|
+
rows = []
|
|
163
|
+
for r, cand in enumerate(idx):
|
|
164
|
+
cand = cand[np.argsort(-probs[r, cand])]
|
|
165
|
+
rows.append([self._prediction(int(j), float(probs[r, j])) for j in cand])
|
|
166
|
+
return rows
|
|
167
|
+
|
|
168
|
+
def _prediction(self, j: int, p: float) -> Prediction:
|
|
169
|
+
label = self.labels[j]
|
|
170
|
+
return Prediction(label, self.names.get(label, label), round(p, 6))
|
|
171
|
+
|
|
172
|
+
def predict(self, texts: str | list[str], k: int = 3) -> list[Prediction] | list[list[Prediction]]:
|
|
173
|
+
"""The k most likely languages of a text, or of each of a list of texts, from its first
|
|
174
|
+
max_len bytes. For a text longer than that, identify_document reads all of it."""
|
|
175
|
+
if isinstance(texts, str):
|
|
176
|
+
return self.top(self.probabilities([texts]), k)[0]
|
|
177
|
+
return self.top(self.probabilities(list(texts)), k)
|
|
178
|
+
|
|
179
|
+
def document_windows(self, text: str, max_windows: int = 256) -> tuple[str, list[tuple[int, int]]]:
|
|
180
|
+
"""The normalised document and the windows to read, spread evenly when there are more
|
|
181
|
+
than max_windows, so a long document costs a bounded amount."""
|
|
182
|
+
norm = normalize(text)
|
|
183
|
+
spans = windows(norm, self.max_len - 1)
|
|
184
|
+
if len(spans) > max_windows:
|
|
185
|
+
pick = np.linspace(0, len(spans) - 1, max_windows).round().astype(int)
|
|
186
|
+
spans = [spans[i] for i in sorted(set(pick.tolist()))]
|
|
187
|
+
return norm, spans
|
|
188
|
+
|
|
189
|
+
def combine(self, norm: str, spans: list[tuple[int, int]], probs: np.ndarray, k: int = 3) -> DocumentResult:
|
|
190
|
+
"""The document's languages from its windows' probabilities, and its runs of one language."""
|
|
191
|
+
if not spans:
|
|
192
|
+
return DocumentResult([], [], 0, len(norm))
|
|
193
|
+
weights = np.array([b - a for a, b in spans], dtype=np.float32)
|
|
194
|
+
overall = (probs * weights[:, None]).sum(axis=0) / weights.sum()
|
|
195
|
+
languages = self.top(overall[None, :], k)[0]
|
|
196
|
+
best = probs.argmax(axis=1)
|
|
197
|
+
segments: list[Segment] = []
|
|
198
|
+
run_start = 0
|
|
199
|
+
for i in range(1, len(spans) + 1):
|
|
200
|
+
if i == len(spans) or best[i] != best[run_start]:
|
|
201
|
+
j = int(best[run_start])
|
|
202
|
+
p = float(probs[run_start:i, j].mean())
|
|
203
|
+
pred = self._prediction(j, p)
|
|
204
|
+
segments.append(Segment(spans[run_start][0], spans[i - 1][1], pred.label, pred.language, pred.probability))
|
|
205
|
+
run_start = i
|
|
206
|
+
return DocumentResult(languages, segments, len(spans), len(norm))
|
|
207
|
+
|
|
208
|
+
def identify_document(self, text: str, k: int = 3, max_windows: int = 256) -> DocumentResult:
|
|
209
|
+
"""A whole document, however long: read in windows of max_len bytes."""
|
|
210
|
+
norm, spans = self.document_windows(text, max_windows)
|
|
211
|
+
probs = self.probabilities([norm[a:b] for a, b in spans])
|
|
212
|
+
return self.combine(norm, spans, probs, k)
|
millid/server.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""A standalone HTTP service: `millid serve`, or `uvicorn millid.server:app_from_env --factory`.
|
|
2
|
+
|
|
3
|
+
An application with its own authentication can mount its own route on the same Registry and
|
|
4
|
+
MicroBatcher instead; this one is for running MillID as a service of its own.
|
|
5
|
+
|
|
6
|
+
MILLID_MODELS name=ref[@device][#threads],... (required)
|
|
7
|
+
MILLID_DEFAULT the model used when a request names none (default: the first)
|
|
8
|
+
MILLID_MAX_BATCH passages per model call (256)
|
|
9
|
+
MILLID_MAX_WAIT_MS how long a request may wait for others to join its batch (2)
|
|
10
|
+
MILLID_GPU_MEM_LIMIT_MB a cap on each GPU session's memory, when the GPU is shared
|
|
11
|
+
HF_TOKEN for private model repos
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
# No `from __future__ import annotations` here: FastAPI resolves the request model from the
|
|
15
|
+
# annotation, and the model is defined inside create_app, out of reach of a string annotation.
|
|
16
|
+
import os
|
|
17
|
+
from contextlib import asynccontextmanager
|
|
18
|
+
|
|
19
|
+
from millid.registry import Registry
|
|
20
|
+
|
|
21
|
+
MAX_TEXTS = 1000
|
|
22
|
+
MAX_CHARS = 1_000_000
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def create_app(registry: Registry):
|
|
26
|
+
from fastapi import FastAPI, HTTPException
|
|
27
|
+
from pydantic import BaseModel, Field, model_validator
|
|
28
|
+
|
|
29
|
+
class IdentifyRequest(BaseModel):
|
|
30
|
+
texts: list[str] | None = Field(None, max_length=MAX_TEXTS, description="passages, each read from its first 255 bytes")
|
|
31
|
+
text: str | None = Field(None, max_length=MAX_CHARS, description="one passage, or with document=true a whole document")
|
|
32
|
+
document: bool = Field(False, description="read `text` whole, in windows, and report its languages and segments")
|
|
33
|
+
k: int = Field(3, ge=1, le=20)
|
|
34
|
+
model: str | None = Field(None, description="a model name from GET /models; the default when omitted")
|
|
35
|
+
|
|
36
|
+
@model_validator(mode="after")
|
|
37
|
+
def one_input(self):
|
|
38
|
+
if (self.texts is None) == (self.text is None):
|
|
39
|
+
raise ValueError("give exactly one of `texts` or `text`")
|
|
40
|
+
if self.document and self.text is None:
|
|
41
|
+
raise ValueError("document=true reads `text`")
|
|
42
|
+
return self
|
|
43
|
+
|
|
44
|
+
@asynccontextmanager
|
|
45
|
+
async def lifespan(_app):
|
|
46
|
+
if not registry.models:
|
|
47
|
+
registry.load()
|
|
48
|
+
yield
|
|
49
|
+
await registry.aclose()
|
|
50
|
+
|
|
51
|
+
app = FastAPI(title="MillID", description="Language identification for 1,600+ language-script pairs.", lifespan=lifespan)
|
|
52
|
+
|
|
53
|
+
@app.get("/health")
|
|
54
|
+
async def health():
|
|
55
|
+
return {"status": "ok", "models": [m["name"] for m in registry.describe()]}
|
|
56
|
+
|
|
57
|
+
@app.get("/models")
|
|
58
|
+
async def models():
|
|
59
|
+
return {"models": registry.describe()}
|
|
60
|
+
|
|
61
|
+
@app.post("/identify")
|
|
62
|
+
async def identify(req: IdentifyRequest):
|
|
63
|
+
try:
|
|
64
|
+
name = registry.resolve(req.model)
|
|
65
|
+
except KeyError as e:
|
|
66
|
+
raise HTTPException(400, str(e)) from e
|
|
67
|
+
batcher = registry.batcher(name)
|
|
68
|
+
if req.document:
|
|
69
|
+
doc = await batcher.identify_document(req.text, req.k)
|
|
70
|
+
return {"model": name, "document": doc}
|
|
71
|
+
texts = req.texts if req.texts is not None else [req.text]
|
|
72
|
+
results = await batcher.predict(texts, req.k)
|
|
73
|
+
return {"model": name, "results": [{"languages": r} for r in results]}
|
|
74
|
+
|
|
75
|
+
return app
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def app_from_env():
|
|
79
|
+
registry = Registry.from_text(
|
|
80
|
+
os.environ["MILLID_MODELS"],
|
|
81
|
+
default=os.environ.get("MILLID_DEFAULT") or None,
|
|
82
|
+
max_batch=int(os.environ.get("MILLID_MAX_BATCH", "256")),
|
|
83
|
+
max_wait_ms=float(os.environ.get("MILLID_MAX_WAIT_MS", "2")),
|
|
84
|
+
token=os.environ.get("HF_TOKEN") or None,
|
|
85
|
+
gpu_mem_limit_mb=int(os.environ["MILLID_GPU_MEM_LIMIT_MB"]) if os.environ.get("MILLID_GPU_MEM_LIMIT_MB") else None,
|
|
86
|
+
)
|
|
87
|
+
return create_app(registry)
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: millid
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Detect the language of any text, offline: 1,550 languages in 56 scripts, many of them low-resource, with ONNX Runtime (no PyTorch, no server).
|
|
5
|
+
Project-URL: Homepage, https://huggingface.co/baobabtech/millid-tiny-v1.5
|
|
6
|
+
Project-URL: Documentation, https://github.com/baobab-tech/millid#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/baobab-tech/millid
|
|
8
|
+
Project-URL: Issues, https://github.com/baobab-tech/millid/issues
|
|
9
|
+
Project-URL: Leaderboard, https://huggingface.co/baobabtech/millid
|
|
10
|
+
Project-URL: JavaScript package, https://www.npmjs.com/package/@baobabtechai/millid
|
|
11
|
+
Author: Baobab Tech
|
|
12
|
+
License-Expression: Apache-2.0
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: african-languages,langid,language-detection,language-identification,low-resource-languages,multilingual,nlp,onnx,onnxruntime
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Intended Audience :: Science/Research
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
25
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
26
|
+
Requires-Python: >=3.10
|
|
27
|
+
Requires-Dist: huggingface-hub>=0.25
|
|
28
|
+
Requires-Dist: numpy>=1.24
|
|
29
|
+
Provides-Extra: cpu
|
|
30
|
+
Requires-Dist: onnxruntime>=1.18; extra == 'cpu'
|
|
31
|
+
Provides-Extra: data
|
|
32
|
+
Requires-Dist: datasets; extra == 'data'
|
|
33
|
+
Requires-Dist: fasttext-wheel; extra == 'data'
|
|
34
|
+
Requires-Dist: langcodes; extra == 'data'
|
|
35
|
+
Requires-Dist: pandas; extra == 'data'
|
|
36
|
+
Requires-Dist: pyarrow; extra == 'data'
|
|
37
|
+
Requires-Dist: pymupdf; extra == 'data'
|
|
38
|
+
Provides-Extra: dev
|
|
39
|
+
Requires-Dist: httpx; extra == 'dev'
|
|
40
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
41
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
42
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
43
|
+
Provides-Extra: gpu
|
|
44
|
+
Requires-Dist: onnxruntime-gpu[cuda,cudnn]>=1.20; extra == 'gpu'
|
|
45
|
+
Provides-Extra: server
|
|
46
|
+
Requires-Dist: fastapi>=0.110; extra == 'server'
|
|
47
|
+
Requires-Dist: pydantic>=2.6; extra == 'server'
|
|
48
|
+
Requires-Dist: uvicorn[standard]>=0.29; extra == 'server'
|
|
49
|
+
Provides-Extra: train
|
|
50
|
+
Requires-Dist: fasttext-wheel; extra == 'train'
|
|
51
|
+
Requires-Dist: onnx>=1.16; extra == 'train'
|
|
52
|
+
Requires-Dist: onnxscript; extra == 'train'
|
|
53
|
+
Requires-Dist: pandas; extra == 'train'
|
|
54
|
+
Requires-Dist: pyarrow; extra == 'train'
|
|
55
|
+
Requires-Dist: safetensors; extra == 'train'
|
|
56
|
+
Requires-Dist: torch>=2.4; extra == 'train'
|
|
57
|
+
Requires-Dist: tyro>=0.8; extra == 'train'
|
|
58
|
+
Requires-Dist: wandb; extra == 'train'
|
|
59
|
+
Description-Content-Type: text/markdown
|
|
60
|
+
|
|
61
|
+
# MillID
|
|
62
|
+
|
|
63
|
+
**Detect the language of any text, offline, in Python.** MillID recognises 1,550 languages written in 56 scripts, including hundreds of African, Asian and Indigenous languages that common language detectors do not cover. It runs on a CPU with no PyTorch and no server; the smallest model is 11 MB.
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from millid import MillID
|
|
67
|
+
|
|
68
|
+
model = MillID.from_pretrained("tiny-v1.5")
|
|
69
|
+
model.predict("Mo fẹ́ràn láti ka ìwé ní àkókò òmìnira mi.", k=1)
|
|
70
|
+
# [Prediction(label='yor_Latn', language='Yoruba', probability=0.973627)]
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## What is MillID?
|
|
74
|
+
|
|
75
|
+
MillID (MultiLingual Language IDentifier) is an open language identification model built by [Baobab Tech](https://huggingface.co/baobabtech). Give it a piece of text, from a short sentence to a whole document, and it tells you which language the text is written in, with a probability for each answer. Every answer names a language and its script, so Serbian in Cyrillic (`srp_Cyrl`) and Serbian in Latin (`srp_Latn`) are told apart.
|
|
76
|
+
|
|
77
|
+
Developers use it to:
|
|
78
|
+
|
|
79
|
+
- send each document to the right translation, OCR or speech model;
|
|
80
|
+
- sort or filter text by language when building a dataset;
|
|
81
|
+
- show an interface in the reader's language, or flag text in an unexpected one;
|
|
82
|
+
- count which languages a collection of documents contains.
|
|
83
|
+
|
|
84
|
+
## What this package does
|
|
85
|
+
|
|
86
|
+
This package runs MillID on your own machine. The first time you load a model it downloads the model's files from the [Hugging Face Hub](https://huggingface.co/baobabtech/millid-tiny-v1.5) into the Hugging Face cache; after that it works offline. The model runs in [ONNX Runtime](https://onnxruntime.ai), on a CPU or an NVIDIA GPU, with NumPy for the text encoding. There is no API to call and no PyTorch to install, and the text you identify never leaves your machine.
|
|
87
|
+
|
|
88
|
+
It also gives you a command-line tool and, if you want one, an HTTP service. The JavaScript package [`@baobabtechai/millid`](https://www.npmjs.com/package/@baobabtechai/millid) gives the same answers in Node.js and the browser.
|
|
89
|
+
|
|
90
|
+
## Install
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
pip install "millid[cpu]" # ONNX Runtime for the CPU
|
|
94
|
+
pip install "millid[gpu]" # ONNX Runtime for NVIDIA GPUs (CUDA 12, its libraries from pip)
|
|
95
|
+
pip install "millid[cpu,server]" # and the HTTP service
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Python 3.10 or later. ONNX Runtime comes as an extra because its CPU and GPU builds cannot be installed side by side: choose one.
|
|
99
|
+
|
|
100
|
+
## Quick start
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from millid import MillID
|
|
104
|
+
|
|
105
|
+
model = MillID.from_pretrained("tiny-v1.5") # downloads 11 MB once
|
|
106
|
+
|
|
107
|
+
model.predict("Je voudrais réserver une table pour deux personnes ce soir.", k=2)
|
|
108
|
+
# [Prediction(label='fra_Latn', language='French', probability=0.954421),
|
|
109
|
+
# Prediction(label='frp_Latn', language='Arpitan', probability=0.001443)]
|
|
110
|
+
|
|
111
|
+
model.predict(["Lave men ou ak savon anvan ou manje.", "Ndimakonda kuwerenga mabuku nthawi yanga yaulere."], k=1)
|
|
112
|
+
# [[Prediction(label='hat_Latn', language='Haitian Creole', probability=0.978552)],
|
|
113
|
+
# [Prediction(label='nya_Latn', language='Nyanja', probability=0.940327)]]
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`predict(text, k)` returns the `k` most likely languages (3 by default), most likely first. Pass a list to identify many texts in one call: they are batched together, which is much faster than one call per text.
|
|
117
|
+
|
|
118
|
+
## Command line
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
millid predict "Lave men ou ak savon anvan ou manje." -k 2
|
|
122
|
+
# hat_Latn 0.979, crs_Latn 0.000 Lave men ou ak savon anvan ou manje.
|
|
123
|
+
|
|
124
|
+
cat sentences.txt | millid predict -k 1 # one text per line
|
|
125
|
+
millid predict --document < report.txt # the whole file as one document, as JSON
|
|
126
|
+
millid predict --model large-v1.5 --device cuda "..." # another model, on the GPU
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Choose a model
|
|
130
|
+
|
|
131
|
+
| Model | Download | Top-1 accuracy | Macro F1 | Best for |
|
|
132
|
+
|---|---|---|---|---|
|
|
133
|
+
| `tiny-v1.5` (default) | 11 MB | 95.9% | 0.955 | any CPU, laptops, small servers |
|
|
134
|
+
| `medium-v1` | 455 MB | 96.2% | 0.958 | servers |
|
|
135
|
+
| `large-v1.5` | 764 MB | 96.7% | 0.965 | servers with a GPU: the most accurate |
|
|
136
|
+
|
|
137
|
+
Measured on 240,241 test passages in 1,621 languages, from documents the models never saw in training. Macro F1 weighs every language equally, so it shows how well the small languages are served, not just the large ones. The [leaderboard](https://huggingface.co/baobabtech/millid) compares the three with GlotLID and Meta's fastText identifier, language by language.
|
|
138
|
+
|
|
139
|
+
`from_pretrained` also takes a Hugging Face repo id (`"baobabtech/millid-large-v1.5"`) or a local directory holding `config.json`, `labels.json` and `onnx/model.onnx`, and these options:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
model = MillID.from_pretrained(
|
|
143
|
+
"large-v1.5",
|
|
144
|
+
device="cuda", # "cpu" (the default), "cuda", or "auto": the GPU when there is one
|
|
145
|
+
threads=4, # CPU threads for ONNX Runtime; its default when omitted
|
|
146
|
+
batch_size=64, # texts per model call
|
|
147
|
+
)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Reading the results
|
|
151
|
+
|
|
152
|
+
Each answer is a `Prediction` with three fields:
|
|
153
|
+
|
|
154
|
+
| Field | Example | Meaning |
|
|
155
|
+
|---|---|---|
|
|
156
|
+
| `label` | `'yor_Latn'` | the language's [ISO 639-3](https://iso639-3.sil.org) code and its [ISO 15924](https://www.unicode.org/iso15924/) script code |
|
|
157
|
+
| `language` | `'Yoruba'` | the language's English name |
|
|
158
|
+
| `probability` | `0.973627` | how likely this answer is, from 0 to 1; the answers for a text add up to at most 1 |
|
|
159
|
+
|
|
160
|
+
A few labels end in a script alone, such as `und_Tibt`: text in that script whose language MillID cannot name more precisely.
|
|
161
|
+
|
|
162
|
+
## Long text and whole documents
|
|
163
|
+
|
|
164
|
+
`predict` reads the first 255 bytes of a text, about 250 characters of English or 85 of Hindi. For anything longer, use `identify_document`: it reads the whole text in windows, gives the document's languages weighted by how much of the text each one covers, and marks where each language runs.
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
doc = model.identify_document(long_text, k=2)
|
|
168
|
+
doc.languages
|
|
169
|
+
# [Prediction(label='eng_Latn', language='English', probability=0.576472),
|
|
170
|
+
# Prediction(label='fra_Latn', language='French', probability=0.381211)]
|
|
171
|
+
doc.segments
|
|
172
|
+
# [Segment(start=0, end=250, label='eng_Latn', language='English', probability=0.952214),
|
|
173
|
+
# Segment(start=251, end=414, label='fra_Latn', language='French', probability=0.96499)]
|
|
174
|
+
doc.windows, doc.characters
|
|
175
|
+
# (2, 414)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`start` and `end` count characters in the text after normalisation (`millid.normalize(text)`), which collapses whitespace and applies Unicode NFKC.
|
|
179
|
+
|
|
180
|
+
## An HTTP service
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
millid serve --models "tiny-v1.5=baobabtech/millid-tiny-v1.5@cpu" --port 8050
|
|
184
|
+
curl -s localhost:8050/identify -H 'content-type: application/json' -d '{"text": "Lave men ou ak savon anvan ou manje.", "k": 1}'
|
|
185
|
+
# {"model": "tiny-v1.5", "results": [{"languages": [{"label": "hat_Latn", "language": "Haitian Creole", "probability": 0.978552}]}]}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
`POST /identify` takes `text` or `texts`, `k`, `model`, and `document: true` for a whole document; `GET /models` describes the loaded models and `GET /health` reports that the service is up. Requests that arrive together are answered in shared batches, so throughput grows with load. To serve MillID inside an application of your own, build on `millid.Registry` and `millid.MicroBatcher`.
|
|
189
|
+
|
|
190
|
+
## Tips
|
|
191
|
+
|
|
192
|
+
- **Give it a sentence or more.** A word or a short greeting carries little evidence: "Bonjour tout le monde" alone comes back as `nrm_Latn` (Norman) rather than French. A full sentence or more gives much more reliable answers.
|
|
193
|
+
- **Treat a low probability as unsure.** When the first answer is below 0.5, look at the next ones too, or ask for more text.
|
|
194
|
+
- **Close languages share their answers.** Swahili and Congo Swahili, or Bosnian and Croatian, differ by a few words; a short passage of either often gets both in its top answers. Ask for `k=3` and decide with what you know about your text.
|
|
195
|
+
- **Pass the text as it is.** Accents, tone marks and the script are much of what the model reads: do not strip, transliterate or romanise it first.
|
|
196
|
+
- **One text alone and the same text in a batch can score a little differently.** A batch is lower-cased as one string; call `predict` with one text where scores must not depend on their neighbours.
|
|
197
|
+
|
|
198
|
+
## API
|
|
199
|
+
|
|
200
|
+
| | |
|
|
201
|
+
|---|---|
|
|
202
|
+
| `MillID.from_pretrained(ref="tiny-v1.5", revision=None, token=None, **options)` | Load a model: `"tiny-v1.5"`, `"medium-v1"`, `"large-v1.5"`, a Hugging Face repo id, or a directory. `token` only for a private repo; options `device`, `threads`, `batch_size`, `gpu_mem_limit_mb` |
|
|
203
|
+
| `model.predict(text, k=3)` | The `k` most likely languages of a text, as `Prediction`s. A list of texts gives one list per text |
|
|
204
|
+
| `model.identify_document(text, k=3, max_windows=256)` | A text of any length, as a `DocumentResult`: `languages`, `segments`, `windows`, `characters` |
|
|
205
|
+
| `model.probabilities(texts)` | A NumPy array, one row per text, a probability for each label in `model.labels` |
|
|
206
|
+
| `millid.MODELS` | The released models by short name |
|
|
207
|
+
| `millid.normalize`, `millid.encode_batch` | The model's input, to run the ONNX file elsewhere |
|
|
208
|
+
|
|
209
|
+
`MillID` is `millid.LanguageIdentifier` under a shorter name. A model is safe to call from several threads at once.
|
|
210
|
+
|
|
211
|
+
## How it works
|
|
212
|
+
|
|
213
|
+
MillID is a small transformer that reads text as UTF-8 bytes rather than words, so there is no vocabulary to outgrow: any script, even one it has rarely seen, is input it can read. Each byte is described by the byte itself, the Unicode script of its character and the character sequences ending there; the network turns a passage into one vector and scores it against a vector for every label, built from the label itself, its language (shared across scripts) and its script. The full design is in [the architecture document](https://github.com/baobab-tech/millid/blob/main/training/ARCHITECTURE.md), and each model's card on the Hub has its evaluation.
|
|
214
|
+
|
|
215
|
+
## Links
|
|
216
|
+
|
|
217
|
+
- Models: [tiny v1.5](https://huggingface.co/baobabtech/millid-tiny-v1.5), [medium v1](https://huggingface.co/baobabtech/millid-medium-v1), [large v1.5](https://huggingface.co/baobabtech/millid-large-v1.5)
|
|
218
|
+
- Leaderboard: [baobabtech/millid](https://huggingface.co/baobabtech/millid)
|
|
219
|
+
- Dataset: [baobabtech/millid-dataset](https://huggingface.co/datasets/baobabtech/millid-dataset)
|
|
220
|
+
- JavaScript package: [`@baobabtechai/millid` on npm](https://www.npmjs.com/package/@baobabtechai/millid)
|
|
221
|
+
- Source, training code and issues: [github.com/baobab-tech/millid](https://github.com/baobab-tech/millid)
|
|
222
|
+
|
|
223
|
+
## Licence
|
|
224
|
+
|
|
225
|
+
Apache-2.0, for the code and the model weights. Built by [Baobab Tech](https://huggingface.co/baobabtech).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
millid/__init__.py,sha256=Wj7Q73PL2ZwTUFyJ_WUdvXWQ0bNf-ygigQd3U0zi5Tw,1108
|
|
2
|
+
millid/batching.py,sha256=gfoYDmlgaRhOn3JcPJnogc5nduRxrTKhP1hNAmWIpLo,4043
|
|
3
|
+
millid/cli.py,sha256=Wl8VqvnoKrPONx9gjB9dYLoDRoo6cZIMEmxoa9EvyqA,2600
|
|
4
|
+
millid/encoding.py,sha256=YVByQ4Ek5BQBBifTvoyToDrErFclF_ewP6Hfqfmz98g,6603
|
|
5
|
+
millid/registry.py,sha256=xG1tqLSNufV18ZwuwP64mUjiOxwZbOSHv83BjbX6R8c,4157
|
|
6
|
+
millid/runtime.py,sha256=Hp5EJw8k1QoLrdwuHi9ihsMGVvgG_TLIZXz2CZEGzmU,9667
|
|
7
|
+
millid/server.py,sha256=DZtRL8lk159VDC7_wmPtkavWNth-OkUTj3CZcztutgc,3702
|
|
8
|
+
millid/data/scripts.json,sha256=vNvvBJj3rQSbZol-0l_3vizFZ9EBWWMO8nizWj5u_kQ,13372
|
|
9
|
+
millid-0.2.0.dist-info/METADATA,sha256=OqSsfYkKnpelUYyO6bD156rRm07-hBBcb2meAKvSpSw,13166
|
|
10
|
+
millid-0.2.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
11
|
+
millid-0.2.0.dist-info/entry_points.txt,sha256=mPo8tWGWBEs-uAoKew5K5pWVh0_jK7AvDd1aReZ1yNI,43
|
|
12
|
+
millid-0.2.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
13
|
+
millid-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|