# Project export: DreamDirector

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: UC Berkeley AI Hackathon 2025
- Tagline: Bringing any story to life with real-time, AI-generated cinematics, characters, and visuals, placing you at the heart of the narrative.
- Devpost: https://devpost.com/software/cinematic-director
- GitHub: https://github.com/Abdullah0x0/dreamdirector
- Video: https://www.youtube.com/embed/2Az4FpP4ZL0?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (Google: Best Use of Gemini; Nobel Era Group: Best Projects Leveraging LLM Agents Supported by Nobel Era Group & Berkeley RDI)
- Team: 2 GitHub contributor(s) — Abdullah Choudhry (8 commits), 0nkn (1 commits)

## Devpost submission (written by the team)

### Inspiration

We love immersive experiences. We dreamed of a platform where you could not just imagine the story, but see it unfold like a movie with adaptive music that responds to your emotions. The latest advances in multimodal AI from Google, including Gemini, Imagen 3.0, Veo 2.0, and Lyria RealTime, gave us the tools to finally build it: a true AI storyteller that weaves narrative, visuals, and dynamic audio together in real time.

### What it does

DreamDirector is your personal AI Cinematic Director. The entire experience starts with you; you can type in a prompt for any world you want to build, any story you want to tell. Whether it's a 'cyberpunk mystery' or a 'fantasy quest', our multi-agent AI system collaborates to bring that world to life. The system generates stunning 4K images with visual consistency tracking, produces cinematic 8-second video sequences for dramatic moments, and creates adaptive music that evolves with your story's emotional tone. Every choice you make matters, with the AI maintaining persistent memory of characters, locations, and world state across your entire journey.

### How we built it

Architecture & Technology Stack Frontend (React 18 + Modern Web) React 18 with Vite for lightning-fast development Tailwind CSS with custom cinematic themes Framer Motion for advanced animations and transitions React Router Dom for seamless navigation Axios for API communication Backend (FastAPI + Python) FastAPI with async/await for high-performance API handling Uvicorn ASGI server with real-time capabilities Pydantic for data validation and type safety Python-multipart for media file handling CORS middleware for cross-origin support AI & Multi-Agent System (Google ADK + GenAI) Google ADK (Application Development Kit) for agent orchestration Google GenAI SDK with Gemini models for intelligent reasoning Google Imagen 3.0 for consistent visual generation Google Veo 2.0 for cinematic video sequences Google Lyria RealTime for streaming adaptive music Multi-Agent Workflow We architected DreamDirector as a team of specialized AI agents working through the Google ADK framework: Story Director Agent Orchestrates narrative flow using Gemini's reasoning capabilities Manages three-act story structure and pacing Generates meaningful user choices with preview consequences Maintains character development and plot consistency Visual Consistency Agent Uses Imagen 3.0 with character/location reference tracking Maintains visual DNA across all generated content Ensures professional cinematographic composition Applies consistent artistic style and color palettes Adaptive Music Composer Leverages Lyria RealTime for streaming audio generation Creates layered compositions (atmospheric, character, action themes) Responds to emotional tone and story tension in real-time Supports multiple genres from cyberpunk synthwave to orchestral fantasy Media Orchestrator Coordinates multi-modal generation timing Optimizes resource usage across Google's APIs Handles video generation with image seeds for consistency Manages media balance for optimal user experience User Choice System Our choice system goes beyond simple branching narratives: Dynamic Choice Generation where AI creates contextual choices based on current story state Visual Preview System where users see outcomes through generated imagery Persistent Consequences where every decision affects character relationships and world state Adaptive Difficulty where story complexity adjusts to user engagement patterns Memory Integration where choices influence future scene generation and character interactions

### Challenges we ran into

Orchestrating multiple cutting-edge AI models in real-time presented significant challenges. Ensuring visual consistency across Imagen 3.0 generations required sophisticated prompt engineering and reference image tracking. Integrating Lyria RealTime's streaming audio with FastAPI's async architecture demanded careful threading and session management. The most complex challenge was building a coherent multi-agent system where each AI agent could communicate through structured function calls while maintaining narrative coherence and fluid user experience.

### Accomplishments we're proud of

