arnabbumba077 commited on
Commit
6b37c01
·
verified ·
1 Parent(s): fa5d9eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -131
app.py CHANGED
@@ -1,131 +1,122 @@
1
- import os
2
- import streamlit as st
3
- from dotenv import load_dotenv
4
- from langchain_core.messages import AIMessage, HumanMessage
5
- from langchain_community.llms import HuggingFaceEndpoint
6
- from langchain_core.output_parsers import StrOutputParser
7
- from langchain_core.prompts import ChatPromptTemplate
8
- import folium
9
- from streamlit_folium import st_folium
10
- from geopy.geocoders import Nominatim
11
-
12
- # Load environment variables
13
- load_dotenv()
14
-
15
- api_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
16
-
17
- repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
18
- task = "text-generation"
19
-
20
- # Streamlit configuration
21
- st.set_page_config(page_title="Travel Planner.AI", page_icon="🌍")
22
- st.title("Travel Planner.AI ✈️")
23
-
24
- # Prompt template for the travel assistant
25
- template = """
26
- You are a travel assistant chatbot named Travel Planner.AI designed to help users plan their trips and provide travel-related information. Here are some scenarios you should be able to handle:
27
-
28
- 1. Booking Flights: Assist users with booking flights to their desired destinations. Ask for departure city, destination city, travel dates, and any specific preferences (e.g., direct flights, airline preferences). Check available airlines and book the tickets accordingly.
29
-
30
- 2. Booking Hotels, Hostels etc: Help users find and book accommodations. Inquire about city or region, check-in/check-out dates, number of guests, and accommodation preferences (e.g., budget, amenities).
31
-
32
- 3. Booking Rental Cars: Facilitate the booking of rental cars for travel convenience. Gather details such as pickup/drop-off locations, dates, car preferences (e.g., size, type), and any additional requirements.
33
-
34
- 4. Destination Information: Provide information about popular travel destinations. Offer insights on attractions, local cuisine, cultural highlights, weather conditions, and best times to visit.
35
-
36
- 5. Travel Tips: Offer practical travel tips and advice. Topics may include packing essentials, visa requirements, currency exchange, local customs, and safety tips.
37
-
38
- 6. Weather Updates: Give current weather updates for specific destinations or regions. Include temperature forecasts, precipitation chances, and any weather advisories.
39
-
40
- 7. Local Attractions and Hidden Gems: Suggest local attractions and points of interest based on the user's destination. Highlight must-see landmarks, museums, parks, and recreational activities. Also give some hidden gem locations which tourists don’t go to but are awesome.
41
-
42
- 8. Customer Service: Address customer service inquiries and provide assistance with travel-related issues. Handle queries about bookings, cancellations, refunds, and general support.
43
-
44
- Please ensure responses are informative, accurate, and tailored to the user's queries and preferences. Use natural language to engage users and provide a seamless experience throughout their travel planning journey.
45
-
46
- Chat history:
47
- {chat_history}
48
-
49
- User question:
50
- {user_question}
51
- """
52
-
53
- prompt = ChatPromptTemplate.from_template(template)
54
-
55
- def get_response(user_query, chat_history):
56
- llm = HuggingFaceEndpoint(
57
- huggingfacehub_api_token=api_token,
58
- repo_id=repo_id,
59
- task=task
60
- )
61
- chain = prompt | llm | StrOutputParser()
62
- response = chain.invoke({"chat_history": chat_history, "user_question": user_query})
63
- return response
64
-
65
- if "chat_history" not in st.session_state:
66
- st.session_state.chat_history = [AIMessage(content="Hello, I am Travel Planner.AI. How can I help you?")]
67
-
68
- # Geolocator for reverse geocoding
69
- geolocator = Nominatim(user_agent="travel_planner")
70
-
71
- # Function to reverse geocode coordinates
72
- def get_place_name(lat, lon):
73
- location = geolocator.reverse((lat, lon), language='en')
74
- return location.address if location else "Unknown location"
75
-
76
- # Add a map to the Streamlit app
77
- st.subheader("Select Your Travel Route")
78
- m = folium.Map(location=[20, 0], zoom_start=2, tiles="CartoDB Positron")
79
-
80
- if "departure_location" not in st.session_state:
81
- st.session_state.departure_location = None
82
- if "destination_location" not in st.session_state:
83
- st.session_state.destination_location = None
84
-
85
- # User selects departure location
86
- st.write("Select your departure location:")
87
- departure = st_folium(m, height=350, width=700, key="departure")
88
-
89
- if departure and departure['last_clicked']:
90
- lat, lon = departure['last_clicked']['lat'], departure['last_clicked']['lng']
91
- departure_location = get_place_name(lat, lon)
92
- st.session_state.departure_location = departure_location
93
- st.write(f"Departure Location: {departure_location}")
94
-
95
- # User selects destination location
96
- st.write("Select your destination location:")
97
- destination = st_folium(m, height=350, width=700, key="destination")
98
-
99
- if destination and destination['last_clicked']:
100
- lat, lon = destination['last_clicked']['lat'], destination['last_clicked']['lng']
101
- destination_location = get_place_name(lat, lon)
102
- st.session_state.destination_location = destination_location
103
- st.write(f"Destination Location: {destination_location}")
104
-
105
- for message in st.session_state.chat_history:
106
- if isinstance(message, AIMessage):
107
- with st.chat_message("AI"):
108
- st.write(message.content)
109
- elif isinstance(message, HumanMessage):
110
- with st.chat_message("Human"):
111
- st.write(message.content)
112
-
113
- user_query = st.chat_input("Type your message here...")
114
- if user_query:
115
- # Include selected locations in the user query
116
- if st.session_state.departure_location and st.session_state.destination_location:
117
- user_query = f"From: {st.session_state.departure_location}\nTo: {st.session_state.destination_location}\n{user_query}"
118
-
119
- st.session_state.chat_history.append(HumanMessage(content=user_query))
120
-
121
- with st.chat_message("Human"):
122
- st.markdown(user_query)
123
-
124
- response = get_response(user_query, st.session_state.chat_history)
125
-
126
- response = response.replace("AI response:", "").replace("chat response:", "").replace("bot response:", "").strip()
127
-
128
- with st.chat_message("AI"):
129
- st.write(response)
130
-
131
- st.session_state.chat_history.append(AIMessage(content=response))
 
