genstory

package
v0.0.0-...-ce97658 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 17, 2024 License: Apache-2.0 Imports: 5 Imported by: 8

README

genstory: Quick and dirty story generation

This is just a playground for flavor text generation. It's not very good, but it's a start. Please note that this is still a work in progress, but please feel free to make suggestions or contribute / improve. Currently, there are two ways to set up text generation:

  1. Using the templates
  2. Using the rules / grammar

Templates

The template system uses simple text templates with placeholders for the various parts of the story which will be replaced using the token pools defined in the configs for the story generation.

Example
package main

import (
    "fmt"
    "github.com/Flokey82/go_gens/genstory"
)

func main() {
	// Define some tokens.
	tokenColor := "[color]"
	tokenItem := "[item]"
	tokenLocation := "[location]"
	tokenPerson := "[person]"

	// Set up a config for the generator.
	cfg := &genstory.TextConfig{
		TokenPools: map[string][]string{
			tokenColor:    {"red", "blue", "green", "yellow"},
			tokenItem:     {"skirt", "dress", "shirt", "sock"},
			tokenLocation: {"forest", "mountain", "cave", "lake"},
		},
		TokenIsMandatory: map[string]bool{
			tokenPerson: true,
		},
		Tokens: []string{tokenColor, tokenItem, tokenLocation, tokenPerson},
		Templates: []string{
			"The [color] [item] was found in the [location] by someone called [person:quote].",
			"The [item] was found by [person] in the [location].",
			"[person] lost my [item] in the [location].",
		},
		UseAllProvided: true,
	}
	for i := 0; i < 10; i++ {
		// Generate a story.
		story, err := cfg.Generate([]genstory.TokenReplacement{
			{Token: tokenPerson, Replacement: "John"},
		})
		if err != nil {
			log.Println(err)
			continue
		}
		fmt.Println(story.Text)
	}
}

Rules / Grammar

The rule system is a bit more complex and allows for more flexibility like recursive expansions, assignment of individual tokens to labels (like the names of people, places, etc. for reuse), and more.

Example
package main

import (
    "fmt"
    "github.com/Flokey82/go_gens/genstory"
)

func main() {
	rules := &genstory.Rules{
		Expansions: map[string][]string{
			"animal": {
				"cat",
				"dog",
				"mouse",
				"elephant",
				"tiger",
				"lion",
			},
			"name": {
				"John",
				"Jane",
				"Bob",
				"Mary",
				"Peter",
				"Paul",
			},
			"event": {
				"snuggled by [animal:a] named [attacker/name:quote]",
				"bitten by [animal:a] named [attacker/name:quote]",
				"chased by [animal:a] named [attacker/name:quote]",
				"licked by [animal:a] named [attacker/name:quote]",
				"purred at by [animal:a] named [attacker/name:quote]",
			},
		},
		Start: "Yesterday, the quiet town of Everwood was shocked to discover that mayor [mayor/name] was [event]. [mayor/name] was visibly shaken by the incident." +
			"\"I'm not sure what to make of this,\" said [mayor/name]. \"I've never been [event] before.\"",
	}

	story := rules.NewStory(time.Now().UnixNano())
	txt, err := story.Expand()
	if err != nil {
		log.Fatal(err)
	}
	log.Println(txt)
}

Documentation

Overview

Package genstory provides means to generate text from templates and / or rules.

Index

Constants

This section is empty.

Variables

View Source
var DefaultModifiers = map[string]func(string) string{
	"title":             strings.Title,
	"capitalize":        genlanguage.Capitalize,
	"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 {

		return genlanguage.GetArticle(s) + " " + s
	},
}

DefaultModifiers is a map of default modifiers that can be used in templates.

View Source
var DefaultTextGenerator = NewTextGenerator(defaultRand)
View Source
var ExampleRules = &Rules{
	Expansions: map[string][]string{
		"animal": genlanguage.GenBase[genlanguage.GenBaseAnimal],
		"name": {
			"John",
			"Jane",
			"Bob",
			"Mary",
			"Peter",
			"Paul",
			"George",
			"Ringo",
		},
		"victim": {
			"old lady",
			"blind person",
			"child",
		},
		"loot": {
			"money",
			"jewels",
			"gold",
			"silver",
			"coins",
		},
		"crime": {
			"arson",
			"extortion",
			"racketeering",
			"theft from [victim:a]",
			"theft of [loot]",
			"crimes against humanity",
			"defrauding [victim:a]",
			"running a crypto scam",
		},
		"tragedy": {
			", but [petname] was eaten by [name] the [animal]",
			", but [petname] the [pet] died",
			", but [petname] the [pet] ran away",
			", but [petname] the [pet] was stolen",
			", but [petname] the [pet] was arrested for [crime]",
		},
	},
	Start: "[hero/name:quote] bought [pet/animal:a]. [hero] loved the [pet] and named it [petname/name][tragedy].",
}

Functions

func ApplyModifiers

func ApplyModifiers(s string, modifiers []string) string

Types

type ExtractedToken

type ExtractedToken struct {
	Token     string   // The name of the token.
	FullToken string   // The full token, including the square brackets and modifiers.
	Modifiers []string // A list of modifiers for the token.
	Start     int      // The start position of the token in the string.
	End       int      // The end position of the token in the string.
}