We successfully created the first truly multimodal storytelling engine that combines Gemini's reasoning, Imagen's visuals, Veo's cinematography, and Lyria's music into a seamless experience. Our multi-agent architecture represents a breakthrough in AI collaboration; each agent specializes in its domain while contributing to a unified creative vision. We're especially proud of our visual consistency system that maintains character appearance and world continuity across an entire story session, and our adaptive music system that creates Hollywood-quality soundtracks in real-time.

### What we learned

This hackathon was a masterclass in practical multimodal AI engineering. We learned how to architect complex agent systems using Google ADK's tool framework, mastered advanced prompt engineering for consistent visual generation, and discovered the nuances of real-time audio streaming. Most importantly, we proved that sophisticated AI agent collaboration can create experiences far richer than any single model can do alone.

### What's next

We envision expanding DreamDirector into a comprehensive creative platform. Our roadmap includes: Multiplayer Adventures with shared AI-crafted worlds for collaborative storytelling Creator Tools to allow users to define custom genres and fine-tune agent behaviors Extended Media Support for integration with more Google AI APIs as they become available Mobile Experience for native iOS/Android apps with offline story caching Community Features for story sharing, remixing, and collaborative world-building Submission for the UC Berkeley AI Hackathon 2025 - Creativity Track DreamDirector represents the future of AI-powered interactive entertainment, showcasing how multiple specialized agents can collaborate to create magical user experiences. Problem and Market Opportunity The creator economy demands high-quality multimedia content, but individual creators face immense time and cost barriers. DreamDirector democratizes cinematic storytelling by turning weeks of traditional production into seconds of AI-powered generation, making professional-quality interactive media accessible to everyone. Multi-Agent Innovation and Technical Excellence Our core innovation is a sophisticated multi-agent system built on Google ADK that goes far beyond simple prompt chaining. Each agent maintains specialized knowledge domains and communicates through structured function calls with persistent state management. This architecture enables complex creative workflows while maintaining reliability and coherence. Scalability and Impact Built on Google's cloud-native APIs with async FastAPI architecture, DreamDirector is designed for massive scale. Our vision is to keep the core storytelling experience free for creators, students, and hobbyists while building sustainable revenue through enterprise API licensing for professional studios seeking to integrate our multi-agent creative engine into their workflows. DreamDirector, in short, is the foundation for the next generation of interactive entertainment.

## README (from the GitHub repository)

# 🎬 DreamDirector - AI-Powered Cinematic Storytelling

> **"Tell me your dream story and I'll make you live it"**

DreamDirector is a revolutionary multimodal storytelling experience that combines cutting-edge AI technologies to create infinite, interactive narratives with real-time visual, audio, and video generation. Built for the UC Berkeley AI Hackathon 2025, this project represents the future of immersive digital storytelling.

<p align="center">
  <img src="https://github.com/user-attachments/assets/46ac8eb6-4c1e-4730-b716-030f5e903c44" alt="DreamDirector Landing Page" width="800">
  <br>
  <em>The main landing page, inviting users to start their cinematic adventure.</em>
</p>

<p align="center">
  <img src="https://github.com/user-attachments/assets/6170e172-9fac-4c37-a00d-860a548e777e" alt="About DreamDirector" width="800">
  <br>
  <em>A breakdown of the key features and the Google AI tech stack.</em>
</p>

<p align="center">
  <img src="https://github.com/user-attachments/assets/54bbbda5-a042-4949-9fb7-bf0cb616ca87" alt="Empty Media Gallery" width="800">
  <br>
  <em>The user's personal media gallery, ready to be filled with generated content.</em>
</p>

<p align="center">
  <img src="https://github.com/user-attachments/assets/58b5273b-774a-4882-8b44-9be1133a976f" alt="Starting a Story" width="800">
  <br>
  <em>The user's journey begins with a simple prompt for any world they can imagine.</em>
</p>

<p align="center">
  <img src="https://github.com/user-attachments/assets/6b956dc9-0ad3-4b77-96f2-2163be59d4ad" alt="Gameplay Loop" width="800">
  <br>
  <em>Our core experience: the AI drives the story, generates visuals, and presents choices.</em>
</p>

<p align="center">
  <img src="https://github.com/user-attachments/assets/b4006d78-3ca0-4f16-a678-8099d0d327c7" alt="AI Generated Video" width="800">
  <br>
  <em>Cinematic videos are generated in real-time for key story moments.</em>
</p>

<p align="center">
  <img src="https://github.com/user-attachments/assets/1478ca2a-901b-4c8b-bf42-10fa5ebdecc6" alt="Filled Media Gallery" width="800">
  <br>
  <em>The gallery automatically saves every image, video, and music track from the story.</em>
</p>



## ✨ Key Features

### 🤖 Multi-Agent AI System
- **Story Director Agent** - Orchestrates narrative flow and pacing
- **Visual Consistency Agent** - Maintains character and location coherence
- **Music Composer Agent** - Creates adaptive, emotionally-responsive soundtracks
- **Media Generation Agent** - Coordinates real-time content creation

### 🎭 Real-Time Media Generation
- **Cinematic Images** - Google Imagen 3.0 with visual consistency tracking
- **Dynamic Videos** - Google Veo 2.0 for scene-to-scene transitions
- **Adaptive Music** - Google Lyria RealTime for contextual soundscapes
- **Professional Quality** - 4K visuals, 48kHz audio, cinematic composition

### 🎯 Interactive Storytelling
- **Choice-Driven Narratives** - Every decision shapes your unique story
- **Persistent Memory** - Characters and world state maintained across scenes
- **Emotional Intelligence** - AI responds to user personality and preferences
- **Infinite Replayability** - No two adventures are ever the same

## 🛠️ Technology Stack

### Frontend Technologies
- **React 18** - Modern component-based UI framework
- **Vite** - Lightning-fast build tool and development server
- **React Router Dom** - Client-side routing and navigation
- **Framer Motion** - Advanced animations and interactive transitions  
- **Tailwind CSS** - Utility-first styling with custom cinematic theme
- **Lucide React** - Beautiful, customizable icon library
- **Axios** - Promise-based HTTP client for API communication

### Backend Technologies
- **FastAPI** - High-performance Python web framework
- **Uvicorn** - Lightning-fast ASGI server with async support
- **Pydantic** - Data validation and settings management
- **Python Multipart** - File upload and media handling
- **Python-dotenv** - Environment configuration management
- **CORS Middleware** - Cross-origin resource sharing support

### AI
- **Google ADK (Application Development Kit)** - Core AI agent orchestration
- **Google GenAI SDK** - Multimodal content generation APIs
- **Google Imagen 3.0** - State-of-the-art image generation with consistency
- **Google Veo 2.0** - Advanced video generation from image seeds  
- **Google Lyria RealTime** - Streaming music composition and generation
- **Streamlit** - Interactive AI demonstrations and prototyping

### Development & Build Tools
- **PostCSS** - CSS transformation and optimization
- **Autoprefixer** - Automatic vendor prefix management
- **Git** - Version control and collaboration
- **Node.js** - JavaScript runtime for frontend tooling

## 🎨 AI Agents & Capabilities

### 📖 Narrative Director
- **Story Architecture** - Creates compelling three-act structures
- **Character Development** - Maintains personality consistency
- **Plot Progression** - Balances pacing and dramatic tension
- **Choice Generation** - Crafts meaningful decision points

### 🎬 Visual Consistency Engine  
- **Character References** - Maintains visual identity across scenes
- **Location Memory** - Ensures environmental continuity
- **Style Coherence** - Applies consistent artistic direction
- **Scene Composition** - Professional cinematographic framing

### 🎵 Adaptive Music Composer
- **Emotional Scoring** - Music responds to story mood and tension
- **Real-Time Generation** - Seamless audio streaming during gameplay
- **Layered Composition** - Combines atmospheric, character, and action themes
- **Genre Adaptation** - Matches musical style to story setting

### 🎯 Media Orchestrator
- **Generation Optimization** - Balances quality with performance
- **Content Synchronization** - Coordinates multi-modal generation
- **Resource Management** - Efficient GPU and API usage
- **Quality Assurance** - Ensures professional-grade output

## 🌟 Project Highlights

### Innovation
- **Multi-Modal AI Collaboration** - First-of-its-kind agent orchestration
- **Real-Time Generation** - Live content creation during user interaction
- **Visual Consistency** - Breakthrough character/location memory system
- **Adaptive Soundscapes** - Dynamic music that evolves with narrative

### Technical Excellence
- **Async Architecture** - Non-blocking, high-performance backend
- **Streaming APIs** - Real-time audio/video generation pipeline
- **State Management** - Persistent game world across sessions
- **Error Resilience** - Graceful handling of AI generation failures

