### Crystal Word Generation Usage Examples Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Practical examples demonstrating how to use the `GeneratorBuilder` to configure and create `Generator` instances for various word generation scenarios, including basic generation, vowel-initial words, sequential generation, weighted phonemes, and complex constraints. ```Crystal # Basic word generation generator = GeneratorBuilder.create .with_phonemes(["p", "t", "k", "s", "r"], ["a", "e", "i", "o"]) .with_syllable_patterns(["CV", "CVC"]) .with_syllable_count(SyllableCountSpec.range(2, 4)) .with_romanization({"p" => "p", "t" => "t", "a" => "a"}) # 1:1 mapping .build word = generator.generate # "taros" # Vowel-initial words vowel_gen = GeneratorBuilder.create .with_phonemes(["p", "t", "k"], ["a", "e", "i"]) .with_syllable_patterns(["V", "CV", "CVC"]) .starting_with(:vowel) .build vowel_word = vowel_gen.generate # "atek" # Sequential generation sequential = GeneratorBuilder.create .with_phonemes(["r", "t"], ["a", "e"]) .with_syllable_patterns(["CV"]) .with_syllable_count(SyllableCountSpec.exact(1)) .sequential_mode(8) .build words = [] of String while word = sequential.next_sequential words << word end # words = ["ra", "re", "ta", "te"] # Weighted phonemes weighted = GeneratorBuilder.create .with_phonemes(["p", "t", "k"], ["a", "e"]) .with_weights({"p" => 2.0, "t" => 1.0, "k" => 0.5, "a" => 1.5, "e" => 1.0}) .with_syllable_patterns(["CV"]) .build # Complex constraints constrained = GeneratorBuilder.create .with_phonemes(["p", "t", "r", "s"], ["a", "e", "o"]) .with_syllable_patterns(["CCV", "CV"]) # Allow clusters .with_constraints(["rr", "ss"]) # No double consonants .build ``` -------------------------------- ### WordMage Development Commands Source: https://github.com/petterthowsen/wordmage/blob/master/CLAUDE.md Essential commands for developers working with the WordMage library. This includes running the test suite, building the library, and executing comprehensive examples to verify functionality. ```bash crystal spec # Run tests crystal build src/wordmage.cr # Build library crystal run example.cr # Run comprehensive examples ``` -------------------------------- ### Generate Vowel-Starting Words with WordMage in Crystal Source: https://github.com/petterthowsen/wordmage/blob/master/README.md This Crystal code example demonstrates how to utilize the WordMage library to generate words with specific characteristics. It configures a `GeneratorBuilder` to define phonemes, syllable patterns, and syllable count ranges, ensuring generated words start with a vowel. The snippet then generates and prints five such words. ```crystal require "wordmage" puts "=== Words starting with vowels ===" vowel_gen = WordMage::GeneratorBuilder.create .with_phonemes(["p", "t", "k", "r"], ["a", "e", "i", "o"]) .with_syllable_patterns(["V", "CV", "CVC"]) .with_syllable_count(WordMage::SyllableCountSpec.range(2, 3)) .starting_with(:vowel) .build 5.times do puts vowel_gen.generate end ``` -------------------------------- ### Crystal Implementation of PhonemeSet Methods Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Provides Crystal code examples for `PhonemeSet` methods, specifically `get_consonants` and `sample_phoneme`. These methods demonstrate how phonemes are filtered by position and sampled, optionally considering weights. ```Crystal class PhonemeSet def get_consonants(position : Symbol? = nil) : Array(String) base = @consonants.to_a if position && rules = @position_rules[position]? base.select { |p| rules.includes?(p) } else base end end def sample_phoneme(type : Symbol, position : Symbol? = nil) : String candidates = case type when :consonant then get_consonants(position) when :vowel then get_vowels(position) else [] of String end if @weights.empty? candidates.sample else weighted_sample(candidates) end end end ``` -------------------------------- ### Generate Basic Words with WordMage Source: https://github.com/petterthowsen/wordmage/blob/master/CLAUDE.md Demonstrates how to create a basic word generator instance using `WordMage::GeneratorBuilder`. This example configures the generator to produce vowel-initial words with a specified syllable count and patterns, accepting both IPA strings and Phoneme instances. ```crystal # Generate vowel-initial words with 2-3 syllables # Methods accept both IPA strings and Phoneme instances generator = WordMage::GeneratorBuilder.create .with_phonemes(["p", "t", "k", "r"], ["a", "e", "i", "o"]) # IPA strings .with_syllable_patterns(["CV", "CVC"]) .with_syllable_count(WordMage::SyllableCountSpec.range(2, 3)) .starting_with(:vowel) .build word = generator.generate # "arek", "itopa", etc. ``` -------------------------------- ### Crystal Generator Class Implementation Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Implementation of the `Generator` class in Crystal, showing how words are generated based on different modes (random, sequential) and how syllable and phoneme constraints are applied. It includes private methods for random generation and starting type validation. ```Crystal enum GenerationMode Random Sequential WeightedRandom end class Generator def generate : String case @mode when .sequential? next_sequential || raise "No more sequential words available" else generate_random end end private def generate_random : String syllable_count = @word_spec.generate_syllable_count syllables = [] of Array(String) (0...syllable_count).each do |i| position = case i when 0 then :initial when syllable_count - 1 then :final else :medial end template = @word_spec.select_template(position) syllables << template.generate(@phoneme_set, position) end phonemes = syllables.flatten # Check word-level constraints and starting type if @word_spec.validate_word(phonemes) && matches_starting_type?(phonemes) @romanizer.romanize(phonemes) else generate_random # Retry end end private def matches_starting_type?(phonemes : Array(String)) : Bool return true unless starting_type = @word_spec.starting_type first_phoneme = phonemes.first? return false unless first_phoneme case starting_type when :vowel then @phoneme_set.is_vowel?(first_phoneme) when :consonant then !@phoneme_set.is_vowel?(first_phoneme) else true end end end ``` -------------------------------- ### Add WordMage Dependency to shard.yml Source: https://github.com/petterthowsen/wordmage/blob/master/README.md This YAML snippet illustrates how to declare the WordMage library as a dependency within your Crystal project's `shard.yml` file. It specifies the GitHub repository as the source. After adding this configuration, you would typically run `shards install` to fetch the library. ```yaml dependencies: wordmage: github: petterthowsen/wordmage ``` -------------------------------- ### WordSpec Class API Reference Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Defines the `WordSpec` class, used to specify requirements for word generation, including syllable count, starting phoneme type, applicable syllable templates, and word-level constraints. It includes methods for generating syllable counts and validating complete words. ```APIDOC WordSpec: Purpose: Specify word generation requirements Attributes: syllable_count : SyllableCountSpec starting_type : Symbol? # :vowel, :consonant, or nil (any) syllable_templates : Array(SyllableTemplate) word_constraints : Array(String) # word-level constraint patterns Methods: generate_syllable_count : Int32 select_template(position : Symbol) : SyllableTemplate validate_word(phonemes : Array(String)) : Bool ``` -------------------------------- ### Run WordMage Tests Source: https://github.com/petterthowsen/wordmage/blob/master/CLAUDE.md Commands to execute the WordMage test suite, including running all tests or a specific test file, ensuring comprehensive coverage of all functionalities. ```bash crystal spec crystal spec spec/generator_spec.cr ``` -------------------------------- ### Crystal GeneratorBuilder Class Implementation Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Implementation of the `GeneratorBuilder` class in Crystal, demonstrating the fluent interface for setting up a `Generator` instance with various parameters like phoneme sets, syllable patterns, and generation modes. The `build` method consolidates all configurations into a `Generator` object. ```Crystal class GeneratorBuilder def self.create new end def with_phonemes(consonants : Array(String), vowels : Array(String)) @phoneme_set = PhonemeSet.new(consonants.to_set, vowels.to_set) self end def with_weights(weights : Hash(String, Float32)) @phoneme_set.not_nil!.weights = weights self end def with_syllable_patterns(patterns : Array(String)) @syllable_templates = patterns.map { |p| SyllableTemplate.new(p) } self end def with_syllable_count(spec : SyllableCountSpec) @syllable_count = spec self end def starting_with(type : Symbol) @starting_type = type self end def with_constraints(patterns : Array(String)) @constraints = patterns self end def with_romanization(mappings : Hash(String, String)) @romanizer = RomanizationMap.new(mappings) self end def sequential_mode(max_words : Int32 = 1000) @mode = GenerationMode::Sequential @max_words = max_words self end def random_mode @mode = GenerationMode::Random self end def build : Generator word_spec = WordSpec.new( syllable_count: @syllable_count.not_nil!, starting_type: @starting_type, syllable_templates: @syllable_templates.not_nil!, word_constraints: @constraints || [] of String ) Generator.new( phoneme_set: @phoneme_set.not_nil!, word_spec: word_spec, romanizer: @romanizer || RomanizationMap.new, mode: @mode || GenerationMode::Random ) end end ``` -------------------------------- ### Utilize IPA Phoneme System in WordMage Source: https://github.com/petterthowsen/wordmage/blob/master/CLAUDE.md Shows how to integrate actual IPA `Phoneme` instances for precise phonetic control. This includes accessing built-in IPA phonemes, selecting specific phoneme types based on features, mixing IPA strings with Phoneme instances, and using utility methods for phoneme resolution. ```crystal # Use actual IPA Phoneme instances for precise phonetic control require "wordmage/IPA" # Access built-in IPA phonemes front_vowels = WordMage::IPA::BasicPhonemes.select(&.as(WordMage::IPA::Vowel).front?) voiced_stops = WordMage::IPA::BasicPhonemes.select do |p| p.is_a?(WordMage::IPA::Consonant) && p.manner.plosive? && p.voiced end # Mix IPA strings and Phoneme instances generator = WordMage::GeneratorBuilder.create .with_phonemes(voiced_stops, front_vowels) # Phoneme instances .with_syllable_patterns(["CV", "CVC"]) .starting_with_sequence("br") # Romanized cluster .build # Utility methods for phoneme resolution phoneme = WordMage::IPA::Utils.find_phoneme("t") # Returns Consonant instance is_vowel = WordMage::IPA::Utils.is_vowel?("a") # Returns true ``` -------------------------------- ### GeneratorBuilder Class API Reference Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Provides a fluent API for configuring and constructing `Generator` instances, allowing specification of phonemes, syllable patterns, constraints, and generation modes. Each method returns `self` for method chaining. ```APIDOC class GeneratorBuilder # Purpose: Fluent configuration API for Generator # Methods: # - self.create : GeneratorBuilder # Initializes a new GeneratorBuilder instance. # Returns: A new GeneratorBuilder. # - with_phonemes(consonants : Array(String), vowels : Array(String)) : self # Sets the phoneme set for word generation. # Parameters: # - consonants: An array of consonant phonemes. # - vowels: An array of vowel phonemes. # - with_weights(weights : Hash(String, Float32)) : self # Applies weights to phonemes for weighted random generation. # Parameters: # - weights: A hash mapping phonemes to their float weights. # - with_syllable_patterns(patterns : Array(String)) : self # Defines the allowed syllable patterns (e.g., "CV", "CVC"). # Parameters: # - patterns: An array of syllable pattern strings. # - with_syllable_count(spec : SyllableCountSpec) : self # Specifies the number of syllables per word. # Parameters: # - spec: A SyllableCountSpec object (e.g., range, exact). # - starting_with(type : Symbol) : self # Sets a constraint for the starting phoneme type of generated words. # Parameters: # - type: A symbol indicating the starting type (:vowel, :consonant). # - with_constraints(patterns : Array(String)) : self # Adds word-level constraints (e.g., disallowing certain phoneme sequences). # Parameters: # - patterns: An array of string patterns representing forbidden sequences. # - with_romanization(mappings : Hash(String, String)) : self # Provides a mapping for romanizing generated phonemes into readable words. # Parameters: # - mappings: A hash mapping phonemes to their romanized string representations. # - sequential_mode(max_words : Int32 = 1000) : self # Configures the generator for sequential word generation. # Parameters: # - max_words: The maximum number of words to generate sequentially (default: 1000). # - random_mode : self # Configures the generator for random word generation. # - build : Generator # Constructs and returns a new Generator instance based on the configured parameters. # Returns: A fully configured Generator object. ``` -------------------------------- ### Crystal Implementation of SyllableTemplate Methods Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Provides Crystal code for the `generate` and `validate` methods of the `SyllableTemplate` class. The `generate` method constructs a syllable based on the template's pattern and phoneme sampling, while `validate` checks if the generated syllable adheres to specified constraints. ```Crystal class SyllableTemplate def generate(phonemes : PhonemeSet, position : Symbol) : Array(String) syllable = [] of String @pattern.each_char do |symbol| case symbol when 'C' syllable << phonemes.sample_phoneme(:consonant, position) when 'V' if allows_hiatus? && Random.rand < @hiatus_probability syllable << phonemes.sample_phoneme(:vowel, position) syllable << phonemes.sample_phoneme(:vowel, position) else syllable << phonemes.sample_phoneme(:vowel, position) end end end # Retry if constraints violated if validate(syllable) syllable else generate(phonemes, position) end end def validate(syllable : Array(String)) : Bool sequence = syllable.join @constraints.none? { |pattern| sequence.matches?(Regex.new(pattern)) } end end ``` -------------------------------- ### PhonemeSet Class API Reference Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Defines the `PhonemeSet` class, responsible for managing phonemes, their types (consonants/vowels), positional rules, and optional weights. It provides methods for adding phonemes, retrieving filtered lists, and sampling phonemes based on type and position. ```APIDOC PhonemeSet: Purpose: Unified phoneme management with positional constraints Attributes: consonants : Set(String) vowels : Set(String) position_rules : Hash(Symbol, Set(String)) # e.g., {:word_initial => ["p", "t", "k"]} weights : Hash(String, Float32) # optional phoneme weights Methods: add_phoneme(phoneme : String, type : Symbol, positions : Array(Symbol) = [] of Symbol) add_weight(phoneme : String, weight : Float32) get_consonants(position : Symbol? = nil) : Array(String) get_vowels(position : Symbol? = nil) : Array(String) is_vowel?(phoneme : String) : Bool sample_phoneme(type : Symbol, position : Symbol? = nil) : String ``` -------------------------------- ### Analyze Word Phonological Patterns with WordMage Source: https://github.com/petterthowsen/wordmage/blob/master/CLAUDE.md Demonstrates using `WordMage::Analyzer` to examine existing words for phonological features. This includes detecting gemination and vowel lengthening patterns, and obtaining a recommended budget based on the analysis. ```crystal # Analyze existing words for phonological patterns romanization = {"t" => "t", "n" => "n", "a" => "ɑ", "e" => "ɛ"} analyzer = WordMage::Analyzer.new(WordMage::RomanizationMap.new(romanization)) words = ["tenna", "kaara", "silloot", "normal"] analysis = analyzer.analyze(words) puts analysis.gemination_patterns # {"nn" => 0.33, "ll" => 0.33} puts analysis.vowel_lengthening_patterns # {"ɑɑ" => 0.67, "ɔɔ" => 0.33} puts analysis.recommended_budget # 8 ``` -------------------------------- ### Crystal Implementation of RomanizationMap Methods Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Provides the Crystal code for the `RomanizationMap` class, including its constructor and the `romanize` method. The `romanize` method iterates through an array of phonemes, applying defined mappings to convert them into a single romanized string. ```Crystal class RomanizationMap def initialize(@mappings = {} of String => String) end def romanize(phonemes : Array(String)) : String phonemes.map { |p| @mappings[p]? || p }.join end end ``` -------------------------------- ### Generator Class API Reference Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Defines the core word generation engine, including its attributes, generation modes, and methods for producing single or batch words. It outlines the internal logic for selecting syllables, applying constraints, and romanizing phonemes. ```APIDOC enum GenerationMode Random Sequential WeightedRandom end class Generator # Purpose: Main generation engine with sampling modes # Attributes: # - phoneme_set : PhonemeSet # - word_spec : WordSpec # - romanizer : RomanizationMap # - mode : GenerationMode # Methods: # - generate : String # Generates a single word based on the configured mode. If in sequential mode, it attempts to get the next word; otherwise, it generates a random word. # - generate_batch(count : Int32) : Array(String) # Generates a specified number of words. # Parameters: # - count: The number of words to generate. # Returns: An array of generated words. # - next_sequential : String? # Retrieves the next word in sequential generation mode. Returns `nil` if no more sequential words are available. # - reset_sequential # Resets the state for sequential generation, allowing the sequence to start over. ``` -------------------------------- ### RomanizationMap Class API Reference Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Defines the `RomanizationMap` class, which handles the conversion of phonemes into a written, romanized form. It allows adding specific phoneme-to-romanization mappings and provides a method to apply these mappings to an array of phonemes. ```APIDOC RomanizationMap: Purpose: Convert phonemes to written form Attributes: mappings : Hash(String, String) Methods: add_mapping(phoneme : String, romanization : String) romanize(phonemes : Array(String)) : String ``` -------------------------------- ### SyllableTemplate Class API Reference Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Defines the `SyllableTemplate` class, used to specify the structure of syllables, including patterns like 'CVC', constraints, hiatus probability, and positional weights. It offers methods for generating syllables based on phoneme sets and validating generated syllables against defined constraints. ```APIDOC SyllableTemplate: Purpose: Define syllable structure with constraints Attributes: pattern : String # "CV", "CVC", "CCV", etc. constraints : Array(String) # regex patterns that must NOT match hiatus_probability : Float32 # chance of V->VV position_weights : Hash(Symbol, Float32) # weight by syllable position Methods: generate(phonemes : PhonemeSet, position : Symbol) : Array(String) allows_hiatus? : Bool validate(syllable : Array(String)) : Bool ``` -------------------------------- ### Generate Words with Advanced Phonological Constraints Source: https://github.com/petterthowsen/wordmage/blob/master/CLAUDE.md Illustrates configuring the WordMage generator with complex constraints. This includes thematic vowels, sequence constraints (start/end), gemination, and vowel lengthening probabilities for more nuanced word creation, using romanized forms for consonant clusters. ```crystal # Generate words with complex constraints and phonological features # Consonant clusters configured using romanized forms (not IPA) generator = WordMage::GeneratorBuilder.create .with_phonemes(["t", "n", "k", "r", "l", "s"], ["a", "e", "i", "o"]) .with_syllable_patterns(["CV", "CVC", "CCV"]) .with_syllable_count(WordMage::SyllableCountSpec.range(2, 4)) .with_thematic_vowel("a") # Last vowel must be 'a' .starting_with_sequence("thr") # Words start with "thr" (romanized) .ending_with_sequence("ath") # Words end with "ath" (romanized) .with_gemination_probability(0.2) # 20% consonant doubling .with_vowel_lengthening_probability(0.1) # 10% vowel lengthening .build word = generator.generate # "thrennorath", "thrasillath", etc. ``` -------------------------------- ### Crystal Implementation of SyllableCountSpec Struct Source: https://github.com/petterthowsen/wordmage/blob/master/plan-v3.md Provides the Crystal definition for the `SyllableCountSpec` struct, an internal component of `WordSpec`. This struct manages different types of syllable count specifications (exact, range, weighted) and includes a method to generate a syllable count based on the defined type. ```Crystal struct SyllableCountSpec enum Type Exact Range Weighted end getter type : Type getter min : Int32 getter max : Int32 getter weights : Hash(Int32, Float32)? def self.exact(count : Int32) new(Type::Exact, count, count) end def self.range(min : Int32, max : Int32) new(Type::Range, min, max) end def generate_count : Int32 case @type when .exact? then @min when .range? then Random.rand(@min..@max) when .weighted? then weighted_choice(@weights.not_nil!) end end end ``` -------------------------------- ### Enable/Disable Phonological Features with WordMage Source: https://github.com/petterthowsen/wordmage/blob/master/CLAUDE.md Shows how to easily control phonological features like gemination and vowel lengthening using convenience methods on the `GeneratorBuilder`. These methods accept both IPA strings and Phoneme instances for flexible configuration. ```crystal # Enable/disable phonological features easily # Methods accept both IPA strings and Phoneme instances generator = WordMage::GeneratorBuilder.create .with_phonemes(["t", "n", "k"], ["a", "e", "i"]) # IPA strings .with_syllable_patterns(["CV", "CVC"]) .enable_gemination # 100% gemination .disable_vowel_lengthening # 0% vowel lengthening .build ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.