File size: 12,899 Bytes
77a06d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""
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)