### User Experience
- **Cinematic Interface** - Movie-quality visual design and animations
- **Intuitive Navigation** - Seamless story progression and choice making
- **Performance Optimized** - Fast loading, smooth interactions
- **Accessibility** - Responsive design for all device types

## 🏆 Competition Context

**UC Berkeley AI Hackathon 2025 - Creativity Track**

DreamDirector represents a new paradigm in interactive entertainment, combining Google's most advanced AI technologies into a cohesive, magical user experience. The project showcases the potential of multi-agent AI systems working in harmony to create something greater than the sum of their parts.

## 🚀 Architecture Overview

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   React Frontend │    │   FastAPI Backend │    │  AI Agent System │
│                 │    │                  │    │                 │  
│ • Story UI      │◄──►│ • API Routes     │◄──►│ • Story Director│
│ • Media Gallery │    │ • Media Serving  │    │ • Visual Agent  │
│ • Choice System │    │ • State Mgmt     │    │ • Music Agent   │
│ • Animations    │    │ • File Handling  │    │ • Media Agent   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                │
                                ▼
                       ┌─────────────────┐
                       │  Google AI APIs │ 
                       │                 │
             

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 40 recognized source files, 560 KB.
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Streamlit (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code

## Codebase structure (from repository index)

### Files (53 of 53)

```
.dockerignore
.gitignore
.history/backend/app_20250622090447.py
.history/backend/app_20250622094114.py
.history/backend/app_20250622094124.py
.history/backend/app_20250622094133.py
.history/backend/app_20250622094140.py
.history/backend/app_20250622094902.py
.history/backend/app_20250622095438.py
.history/backend/requirements_20250622064005.txt
.history/backend/requirements_20250622093327.txt
.history/backend/requirements_20250622093435.txt
.history/README_20250622092127.md
.history/README_20250622092255.md
.history/README_20250622092315.md
.history/src/context/AppContext_20250622085024.jsx
.history/src/context/AppContext_20250622094803.jsx
.history/src/context/AppContext_20250622094812.jsx
.history/src/context/AppContext_20250622095434.jsx
.history/src/context/AppContext_20250622095808.jsx
.history/src/context/AppContext_20250622095821.jsx
.history/src/context/AppContext_20250622100600.jsx
.history/src/pages/StoryPage_20250622090447.jsx
.history/src/pages/StoryPage_20250622094826.jsx
.history/src/pages/StoryPage_20250622094842.jsx
.history/src/pages/StoryPage_20250622095436.jsx
agents/__init__.py
agents/.env~
agents/agent.py
agents/requirements.txt
backend/app.py
backend/requirements.txt
deploy.sh
Dockerfile
index.html
LICENSE
old_description.md
package.json
postcss.config.js
railway.toml
README.md
src/App.jsx
src/components/Navbar.jsx
src/context/AppContext.jsx
src/index.css
src/main.jsx
src/pages/AboutPage.jsx
src/pages/GalleryPage.jsx
src/pages/HomePage.jsx
src/pages/StoryPage.jsx
start-dev.bat
tailwind.config.js
vite.config.js
```

### Dependencies

- agents/requirements.txt: asyncio@>=3.4.3, google-adk@>=1.0.0, google-genai@>=1.10.0, pillow@>=10.0.0, python-dotenv@>=1.0.0, requests@>=2.31.0, streamlit@>=1.28.0
- backend/requirements.txt: fastapi@>=0.104.0, google-adk@>=1.0.0, google-genai@>=1.10.0, pillow@>=10.0.0, pydantic@>=2.4.0, python-dotenv@>=1.0.0, python-multipart@>=0.0.6, requests@>=2.31.0, streamlit@>=1.28.0, uvicorn[standard]@>=0.24.0
- package.json: @types/react@^18.2.37, @types/react-dom@^18.2.15, @vitejs/plugin-react@^4.1.0, autoprefixer@^10.4.16, axios@^1.6.0, framer-motion@^10.16.0, lucide-react@^0.290.0, postcss@^8.4.31, react@^18.2.0, react-dom@^18.2.0, react-router-dom@^6.8.0, tailwindcss@^3.3.0, vite@^4.5.0

### Recent commits (newest first)

- Fix route conflicts causing 404 health check errors
- Fix PORT environment variable handling for Railway deployment
- Add Railway deployment configuration
- Merge branch 'main' of https://github.com/Abdullah0x0/dreamdirector
- Fix
- Update README.md
- Update
- Add DreamDirector
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### old_description.md

```markdown
## Inspiration
We love immersive games but always felt constrained by text-only interfaces. We dreamed of a platform where you could not just imagine the story, but see it unfold like a movie with adaptive music that responds to your emotions. The latest advances in multimodal AI from Google—including Gemini, Imagen 3.0, Veo 2.0, and Lyria RealTime—gave us the tools to finally build it: a true AI storyteller that weaves narrative, visuals, and dynamic audio together in real time.

## What it does
DreamDirector is your personal AI Cinematic Director for any adventure you can imagine. You start with a simple story idea—cyberpunk mystery, space opera, fantasy quest—and our sophisticated multi-agent AI system collaborates to build a rich, interactive world. The system generates stunning 4K images with visual consistency tracking, produces cinematic 8-second video sequences for dramatic moments, and creates adaptive music that evolves with your story's emotional tone. Every choice you make matters, with the AI maintaining persistent memory of characters, locations, and world state across your entire journey.

## How we built it

### Architecture & Technology Stack
**Frontend (React 18 + Modern Web)**
- React 18 with Vite for lightning-fast development
- Tailwind CSS with custom cinematic themes
- Framer Motion for advanced animations and transitions
- React Router Dom for seamless navigation
- Axios for API communication

**Backend (FastAPI + Python)**
- FastAPI with async/await for high-performance API handling
- Uvicorn ASGI server with real-time capabilities
- Pydantic for data validation and type safety
- Python-multipart for media file handling
- CORS middleware for cross-origin support

**AI & Multi-Agent System (Google ADK + GenAI)**
- Google ADK (Application Development Kit) for agent orchestration
- Google GenAI SDK with Gemini models for intelligent reasoning
- Google Imagen 3.0 for consistent visual generation
- Google Veo 2.0 for cinematic video sequences
- Google Lyria RealTime for streaming adaptive music

### Multi-Agent Workflow
We architected DreamDirector as a team of specialized AI agents working through the Google ADK framework:

**🎭 Story Director Agent**
- Orchestrates narrative flow using Gemini's reasoning capabilities
- Manages three-act story structure and pacing
- Generates meaningful user choices with preview consequences
- Maintains character development and plot consistency

**🎨 Visual Consistency Agent**
- Uses Imagen 3.0 with character/location reference tracking
- Maintains visual DNA across all generated content
- Ensures professional cinematographic composition
- Applies consistent artistic style and color palettes

**🎵 Adaptive Music Composer**
- Leverages Lyria RealTime for streaming audio generation
- Creates layered compositions (atmospheric, character, action themes)
- Responds to emotional tone and story tension in real-time
- Supports multiple genres from cyberpunk synthwave to orchestral fantasy

**🎬 Medi
[truncated — 4543 more characters]
```

### .history/README_20250622092127.md

```markdown
# dreamdirector
```

### package.json

```
{
  "name": "dreamdirector-ui",
  "version": "1.0.0",
  "description": "🎬 DreamDirector - AI-Powered Cinematic Storytelling Interface",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "start": "vite"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.8.0",
    "axios": "^1.6.0",
    "framer-motion": "^10.16.0",
    "lucide-react": "^0.290.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.37",
    "@types/react-dom": "^18.2.15",     
    "@vitejs/plugin-react": "^4.1.0",
    "vite": "^4.5.0",
    "tailwindcss": "^3.3.0",
    "autoprefixer": "^10.4.16",
    "postcss": "^8.4.31"
  },
  "keywords": ["ai", "storytelling", "hackathon", "google-adk", "multimedia"],
  "author": "UC Berkeley AI Hackathon 2025",
  "license": "MIT"
} 
```

### Dockerfile

```
# Multi-stage Docker build for DreamDirector
FROM node:18-alpine AS frontend-builder

# Build frontend
WORKDIR /app/frontend
COPY package*.json ./
RUN npm install

COPY src/ ./src/
COPY index.html ./
COPY vite.config.js ./
COPY tailwind.config.js ./
COPY postcss.config.js ./

RUN npm run build

# Python backend stage  
FROM python:3.11-slim

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    curl \
    ffmpeg \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Copy requirements and install Python dependencies
COPY backend/requirements.txt ./backend/
COPY agents/requirements.txt ./agents/
RUN pip install --no-cache-dir -r backend/requirements.txt
RUN pip install --no-cache-dir -r agents/requirements.txt

# Copy application code
COPY backend/ ./backend/
COPY agents/ ./agents/

# Copy built frontend from previous stage
COPY --from=frontend-builder /app/frontend/dist ./static

# Create directories for generated files
RUN mkdir -p /app/media /app/generated

# Set environment variables
ENV PYTHONPATH=/app
ENV PORT=8000

# Expose port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8000/api/health || exit 1

# Start command - use shell to expand PORT environment variable
CMD sh -c "python -m uvicorn backend.app:app --host 0.0.0.0 --port ${PORT:-8000}" 
```

### agents/requirements.txt

```
# AI Dungeon Master - Creativity Track Requirements
# UC Berkeley AI Hackathon 2025

# Core Google ADK
google-adk>=1.0.0
google-genai>=1.10.0

# Additional utilities
python-dotenv>=1.0.0
streamlit>=1.28.0
asyncio>=3.4.3

# Optional: For enhanced demos
pillow>=10.0.0
requests>=2.31.0 
```

### backend/requirements.txt

```
# Core FastAPI Backend
fastapi>=0.104.0
uvicorn[standard]>=0.24.0
python-multipart>=0.0.6
pydantic>=2.4.0
python-dotenv>=1.0.0

# AI Agent Dependencies (from agents/requirements.txt)
google-adk>=1.0.0
google-genai>=1.10.0
pillow>=10.0.0
requests>=2.31.0
streamlit>=1.28.0

# Additional Python packages needed by agent.py
# (asyncio is built into Python 3.4+, no need to install) 
```

### src/main.jsx

```javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
) 
```

### src/App.jsx

```javascript
import React, { useState, useEffect } from 'react'
import { Routes, Route } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import Navbar from './components/Navbar'
import HomePage from './pages/HomePage'
import StoryPage from './pages/StoryPage'
import GalleryPage from './pages/GalleryPage'
import AboutPage from './pages/AboutPage'
import { AppProvider } from './context/AppContext'

function App() {
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    // Simulate app initialization
    const timer = setTimeout(() => {
      setIsLoading(false)
    }, 2000)

    return () => clearTimeout(timer)
  }, [])

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-cinematic-bg">
        <motion.div
          initial={{ opacity: 0, scale: 0.5 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center"
        >
          <div className="text-6xl mb-4">🎬</div>
          <h1 className="text-4xl font-cinematic gradient-text mb-4">
            DreamDirector
          </h1>
          <div className="loading-dots text-lg">Loading your cinematic experience</div>
        </motion.div>
      </div>
    )
  }

  return (
    <AppProvider>
      <div className="min-h-screen bg-cinematic-bg text-white">
        <Navbar />
        
        <AnimatePresence mode="wait">
          <Routes>
            <Route path="/" element={<HomePage />} />
            <Route path="/story" element={<StoryPage />} />
            <Route path="/gallery" element={<GalleryPage />} />
            <Route path="/about" element={<AboutPage />} />
          </Routes>
        </AnimatePresence>
      </div>
    </AppProvider>
  )
}

export default App 
```

### backend/app.py

```python
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel
import sys
import os
import asyncio
from pathlib import Path
from datetime import datetime

# Add the agents directory to Python path
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'agents'))

try:
    from agent import (
        start_new_adventure,
        present_story_choice,
        resolve_user_choice,
        generate_establishing_scene,
        orchestrate_adaptive_music,
        create_single_choice_image,
        create_epic_climax_video,
        get_story_status,
        game_state,
        begin_opening_scene,
        continue_narrative,
        create_story_climax,
        generate_direct_video
    )
    AGENT_AVAILABLE = True
except ImportError as e:
    print(f"⚠️ Could not import agent functions: {e}")
    AGENT_AVAILABLE = False

app = FastAPI(
    title="DreamDirector API",
    description="🎬 AI-Powered Cinematic Storytelling Backend",
    version="1.0.0"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:3000", 
        "http://127.0.0.1:3000",
        "https://*.railway.app",
        "https://*.up.railway.app"
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Serve static files (generated media)
media_dir = Path("../agents")  # Files are generated in agents directory
if media_dir.exists():
    app.mount("/media", StaticFiles(directory=str(media_dir)), name="media")
else:
    # Fallback to current directory
    media_dir = Path(".")
    app.mount("/media", StaticFiles(directory=str(media_dir)), name="media")

# Serve frontend static files (for production)
static_dir = Path("static")
if static_dir.exists():
    app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")

# Request/Response Models
class StoryRequest(BaseModel):
    story_request: str

class ChoiceRequest(BaseModel):
    choice: str

class MediaRequest(BaseModel):
    type: str  # 'image', 'video', 'music'
    prompt: str
    emotional_tone: str = "mysterious"

class StoryResponse(BaseModel):
    narrative: str
    choices: list[str] = []
    scene_description: str = ""
    mood: str = "mysterious"
    scene_id: str = ""
    media_files: dict = {}
    story_complete: bool = False
    story_progression: list = []
    choices_remaining: int = 0
    current_choice: int = 0
    total_choices: int = 0

# API info endpoint 
@app.get("/api/info")
async def api_info():
    return {
        "message": "🎬 DreamDirector API - REAL AI ONLY!",
        "agent_available": AGENT_AVAILABLE,
        "mode": "PRODUCTION - Using agent.py only",
        "mock_data": "DISABLED",
        "endpoints": [
            "/api/start-story",
            "/api/make-choice", 
            "/api/generate-media",
            "/api/story-status",
            "/api/media-files"
        ]
    }

@app.get("/api/health")
async def health_check():
    return {
        "status": "healthy",
        "agent_available": AGENT_AVAILABLE,
        "media_directory": str(media_dir.absolute()) if media_dir.exists() else "not found"
    }

# Start a new story
@app.post("/api/start-story", response_model=StoryResponse)
async def start_story(request: StoryRequest):
    if not AGENT_AVAILABLE:
        raise HTTPException(status_code=503, detail="AI Agent system not available. Please check Google ADK installation.")
    
    try:
        print(f"🎬 Starting story using agent.py: {request.story_request}")
        
        # Step 1: Initialize the adventure with real AI
        init_result = start_new_adventure(request.story_request)
        print(f"✅ Adventure initialized: {init_result.get('status')}")
        
        # Step 2: Begin opening scene with real AI
        opening_result = begin_opening_scene()
        print(f"✅ Opening scene created: {opening_result.get('status')}")
        
        # Step 3: Let AI generate the actual story situation and choices
        # Don't provide hardcoded text - let the AI create everything
        choice_result = present_story_choice("")  # Empty string - let AI generate situation
        print(f"✅ Choices presented: {choice_result.get('status')}")
        
        # Extract ONLY real AI-generated content
        ai_narrative = ""
        if opening_result.get('opening_scene', {}).get('narrative'):
            ai_narrative = opening_result['opening_scene']['narrative']
        elif init_result.get('scenario', {}).get('hook'):
            ai_narrative = init_result['scenario']['hook']
        else:
            ai_narrative = "Story initializing..."
            
        ai_situation = choice_result.get('situation', '')
        if ai_situation:
            ai_narrative += f" {ai_situation}"
        
        return StoryResponse(
            narrative=ai_narrative,
            choices=[
                choice_result.get('choice_a', ''),
                choice_result.get('choice_b', ''),
                choice_result.get('choice_c', '')
            ],
            scene_description=init_result.get('scenario', {}).get('setting', request.story_request),
            mood=game_state.current_mood,
            scene_id='opening_scene',
            media_files={},
            story_complete=False,
            story_progression=[],
            choices_remaining=5,
            current_choice=0,
            total_choices=5
        )
    except Exception as e:
        print(f"❌ Agent.py error: {str(e)}")
        raise HTTPException(status_code=500, detail=f"AI Agent error: {str(e)}")

# Make a choice in the story
@app.post("/api/make-choice", response_model=StoryResponse)
async def make_choice(request: ChoiceRequest):
    if not AGENT_AVAILABLE:
        raise HTTPException(status_code=503, detail="AI Agent system not available. Please check Google ADK installation.")
    
    try:
        print(f"🎭 Proce
[truncated — 13284 more characters]
```

### postcss.config.js

```javascript
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
} 
```

[32 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]