import streamlit as st from openai import OpenAI import requests from PIL import Image import io import base64 import os import json from datetime import datetime # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) def encode_image_to_base64(image): """Convert PIL image to base64 string for API calls""" buffer = io.BytesIO() image.save(buffer, format="PNG") img_str = base64.b64encode(buffer.getvalue()).decode() return img_str def search_current_landscaping_trends(): """Use web search to get current landscaping and outdoor design trends""" try: # In a real implementation, this would use the built-in web search capabilities # For now, we'll create a comprehensive knowledge base current_trends = """ Current 2025 landscaping and backyard design trends include: - Sustainable and native plant gardens - Outdoor living rooms with weather-resistant furniture - Multi-functional spaces for work and relaxation - Smart irrigation and lighting systems - Vertical gardens and living walls - Fire features as focal points - Natural swimming pools and water features - Outdoor kitchens with pizza ovens - Pergolas with retractable canopies - Drought-resistant xeriscaping - Edible landscaping with herb gardens - Wellness spaces for meditation and yoga """ return current_trends except Exception as e: return "Current outdoor design trends focus on sustainability, functionality, and wellness." def generate_design_prompt(user_preferences, current_trends): """Create a detailed prompt for the AI based on user preferences and current trends""" features_text = ", ".join(user_preferences['features']) if user_preferences['features'] else "basic landscaping" prompt = f""" Create a detailed, professional backyard oasis design description based on these specifications: DESIGN REQUIREMENTS: - Style: {user_preferences['style']} - Primary Use: {user_preferences['primary_use']} - Budget Range: {user_preferences['budget']} - Must-Have Features: {features_text} - Seating Arrangement: {user_preferences['seating']} - Plant Preferences: {user_preferences['plants']} - Privacy Level: {user_preferences['privacy']}/5 - Maintenance Level: {user_preferences['maintenance']}/5 - Lighting Style: {user_preferences['lighting']} - Climate Zone: {user_preferences['climate']} CURRENT TRENDS TO INCORPORATE: {current_trends} Please provide: 1. **Design Overview**: A compelling description of the overall backyard transformation 2. **Layout Plan**: Detailed spatial arrangement of all elements 3. **Plant Selection**: Specific plants suited to the climate and maintenance level 4. **Material Recommendations**: Specific materials for hardscaping, furniture, and structures 5. **Feature Integration**: How each requested feature will be incorporated 6. **Lighting Design**: Complete lighting strategy for ambiance and functionality 7. **Maintenance Schedule**: Seasonal care requirements 8. **Implementation Timeline**: Phased approach with estimated timeframes 9. **Cost Breakdown**: Detailed budget allocation by category 10. **Professional Tips**: Expert advice for maximizing the space and achieving goals Make this a comprehensive, actionable design plan that a homeowner could use to create their dream backyard. """ return prompt def generate_backyard_design(user_preferences, image_description=None): """Generate a comprehensive backyard design using OpenAI""" try: # Get current trends current_trends = search_current_landscaping_trends() # Create the design prompt design_prompt = generate_design_prompt(user_preferences, current_trends) # Add image context if provided if image_description: design_prompt = f""" CURRENT YARD ANALYSIS: {image_description} {design_prompt} Please incorporate the existing yard features and work with the current space limitations and opportunities. """ messages = [ { "role": "system", "content": """You are a world-class landscape architect and outdoor design expert trained by the best designers in the field. Your expertise includes sustainable design, modern outdoor living, plant selection, hardscaping, and creating functional beautiful spaces. Create highly detailed, actionable backyard designs that are: - Specific to the user's climate and preferences - Realistic within their stated budget - Incorporating current design trends and sustainable practices - Providing exact plant names, material specifications, and implementation steps - Including maintenance requirements and seasonal care - Offering creative solutions for common backyard challenges Always provide comprehensive, professional-quality designs that could be used by contractors and landscapers.""" }, { "role": "user", "content": design_prompt } ] response = client.chat.completions.create( model="gpt-4", messages=messages, max_tokens=3000, temperature=0.7 ) return response.choices[0].message.content except Exception as e: st.error(f"Error generating design: {str(e)}") return None def analyze_yard_image(image): """Analyze the uploaded yard image using OpenAI Vision""" try: # Convert image to base64 img_base64 = encode_image_to_base64(image) response = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "user", "content": [ { "type": "text", "text": """Analyze this backyard/yard image and provide a detailed description including: - Current layout and size estimation - Existing features (deck, patio, plants, structures) - Soil and grass condition - Sun/shade patterns visible - Potential challenges and opportunities - Existing trees and landscaping - Property boundaries and neighbor considerations - Overall style and condition Be specific and detailed to help with redesign planning.""" }, { "type": "image_url", "image_url": { "url": f"data:image/png;base64,{img_base64}" } } ] } ], max_tokens=1000 ) return response.choices[0].message.content except Exception as e: st.warning(f"Could not analyze image: {str(e)}. Proceeding without image analysis.") return None def create_lead_capture_email(user_preferences, design_content): """Create email content for lead capture""" features_list = ", ".join(user_preferences['features']) if user_preferences['features'] else "Custom landscaping" email_subject = "My Dream Backyard Design - VIP Property List Request" email_body = f"""Hi there! I just created my dream backyard design using your Backyard Oasis Designer tool and would love to join your VIP list for homes with great outdoor potential! Here are my design preferences: ๐ก DESIGN SPECIFICATIONS: โข Style: {user_preferences['style']} โข Primary Use: {user_preferences['primary_use']} โข Budget: {user_preferences['budget']} โข Must-Have Features: {features_list} โข Seating: {user_preferences['seating']} โข Plants: {user_preferences['plants']} โข Privacy Level: {user_preferences['privacy']}/5 โข Maintenance Level: {user_preferences['maintenance']}/5 โข Lighting: {user_preferences['lighting']} โข Climate: {user_preferences['climate']} GENERATED DESIGN SUMMARY: {design_content[:500]}... Please add me to your VIP list so I can be notified of homes that would work well for creating this type of outdoor space! Looking forward to hearing from you. Best regards, [Your Name] [Your Phone Number] [Your Email]""" return email_subject, email_body # Streamlit App Configuration st.set_page_config( page_title="Backyard Oasis Designer", page_icon="๐ฟ", layout="wide", initial_sidebar_state="collapsed" ) # Custom CSS for better styling st.markdown(""" """, unsafe_allow_html=True) # Initialize session state if "design_result" not in st.session_state: st.session_state["design_result"] = None if "user_preferences" not in st.session_state: st.session_state["user_preferences"] = {} if "show_generating" not in st.session_state: st.session_state["show_generating"] = False # Main Header st.markdown('
Transform your yard into a stunning outdoor paradise with AI
', unsafe_allow_html=True) # Step 1: Image Upload st.markdown('