import streamlit as st
import os
import json
from datetime import datetime
import pandas as pd
try:
from openai import OpenAI
except ImportError:
st.error("OpenAI package not installed. Please add 'openai' to requirements.txt")
st.stop()
# Configure page
st.set_page_config(
page_title="🛥️ Smart Boat Insurance Calculator",
page_icon="🛥️",
layout="wide",
initial_sidebar_state="expanded"
)
# Initialize OpenAI client
@st.cache_resource
def init_openai():
# Try multiple ways to get the API key
api_key = None
# Method 1: Try Streamlit secrets (for local development)
try:
if hasattr(st, 'secrets') and 'OPENAI_API_KEY' in st.secrets:
api_key = st.secrets['OPENAI_API_KEY']
except:
pass
# Method 2: Try environment variables (for Hugging Face Spaces)
if not api_key:
api_key = os.getenv('OPENAI_API_KEY')
# Method 3: Try Hugging Face Spaces secrets format
if not api_key:
try:
# Hugging Face Spaces may store secrets differently
api_key = os.environ.get('OPENAI_API_KEY')
except:
pass
if not api_key:
st.error("""
🔑 OpenAI API key not found!
For Hugging Face Spaces:
1. Go to your Space Settings
2. Click on 'Repository secrets'
3. Add a new secret with:
- Name: OPENAI_API_KEY
- Value: your_openai_api_key_here
4. Restart your Space
Current environment variables available:
""" + str([k for k in os.environ.keys() if 'API' in k or 'KEY' in k]))
st.stop()
return OpenAI(api_key=api_key)
client = init_openai()
# Debug section (remove this after it works)
with st.expander("🔧 Debug Info (remove after setup)", expanded=False):
st.write("Environment variables containing 'KEY' or 'API':")
debug_vars = {k: "***" + v[-4:] if v and len(v) > 4 else "Not set"
for k, v in os.environ.items()
if 'KEY' in k.upper() or 'API' in k.upper()}
st.json(debug_vars)
st.write("Streamlit secrets available:")
try:
secret_keys = list(st.secrets.keys()) if hasattr(st, 'secrets') else []
st.write(secret_keys)
except:
st.write("No secrets accessible via st.secrets")
# Custom CSS for better styling
st.markdown("""
""", unsafe_allow_html=True)
# Header
st.markdown("""
🛥️ Smart Boat Insurance Calculator
Get instant premium estimates and state-specific legal requirements for your boat insurance
""", unsafe_allow_html=True)
# Sidebar for navigation
st.sidebar.title("🧭 Navigation")
tool_choice = st.sidebar.radio(
"Choose a tool:",
["💰 Premium Calculator", "📋 State Legal Checklist", "📊 Compare Both"]
)
# Function to get premium estimate
def get_premium_estimate(boat_data):
prompt = f"""
As a boat insurance expert, provide a monthly premium estimate for a boat with these details:
Boat Type: {boat_data['type']}
Boat Age: {boat_data['age']} years
Boat Value: ${boat_data['value']:,}
Location: {boat_data['location']}
Primary Use: {boat_data['usage']}
Experience Level: {boat_data['experience']}
Safety Features: {boat_data['safety_features']}
Storage Location: {boat_data['storage']}
Annual Usage: {boat_data['annual_hours']} hours
Please provide:
1. A realistic monthly premium range (low-high)
2. Key factors affecting the price
3. Money-saving tips specific to this boat profile
4. Coverage recommendations
Format as JSON with keys: premium_low, premium_high, factors, tips, coverage_recommendations
"""
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.3
)
return response.choices[0].message.content
except Exception as e:
return f"Error getting estimate: {str(e)}"
# Function to get state-specific checklist
def get_state_checklist(state, boat_type="General"):
prompt = f"""
As a boat insurance legal expert, provide a comprehensive checklist of boat insurance requirements and recommendations for {state}.
Boat Type: {boat_type}
Please provide:
1. Mandatory insurance requirements (if any)
2. Recommended coverage types
3. Minimum liability limits
4. Special state-specific considerations
5. Registration and documentation requirements
6. Penalty information for non-compliance
Format as a detailed checklist with clear action items.
"""
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.2
)
return response.choices[0].message.content
except Exception as e:
return f"Error getting checklist: {str(e)}"
# Premium Calculator Tool
if tool_choice in ["💰 Premium Calculator", "📊 Compare Both"]:
st.markdown('', unsafe_allow_html=True)
st.header("💰 Boat Insurance Premium Calculator")
st.write("Get an AI-powered estimate of your boat insurance costs")
col1, col2 = st.columns(2)
with col1:
st.subheader("Boat Details")
boat_type = st.selectbox(
"Boat Type",
["Sailboat", "Motorboat", "Yacht", "Pontoon", "Fishing Boat", "Jet Ski", "Speedboat", "Catamaran", "Other"]
)
boat_age = st.slider("Boat Age (years)", 0, 50, 10)
boat_value = st.number_input(
"Estimated Boat Value ($)",
min_value=1000,
max_value=10000000,
value=50000,
step=5000
)
location = st.selectbox(
"Primary Location",
["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut",
"Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire",
"New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
"Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia",
"Wisconsin", "Wyoming"]
)
with col2:
st.subheader("Usage & Experience")
usage = st.selectbox(
"Primary Use",
["Recreational", "Fishing", "Racing", "Commercial", "Charter", "Liveaboard"]
)
experience = st.selectbox(
"Boating Experience",
["Beginner (0-2 years)", "Intermediate (3-10 years)", "Experienced (10+ years)", "Professional"]
)
safety_features = st.multiselect(
"Safety Features",
["GPS/Navigation System", "Life Jackets", "Fire Extinguisher", "Flares", "Radio/VHF",
"Anchor", "First Aid Kit", "Bilge Pump", "EPIRB", "Radar"]
)
storage = st.selectbox(
"Storage Location",
["Marina", "Home (Driveway)", "Storage Facility", "Dry Stack", "Mooring"]
)
annual_hours = st.slider("Annual Usage (hours)", 0, 500, 100)
if st.button("Calculate Premium Estimate", type="primary"):
with st.spinner("Calculating your premium estimate..."):
boat_data = {
'type': boat_type,
'age': boat_age,
'value': boat_value,
'location': location,
'usage': usage,
'experience': experience,
'safety_features': ', '.join(safety_features) if safety_features else 'None specified',
'storage': storage,
'annual_hours': annual_hours
}
result = get_premium_estimate(boat_data)
st.markdown('
', unsafe_allow_html=True)
st.subheader("📊 Your Premium Estimate")
st.write(result)
st.markdown('
', unsafe_allow_html=True)
# Lead capture
st.markdown("---")
st.subheader("📧 Get Personalized Quotes from Top Insurers")
email = st.text_input("Enter your email for personalized quotes:")
phone = st.text_input("Phone number (optional):")
if st.button("Get My Quotes"):
st.success("Thank you! We'll send you personalized quotes from our partner insurers within 24 hours.")
# Here you would integrate with your CRM/email system
st.markdown('
', unsafe_allow_html=True)
# State Legal Checklist Tool
if tool_choice in ["📋 State Legal Checklist", "📊 Compare Both"]:
st.markdown('', unsafe_allow_html=True)
st.header("📋 State-by-State Legal Requirements")
st.write("Get a customized checklist of insurance requirements for your state")
col1, col2 = st.columns(2)
with col1:
selected_state = st.selectbox(
"Select Your State",
["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut",
"Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire",
"New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
"Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia",
"Wisconsin", "Wyoming"],
key="state_selector"
)
with col2:
checklist_boat_type = st.selectbox(
"Boat Type (for specific requirements)",
["General", "Sailboat", "Motorboat", "Yacht", "Pontoon", "Fishing Boat", "Jet Ski", "Commercial Vessel"],
key="checklist_boat_type"
)
if st.button("Generate Legal Checklist", type="primary"):
with st.spinner(f"Generating legal requirements for {selected_state}..."):
checklist = get_state_checklist(selected_state, checklist_boat_type)
st.markdown('
', unsafe_allow_html=True)
st.subheader(f"📋 {selected_state} Boat Insurance Legal Checklist")
st.write(checklist)
st.markdown('
', unsafe_allow_html=True)
# Download option
if st.button("📄 Download Checklist as PDF"):
st.info("PDF download feature would be implemented here")
st.markdown('
', unsafe_allow_html=True)
# Additional features
st.markdown("---")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
### 🎯 Why Choose Our Tool?
- AI-powered accurate estimates
- State-specific legal guidance
- Instant results
- Free to use
""")
with col2:
st.markdown("""
### 📞 Need Help?
- Expert consultation available
- Compare multiple insurers
- Claims assistance
- 24/7 support
""")
with col3:
st.markdown("""
### 💡 Pro Tips
- Update coverage annually
- Bundle with auto insurance
- Take boating safety courses
- Install safety equipment
""")
# Footer with disclaimer
st.markdown("---")
st.markdown("""
⚠️ Important Disclaimer: This tool provides estimates for informational purposes only.
Actual premiums may vary based on additional factors. Always consult with licensed insurance agents
for official quotes and coverage details.
""", unsafe_allow_html=True)
st.markdown("""
Made with ❤️ for boat owners | Powered by AI | © 2025 Smart Boat Insurance
""", unsafe_allow_html=True)