|
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"): |
|
"""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" |
|
} |
|
) |
|
|
|
|
|
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." |
|
|
|
|
|
dream_description = dream_description.strip() |
|
if user_name: |
|
user_name = user_name.strip() |
|
else: |
|
user_name = "Anonymous" |
|
|
|
try: |
|
|
|
print("Starting 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}" |
|
} |
|
] |
|
|
|
|
|
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 not include_visualization: |
|
return f"""## Dream Analysis |
|
{dream_analysis}""" |
|
|
|
|
|
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}" |
|
} |
|
] |
|
|
|
|
|
try: |
|
visualization_prompt = self._make_api_call(visualization_messages) |
|
|
|
|
|
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: |
|
|
|
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() |
|
|
|
|
|
os.makedirs("dreams", exist_ok=True) |
|
|
|
|
|
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" |
|
|
|
|
|
dream_data = { |
|
"user": user_name, |
|
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), |
|
"dream_description": dream_description, |
|
"analysis": analysis |
|
} |
|
|
|
|
|
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)}" |
|
|
|
|
|
|
|
def create_gradio_interface(): |
|
|
|
interpreter = DeepDreamInterpreter() |
|
|
|
|
|
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 |
|
|
|
|
|
def process_dream(api_key, dream_description, include_visualization, user_name): |
|
|
|
yield "Processing your dream... Please wait." |
|
|
|
|
|
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 |
|
|
|
|
|
if not dream_description or not dream_description.strip(): |
|
yield "Please enter a dream description." |
|
return |
|
|
|
|
|
analysis = interpreter.analyze_dream(dream_description, include_visualization, user_name) |
|
yield analysis |
|
|
|
|
|
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) |
|
|
|
|
|
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 |
|
""") |
|
|
|
|
|
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 |
|
|
|
|
|
if __name__ == "__main__": |
|
app = create_gradio_interface() |
|
app.launch() |