rechunk.go raw

   1  package iskra
   2  
   3  import (
   4  	"fmt"
   5  )
   6  
   7  // Rechunk rewrites every content run from two-character chunks into whole
   8  // words, and returns how many records it rewrote.
   9  //
  10  // Why this exists: the moxie corpus loader tokenised source with Tokenize, and
  11  // the .meta it wrote stores token ids into a dictionary the same tokenizer
  12  // filled. Its SetContent wrote one uint32 per token. This Go port wrote one
  13  // chunk per token and joined chunks with a space on read, which does not
  14  // reproduce the source content. Rechunk recovers the text with that chunk join,
  15  // re-tokenises it by TokenizeWords, and stores a new run; Content then returns
  16  // exactly the recovered text, as one token per word.
  17  func (t *Tree) Rechunk() (int, error) {
  18  	n := t.DB.RecordCount()
  19  	pool := make([]uint32, 0, len(t.TokenPool))
  20  	word := NewDict()
  21  	rewritten := 0
  22  	for ri := uint32(0); ri < n; ri++ {
  23  		m := t.Meta(ri)
  24  		if m == nil {
  25  			continue
  26  		}
  27  		seq := t.TokenSeq(ri)
  28  		if len(seq) == 0 {
  29  			continue
  30  		}
  31  		text, err := t.chunkJoin(seq)
  32  		if err != nil {
  33  			return rewritten, fmt.Errorf("iskra: record %d: %w", ri, err)
  34  		}
  35  		off := uint32(len(pool))
  36  		for _, tok := range TokenizeWords([]byte(text)) {
  37  			pool = append(pool, word.Add([]byte(tok.Text), tok.Class))
  38  		}
  39  		m.SetContentRef(off, uint32(len(pool))-off)
  40  		rewritten++
  41  	}
  42  	t.Dict = word
  43  	t.TokenPool = pool
  44  	return rewritten, nil
  45  }
  46  
  47  // chunkJoin renders a run the way this port's chunk token numbers decode.
  48  //
  49  // The chunk tokenizer advances two bytes per token, so a token is exactly
  50  // either one byte (the last chunk of an odd-length content, or an ASCII
  51  // character) or a two-byte rune. A one-byte token that is not part of a
  52  // multi-byte rune carries the space that followed it: the original run
  53  // interleaved single characters - spaces, punctuation, and two-character
  54  // identifier heads - and that is the only place a space can have been. A
  55  // two-byte token contributes its bytes and no space.
  56  func (t *Tree) chunkJoin(seq []uint32) (string, error) {
  57  	out := make([]byte, 0, len(seq)*3)
  58  	for _, id := range seq {
  59  		if int(id) >= len(t.Dict.Entries) {
  60  			return "", fmt.Errorf("token id %d beyond %d dictionary entries", id, len(t.Dict.Entries))
  61  		}
  62  		b := t.Dict.Get(id)
  63  		if len(b) == 0 {
  64  			continue
  65  		}
  66  		out = append(out, b...)
  67  		if len(b) == 1 {
  68  			out = append(out, ' ')
  69  		}
  70  	}
  71  	return string(out), nil
  72  }
  73