File size: 12,984 Bytes
3d392e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473f1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d392e6
 
 
 
 
 
473f1ba
3d392e6
 
 
 
 
473f1ba
 
 
 
 
 
 
 
 
 
 
 
 
3d392e6
 
 
 
 
 
 
 
473f1ba
3d392e6
 
 
 
 
 
 
 
473f1ba
 
 
 
 
3d392e6
 
 
 
 
 
 
473f1ba
 
 
 
 
 
 
 
 
 
 
 
 
3d392e6
 
 
 
 
 
 
 
473f1ba
3d392e6
 
 
 
 
 
 
 
473f1ba
 
 
 
 
 
 
 
 
 
 
 
3d392e6
 
 
 
 
 
 
473f1ba
3d392e6
 
 
 
 
 
 
473f1ba
 
 
3d392e6
 
 
473f1ba
 
 
 
 
 
 
 
 
 
3d392e6
473f1ba
 
 
 
 
 
 
3d392e6
473f1ba
 
 
 
 
 
 
3d392e6
 
 
 
 
 
 
 
 
473f1ba
3d392e6
473f1ba
 
3d392e6
 
 
473f1ba
 
3d392e6
 
 
 
473f1ba
 
 
 
 
3d392e6
 
 
 
 
 
 
 
473f1ba
3d392e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import json
import os
import time
from openai import OpenAI

class DeepDreamInterpreter:
    def __init__(self, api_key=None):
        self.api_key = api_key
        self.client = None
        if api_key:
            self.setup_client(api_key)
            
    def setup_client(self, api_key):
        """Set up the OpenAI client with the provided API key"""
        if not api_key or not api_key.strip():
            return "Please provide a valid API key."
            
        try:
            self.api_key = api_key
            self.client = OpenAI(
                base_url="https://openrouter.ai/api/v1",
                api_key=api_key,
            )
            # Test the API key with a simple request
            test_response = self.client.chat.completions.create(
                extra_headers={
                    "HTTP-Referer": "https://deepdreaminterpreter.com",
                    "X-Title": "Deep Dream Interpreter",
                },
                model="google/gemini-2.5-flash-preview:thinking",
                messages=[
                    {"role": "user", "content": "Hello, this is a test."}
                ],
                max_tokens=5  # Keep it minimal for the test
            )
            return "API key configured successfully!"
        except Exception as e:
            self.client = None
            self.api_key = None
            return f"API configuration failed: {str(e)}"
        
    def analyze_dream(self, dream_description, include_visualization=True, user_name="Anonymous"):
        """Analyze the provided dream description using Gemini 2.5 Flash"""
        if not self.client:
            return "Please configure your API key first."
            
        if not dream_description or not dream_description.strip():
            return "Please enter a dream description to analyze."
            
        try:
            # First pass: Dream analysis with thinking capabilities
            print("Starting dream analysis...")
            
            # System prompt for dream analysis
            system_prompt = """You are an expert dream analyst. Analyze the following dream description, identifying key symbols, emotions, themes, and potential psychological meanings. 
            Structure your analysis in these sections: 
            - Summary
            - Key Symbols
            - Emotional Landscape
            - Themes
            - Psychological Interpretation
            
            Be thoughtful, nuanced, and avoid overgeneralizations."""
            
            analysis_response = self.client.chat.completions.create(
                extra_headers={
                    "HTTP-Referer": "https://deepdreaminterpreter.com",
                    "X-Title": "Deep Dream Interpreter",
                },
                model="google/gemini-2.5-flash-preview:thinking",
                messages=[
                    {
                        "role": "system",
                        "content": system_prompt
                    },
                    {
                        "role": "user",
                        "content": f"Dream description from user {user_name}: {dream_description}"
                    }
                ]
            )
            
            # Check if we got a valid response
            if not analysis_response or not hasattr(analysis_response, 'choices') or not analysis_response.choices:
                return "Error: Received an invalid response from the API during analysis."
                
            dream_analysis = analysis_response.choices[0].message.content
            
            # If visualization is not needed, return just the analysis
            if not include_visualization:
                return dream_analysis
                
            # Second pass: Visual interpretation
            print("Generating visualization prompt...")
            
            # System prompt for visualization
            visualization_system_prompt = """Based on this dream analysis, create a detailed visual description that could be used as a prompt for an image generation model. 
            Make it evocative and detailed, including:
            - Colors and lighting
            - Atmosphere and mood
            - Composition and perspective
            - Key elements and their arrangement
            - Symbolic representations
            
            Create something that captures the essence and emotional quality of the dream."""
            
            visualization_response = self.client.chat.completions.create(
                extra_headers={
                    "HTTP-Referer": "https://deepdreaminterpreter.com",
                    "X-Title": "Deep Dream Interpreter",
                },
                model="google/gemini-2.5-flash-preview:thinking",
                messages=[
                    {
                        "role": "system",
                        "content": visualization_system_prompt
                    },
                    {
                        "role": "user",
                        "content": f"Dream analysis: {dream_analysis}"
                    }
                ]
            )
            
            # Check if we got a valid response
            if not visualization_response or not hasattr(visualization_response, 'choices') or not visualization_response.choices:
                # If visualization fails, still return the analysis
                return f"""## Dream Analysis

{dream_analysis}

## Visualization Prompt

Error: Unable to generate visualization prompt. Please try again later.
"""
            
            # Combine the results
            full_response = f"""## Dream Analysis

{dream_analysis}

## Visualization Prompt

{visualization_response.choices[0].message.content}

---
*Note: This visualization prompt can be used with image generation models like DALL-E, Midjourney, or Stable Diffusion to create a visual representation of your dream.*
"""
            return full_response
            
        except Exception as e:
            error_message = str(e)
            print(f"Error during analysis: {error_message}")
            return f"Error during analysis: {error_message}\n\nPlease check your API key and try again."
            
    def save_dream(self, user_name, dream_description, analysis):
        """Save the dream and its analysis to a JSON file"""
        try:
            if not user_name or not user_name.strip():
                user_name = "Anonymous"
                
            # Create dreams directory if it doesn't exist
            os.makedirs("dreams", exist_ok=True)
                
            # Create a filename based on user and timestamp
            timestamp = time.strftime("%Y%m%d-%H%M%S")
            filename = f"dreams/{user_name.replace(' ', '_')}_{timestamp}.json"
            
            # Create the dream data
            dream_data = {
                "user": user_name,
                "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
                "dream_description": dream_description,
                "analysis": analysis
            }
            
            # Save to file
            with open(filename, "w", encoding="utf-8") as f:
                json.dump(dream_data, f, indent=4, ensure_ascii=False)
                
            return f"Dream saved to {filename}"
        except Exception as e:
            return f"Error saving dream: {str(e)}"


