Spaces:
Runtime error
Runtime error
| """ | |
| HuggingFace Spaces App for DReamMachine | |
| Gradio interface for the multi-agent dream orchestration system | |
| """ | |
| import os | |
| import gradio as gr | |
| import logging | |
| from datetime import datetime | |
| import json | |
| from typing import List, Tuple | |
| from orchestrator import DreamOrchestrator | |
| from data_logger import DataLogger | |
| # Configure logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| handlers=[ | |
| logging.StreamHandler(), | |
| logging.FileHandler('dreammachine.log') | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Initialize orchestrator (will use HF_TOKEN from environment) | |
| orchestrator = None | |
| data_logger = None | |
| def initialize_system(): | |
| """Initialize the orchestrator and data logger""" | |
| global orchestrator, data_logger | |
| try: | |
| hf_token = os.getenv('HF_TOKEN') | |
| if not hf_token: | |
| logger.warning("HF_TOKEN not found. Some features may be limited.") | |
| return "β οΈ HF_TOKEN not set. Please add it in Space settings." | |
| orchestrator = DreamOrchestrator(config_path="config.yaml", hf_token=hf_token) | |
| data_logger = DataLogger(config_path="config.yaml", hf_token=hf_token) | |
| # Initialize HuggingFace dataset | |
| try: | |
| data_logger.initialize_hf_dataset() | |
| except Exception as e: | |
| logger.warning(f"Could not initialize HF dataset: {str(e)}") | |
| logger.info("System initialized successfully") | |
| return "β System initialized successfully!" | |
| except Exception as e: | |
| logger.error(f"Failed to initialize system: {str(e)}") | |
| import traceback | |
| logger.error(traceback.format_exc()) | |
| return f"β Initialization error: {str(e)}" | |
| def run_single_dream_round(stage: str = "init_1_25") -> Tuple[str, str, str, str, str]: | |
| """ | |
| Run a single dream round and return results | |
| Returns: | |
| Tuple of (summary, pitch, technical, feasibility, scorecard) | |
| """ | |
| global orchestrator | |
| if orchestrator is None: | |
| init_msg = initialize_system() | |
| if "error" in init_msg.lower(): | |
| return init_msg, "", "", "", "" | |
| try: | |
| logger.info(f"Running dream round with stage: {stage}") | |
| # Run the dream round | |
| session_data = orchestrator.run_dream_round(stage=stage) | |
| # Extract results | |
| summary = f""" | |
| # Dream Session Complete! | |
| **Session ID**: {session_data.get('session_id', 'N/A')} | |
| **Life Stage**: {session_data.get('life_stage', 'N/A')} | |
| **Execution Time**: {session_data.get('execution_time_seconds', 0):.2f} seconds | |
| ## Scores | |
| - **Originality**: {session_data['curator_scorecard'].get('originality', 'N/A')}/10 | |
| - **Feasibility**: {session_data['curator_scorecard'].get('feasibility', 'N/A')}/10 | |
| - **Global Impact**: {session_data['curator_scorecard'].get('global_impact', 'N/A')}/10 | |
| - **Narrative Coherence**: {session_data['curator_scorecard'].get('narrative_coherence', 'N/A')}/10 | |
| **Reforge Flag**: {"β Yes" if session_data['curator_scorecard'].get('reforge_flag') else "β No"} | |
| ## Next Action | |
| **Type**: {session_data['next_action'].get('type', 'N/A')} | |
| **Reason**: {session_data['next_action'].get('reason', 'N/A')} | |
| """ | |
| pitch = session_data.get('pitch_narrative', '') | |
| technical = session_data.get('technical_components', '') | |
| feasibility = session_data.get('feasibility_report', '') | |
| scorecard = json.dumps(session_data.get('curator_scorecard', {}), indent=2) | |
| return summary, pitch, technical, feasibility, scorecard | |
| except Exception as e: | |
| error_msg = f"Error running dream round: {str(e)}" | |
| logger.error(error_msg) | |
| return error_msg, "", "", "", "" | |
| def run_batch_rounds(num_rounds: int, sleep_between: int) -> str: | |
| """ | |
| Run multiple dream rounds in batch | |
| Args: | |
| num_rounds: Number of rounds to run | |
| sleep_between: Seconds between rounds | |
| Returns: | |
| Summary of batch execution | |
| """ | |
| global orchestrator | |
| if orchestrator is None: | |
| init_msg = initialize_system() | |
| if "error" in init_msg.lower(): | |
| return init_msg | |
| try: | |
| logger.info(f"Starting batch mode: {num_rounds} rounds") | |
| results = orchestrator.run_batch_mode( | |
| num_rounds=int(num_rounds), | |
| sleep_between=int(sleep_between) | |
| ) | |
| # Generate summary | |
| summary = f"# Batch Execution Complete!\n\n" | |
| summary += f"**Total Rounds**: {len(results)}\n" | |
| summary += f"**Successful**: {len([r for r in results if r.get('curator_scorecard')])}\n\n" | |
| # Count outcomes | |
| reforge_count = sum(1 for r in results if r.get('curator_scorecard', {}).get('reforge_flag')) | |
| summary += f"**Reforge-Eligible Ideas**: {reforge_count}\n\n" | |
| # Average scores | |
| if results: | |
| avg_originality = sum(r.get('curator_scorecard', {}).get('originality', 0) for r in results) / len(results) | |
| avg_feasibility = sum(r.get('curator_scorecard', {}).get('feasibility', 0) for r in results) / len(results) | |
| avg_impact = sum(r.get('curator_scorecard', {}).get('global_impact', 0) for r in results) / len(results) | |
| summary += f"## Average Scores\n" | |
| summary += f"- Originality: {avg_originality:.1f}/10\n" | |
| summary += f"- Feasibility: {avg_feasibility:.1f}/10\n" | |
| summary += f"- Global Impact: {avg_impact:.1f}/10\n\n" | |
| # List sessions | |
| summary += f"## Session IDs\n" | |
| for i, result in enumerate(results, 1): | |
| session_id = result.get('session_id', 'N/A') | |
| reforge = "β" if result.get('curator_scorecard', {}).get('reforge_flag') else "β" | |
| summary += f"{i}. {session_id} (Reforge: {reforge})\n" | |
| return summary | |
| except Exception as e: | |
| error_msg = f"Error in batch mode: {str(e)}" | |
| logger.error(error_msg) | |
| return error_msg | |
| def view_session_history() -> str: | |
| """View all logged sessions""" | |
| global data_logger | |
| if data_logger is None: | |
| data_logger = DataLogger(config_path="config.yaml", hf_token=os.getenv('HF_TOKEN')) | |
| try: | |
| sessions = data_logger.get_all_sessions() | |
| if not sessions: | |
| return "No sessions found in history." | |
| summary = f"# Session History ({len(sessions)} total)\n\n" | |
| for i, session in enumerate(sessions, 1): | |
| scorecard = session.get('curator_scorecard', {}) | |
| summary += f"## {i}. {session.get('session_id', 'Unknown')}\n" | |
| summary += f"- **Stage**: {session.get('life_stage', 'N/A')}\n" | |
| summary += f"- **Timestamp**: {session.get('timestamp', 'N/A')}\n" | |
| summary += f"- **Originality**: {scorecard.get('originality', 'N/A')}/10\n" | |
| summary += f"- **Feasibility**: {scorecard.get('feasibility', 'N/A')}/10\n" | |
| summary += f"- **Reforge**: {'Yes' if scorecard.get('reforge_flag') else 'No'}\n\n" | |
| return summary | |
| except Exception as e: | |
| return f"Error loading history: {str(e)}" | |
| # Create Gradio interface | |
| with gr.Blocks(title="DReamMachine - LLM Brainstorm System", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown(""" | |
| # π DReamMachine: Dream A LiL(LLM) Dream | |
| Multi-agent LLM orchestration system for breakthrough innovation discovery via guided hallucination. | |
| ## How It Works | |
| 1. **Dreamers** (3x creative LLMs) generate radical ideas | |
| 2. **Writer/Logger/Narrator** refine concepts into coherent narratives | |
| 3. **Deep Thinker** evaluates scientific feasibility | |
| 4. **Curator** scores ideas across multiple dimensions | |
| 5. **System** decides whether to advance ideas through life stages (1-25, 26-50, 51-75, 76-100 years) | |
| Ideas that score high on originality AND feasibility progress through simulated 100-year lifespans! | |
| """) | |
| # Status indicator | |
| with gr.Row(): | |
| status_text = gr.Markdown("### System Status") | |
| init_btn = gr.Button("π Initialize System", size="sm", variant="secondary") | |
| init_output = gr.Markdown("") | |
| init_btn.click(fn=initialize_system, inputs=[], outputs=[init_output]) | |
| with gr.Tab("Single Dream Round"): | |
| gr.Markdown("### Run a single dream round") | |
| stage_selector = gr.Dropdown( | |
| choices=["init_1_25", "mid_26_50", "late_51_75", "final_76_100"], | |
| value="init_1_25", | |
| label="Life Stage", | |
| info="Select which life stage to run" | |
| ) | |
| run_single_btn = gr.Button("π Run Dream Round", variant="primary", size="lg") | |
| with gr.Row(): | |
| with gr.Column(): | |
| summary_output = gr.Markdown(label="Session Summary") | |
| with gr.Accordion("Dream Outputs", open=False): | |
| pitch_output = gr.Textbox(label="Narrative Pitch", lines=10) | |
| technical_output = gr.Textbox(label="Technical Components", lines=10) | |
| feasibility_output = gr.Textbox(label="Feasibility Report", lines=10) | |
| scorecard_output = gr.Textbox(label="Curator Scorecard (JSON)", lines=10) | |
| run_single_btn.click( | |
| fn=run_single_dream_round, | |
| inputs=[stage_selector], | |
| outputs=[summary_output, pitch_output, technical_output, feasibility_output, scorecard_output] | |
| ) | |
| with gr.Tab("Batch Mode"): | |
| gr.Markdown("### Run multiple dream rounds automatically") | |
| with gr.Row(): | |
| num_rounds_input = gr.Slider( | |
| minimum=1, | |
| maximum=50, | |
| value=5, | |
| step=1, | |
| label="Number of Rounds" | |
| ) | |
| sleep_input = gr.Slider( | |
| minimum=0, | |
| maximum=300, | |
| value=10, | |
| step=5, | |
| label="Sleep Between Rounds (seconds)" | |
| ) | |
| run_batch_btn = gr.Button("π Run Batch Mode", variant="primary", size="lg") | |
| batch_output = gr.Markdown(label="Batch Results") | |
| run_batch_btn.click( | |
| fn=run_batch_rounds, | |
| inputs=[num_rounds_input, sleep_input], | |
| outputs=[batch_output] | |
| ) | |
| with gr.Tab("Session History"): | |
| gr.Markdown("### View all logged sessions") | |
| refresh_history_btn = gr.Button("π Refresh History", variant="secondary") | |
| history_output = gr.Markdown(label="Session History") | |
| refresh_history_btn.click( | |
| fn=view_session_history, | |
| inputs=[], | |
| outputs=[history_output] | |
| ) | |
| with gr.Tab("About"): | |
| gr.Markdown(""" | |
| ## π― Project Concept | |
| **DReamMachine** is an experimental system that uses "controlled hallucination" to discover breakthrough innovations. | |
| By guiding LLMs through a simulated 100-year creative journey, the system explores the full lifecycle of ideas - | |
| from initial discovery through real-world challenges to mass adoption and legacy. | |
| ### The 7-Step Dream Cycle | |
| Each "dream round" follows this process: | |
| 1. **Setup**: Initialize life stage prompt and constraints | |
| 2. **Dream & Generate**: 3 creative LLMs generate wild ideas | |
| 3. **Log & Narrate**: Writer/Logger/Narrator refine outputs | |
| 4. **Deep Think & Verify**: Analytical LLM checks feasibility | |
| 5. **Curate & Grade**: Evaluation LLM scores the concept | |
| 6. **Data Storage**: Archive to HuggingFace dataset | |
| 7. **Reforge Loop**: Advance successful ideas to next life stage | |
| ### Life Stages | |
| - **Ages 1-25**: Foundational Discovery (bold creativity) | |
| - **Ages 26-50**: Commercialization & Crisis (real-world testing) | |
| - **Ages 51-75**: Mass Adoption & Ethics (societal impact) | |
| - **Ages 76-100**: Legacy & Vision (long-term thinking) | |
| ### Scoring Criteria | |
| - **Originality** (1-10): How novel is the idea? | |
| - **Feasibility** (1-10): Can this actually be built? | |
| - **Global Impact** (1-10): How many people benefit? | |
| - **Narrative Coherence** (1-10): Is the pitch compelling? | |
| Ideas with Feasibility > 7 AND Originality > 5 advance to the next life stage! | |
| --- | |
| **Created by**: Dave Roby / DRStudios | |
| **Inspired by**: Conversations with Gemini 2.5 Flash | |
| **Built with**: Claude Sonnet 4.5 via Claude Code | |
| """) | |
| if __name__ == "__main__": | |
| # For HuggingFace Spaces | |
| # Try to initialize on startup (but don't crash if it fails) | |
| try: | |
| logger.info("Attempting to initialize system on startup...") | |
| result = initialize_system() | |
| logger.info(f"Initialization result: {result}") | |
| except Exception as e: | |
| logger.error(f"Startup initialization failed: {str(e)}") | |
| logger.error("App will start anyway. Initialize manually from the interface.") | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |