File size: 13,686 Bytes
3d392e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473f1ba
 
 
 
ad4105e
473f1ba
 
ad4105e
473f1ba
ad4105e
473f1ba
 
 
 
ad4105e
0b29bac
ad4105e
 
 
 
 
185cad2
 
 
 
 
 
 
ad4105e
 
 
185cad2
ad4105e
 
 
 
 
 
185cad2
 
 
3d392e6
 
185cad2
3d392e6
 
 
473f1ba
3d392e6
ad4105e
 
 
 
 
 
 
3d392e6
 
 
 
473f1ba
 
ad4105e
 
 
 
 
 
 
 
 
 
 
 
3d392e6
ad4105e
 
 
 
 
3d392e6
ad4105e
 
 
 
 
3d392e6
 
 
ad4105e
 
3d392e6
 
 
473f1ba
ad4105e
 
 
 
 
 
 
 
 
 
 
 
3d392e6
ad4105e
 
 
 
 
3d392e6
ad4105e
 
 
 
 
 
473f1ba
 
ad4105e
 
 
473f1ba
ad4105e
 
 
 
 
 
3d392e6
 
ad4105e
3d392e6
ad4105e
3d392e6
 
 
473f1ba
 
 
3d392e6
 
 
473f1ba
 
 
ad4105e
 
473f1ba
 
 
 
 
 
ad4105e
 
3d392e6
473f1ba
 
 
 
 
 
 
3d392e6
473f1ba
 
 
 
 
 
 
3d392e6
 
 
 
 
 
 
 
 
473f1ba
3d392e6
473f1ba
 
3d392e6
 
 
ad4105e
 
 
473f1ba
 
3d392e6
 
ad4105e
 
3d392e6
473f1ba
 
ad4105e
 
473f1ba
 
3d392e6
ad4105e
3d392e6
 
 
ad4105e
3d392e6
 
473f1ba
3d392e6
 
 
 
 
 
 
 
 
185cad2
3d392e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185cad2
3d392e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad4105e
185cad2
ad4105e
 
 
3d392e6
185cad2
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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.strip()
            self.client = OpenAI(
                base_url="https://openrouter.ai/api/v1",
                api_key=self.api_key,
            )
            return "API key configured successfully! You can now analyze dreams."
        except Exception as e:
            self.client = None
            self.api_key = None
            return f"API configuration failed: {str(e)}"
    
    def _make_api_call(self, messages, model="google/gemini-flash-1.5"):  #google/gemini-flash-1.5   google/gemini-2.0-flash-exp:free
        """Make an API call to OpenRouter with proper error handling"""
        if not self.client:
            raise ValueError("API client not configured")
            
        try:
            response = self.client.chat.completions.create(
                model=model,
                messages=messages,
                extra_headers={
                    "HTTP-Referer": "https://deepdreaminterpreter.com",
                    "X-Title": "Deep Dream Interpreter"
                }
            )
            
            # Extract the content
            content = response.choices[0].message.content
            if not content:
                raise ValueError("Empty content in API response")
                
            return content
            
        except Exception as e:
            error_msg = f"API error: {str(e)}"
            print(f"API error: {error_msg}")
            raise ValueError(error_msg)
        
    def analyze_dream(self, dream_description, include_visualization=True, user_name="Anonymous"):
        """Analyze the provided dream description using Gemini Flash 1.5"""
        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."
        
        # Clean input
        dream_description = dream_description.strip()
        if user_name:
            user_name = user_name.strip()
        else:
            user_name = "Anonymous"
            
        try:
            # First pass: Dream analysis with thinking capabilities
            print("Starting dream analysis...")
            
            # System prompt for dream analysis
            analysis_messages = [
                {
                    "role": "system",
                    "content": """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."""
                },
                {
                    "role": "user",
                    "content": f"Dream description from user {user_name}: {dream_description}"
                }
            ]
            
            # Make API call for dream analysis
            try:
                dream_analysis = self._make_api_call(analysis_messages)
            except ValueError as e:
                return f"Dream analysis failed: {str(e)}\n\nPlease check your API key and try again."
            
            # If visualization is not needed, return just the analysis
            if not include_visualization:
                return f"""## Dream Analysis
{dream_analysis}"""
                
            # Second pass: Visual interpretation
            print("Generating visualization prompt...")
            
            visualization_messages = [
                {
                    "role": "system",
                    "content": """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."""
                },
                {
                    "role": "user",
                    "content": f"Dream analysis: {dream_analysis}"
                }
            ]
            
            # Make API call for visualization
            try:
                visualization_prompt = self._make_api_call(visualization_messages)
                
                # Combine the results
                full_response = f"""## Dream Analysis
{dream_analysis}
## Visualization Prompt
{visualization_prompt}
---
*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 ValueError as e:
                # If visualization fails, still return the analysis
                print(f"Visualization error: {str(e)}")
                return f"""## Dream Analysis
{dream_analysis}
## Visualization Prompt
Error: Unable to generate visualization prompt. Please try again later.
---
*Note: The dream analysis was successful, but we encountered an issue generating the visualization prompt.*
"""
            
        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"
            else:
                user_name = user_name.strip()
                
            # 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")
            safe_username = ''.join(c if c.isalnum() or c == '_' else '_' for c in user_name.replace(' ', '_'))
            filename = f"dreams/{safe_username}_{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):
        # Show processing message
        yield "Processing your dream... Please wait."
        
        # 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:
                yield setup_message
                return
        
        # Validate dream description
        if not dream_description or not dream_description.strip():
            yield "Please enter a dream description."
            return
        
        # Perform analysis
        analysis = interpreter.analyze_dream(dream_description, include_visualization, user_name)
        yield analysis
    
    # Define the save function
    def save_dream_entry(api_key, user_name, dream_description, analysis_output):
        if not analysis_output or analysis_output == "Processing your dream... Please wait." 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 Flash 1.5.")
        
        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 Flash 1.5 model 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
            
            ### Troubleshooting:
            - If you encounter an error, make sure your API key is valid and has access to the Gemini Flash 1.5 model
            - Check that your OpenRouter account has sufficient credits
            - Try a shorter dream description if you're experiencing timeout issues
            
            ### Requirements:
            - An OpenRouter API key with access to Google's Gemini Flash 1.5 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()