/
genstory.go
335 lines (289 loc) · 11 KB
/
genstory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// Package genstory provides means to generate text from templates and / or rules.
package genstory
import (
"errors"
"math/rand"
"strings"
"github.com/Flokey82/go_gens/genlanguage"
)
// TokenReplacement is a replacement for a token in a text.
// TODO: Allow infinite re-use of tokens.
type TokenReplacement struct {
Token string // The token to replace.
Replacement string // The replacement text.
}
// TextConfig is a configuration for generating text.
type TextConfig struct {
TokenPools map[string][]string // A map of token names to a list of possible values.
TokenIsMandatory map[string]bool // A map of token names to a boolean indicating whether the token is mandatory.
Tokens []string // A list of tokens that are required to be replaced.
Templates []string // A list of possible templates.
Title bool // Capitalize the first letter of each word in the text.
UseAllProvided bool // Use all provided tokens, even if they are not used in the template.
UseAlliteration bool // Use alliteration in the text (from token to token)
Modifiers map[string]func(string) string // A map of token names to a function that modifies the replacement text.
}
// Generate generates a text from the provided tokens and the configuration.
func (c *TextConfig) Generate(provided []TokenReplacement) (*Generated, error) {
return DefaultTextGenerator.GenerateFromConfig(provided, c, nil)
}
// GenerateAndGiveMeTheTemplate generates a text from the provided tokens and the configuration.
// It also returns the template that was used to generate the text.
func (c *TextConfig) GenerateAndGiveMeTheTemplate(provided []TokenReplacement) (*Generated, error) {
return DefaultTextGenerator.GenerateFromConfig(provided, c, nil)
}
// GenerateWithTemplate generates a text from the provided tokens and the provided template.
func (c *TextConfig) GenerateWithTemplate(provided []TokenReplacement, template string) (*Generated, error) {
return DefaultTextGenerator.GenerateFromConfig(provided, c, []string{template})
}
// GetTemplatesWithTokens returns a list of templates that contain all the provided tokens.
func (c *TextConfig) GetTemplatesWithTokens(tokens []string) []string {
var templates []string
Loop:
for _, template := range c.Templates {
exTokens, err := ExtractTokens(template)
if err != nil {
continue
}
hasToken := make(map[string]bool)
for _, tok := range exTokens {
hasToken[tok.Token] = true
}
for _, token := range tokens {
if !hasToken[token] {
continue Loop
}
}
templates = append(templates, template)
}
return templates
}
// TextGenerator is a generator for text using TextConfigs.
// Using this over the TextConfig methods allows you to use a custom random number generator
// and to (re-)set the random number generator's seed.
type TextGenerator struct {
RandInterface
}
// NewTextGenerator creates a new TextGenerator using the provided random number generator.
func NewTextGenerator(rng RandInterface) *TextGenerator {
return &TextGenerator{
RandInterface: rng,
}
}
// Generate generates a text from the provided tokens and the configuration.
func (g *TextGenerator) Generate(provided []TokenReplacement, config *TextConfig) (*Generated, error) {
return g.GenerateFromConfig(provided, config, nil)
}
// GenerateAndGiveMeTheTemplate generates a text from the provided tokens and the configuration.
// It also returns the template that was used to generate the text.
func (g *TextGenerator) GenerateAndGiveMeTheTemplate(provided []TokenReplacement, config *TextConfig) (*Generated, error) {
return g.GenerateFromConfig(provided, config, nil)
}
// GenerateButUseThisTemplate generates a text from the provided tokens and the provided template.
func (g *TextGenerator) GenerateButUseThisTemplate(provided []TokenReplacement, config *TextConfig, template string) (*Generated, error) {
return g.GenerateFromConfig(provided, config, []string{template})
}
// Generated provides information about a generated text.
type Generated struct {
Text string
Template string
Tokens []TokenReplacement
}
func (g *TextGenerator) GenerateFromConfig(provided []TokenReplacement, config *TextConfig, altTemplates []string) (*Generated, error) {
templates := config.Templates
if altTemplates != nil {
templates = altTemplates
}
tokens := config.Tokens
isMandatory := config.TokenIsMandatory
tokenRandom := config.TokenPools
modifierFuncs := config.Modifiers
capitalize := config.Title
useAllProvided := config.UseAllProvided
// Function for applying modifiers to a string.
applyModifiers := func(s string, modifiers []string) string {
for _, modifier := range modifiers {
// Check if we have a custom modifier function for this token.
if modifierFuncs != nil {
if fn, ok := modifierFuncs[modifier]; ok {
s = fn(s)
}
}
if fn, ok := DefaultModifiers[modifier]; ok {
s = fn(s)
}
}
return s
}
// Count how many token replacements we have for each token.
tokenReplacements := make(map[string][]string)
for _, replacement := range provided {
tokenReplacements[replacement.Token] = append(tokenReplacements[replacement.Token], replacement.Replacement)
}
type candidate struct {
template string
extractedTokens []ExtractedToken
}
// Loop over all templates and find the ones where we have all required tokens.
var possibleTemplates []candidate
for _, i := range rand.Perm(len(templates)) {
template := templates[i]
// TODO: Maybe cache the extracted tokens somewhere.
extracted, err := ExtractTokens(template)
if err != nil {
return nil, err
}
// Count how many times each token appears in the template.
tokenCounts := make(map[string]int)
for _, token := range extracted {
tokenCounts[token.Token]++
}
// Check if we have all required tokens the required number of times.
// TODO: Allow tokens to be re-usable.
var missingToken bool
for _, token := range tokens {
if len(tokenReplacements[token]) < tokenCounts[token] {
// Check if the current token is mandatory or if we don't have any replacements for it.
// TODO: Maybe check if the sum of provided tokens and token replacements satisfies the template.
if isMandatory[token] || len(tokenRandom[token]) == 0 {
missingToken = true
break
}
}
}
// Something is missing, skip this template.
if missingToken {
continue
}
// Also make sure all tokens we have provided are available in the template,
// since we want to pick a complete template, referencing all provided tokens.
if useAllProvided {
for _, replacement := range provided {
// TODO: Take in account that tokens might have modifiers, which defeats strings.Count.
if tokenCounts[replacement.Token] < len(tokenReplacements[replacement.Token]) {
missingToken = true
break
}
}
// Something is missing, skip this template.
if missingToken {
continue
}
}
// We have all required tokens, add the template to the list of possible templates.
possibleTemplates = append(possibleTemplates, candidate{
template: template,
extractedTokens: extracted,
})
}
// If we have no possible templates, return an error.
if len(possibleTemplates) == 0 {
return nil, errors.New("no possible templates satisfying the provided tokens")
}
// Pick a random text.
chosen := possibleTemplates[rand.Intn(len(possibleTemplates))]
generated := &Generated{
Text: chosen.template,
Template: chosen.template,
}
// Relplace each token one by one until we can't find any more.
replacementsUsed := make(map[string]int)
var lastToken string
for _, token := range chosen.extractedTokens {
// Replace all tokens with the provided replacements or a random value.
var replacement string
if replacementsUsed[token.Token] < len(tokenReplacements[token.Token]) {
replacement = tokenReplacements[token.Token][replacementsUsed[token.Token]]
replacementsUsed[token.Token]++
} else {
// If we have alliteration enabled, we might want to try to find a
// replacement that starts with the same letter as the previous token.
if config.UseAlliteration && lastToken != "" {
for _, idx := range rand.Perm(len(tokenRandom[token.Token])) {
replacement = tokenRandom[token.Token][idx]
// NOTE: This will panic if the token is empty.
if strings.ToLower(replacement[:1]) == strings.ToLower(lastToken[:1]) {
break
}
}
}
// If we still don't have a matching replacement, just pick a random one.
if replacement == "" {
replacement = randArrayString(g, tokenRandom[token.Token])
}
}
// Remember the token and the replacement we used.
generated.Tokens = append(generated.Tokens, TokenReplacement{
Token: token.Token,
Replacement: replacement,
})
// Remember the last token we used.
lastToken = replacement
// Apply modifiers.
replacement = applyModifiers(replacement, token.Modifiers)
// Replace the token with the replacement.
generated.Text = strings.Replace(generated.Text, token.FullToken, replacement, 1)
}
if capitalize {
// Capitalize the first letter of each word in the text.
generated.Text = strings.Title(generated.Text)
} else {
// Capitalize the first letter of the text.
// We have to make sure we don't just use the slice operator, since that
// might corrupt UTF-8 characters.
generated.Text = genlanguage.Capitalize(generated.Text)
}
return generated, nil
}
func randArrayString(rng RandInterface, arr []string) string {
if len(arr) == 0 {
return ""
}
return arr[rng.Intn(len(arr))]
}
func ApplyModifiers(s string, modifiers []string) string {
for _, modifier := range modifiers {
if fn, ok := DefaultModifiers[modifier]; ok {
s = fn(s)
}
}
return s
}
// DefaultModifiers is a map of default modifiers that can be used in templates.
var DefaultModifiers = map[string]func(string) string{
"title": strings.Title, // Title case.
"capitalize": genlanguage.Capitalize, // Capitalize the first letter.
"upper": strings.ToUpper,
"lower": strings.ToLower,
"adjecive": genlanguage.GetAdjective,
"nounplural": genlanguage.GetNounPlural,
"past": genlanguage.GetPastTense,
"presentsingular": genlanguage.GetPresentSingular,
"presentparticiple": genlanguage.GetPresentParticiple,
"quote": func(s string) string {
return "'" + s + "'"
},
"doublequote": func(s string) string {
return "\"" + s + "\""
},
"trimvowels": func(s string) string {
return genlanguage.TrimVowels(s, 3)
},
"a": func(s string) string {
// Add an article to the string.
return genlanguage.GetArticle(s) + " " + s
},
}
type RandInterface interface {
Intn(n int) int
Seed(seed int64)
}
type randWrapper struct{}
func (r *randWrapper) Intn(n int) int {
return rand.Intn(n)
}
func (r *randWrapper) Seed(seed int64) {
rand.Seed(seed)
}
var defaultRand = &randWrapper{}
var DefaultTextGenerator = NewTextGenerator(defaultRand)