ExtractedToken is a token extracted from a string.

func ExtractToken

func ExtractToken(s string) ExtractedToken

ExtractToken extracts a single token from a string.

func ExtractTokens

func ExtractTokens(s string) ([]ExtractedToken, error)

ExtractTokens extracts all tokens from a string. A token is a string surrounded by square brackets ('[]') and can have modifiers, separated by a colon (':'). Example: "[token:upper:quote]"

type Generated

type Generated struct {
	Text     string
	Template string
	Tokens   []TokenReplacement
}

Generated provides information about a generated text.

type GrammarToken

type GrammarToken struct {
	Token     string   // The token, including brackets.
	Pool      string   // The pool from which to pick a random value.
	FullToken string   // The full token, including modifiers.
	Modifiers []string // The modifiers for the token.
	Start     int
	End       int
}

GrammarToken represents a token in a grammar rule. TODO: - Add flags to prevent re-use of expansions (10 people named John). - Add flags for n-repetitions. - Allow association of token expansions with tokens. ([green->house]) - Add conditionals.

func ExtractGrammarToken

func ExtractGrammarToken(s string) GrammarToken

ExtractGrammarToken extracts a single token from a string.

func ExtractGrammarTokens

func ExtractGrammarTokens(s string) ([]GrammarToken, error)

ExtractGrammarTokens extracts all tokens from a string. A token is a string surrounded by square brackets ('[]'), has a pool reference (e.g. "hero/name") and can have modifiers, separated by a colon (':'). The pool reference (denoted by a slash '/') is used to find the expansion pool for the token.

type RandInterface

type RandInterface interface {
	Intn(n int) int
	Seed(seed int64)
}

type Rules

type Rules struct {
	Expansions map[string][]string // Pool of expansions for each token
	Start      string              // Start rule
}

Rules defines the rules for a story.

func (*Rules) NewStory

func (r *Rules) NewStory(seed int64) *Story

NewStory creates a new story from the given rules.

type Story

type Story struct {
	*Rules                     // Rules for the story
	Assigned map[string]string // Assigned expansions for tokens that have assigned expansions
	// contains filtered or unexported fields
}

Story is a new story instance that can be expanded from a set of rules. After expansion, all assigned token expansions will be stored in Assigned if they are needed for later use. (For example, the names picked for the hero, name of the pet, and what animal he rode into town).

func (*Story) Expand

func (g *Story) Expand() (string, error)

Expand expands the story from the start rule.

func (*Story) ExpandRule

func (g *Story) ExpandRule(rule string) (string, error)

ExpandRule expands from the start rule.

func (*Story) ExpandToken

func (g *Story) ExpandToken(token GrammarToken) (string, error)

ExpandToken expands a single token.

type TextConfig

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.
}

TextConfig is a configuration for generating text.

func (*TextConfig) Generate

func (c *TextConfig) Generate(provided []TokenReplacement) (*Generated, error)

Generate generates a text from the provided tokens and the configuration.

func (*TextConfig) GenerateAndGiveMeTheTemplate

func (c *TextConfig) GenerateAndGiveMeTheTemplate(provided []TokenReplacement) (*Generated, error)

GenerateAndGiveMeTheTemplate generates a text from the provided tokens and the configuration. It also returns the template that was used to generate the text.

func (*TextConfig) GenerateWithTemplate

func (c *TextConfig) GenerateWithTemplate(provided []TokenReplacement, template string) (*Generated, error)

GenerateWithTemplate generates a text from the provided tokens and the provided template.

type TextGenerator

type TextGenerator struct {
	RandInterface
}

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.

func NewTextGenerator

func NewTextGenerator(rng RandInterface) *TextGenerator

NewTextGenerator creates a new TextGenerator using the provided random number generator.

func (*TextGenerator) Generate

func (g *TextGenerator) Generate(provided []TokenReplacement, config *TextConfig) (*Generated, error)

Generate generates a text from the provided tokens and the configuration.

func (*TextGenerator) GenerateAndGiveMeTheTemplate

func (g *TextGenerator) GenerateAndGiveMeTheTemplate(provided []TokenReplacement, config *TextConfig) (*Generated, error)

GenerateAndGiveMeTheTemplate generates a text from the provided tokens and the configuration. It also returns the template that was used to generate the text.

func (*TextGenerator) GenerateButUseThisTemplate

func (g *TextGenerator) GenerateButUseThisTemplate(provided []TokenReplacement, config *TextConfig, template string) (*Generated, error)

GenerateButUseThisTemplate generates a text from the provided tokens and the provided template.

func (*TextGenerator) GenerateFromConfig

func (g *TextGenerator) GenerateFromConfig(provided []TokenReplacement, config *TextConfig, altTemplates []string) (*Generated, error)

type TokenReplacement

type TokenReplacement struct {
	Token       string // The token to replace.
	Replacement string // The replacement text.
}

TokenReplacement is a replacement for a token in a text. TODO: Allow infinite re-use of tokens.

Directories

Path Synopsis
Package genbooks is an example application of genstory for generating book titles.
Package genbooks is an example application of genstory for generating book titles.
Package genweapons is an example application of genstory for generating weapon flavor text.
Package genweapons is an example application of genstory for generating weapon flavor text.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL