Update app.py
Browse files
app.py
CHANGED
@@ -2,6 +2,7 @@ import gradio as gr
|
|
2 |
import json
|
3 |
import os
|
4 |
import time
|
|
|
5 |
from openai import OpenAI
|
6 |
|
7 |
class DeepDreamInterpreter:
|
@@ -17,28 +18,74 @@ class DeepDreamInterpreter:
|
|
17 |
return "Please provide a valid API key."
|
18 |
|
19 |
try:
|
20 |
-
self.api_key = api_key
|
21 |
self.client = OpenAI(
|
22 |
base_url="https://openrouter.ai/api/v1",
|
23 |
-
api_key=api_key,
|
24 |
)
|
25 |
-
|
26 |
-
test_response = self.client.chat.completions.create(
|
27 |
-
extra_headers={
|
28 |
-
"HTTP-Referer": "https://deepdreaminterpreter.com",
|
29 |
-
"X-Title": "Deep Dream Interpreter",
|
30 |
-
},
|
31 |
-
model="google/gemini-2.5-flash-preview:thinking",
|
32 |
-
messages=[
|
33 |
-
{"role": "user", "content": "Hello, this is a test."}
|
34 |
-
],
|
35 |
-
max_tokens=5 # Keep it minimal for the test
|
36 |
-
)
|
37 |
-
return "API key configured successfully!"
|
38 |
except Exception as e:
|
39 |
self.client = None
|
40 |
self.api_key = None
|
41 |
return f"API configuration failed: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
def analyze_dream(self, dream_description, include_visualization=True, user_name="Anonymous"):
|
44 |
"""Analyze the provided dream description using Gemini 2.5 Flash"""
|
@@ -47,107 +94,104 @@ class DeepDreamInterpreter:
|
|
47 |
|
48 |
if not dream_description or not dream_description.strip():
|
49 |
return "Please enter a dream description to analyze."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
try:
|
52 |
# First pass: Dream analysis with thinking capabilities
|
53 |
print("Starting dream analysis...")
|
54 |
|
55 |
# System prompt for dream analysis
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
"HTTP-Referer": "https://deepdreaminterpreter.com",
|
69 |
-
"X-Title": "Deep Dream Interpreter",
|
70 |
},
|
71 |
-
|
72 |
-
|
73 |
-
{
|
74 |
-
|
75 |
-
|
76 |
-
},
|
77 |
-
{
|
78 |
-
"role": "user",
|
79 |
-
"content": f"Dream description from user {user_name}: {dream_description}"
|
80 |
-
}
|
81 |
-
]
|
82 |
-
)
|
83 |
|
84 |
-
#
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
|
90 |
# If visualization is not needed, return just the analysis
|
91 |
if not include_visualization:
|
92 |
-
return
|
|
|
|
|
93 |
|
94 |
# Second pass: Visual interpretation
|
95 |
print("Generating visualization prompt...")
|
96 |
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
extra_headers={
|
110 |
-
"HTTP-Referer": "https://deepdreaminterpreter.com",
|
111 |
-
"X-Title": "Deep Dream Interpreter",
|
112 |
},
|
113 |
-
|
114 |
-
|
115 |
-
{
|
116 |
-
|
117 |
-
|
118 |
-
},
|
119 |
-
{
|
120 |
-
"role": "user",
|
121 |
-
"content": f"Dream analysis: {dream_analysis}"
|
122 |
-
}
|
123 |
-
]
|
124 |
-
)
|
125 |
|
126 |
-
#
|
127 |
-
|
128 |
-
|
129 |
-
|
|
|
|
|
130 |
|
131 |
{dream_analysis}
|
132 |
|
133 |
## Visualization Prompt
|
134 |
|
135 |
-
|
|
|
|
|
|
|
136 |
"""
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
140 |
|
141 |
{dream_analysis}
|
142 |
|
143 |
## Visualization Prompt
|
144 |
|
145 |
-
|
146 |
|
147 |
---
|
148 |
-
*Note:
|
149 |
"""
|
150 |
-
return full_response
|
151 |
|
152 |
except Exception as e:
|
153 |
error_message = str(e)
|
@@ -159,13 +203,16 @@ Error: Unable to generate visualization prompt. Please try again later.
|
|
159 |
try:
|
160 |
if not user_name or not user_name.strip():
|
161 |
user_name = "Anonymous"
|
|
|
|
|
162 |
|
163 |
# Create dreams directory if it doesn't exist
|
164 |
os.makedirs("dreams", exist_ok=True)
|
165 |
|
166 |
# Create a filename based on user and timestamp
|
167 |
timestamp = time.strftime("%Y%m%d-%H%M%S")
|
168 |
-
|
|
|
169 |
|
170 |
# Create the dream data
|
171 |
dream_data = {
|
@@ -198,23 +245,28 @@ def create_gradio_interface():
|
|
198 |
|
199 |
# Define the process function for dream analysis
|
200 |
def process_dream(api_key, dream_description, include_visualization, user_name):
|
|
|
|
|
|
|
201 |
# If API key changed or not set up, configure it first
|
202 |
if not interpreter.client or api_key.strip() != interpreter.api_key:
|
203 |
setup_message = interpreter.setup_client(api_key)
|
204 |
if "successfully" not in setup_message:
|
205 |
-
|
|
|
206 |
|
207 |
# Validate dream description
|
208 |
if not dream_description or not dream_description.strip():
|
209 |
-
|
|
|
210 |
|
211 |
# Perform analysis
|
212 |
analysis = interpreter.analyze_dream(dream_description, include_visualization, user_name)
|
213 |
-
|
214 |
|
215 |
# Define the save function
|
216 |
def save_dream_entry(api_key, user_name, dream_description, analysis_output):
|
217 |
-
if not analysis_output or "Error" in analysis_output:
|
218 |
return "Nothing to save or analysis contains errors."
|
219 |
|
220 |
if not interpreter.client or api_key.strip() != interpreter.api_key:
|
@@ -284,6 +336,11 @@ def create_gradio_interface():
|
|
284 |
3. Click "Analyze Dream"
|
285 |
4. Optionally save your analysis
|
286 |
|
|
|
|
|
|
|
|
|
|
|
287 |
### Requirements:
|
288 |
- An OpenRouter API key with access to Google's Gemini 2.5 Flash Preview model
|
289 |
""")
|
|
|
2 |
import json
|
3 |
import os
|
4 |
import time
|
5 |
+
import requests
|
6 |
from openai import OpenAI
|
7 |
|
8 |
class DeepDreamInterpreter:
|
|
|
18 |
return "Please provide a valid API key."
|
19 |
|
20 |
try:
|
21 |
+
self.api_key = api_key.strip()
|
22 |
self.client = OpenAI(
|
23 |
base_url="https://openrouter.ai/api/v1",
|
24 |
+
api_key=self.api_key,
|
25 |
)
|
26 |
+
return "API key configured successfully! You can now analyze dreams."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
except Exception as e:
|
28 |
self.client = None
|
29 |
self.api_key = None
|
30 |
return f"API configuration failed: {str(e)}"
|
31 |
+
|
32 |
+
def _make_api_call(self, messages, model="google/gemini-2.5-flash-preview:thinking"):
|
33 |
+
"""Make an API call to OpenRouter with proper error handling"""
|
34 |
+
if not self.client:
|
35 |
+
raise ValueError("API client not configured")
|
36 |
+
|
37 |
+
try:
|
38 |
+
# Direct API call using requests for more control
|
39 |
+
headers = {
|
40 |
+
"Authorization": f"Bearer {self.api_key}",
|
41 |
+
"Content-Type": "application/json",
|
42 |
+
"HTTP-Referer": "https://deepdreaminterpreter.com",
|
43 |
+
"X-Title": "Deep Dream Interpreter"
|
44 |
+
}
|
45 |
+
|
46 |
+
payload = {
|
47 |
+
"model": model,
|
48 |
+
"messages": messages
|
49 |
+
}
|
50 |
+
|
51 |
+
response = requests.post(
|
52 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
53 |
+
headers=headers,
|
54 |
+
json=payload
|
55 |
+
)
|
56 |
+
|
57 |
+
# Check if response is successful
|
58 |
+
if response.status_code != 200:
|
59 |
+
error_msg = f"API Error (Status {response.status_code}): "
|
60 |
+
try:
|
61 |
+
error_data = response.json()
|
62 |
+
error_msg += error_data.get('error', {}).get('message', 'Unknown error')
|
63 |
+
except:
|
64 |
+
error_msg += response.text[:100] + "..."
|
65 |
+
|
66 |
+
print(f"API error: {error_msg}")
|
67 |
+
raise ValueError(error_msg)
|
68 |
+
|
69 |
+
# Parse the response
|
70 |
+
data = response.json()
|
71 |
+
|
72 |
+
# Validate response structure
|
73 |
+
if 'choices' not in data or not data['choices'] or 'message' not in data['choices'][0]:
|
74 |
+
raise ValueError("Invalid response structure from API")
|
75 |
+
|
76 |
+
# Extract the content
|
77 |
+
content = data['choices'][0]['message'].get('content', '')
|
78 |
+
if not content:
|
79 |
+
raise ValueError("Empty content in API response")
|
80 |
+
|
81 |
+
return content
|
82 |
+
|
83 |
+
except requests.exceptions.RequestException as e:
|
84 |
+
raise ValueError(f"Network error: {str(e)}")
|
85 |
+
except json.JSONDecodeError:
|
86 |
+
raise ValueError("Invalid JSON response from API")
|
87 |
+
except Exception as e:
|
88 |
+
raise ValueError(f"Error in API call: {str(e)}")
|
89 |
|
90 |
def analyze_dream(self, dream_description, include_visualization=True, user_name="Anonymous"):
|
91 |
"""Analyze the provided dream description using Gemini 2.5 Flash"""
|
|
|
94 |
|
95 |
if not dream_description or not dream_description.strip():
|
96 |
return "Please enter a dream description to analyze."
|
97 |
+
|
98 |
+
# Clean input
|
99 |
+
dream_description = dream_description.strip()
|
100 |
+
if user_name:
|
101 |
+
user_name = user_name.strip()
|
102 |
+
else:
|
103 |
+
user_name = "Anonymous"
|
104 |
|
105 |
try:
|
106 |
# First pass: Dream analysis with thinking capabilities
|
107 |
print("Starting dream analysis...")
|
108 |
|
109 |
# System prompt for dream analysis
|
110 |
+
analysis_messages = [
|
111 |
+
{
|
112 |
+
"role": "system",
|
113 |
+
"content": """You are an expert dream analyst. Analyze the following dream description, identifying key symbols, emotions, themes, and potential psychological meanings.
|
114 |
+
Structure your analysis in these sections:
|
115 |
+
- Summary
|
116 |
+
- Key Symbols
|
117 |
+
- Emotional Landscape
|
118 |
+
- Themes
|
119 |
+
- Psychological Interpretation
|
120 |
+
|
121 |
+
Be thoughtful, nuanced, and avoid overgeneralizations."""
|
|
|
|
|
122 |
},
|
123 |
+
{
|
124 |
+
"role": "user",
|
125 |
+
"content": f"Dream description from user {user_name}: {dream_description}"
|
126 |
+
}
|
127 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
+
# Make API call for dream analysis
|
130 |
+
try:
|
131 |
+
dream_analysis = self._make_api_call(analysis_messages)
|
132 |
+
except ValueError as e:
|
133 |
+
return f"Dream analysis failed: {str(e)}\n\nPlease check your API key and try again."
|
134 |
|
135 |
# If visualization is not needed, return just the analysis
|
136 |
if not include_visualization:
|
137 |
+
return f"""## Dream Analysis
|
138 |
+
|
139 |
+
{dream_analysis}"""
|
140 |
|
141 |
# Second pass: Visual interpretation
|
142 |
print("Generating visualization prompt...")
|
143 |
|
144 |
+
visualization_messages = [
|
145 |
+
{
|
146 |
+
"role": "system",
|
147 |
+
"content": """Based on this dream analysis, create a detailed visual description that could be used as a prompt for an image generation model.
|
148 |
+
Make it evocative and detailed, including:
|
149 |
+
- Colors and lighting
|
150 |
+
- Atmosphere and mood
|
151 |
+
- Composition and perspective
|
152 |
+
- Key elements and their arrangement
|
153 |
+
- Symbolic representations
|
154 |
+
|
155 |
+
Create something that captures the essence and emotional quality of the dream."""
|
|
|
|
|
|
|
156 |
},
|
157 |
+
{
|
158 |
+
"role": "user",
|
159 |
+
"content": f"Dream analysis: {dream_analysis}"
|
160 |
+
}
|
161 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
162 |
|
163 |
+
# Make API call for visualization
|
164 |
+
try:
|
165 |
+
visualization_prompt = self._make_api_call(visualization_messages)
|
166 |
+
|
167 |
+
# Combine the results
|
168 |
+
full_response = f"""## Dream Analysis
|
169 |
|
170 |
{dream_analysis}
|
171 |
|
172 |
## Visualization Prompt
|
173 |
|
174 |
+
{visualization_prompt}
|
175 |
+
|
176 |
+
---
|
177 |
+
*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.*
|
178 |
"""
|
179 |
+
return full_response
|
180 |
+
|
181 |
+
except ValueError as e:
|
182 |
+
# If visualization fails, still return the analysis
|
183 |
+
print(f"Visualization error: {str(e)}")
|
184 |
+
return f"""## Dream Analysis
|
185 |
|
186 |
{dream_analysis}
|
187 |
|
188 |
## Visualization Prompt
|
189 |
|
190 |
+
Error: Unable to generate visualization prompt. Please try again later.
|
191 |
|
192 |
---
|
193 |
+
*Note: The dream analysis was successful, but we encountered an issue generating the visualization prompt.*
|
194 |
"""
|
|
|
195 |
|
196 |
except Exception as e:
|
197 |
error_message = str(e)
|
|
|
203 |
try:
|
204 |
if not user_name or not user_name.strip():
|
205 |
user_name = "Anonymous"
|
206 |
+
else:
|
207 |
+
user_name = user_name.strip()
|
208 |
|
209 |
# Create dreams directory if it doesn't exist
|
210 |
os.makedirs("dreams", exist_ok=True)
|
211 |
|
212 |
# Create a filename based on user and timestamp
|
213 |
timestamp = time.strftime("%Y%m%d-%H%M%S")
|
214 |
+
safe_username = ''.join(c if c.isalnum() or c == '_' else '_' for c in user_name.replace(' ', '_'))
|
215 |
+
filename = f"dreams/{safe_username}_{timestamp}.json"
|
216 |
|
217 |
# Create the dream data
|
218 |
dream_data = {
|
|
|
245 |
|
246 |
# Define the process function for dream analysis
|
247 |
def process_dream(api_key, dream_description, include_visualization, user_name):
|
248 |
+
# Show processing message
|
249 |
+
yield "Processing your dream... Please wait."
|
250 |
+
|
251 |
# If API key changed or not set up, configure it first
|
252 |
if not interpreter.client or api_key.strip() != interpreter.api_key:
|
253 |
setup_message = interpreter.setup_client(api_key)
|
254 |
if "successfully" not in setup_message:
|
255 |
+
yield setup_message
|
256 |
+
return
|
257 |
|
258 |
# Validate dream description
|
259 |
if not dream_description or not dream_description.strip():
|
260 |
+
yield "Please enter a dream description."
|
261 |
+
return
|
262 |
|
263 |
# Perform analysis
|
264 |
analysis = interpreter.analyze_dream(dream_description, include_visualization, user_name)
|
265 |
+
yield analysis
|
266 |
|
267 |
# Define the save function
|
268 |
def save_dream_entry(api_key, user_name, dream_description, analysis_output):
|
269 |
+
if not analysis_output or analysis_output == "Processing your dream... Please wait." or "Error" in analysis_output:
|
270 |
return "Nothing to save or analysis contains errors."
|
271 |
|
272 |
if not interpreter.client or api_key.strip() != interpreter.api_key:
|
|
|
336 |
3. Click "Analyze Dream"
|
337 |
4. Optionally save your analysis
|
338 |
|
339 |
+
### Troubleshooting:
|
340 |
+
- If you encounter an error, make sure your API key is valid and has access to the Gemini 2.5 Flash Preview model
|
341 |
+
- Check that your OpenRouter account has sufficient credits
|
342 |
+
- Try a shorter dream description if you're experiencing timeout issues
|
343 |
+
|
344 |
### Requirements:
|
345 |
- An OpenRouter API key with access to Google's Gemini 2.5 Flash Preview model
|
346 |
""")
|