test/encode.bend source
test/encode.bend on the hub · documented module
# Encodes texts with a tokenizer.json, one line of ids (or an error) per text, for test/compare.py.# Usage: ./encode TOKENIZER_JSON TEXTS OUT, TEXTS being UTF-8 texts separated by NUL bytes.import Baseimport ../tok.bend as TKdef lap(label: String, +t0: Nat) -> IO(Nat): do IO<Nat>: +t : Nat <- IO.now() IO.print_err(label ++ " " ++ Nat.show(Nat.sub(t, t0)) ++ " ms") return tdef got(r: Result<&1, &1, U32 & String, List<&2, U32>>) -> List<&2, U32>: match r: case Done{v}: v case Fail{e}: []def read_done(r: File & Result<&1, &1, U32 & String, List<&2, U32>>) -> IO(List<&2, U32>): match r: case (f, res): do IO<List<&2, U32>>: x : Unit <- File.close(f) IO.pure(List<&2, U32>, got(res))def read_all(path: String) -> IO(List<&2, U32>): do IO<List<&2, U32>>: f : File <- IO.try(File, File.open(path, "r")) r : File & Result<&1, &1, U32 & String, List<&2, U32>> <- File.read_bytes(f, 200000000) read_done(r)# texts separated by 0 bytesdef texts_cut(z: Bool, +b: U32, cur: List<&2, U32>, go: List<&2, U32> -> List<&2, List<&2, U32>>) -> List<&2, List<&2, U32>>: match z: case True{}: List.reverse(&2, U32, cur) <> go([]) case False{}: go(b <> cur)def texts_go(bs: List<&2, U32>, cur: List<&2, U32>) -> List<&2, List<&2, U32>>: match bs: case []: [List.reverse(&2, U32, cur)] case +b <> t: texts_cut(U32.is_eq(b, 0), b, cur, c => texts_go(t, c))def ids_line(ids: List<&2, U32>) -> String: match ids: case []: "" case i <> t: U32.show(i) ++ " " ++ ids_line(t)def show_err(e: TK.Err) -> String: match e: case TK.BadUtf8{at}: "ERR utf8 " ++ U32.show(at) case TK.NoToken{t}: "ERR notoken"def show(r: Result<&2, &2, TK.Err, List<&2, U32>>) -> String: match r: case Done{ids}: ids_line(ids) case Fail{e}: show_err(e)def lines(+tk: TK.Tok, ts: List<&2, List<&2, U32>>) -> String: match ts: case []: "" case t <> rest: show(TK.encode(tk, t)) ++ "\n" ++ lines(tk, rest)def close_w(w: File & Result<&1, &1, U32 & String, Unit>) -> IO(Unit): match w: case (f, r): File.close(f)def run(r: Result<&2, &2, String, TK.Tok>, ts: List<&2, List<&2, U32>>, out: String, +t1: Nat) -> IO(Unit): match r: case Fail{why}: IO.print("refused: " ++ why) case Done{+tk}: do IO<Unit>: f : File <- IO.try(File, File.open(out, "w")) w : File & Result<&1, &1, U32 & String, Unit> <- File.write(f, lines(tk, ts)) t2 : Nat <- lap("encode", t1) close_w(w)def nth(xs: List<&2, String>, n: Nat) -> String: match xs n: case Nil{} _: "" case h <> t 0n: h case h <> t 1n+p: nth(t, p)def reuse(xs: List<String>) -> List<&2, String>: match xs: case []: [] case h <> t: h <> reuse(t)def main() -> IO(Unit): do IO<Unit>: a0 : List<String> <- IO.args() +args : List<&2, String> = reuse(a0) t0 : Nat <- IO.now() +tk : Result<&2, &2, String, TK.Tok> <- TK.open(nth(args, 1n)) t1a : Nat <- lap("open", t0) tx : List<&2, U32> <- read_all(nth(args, 2n)) t1 : Nat <- IO.now() run(tk, texts_go(tx, []), nth(args, 3n), t1)