package iskra import ( "fmt" ) // Rechunk rewrites every content run from two-character chunks into whole // words, and returns how many records it rewrote. // // Why this exists: the moxie corpus loader tokenised source with Tokenize, and // the .meta it wrote stores token ids into a dictionary the same tokenizer // filled. Its SetContent wrote one uint32 per token. This Go port wrote one // chunk per token and joined chunks with a space on read, which does not // reproduce the source content. Rechunk recovers the text with that chunk join, // re-tokenises it by TokenizeWords, and stores a new run; Content then returns // exactly the recovered text, as one token per word. func (t *Tree) Rechunk() (int, error) { n := t.DB.RecordCount() pool := make([]uint32, 0, len(t.TokenPool)) word := NewDict() rewritten := 0 for ri := uint32(0); ri < n; ri++ { m := t.Meta(ri) if m == nil { continue } seq := t.TokenSeq(ri) if len(seq) == 0 { continue } text, err := t.chunkJoin(seq) if err != nil { return rewritten, fmt.Errorf("iskra: record %d: %w", ri, err) } off := uint32(len(pool)) for _, tok := range TokenizeWords([]byte(text)) { pool = append(pool, word.Add([]byte(tok.Text), tok.Class)) } m.SetContentRef(off, uint32(len(pool))-off) rewritten++ } t.Dict = word t.TokenPool = pool return rewritten, nil } // chunkJoin renders a run the way this port's chunk token numbers decode. // // The chunk tokenizer advances two bytes per token, so a token is exactly // either one byte (the last chunk of an odd-length content, or an ASCII // character) or a two-byte rune. A one-byte token that is not part of a // multi-byte rune carries the space that followed it: the original run // interleaved single characters - spaces, punctuation, and two-character // identifier heads - and that is the only place a space can have been. A // two-byte token contributes its bytes and no space. func (t *Tree) chunkJoin(seq []uint32) (string, error) { out := make([]byte, 0, len(seq)*3) for _, id := range seq { if int(id) >= len(t.Dict.Entries) { return "", fmt.Errorf("token id %d beyond %d dictionary entries", id, len(t.Dict.Entries)) } b := t.Dict.Get(id) if len(b) == 0 { continue } out = append(out, b...) if len(b) == 1 { out = append(out, ' ') } } return string(out), nil }