Akj2023's picture
Fix spinner with new UI
d203c46
import streamlit as st
from datetime import datetime, timedelta, date
from config import load_secrets
from agents.agent import Agent
# Load the API secrets at the start of your app
secrets = load_secrets()
# Assuming you only need the OPENAI_API_KEY for this test
agent = Agent(openai_api_key=secrets["OPENAI_API_KEY"], debug=True)
# Then use the secrets as needed, for example
openai_api_key = secrets["OPENAI_API_KEY"]
google_maps_api_key = secrets["GOOGLE_MAPS_API_KEY"]
google_palm_api_key = secrets["GOOGLE_PALM_API_KEY"]
# Title of the application
st.title('Smart Travel Itinerary Suggester')
# Update this function to be used as an on_change callback for the start_date
def update_end_date():
# If end_date is before start_date, set it to one day after start_date
if 'end_date' in st.session_state and st.session_state['end_date'] <= st.session_state['start_date']:
st.session_state['end_date'] = st.session_state['start_date'] + timedelta(days=1)
# Sidebar for input
with st.sidebar:
st.header('Enter Your Travel Details')
# Start location input
start_location = st.text_input('From', help='Enter the starting location for your trip.')
# End location input
end_location = st.text_input('To', help='Enter the final location for your trip.')
# Create the start date input widget
start_date = st.date_input(
'Start Date',
min_value=datetime.today().date(),
key='start_date',
on_change=update_end_date # This will call update_end_date whenever start_date changes
)
# Create the end date input widget
end_date = st.date_input(
'End Date',
min_value=st.session_state.get('start_date', datetime.today().date()) + timedelta(days=1),
value=st.session_state.get('end_date', st.session_state.get('start_date', datetime.today().date()) + timedelta(days=1)),
key='end_date',
help='End Date must be after the Start Date.'
)
# Preferences multiselect
attractions = st.multiselect(
'What attractions are you interested in?',
['Museums', 'Parks', 'Beaches', 'Historical Sites', 'Art Galleries', 'Famous', 'Carnivals'],
help='Select multiple options by holding down the Ctrl (Cmd on Mac) button while clicking.'
)
# Budget slider
budget = st.slider(
'Select your travel budget range',
min_value=100, max_value=5000, value=(500, 1500),
help='Drag the slider to indicate your minimum and maximum travel budget.'
)
# Transportation selectbox
transportation = st.selectbox(
'Preferred mode of transportation',
['Public Transport', 'Rental Car', 'Bike', 'Walk'],
help='Select how you plan to get around at your destination.'
)
# Accommodation radio buttons
accommodation = st.radio(
'Choose accommodation type',
['Hotel', 'Hostel', 'Airbnb', 'Apartment'],
help='Select where you prefer to stay during your trip.'
)
# Daily itinerary planner
schedule = st.selectbox(
'How packed do you want your daily schedule to be?',
['Packed', 'Balanced', 'Relaxed', 'Very Relaxed'],
help='Choose how many activities you would like to do each day.'
)
# Submit button
submit = st.button('Generate Itinerary')
# Main page layout
st.header('Your Itinerary')
# Create a loading spinner
loading_spinner = st.spinner("Generating itinerary...")
# Read custom CSS from the external file
with open("styles.css", "r") as css_file:
custom_css = css_file.read()
if submit:
missing_fields = []
if not start_location:
missing_fields.append("Start Location")
if not end_location:
missing_fields.append("End Location")
if not attractions:
missing_fields.append("Attractions")
if not start_date:
missing_fields.append("Start Date")
if not end_date:
missing_fields.append("End Date")
if not accommodation:
missing_fields.append("Accommodation")
if not schedule:
missing_fields.append("Schedule")
if not transportation:
missing_fields.append("Transportation")
if not missing_fields:
user_details = {
'start_location': start_location,
'end_location': end_location,
'start_date': start_date,
'end_date': end_date,
'attractions': attractions,
'budget': budget,
'transportation': transportation,
'accommodation': accommodation,
'schedule': schedule
}
# Display loading spinner while generating the itinerary
with loading_spinner:
# Apply custom CSS to the spinner only
st.markdown(f"<style>{custom_css}</style>", unsafe_allow_html=True)
# Call the generate_itinerary method (without artificial delay)
itinerary_result = agent.generate_itinerary(user_details)
if itinerary_result and itinerary_result["itinerary_suggestion"]:
# Display the itinerary and other information (same as before)
st.subheader("Itinerary Suggestion")
st.write(itinerary_result["itinerary_suggestion"])
st.write("List of Places:", itinerary_result["list_of_places"])
st.write("Validation Dict:", itinerary_result["validation_dict"])
elif itinerary_result and itinerary_result["itinerary_suggestion"] is None:
# Display a message for unrealistic edge cases (same as before)
st.markdown(
"""<div style='background-color:#ffebeb; padding:10px; border-radius:5px;'>
<p style='color:#ff0000; font-weight:bold;'>Error: The travel plan is not valid.</p>
<p>Please review your input and try again.</p>
</div>""",
unsafe_allow_html=True
)
else:
st.markdown(
"""<div style='background-color:#ffebeb; padding:10px; border-radius:5px;'>
<p style='color:#ff0000; font-weight:bold;'>An error occurred while generating the itinerary.</p>
<p>Please try again later or contact support.</p>
</div>""",
unsafe_allow_html=True
)
note = """Here is your personalized travel itinerary covering all the major locations you want to visit.
This map gives you a general overview of your travel route from start to finish.
For daily plans, please review the sequence of waypoints to ensure the best experience,
as the route may vary based on daily activities and traffic conditions."""
else:
st.error(f'Please fill out the following required fields: {", ".join(missing_fields)}')