# Set up the Gradio interface
def create_gradio_interface():
    # Initialize the interpreter
    interpreter = DeepDreamInterpreter()
    
    # Define the process function for the API key
    def process_api_key(api_key):
        if not api_key or not api_key.strip():
            return "Please enter a valid API key."
        result = interpreter.setup_client(api_key)
        return result
    
    # Define the process function for dream analysis
    def process_dream(api_key, dream_description, include_visualization, user_name):
        # If API key changed or not set up, configure it first
        if not interpreter.client or api_key.strip() != interpreter.api_key:
            setup_message = interpreter.setup_client(api_key)
            if "successfully" not in setup_message:
                return setup_message
        
        # Validate dream description
        if not dream_description or not dream_description.strip():
            return "Please enter a dream description."
        
        # Perform analysis
        analysis = interpreter.analyze_dream(dream_description, include_visualization, user_name)
        return analysis
    
    # Define the save function
    def save_dream_entry(api_key, user_name, dream_description, analysis_output):
        if not analysis_output or "Error" in analysis_output:
            return "Nothing to save or analysis contains errors."
        
        if not interpreter.client or api_key.strip() != interpreter.api_key:
            setup_message = interpreter.setup_client(api_key)
            if "successfully" not in setup_message:
                return setup_message
        
        return interpreter.save_dream(user_name, dream_description, analysis_output)
    
    # Create the Gradio interface
    with gr.Blocks(title="Deep Dream Interpreter") as app:
        gr.Markdown("# 🌙 Deep Dream Interpreter")
        gr.Markdown("Analyze your dreams using Gemini 2.5 Flash with thinking capabilities.")
        
        with gr.Tab("Dream Analysis"):
            with gr.Row():
                with gr.Column():
                    api_key = gr.Textbox(
                        label="OpenRouter API Key", 
                        placeholder="Enter your OpenRouter API key here", 
                        type="password"
                    )
                    api_status = gr.Textbox(label="API Status", interactive=False)
                    api_button = gr.Button("Configure API")
            
            with gr.Row():
                with gr.Column():
                    user_name = gr.Textbox(
                        label="Your Name (Optional)", 
                        placeholder="Enter your name or leave blank for anonymous"
                    )
                    dream_description = gr.Textbox(
                        label="Dream Description", 
                        placeholder="Describe your dream in detail...",
                        lines=10
                    )
                    include_visualization = gr.Checkbox(
                        label="Include visualization prompt", 
                        value=True
                    )
                    
                    with gr.Row():
                        analyze_button = gr.Button("Analyze Dream", variant="primary")
                        save_button = gr.Button("Save Analysis")
                    
                with gr.Column():
                    analysis_output = gr.Markdown(label="Analysis Results")
                    save_status = gr.Textbox(label="Save Status", interactive=False)
        
        with gr.Tab("About"):
            gr.Markdown("""
            ## About Deep Dream Interpreter
            
            This application uses Google's Gemini 2.5 Flash Preview model with thinking capabilities to analyze and interpret dreams. The model analyzes the narrative structure, emotional content, and symbolic elements of your dreams to provide insights and generate visualization prompts.
            
            ### Features:
            - **Dream Analysis**: Get a detailed analysis of your dream's symbols, emotions, and themes
            - **Visualization Prompts**: Receive detailed prompts that can be used with image generation models
            - **Save Your Dreams**: Save your dream descriptions and analyses for future reference
            
            ### Privacy Note:
            Your dream descriptions and analyses are processed using the Gemini model via OpenRouter. Your data is not stored on our servers unless you explicitly save your analysis.
            
            ### Getting Started:
            1. Enter your OpenRouter API key
            2. Enter your dream description
            3. Click "Analyze Dream"
            4. Optionally save your analysis
            
            ### Requirements:
            - An OpenRouter API key with access to Google's Gemini 2.5 Flash Preview model
            """)
        
        # Set up the event handlers
        api_button.click(process_api_key, inputs=api_key, outputs=api_status)
        analyze_button.click(
            process_dream, 
            inputs=[api_key, dream_description, include_visualization, user_name], 
            outputs=analysis_output
        )
        save_button.click(
            save_dream_entry, 
            inputs=[api_key, user_name, dream_description, analysis_output], 
            outputs=save_status
        )
    
    return app

# Create and launch the app
if __name__ == "__main__":
    app = create_gradio_interface()
    app.launch()