1
+ import os
2
+ import streamlit as st
3
+ from dotenv import load_dotenv
4
+ from langchain_core.messages import AIMessage, HumanMessage
5
+ from langchain_core.output_parsers import StrOutputParser
6
+ from langchain_core.prompts import ChatPromptTemplate
7
+ from langchain_groq import ChatGroq
8
+ import folium
9
+ from streamlit_folium import st_folium
10
+ from geopy.geocoders import Nominatim
11
+
12
+ # Load environment variables
13
+ load_dotenv()
14
+ groq_api_key = os.getenv("GROQ_API_KEY")
15
+
16
+ # Streamlit configuration
17
+ st.set_page_config(page_title="Travel Planner.AI", page_icon="🌍")
18
+ st.title("Travel Planner.AI ✈️")
19
+
20
+ # Prompt template
21
+ template = """
22
+ You are a travel assistant chatbot named Travel Planner.AI designed to help users plan their trips and provide travel-related information. Here are some scenarios you should be able to handle:
23
+
24
+ 1. Booking Flights: Assist users with booking flights to their desired destinations. Ask for departure city, destination city, travel dates, and any specific preferences (e.g., direct flights, airline preferences). Check available airlines and book the tickets accordingly.
25
+
26
+ 2. Booking Hotels, Hostels etc: Help users find and book accommodations. Inquire about city or region, check-in/check-out dates, number of guests, and accommodation preferences (e.g., budget, amenities).
27
+
28
+ 3. Booking Rental Cars: Facilitate the booking of rental cars for travel convenience. Gather details such as pickup/drop-off locations, dates, car preferences (e.g., size, type), and any additional requirements.
29
+
30
+ 4. Destination Information: Provide information about popular travel destinations. Offer insights on attractions, local cuisine, cultural highlights, weather conditions, and best times to visit.
31
+
32
+ 5. Travel Tips: Offer practical travel tips and advice. Topics may include packing essentials, visa requirements, currency exchange, local customs, and safety tips.
33
+
34
+ 6. Weather Updates: Give current weather updates for specific destinations or regions. Include temperature forecasts, precipitation chances, and any weather advisories.
35
+
36
+ 7. Local Attractions and Hidden Gems: Suggest local attractions and points of interest based on the user's destination. Highlight must-see landmarks, museums, parks, and recreational activities. Also give some hidden gem locations which tourists don’t go to but are awesome.
37
+
38
+ 8. Customer Service: Address customer service inquiries and provide assistance with travel-related issues. Handle queries about bookings, cancellations, refunds, and general support.
39
+
40
+ Please ensure responses are informative, accurate, and tailored to the user's queries and preferences. Use natural language to engage users and provide a seamless experience throughout their travel planning journey.
41
+
42
+ Chat history:
43
+ {chat_history}
44
+
45
+ User question:
46
+ {user_question}
47
+ """
48
+
49
+ prompt = ChatPromptTemplate.from_template(template)
50
+
51
+ # GROQ LLM response
52
+ def get_response(user_query, chat_history):
53
+ llm = ChatGroq(
54
+ groq_api_key=groq_api_key,
55
+ model_name="llama-3.3-70b-versatile"
56
+ )
57
+ chain = prompt | llm | StrOutputParser()
58
+ response = chain.invoke({"chat_history": chat_history, "user_question": user_query})
59
+ return response
60
+
61
+ # Initialize chat history
62
+ if "chat_history" not in st.session_state:
63
+ st.session_state.chat_history = [AIMessage(content="Hello, I am Travel Planner.AI. How can I help you?")]
64
+
65
+ # Geolocator setup
66
+ geolocator = Nominatim(user_agent="travel_planner")
67
+
68
+ def get_place_name(lat, lon):
69
+ location = geolocator.reverse((lat, lon), language='en')
70
+ return location.address if location else "Unknown location"
71
+
72
+ # Display map
73
+ st.subheader("Select Your Travel Route")
74
+ m = folium.Map(location=[20, 0], zoom_start=2, tiles="CartoDB Positron")
75
+
76
+ # Initialize session state for locations
77
+ if "departure_location" not in st.session_state:
78
+ st.session_state.departure_location = None
79
+ if "destination_location" not in st.session_state:
80
+ st.session_state.destination_location = None
81
+
82
+ # Departure selection
83
+ st.write("Select your departure location:")
84
+ departure = st_folium(m, height=350, width=700, key="departure")
85
+ if departure and departure['last_clicked']:
86
+ lat, lon = departure['last_clicked']['lat'], departure['last_clicked']['lng']
87
+ location = get_place_name(lat, lon)
88
+ st.session_state.departure_location = location
89
+ st.write(f"Departure Location: {location}")
90
+
91
+ # Destination selection
92
+ st.write("Select your destination location:")
93
+ destination = st_folium(m, height=350, width=700, key="destination")
94
+ if destination and destination['last_clicked']:
95
+ lat, lon = destination['last_clicked']['lat'], destination['last_clicked']['lng']
96
+ location = get_place_name(lat, lon)
97
+ st.session_state.destination_location = location
98
+ st.write(f"Destination Location: {location}")
99
+
100
+ # Display previous messages
101
+ for message in st.session_state.chat_history:
102
+ with st.chat_message("AI" if isinstance(message, AIMessage) else "Human"):
103
+ st.write(message.content)
104
+
105
+ # Chat input
106
+ user_query = st.chat_input("Type your message here...")
107
+ if user_query:
108
+ # Attach location context to query
109
+ if st.session_state.departure_location and st.session_state.destination_location:
110
+ user_query = f"From: {st.session_state.departure_location}\nTo: {st.session_state.destination_location}\n{user_query}"
111
+
112
+ st.session_state.chat_history.append(HumanMessage(content=user_query))
113
+ with st.chat_message("Human"):
114
+ st.markdown(user_query)
115
+
116
+ response = get_response(user_query, st.session_state.chat_history)
117
+ response = response.replace("AI response:", "").strip()
118
+
119
+ with st.chat_message("AI"):
120
+ st.write(response)
121
+
122
+ st.session_state.chat_history.append(AIMessage(content=response))