Skip to main content

Algorithmic generation and optimization of AI music style prompts

Project description

Metaphor Machine

PyPI version Python 3.10+ License: MIT

Algorithmic generation and optimization of AI music style prompts.

Metaphor Machine creates structured 5-slot style descriptions for AI music platforms like Suno and Producer.ai, then optimizes them through genetic and Bayesian algorithms to discover high-performing prompt patterns.

Installation

From source, with optimization extras:

git clone git@github.com:stayen/metaphor-machine.git
cd module
pip -e ".[optimization]"

(see also below, for other installation modes)

From Pypi:

pip install metaphor-machine

With optimization extras:

pip install metaphor-machine[optimization]  # numpy, scipy
pip install metaphor-machine[llm]           # anthropic, openai
pip install metaphor-machine[all]           # everything

Quick Start

Basic Generation

from metaphor_machine import StyleComponents, MetaphorGenerator

# Load component pools
components = StyleComponents.from_yaml("style_components.yaml")

# Create generator with seed for reproducibility
generator = MetaphorGenerator(components, seed=42)

# Generate a single metaphor
metaphor = generator.generate_single()
print(metaphor)
# → "dark synthwave, whispered mantras, spiraling synths, neon-alley reverb, dread crescendo"

# Generate a 3-act chain
chain = generator.generate_chain()
print(chain.to_suno_style())
# → "Intro: cinematic orchestral... → Mid: voice opens into... → Outro: melody dissolves..."

Optimization (v1.0)

from metaphor_machine.optimization import (
    GeneticOptimizer,
    GeneticConfig,
    RuleBasedEvaluator,
)

# Create fitness evaluator
evaluator = RuleBasedEvaluator(
    preferred_terms=["darkwave", "ethereal", "haunting"],
    avoided_terms=["pop", "bright"],
)

# Configure genetic algorithm
config = GeneticConfig(
    population_size=30,
    generations=50,
    elite_size=2,
    mutation_rate=0.2,
)

# Run optimization
optimizer = GeneticOptimizer(generator, evaluator, config)
best = optimizer.run(verbose=True)

print(f"Best: {best.metaphor}")
print(f"Score: {best.score:.3f}")

Corpus Storage

from metaphor_machine.corpus import SQLiteCorpus, CorpusEntry

# Store optimization results
corpus = SQLiteCorpus("prompts.db")

for individual in optimizer.get_top_n(20):
    entry = CorpusEntry.from_metaphor(
        individual.metaphor,
        fitness_score=individual.score,
        tags={"genetic", "darkwave"},
        source="genetic_optimizer",
    )
    corpus.add(entry)

# Query high-performing prompts
results = corpus.query(min_score=0.8, tags={"darkwave"})
for entry in results:
    print(f"[{entry.fitness_score:.2f}] {entry.metaphor_text}")

corpus.close()

Metaphor Structure

Each metaphor consists of 5 slots:

Slot Purpose Example
Genre Anchor Base genre (with optional prefix) "dark synthwave", "japanese house"
Intimate Gesture Vocal/lead behavior "whispered mantras"
Dynamic Tension Motion and energy "spiraling synths"
Sensory Bridge Environment/space "neon-alley reverb"
Emotional Anchor Feeling/resolution "dread crescendo"

Genres are organized by family (electronic, hip-hop/urban, world/ethnic, rock/guitar, traditional/acoustic) with optional modifier prefixes (mood, intensity, style, regional, location, instruments).

The combinatorial space exceeds 35 trillion unique combinations.

Optimization Methods

Genetic Algorithm

Evolutionary search through selection, crossover, and mutation:

  • Selection: Tournament, roulette, rank, truncation
  • Crossover: Single-point, two-point, uniform (slot-level)
  • Mutation: Per-slot probability replacement
  • Elitism: Preserve top performers across generations

Bayesian Optimization

Sample-efficient search for expensive evaluations (human rating, actual audio generation):

  • Surrogate model: RBF kernel interpolation
  • Acquisition functions: Expected Improvement, UCB, Thompson sampling
  • External observation: Support for async evaluation workflows

Fitness Evaluators

Evaluator Speed Use Case
RuleBasedEvaluator Fast Keyword matching, length, diversity
SemanticCoherenceEvaluator Fast Slot compatibility scoring
LLMEvaluator Slow Claude/GPT quality assessment
HumanFeedbackEvaluator Slow Interactive ground truth
CompositeEvaluator Varies Weighted combination

CLI Usage

# Generate single metaphor
mm generate

# Generate with seed
mm generate --seed 42

# Generate diverse batch
mm batch --count 10 --min-distance 3

# Generate 3-act chain
mm chain --seed 42

Architecture

metaphor_machine/
├── core/              # Metaphor, Generator, Chain
├── schemas/           # Pydantic models, config
├── optimization/      # Genetic, Bayesian, Fitness
├── corpus/            # SQLite/JSON storage
└── cli/               # Click commands

Roadmap

  • v0.9.9: Core generation engine, CLI, seed reproducibility
  • v1.0.0: Optimization layer (genetic, Bayesian, corpus)
  • v1.1: Variation engine (Markov chains, latent navigation)
  • v1.2: Audio feedback loop (librosa features, embedding similarity)

License

MIT

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

metaphor_machine-1.0.1.tar.gz (64.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

metaphor_machine-1.0.1-py3-none-any.whl (52.6 kB view details)

Uploaded Python 3

File details

Details for the file metaphor_machine-1.0.1.tar.gz.

File metadata

  • Download URL: metaphor_machine-1.0.1.tar.gz
  • Upload date:
  • Size: 64.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for metaphor_machine-1.0.1.tar.gz
Algorithm Hash digest
SHA256 6b2f40c850e1daee9e2f9b3f572fd0bea855f4f732737404cea74873568e5400
MD5 d4043cf5315bf2dbf748eff53a0b3432
BLAKE2b-256 4bef80b334e05d9ca6e4eb4e33aa8636a078c9363ef14b980128e092523be557

See more details on using hashes here.

File details

Details for the file metaphor_machine-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for metaphor_machine-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e9264eb471dbc0e9852f5e2883e26a910af3e18476ab6cb4b51c5834a8395798
MD5 e0cb5c9a753e8b27baff3307fdf06025
BLAKE2b-256 6ff080fe6b40cb325d0c173991080d54c7590dc588ae2b8d0c60b46f361b9f08

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page