markovdemo.gno
4.60 Kb · 141 lines
1// Package markovdemo is a small on-chain demo of the Markov-chain text
2// generator provided by the [p/moul/x/daily/markov](/p/moul/x/daily/markov/v0)
3// library.
4//
5// It holds a single package-level [markov.Chain] as the corpus and wires it to
6// the chain: Feed appends words to that persistent chain (a crossing function,
7// since it mutates on-chain state), while Generate and Render walk it with a
8// seed derived from runtime.ChainHeight() — so babbling is a pure, reproducible
9// query that still varies block to block. It contains no Markov logic of its
10// own — build/walk math all lives in the library.
11package markovdemo
12
13import (
14 "chain/markdown"
15 "chain"
16 "chain/runtime"
17 "strconv"
18 "strings"
19
20 "gno.land/p/moul/x/daily/markov/v0"
21)
22
23// maxGen clamps Generate / Render so output stays bounded.
24const maxGen = 200
25
26// mc is the single on-chain corpus, seeded at deploy time.
27var mc = markov.New()
28
29func init() {
30 // Two seed sentences with heavy two-word-prefix overlap, so a fresh deploy
31 // already babbles something recognizably chain-like.
32 mc.Build("it was the best of times it was the worst of times " +
33 "it was the age of wisdom it was the age of foolishness")
34 mc.Build("i am a free man i am not a number " +
35 "i am the master of my fate i am the captain of my soul")
36}
37
38// seedFor derives a Generate seed from the current chain height so the babble
39// changes block to block yet stays reproducible for anyone querying the same
40// height.
41func seedFor() uint64 {
42 return uint64(runtime.ChainHeight())*2654435761 + 0x9e3779b97f4a7c15
43}
44
45// Feed appends text to the on-chain corpus, extending the Markov chain. Any
46// caller may enrich the corpus — this is the open-membership demo model.
47func Feed(cur realm, text string) string {
48 if strings.TrimSpace(markdown.StripBidiAndZeroWidth(text)) == "" {
49 panic("markov: empty text")
50 }
51 added := mc.Build(text)
52 words, prefixes := mc.Stats()
53 chain.Emit("Feed", "words", strconv.Itoa(added), "total", strconv.Itoa(words))
54 return "fed " + strconv.Itoa(added) + " words; corpus now " +
55 strconv.Itoa(words) + " words across " +
56 strconv.Itoa(prefixes) + " prefixes"
57}
58
59// Generate babbles up to nWords of Markov text from the current corpus, seeded
60// deterministically by the chain height. Read-only.
61func Generate(nWords int) string {
62 if nWords <= 0 {
63 nWords = 20
64 }
65 if nWords > maxGen {
66 nWords = maxGen
67 }
68 return strings.Join(mc.Generate(nWords, seedFor()), " ")
69}
70
71// Stats returns (totalWords, prefixCount) for the current corpus.
72func Stats() (int, int) {
73 return mc.Stats()
74}
75
76// parseN pulls a trailing positive integer out of a Render path such as
77// "/40" or "gen/40"; it returns 0 when there is none.
78func parseN(path string) int {
79 p := strings.Trim(path, "/")
80 if i := strings.LastIndex(p, "/"); i >= 0 {
81 p = p[i+1:]
82 }
83 n, err := strconv.Atoi(p)
84 if err != nil || n < 0 {
85 return 0
86 }
87 return n
88}
89
90// Render shows a freshly generated sample plus corpus stats. The path may
91// carry a word count, e.g. Render("/60").
92func Render(path string) string {
93 n := parseN(path)
94 if n == 0 {
95 n = 40
96 }
97 if n > maxGen {
98 n = maxGen
99 }
100
101 words, prefixes := mc.Stats()
102
103 var b strings.Builder
104 b.WriteString("# Markov Babbler\n\n")
105 b.WriteString("A demo of the [`p/moul/x/daily/markov`](/p/moul/x/daily/markov/v0) " +
106 "library — an on-chain port of Go's classic *\"Generating arbitrary text: " +
107 "a Markov chain algorithm\"* codewalk. Every two-word **prefix** maps to " +
108 "the words that followed it; `Generate` walks that chain, picking suffixes " +
109 "with a PRNG seeded by the block height — deterministic, yet different each " +
110 "block.\n\n")
111
112 b.WriteString("## Fresh sample (" + strconv.Itoa(n) + " words, height " +
113 strconv.FormatInt(runtime.ChainHeight(), 10) + ")\n\n")
114 sample := strings.Join(mc.Generate(n, seedFor()), " ")
115 if sample == "" {
116 sample = "_(empty corpus)_"
117 }
118 b.WriteString("> " + sample + "\n\n")
119
120 b.WriteString("## Corpus\n\n")
121 b.WriteString("- **Words:** " + strconv.Itoa(words) + "\n")
122 b.WriteString("- **Distinct prefixes:** " + strconv.Itoa(prefixes) + "\n")
123 b.WriteString("- **Prefix length:** " + strconv.Itoa(markov.PrefixLen) + " words\n\n")
124
125 b.WriteString("## Some prefixes → suffixes\n\n")
126 b.WriteString("| prefix | can be followed by |\n|---|---|\n")
127 shown := 0
128 mc.Iterate(func(k string, suffixes []string) bool {
129 disp := k
130 if disp == " " || disp == "" {
131 disp = "_(start)_"
132 }
133 b.WriteString("| `" + disp + "` | " + strings.Join(suffixes, ", ") + " |\n")
134 shown++
135 return shown >= 12 // cap the table
136 })
137 b.WriteString("\n_Call `Feed(\"your text here\")` to teach it new words, then " +
138 "reload for a new sample._\n")
139
140 return b.String()
141}