Skip to content

HemantSudarshan/narrative-transformer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

9 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŽญ Narrative Transformation System

Transform classic stories into new genres using AI โ€” preserving narrative essence while reimagining setting, characters, and style.

Built by Hemant Sudarshan

Python 3.8+ OpenAI License: MIT


๐ŸŽฏ What This Does

Takes any classic story and systematically transforms it into a completely different genre:

Cinderella โ†’ Space Opera        (fairy godmother โ†’ AI hologram mentor)
Tortoise & Hare โ†’ Cyberpunk     (race โ†’ data heist competition)
Icarus โ†’ Post-Apocalyptic       (wax wings โ†’ makeshift glider)

๐Ÿ’ก The system is demonstrated on Cinderella, Icarus, and Tortoise & Hare as examples, but is designed to generalize to any public-domain work โ€” Shakespeare, Greek myths, folk tales, or classic literature.

Not just "rewriting" โ€” the system analyzes narrative structure, maps elements systematically, and generates with adaptive pacing control.


โšก Quick Demo

# Install
pip install -r requirements.txt
python -c "import nltk; nltk.download('vader_lexicon')"

# Configure (add your OpenRouter API key)
cp .env.example .env

# Transform!
python run.py \
  --source examples/tortoise_hare.txt \
  --title "The Tortoise and the Hare" \
  --genre cyberpunk \
  --beats 3 \
  --output output/story.txt

Output: 800-1000 word story in ~60 seconds


๐Ÿ—๏ธ How It Works

5-Phase Pipeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   ANALYZE    โ”‚ โ†’  โ”‚     MAP      โ”‚ โ†’  โ”‚   GENERATE   โ”‚ โ†’  โ”‚   ASSEMBLE   โ”‚ โ†’  โ”‚    OUTPUT    โ”‚
โ”‚              โ”‚    โ”‚              โ”‚    โ”‚   (loop)     โ”‚    โ”‚              โ”‚    โ”‚              โ”‚
โ”‚ Extract:     โ”‚    โ”‚ Translate:   โ”‚    โ”‚ Per beat:    โ”‚    โ”‚ Combine:     โ”‚    โ”‚ Final:       โ”‚
โ”‚ โ€ข Characters โ”‚    โ”‚ โ€ข Names      โ”‚    โ”‚ โ€ข Context    โ”‚    โ”‚ โ€ข Scenes     โ”‚    โ”‚ โ€ข Story      โ”‚
โ”‚ โ€ข Themes     โ”‚    โ”‚ โ€ข Locations  โ”‚    โ”‚ โ€ข NTI check  โ”‚    โ”‚ โ€ข Formatting โ”‚    โ”‚ โ€ข Metrics    โ”‚
โ”‚ โ€ข Conflicts  โ”‚    โ”‚ โ€ข Objects    โ”‚    โ”‚ โ€ข Pacing     โ”‚    โ”‚ โ€ข Metadata   โ”‚    โ”‚              โ”‚
โ”‚ โ€ข Beats      โ”‚    โ”‚ โ€ข Concepts   โ”‚    โ”‚ โ€ข State      โ”‚    โ”‚              โ”‚    โ”‚              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Example Character Mapping

Source Cyberpunk Equivalent Preserved Function
Hare Blitz โ€” elite speed-hacker with neural overclocking Overconfident protagonist
Tortoise Shell โ€” methodical old-school coder Underestimated underdog
Race Data heist competition on the Grid Central conflict/challenge
Nap Neural cooldown (overclocked brain forces shutdown) Hubris leading to downfall

๐Ÿ’ก Key Innovation: Narrative Tension Index (NTI)

The Problem: LLMs generate creative text but struggle with consistent pacing โ€” stories often feel flat or peak too early.

The Solution: Quantitative tension measurement with adaptive feedback:

NTI = (1 - certainty) ร— (1 - sentiment)

High NTI = uncertain outcome + negative emotion โ†’ TENSION
Low NTI  = clear outcome + positive emotion โ†’ RESOLUTION

How it works:

  1. Generate scene
  2. Calculate actual NTI using sentiment analysis
  3. Compare to target (based on Save the Cat beat structure)
  4. Adjust next scene's pacing hints
Target Tension Curve (Save the Cat):

2.0 |                               โ˜… โ† Climax
    |                          โ˜…
1.5 |            โ˜…        โ˜…            โ† Midpoint
    |        โ˜…       โ˜…
1.0 |    โ˜…                    โ˜…
    |โ˜…                            โ˜…
0.5 |                                 โ˜… โ† Resolution
    +----------------------------------------
     1  2  3  4  5  6  7  8  9  10 11 12
                     BEATS

๐Ÿ“Š Test Results

Story Target Genre Words Avg NTI Status
Cinderella Space Opera 932 0.60 โœ…
Tortoise & Hare Cyberpunk 874 0.63 โœ…
Icarus Post-Apocalyptic 940 1.33 โœ…

100% success rate across all test transformations


๐ŸŽจ Available Genres

Genre Aesthetic Example Elements
cyberpunk Neon-lit tech dystopia Neural jacks, megacorps, data heists
space_opera Epic galactic adventure Starships, alien councils, hyperspace
victorian_gothic Fog-shrouded horror Gas lamps, sรฉances, dark secrets
post_apocalyptic Survival in ruins Scavengers, wasteland, lost tech
mythic_fantasy Legendary tales Ancient magic, prophecies, quests

๐Ÿ“ Project Structure

narrative-transformer/
โ”œโ”€โ”€ llm_client.py          # Centralized LLM client (retry logic, JSON mode)
โ”œโ”€โ”€ analyzer.py            # Phase 1: Source analysis
โ”œโ”€โ”€ mapper.py              # Phase 2: World mapping
โ”œโ”€โ”€ generator.py           # Phase 3: Scene generation
โ”œโ”€โ”€ tension.py             # NTI calculator & pacing controller
โ”œโ”€โ”€ transformer.py         # Main orchestrator
โ”œโ”€โ”€ config.py              # Genre templates & settings
โ”œโ”€โ”€ models.py              # Data structures
โ”œโ”€โ”€ run.py                 # CLI interface
โ”œโ”€โ”€ run_tests.py           # Test suite (3 stories)
โ”‚
โ”œโ”€โ”€ examples/              # Sample inputs
โ”‚   โ”œโ”€โ”€ cinderella.txt
โ”‚   โ”œโ”€โ”€ tortoise_hare.txt
โ”‚   โ”œโ”€โ”€ icarus.txt
โ”‚   โ””โ”€โ”€ SAMPLE_TRANSFORMATION.md   # Intermediate data example
โ”‚
โ”œโ”€โ”€ output/                # Generated stories
โ”‚
โ”œโ”€โ”€ SOLUTION.md            # Technical documentation
โ””โ”€โ”€ APPROACH.md            # Design decisions & alternatives

๐Ÿ’ป Python API

from transformer import NarrativeTransformer

transformer = NarrativeTransformer()

story, metadata = transformer.transform(
    source_text="Your story here...",
    source_title="My Story",
    target_genre="cyberpunk",
    num_beats=5
)

print(story)
print(f"Words: {metadata['word_count']}")
print(f"Tension: {metadata['avg_tension']:.2f}")

๐Ÿ”ง Configuration

Create .env file:

# OpenRouter (recommended)
OPENAI_API_KEY=sk-or-v1-your-key
OPENAI_BASE_URL=https://openrouter.ai/api/v1
DEFAULT_MODEL=openai/gpt-3.5-turbo

# Settings
TEMPERATURE=0.7
MAX_TOKENS=2000

๐ŸŽฏ Design Decisions

Decision Why
Context-based (not RAG) 2-3 pages fit in context; simpler, faster, debuggable
Beat-by-beat generation Enables state tracking + pacing control
Save the Cat structure Industry-standard framework with clear targets
Quantitative NTI Measurable quality โ†’ feedback loop
Centralized LLM client Retry logic, JSON mode, consistent interface

See APPROACH.md for full analysis of alternatives considered.


๐Ÿ“ˆ Performance

Metric Value
Generation time (3 beats) ~30-60 seconds
API calls per transformation 10-15
Output length 800-1000 words
Retry resilience 3 attempts + exponential backoff

๐Ÿ“š Documentation


๐Ÿ”ฎ Future Improvements

Core Features:

  • Multi-POV support (scenes from different character perspectives)
  • Interactive mode (approve/edit at each stage)
  • Novel-length optimization
  • Style transfer from example texts

Optional Extensions (for contributors):

  • Streamlit UI โ€” Web interface with live progress and tension visualization
  • MLOps Integration โ€” Experiment tracking (MLflow/W&B), cost monitoring, A/B testing
  • GitHub Actions CI โ€” Automated testing on every push
  • REST API โ€” FastAPI endpoint for programmatic access
  • Docker โ€” Containerized deployment

๐Ÿ“„ License

MIT License โ€” See LICENSE for details.


๐Ÿง  The Narrative Tension Index โ€” quantitative pacing control for AI-generated stories

Built as a demonstration of system design, prompt engineering, and creative AI applications.

About

AI-powered narrative transformation system that reimagines classic stories into new genres using LLMs with adaptive pacing control

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages