pleabargain commited on
Commit
1d34f62
·
verified ·
1 Parent(s): 357b49d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -67
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import json
 
4
 
5
  # Hotel data
6
  HOTELS = [
@@ -36,19 +37,127 @@ HOTELS = [
36
  }
37
  ]
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
40
 
41
- def get_suitable_hotels(budget_per_day, holiday_type):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  suitable_hotels = []
43
  for hotel in HOTELS:
44
- if hotel["pricingPerDay"] <= budget_per_day:
45
- # Match hotel type with holiday preference
46
- if (holiday_type == "Relaxation & Wellness" and ("Haven" in hotel["name"] or "Retreat" in hotel["name"])) or \
47
- (holiday_type == "Adventure & Outdoor" and ("Mountain" in hotel["name"] or "Sands" in hotel["name"])) or \
48
- (holiday_type == "Cultural & Sightseeing" and "Urban" in hotel["name"]) or \
49
- (holiday_type == "Family-Friendly" and "Family" in str(hotel["roomTypes"])):
50
- suitable_hotels.append(hotel)
51
- return suitable_hotels if suitable_hotels else HOTELS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  def generate_itinerary(
54
  destination: str,
@@ -61,37 +170,43 @@ def generate_itinerary(
61
  temperature: float,
62
  top_p: float,
63
  ) -> str:
64
- # Calculate budget per day (excluding transportation)
65
- daily_budget = (budget - (budget * 0.3)) / num_days # Assuming 30% for transportation
 
 
66
 
67
- # Get suitable hotels based on budget and holiday type
68
- recommended_hotels = get_suitable_hotels(daily_budget * 0.4, holiday_type) # Assuming 40% of daily budget for accommodation
69
 
70
- # Create hotel recommendations string
71
- hotel_recommendations = "\n".join([
72
- f"- {hotel['name']} (${hotel['pricingPerDay']}/day): {hotel['description']}"
73
- for hotel in recommended_hotels[:2] # Recommend top 2 hotels
74
- ])
 
 
75
 
76
- # Construct a detailed prompt for the AI
77
- prompt = f"""Create a detailed {num_days}-day travel itinerary for a trip:
78
- - From: {origin}
79
- - To: {destination}
80
- - Total Budget: ${budget} (approximately ${daily_budget:.2f} per day after transportation)
81
- - Type of Holiday: {holiday_type}
82
-
83
- Consider these recommended accommodations based on the budget and preferences:
84
- {hotel_recommendations}
85
-
86
- Please include in your itinerary:
87
- 1. A day-by-day breakdown of activities and sightseeing
88
- 2. Estimated costs for each activity
89
- 3. Suggested accommodation from the recommended hotels above
90
- 4. Local transportation recommendations
91
- 5. Must-try local food spots and estimated meal costs
92
- 6. Any money-saving tips
93
 
94
- Format the response with clear day-by-day breakdown and keep track of the budget."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  messages = [
97
  {"role": "system", "content": system_message},
@@ -99,7 +214,6 @@ def generate_itinerary(
99
  ]
100
 
101
  response = ""
102
-
103
  for message in client.chat_completion(
104
  messages,
105
  max_tokens=max_tokens,
@@ -111,34 +225,27 @@ def generate_itinerary(
111
  response += token
112
  yield response
113
 
 
114
  # Create the Gradio interface
115
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
116
  gr.Markdown("# 🌎 AI Travel Itinerary Generator ✈️")
117
- gr.Markdown("Enter your travel details below to get a customized itinerary with hotel recommendations!")
118
 
119
  with gr.Row():
120
  with gr.Column():
121
  origin = gr.Textbox(label="Starting Location", placeholder="e.g., New York, USA")
122
  destination = gr.Textbox(label="Destination", placeholder="e.g., Paris, France")
123
- budget = gr.Slider(minimum=500, maximum=10000, value=2000, step=100, label="Total Budget (USD)")
124
  num_days = gr.Slider(minimum=1, maximum=14, value=3, step=1, label="Number of Days")
125
  holiday_type = gr.Dropdown(
126
- choices=[
127
- "Cultural & Sightseeing",
128
- "Adventure & Outdoor",
129
- "Relaxation & Wellness",
130
- "Food & Culinary",
131
- "Budget Backpacking",
132
- "Luxury & High-End",
133
- "Family-Friendly",
134
- ],
135
  label="Type of Holiday",
136
  value="Cultural & Sightseeing"
137
  )
138
 
139
  with gr.Accordion("Advanced Settings", open=False):
140
  system_message = gr.Textbox(
141
- value="You are an experienced travel planner with extensive knowledge of destinations worldwide. Provide detailed, practical, and budget-conscious travel advice. Always recommend specific activities and keep track of the budget in the itinerary.",
142
  label="System Message",
143
  lines=3
144
  )
@@ -147,24 +254,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
147
  top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p")
148
 
149
  with gr.Row():
150
- with gr.Column():
151
- generate_button = gr.Button("Generate Itinerary", variant="primary")
152
- output = gr.Textbox(
153
- label="Your Custom Itinerary",
154
- lines=20,
155
- show_copy_button=True
156
- )
157
-
158
- # Display available hotels
159
- with gr.Accordion("Available Hotels", open=False):
160
- hotel_info = "\n\n".join([
161
- f"**{hotel['name']}**\n" +
162
- f"- Price per day: ${hotel['pricingPerDay']}\n" +
163
- f"- Room Types: {', '.join(hotel['roomTypes'])}\n" +
164
- f"- {hotel['description']}"
165
- for hotel in HOTELS
166
- ])
167
- gr.Markdown(hotel_info)
168
 
169
  generate_button.click(
170
  fn=generate_itinerary,
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import json
4
+ from typing import Dict, List, Tuple
5
 
6
  # Hotel data
7
  HOTELS = [
 
37
  }
38
  ]
39
 
40
+ # Cost constants
41
+ COST_FACTORS = {
42
+ "local_transport_per_day": {
43
+ "Budget Backpacking": 10,
44
+ "Cultural & Sightseeing": 20,
45
+ "Adventure & Outdoor": 25,
46
+ "Food & Culinary": 20,
47
+ "Relaxation & Wellness": 15,
48
+ "Luxury & High-End": 50,
49
+ "Family-Friendly": 30
50
+ },
51
+ "food_cost_per_day": {
52
+ "Budget Backpacking": 30,
53
+ "Cultural & Sightseeing": 50,
54
+ "Adventure & Outdoor": 45,
55
+ "Food & Culinary": 80,
56
+ "Relaxation & Wellness": 60,
57
+ "Luxury & High-End": 120,
58
+ "Family-Friendly": 70
59
+ },
60
+ "activities_cost_per_day": {
61
+ "Budget Backpacking": 20,
62
+ "Cultural & Sightseeing": 40,
63
+ "Adventure & Outdoor": 60,
64
+ "Food & Culinary": 45,
65
+ "Relaxation & Wellness": 80,
66
+ "Luxury & High-End": 150,
67
+ "Family-Friendly": 70
68
+ }
69
+ }
70
+
71
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
72
 
73
+ def calculate_flight_cost(origin: str, destination: str, budget: int) -> float:
74
+ """Estimate flight cost based on budget and journey type."""
75
+ # Basic estimation - can be enhanced with actual flight data API
76
+ if budget < 2000:
77
+ return budget * 0.3 # 30% of budget for budget trips
78
+ elif budget < 5000:
79
+ return budget * 0.35 # 35% for mid-range trips
80
+ else:
81
+ return budget * 0.4 # 40% for luxury trips
82
+
83
+ def calculate_daily_costs(holiday_type: str) -> Dict[str, float]:
84
+ """Calculate daily costs based on holiday type."""
85
+ return {
86
+ "local_transport": COST_FACTORS["local_transport_per_day"][holiday_type],
87
+ "food": COST_FACTORS["food_cost_per_day"][holiday_type],
88
+ "activities": COST_FACTORS["activities_cost_per_day"][holiday_type]
89
+ }
90
+
91
+ def get_suitable_hotels(budget_per_day: float, holiday_type: str) -> List[Dict]:
92
+ """Get suitable hotels based on daily budget and holiday type."""
93
+ max_hotel_budget = budget_per_day * 0.4 # 40% of daily budget for accommodation
94
+
95
  suitable_hotels = []
96
  for hotel in HOTELS:
97
+ if hotel["pricingPerDay"] <= max_hotel_budget:
98
+ match_score = 0
99
+ # Score hotels based on type match
100
+ if holiday_type == "Relaxation & Wellness" and ("Haven" in hotel["name"] or "Retreat" in hotel["name"]):
101
+ match_score += 2
102
+ elif holiday_type == "Adventure & Outdoor" and ("Mountain" in hotel["name"] or "Sands" in hotel["name"]):
103
+ match_score += 2
104
+ elif holiday_type == "Cultural & Sightseeing" and "Urban" in hotel["name"]:
105
+ match_score += 2
106
+ elif holiday_type == "Family-Friendly" and "Family" in str(hotel["roomTypes"]):
107
+ match_score += 2
108
+
109
+ suitable_hotels.append({"hotel": hotel, "match_score": match_score})
110
+
111
+ # Sort by match score and then price
112
+ sorted_hotels = sorted(suitable_hotels, key=lambda x: (-x["match_score"], x["hotel"]["pricingPerDay"]))
113
+ return [hotel["hotel"] for hotel in sorted_hotels]
114
+
115
+ def calculate_total_costs(
116
+ origin: str,
117
+ destination: str,
118
+ budget: int,
119
+ num_days: int,
120
+ holiday_type: str,
121
+ selected_hotel: Dict
122
+ ) -> Dict[str, float]:
123
+ """Calculate detailed cost breakdown."""
124
+ flight_cost = calculate_flight_cost(origin, destination, budget)
125
+ daily_costs = calculate_daily_costs(holiday_type)
126
+
127
+ accommodation_cost = selected_hotel["pricingPerDay"] * num_days
128
+ local_transport_cost = daily_costs["local_transport"] * num_days
129
+ food_cost = daily_costs["food"] * num_days
130
+ activities_cost = daily_costs["activities"] * num_days
131
+
132
+ total_cost = (
133
+ flight_cost +
134
+ accommodation_cost +
135
+ local_transport_cost +
136
+ food_cost +
137
+ activities_cost
138
+ )
139
+
140
+ return {
141
+ "flight": flight_cost,
142
+ "accommodation": accommodation_cost,
143
+ "local_transport": local_transport_cost,
144
+ "food": food_cost,
145
+ "activities": activities_cost,
146
+ "total": total_cost,
147
+ "per_day": total_cost / num_days
148
+ }
149
+
150
+ def format_cost_breakdown(costs: Dict[str, float]) -> str:
151
+ """Format cost breakdown for display."""
152
+ return f"""Cost Breakdown:
153
+ - Flight: ${costs['flight']:,.2f}
154
+ - Accommodation: ${costs['accommodation']:,.2f}
155
+ - Local Transportation: ${costs['local_transport']:,.2f}
156
+ - Food & Dining: ${costs['food']:,.2f}
157
+ - Activities & Entertainment: ${costs['activities']:,.2f}
158
+
159
+ Total Cost: ${costs['total']:,.2f}
160
+ Average Daily Cost: ${costs['per_day']:,.2f}"""
161
 
162
  def generate_itinerary(
163
  destination: str,
 
170
  temperature: float,
171
  top_p: float,
172
  ) -> str:
173
+ # Calculate initial costs and get hotel recommendations
174
+ recommended_hotels = get_suitable_hotels(budget/num_days, holiday_type)
175
+ if not recommended_hotels:
176
+ return "Error: No suitable hotels found for your budget. Please increase your budget or reduce the number of days."
177
 
178
+ selected_hotel = recommended_hotels[0]
179
+ costs = calculate_total_costs(origin, destination, budget, num_days, holiday_type, selected_hotel)
180
 
181
+ if costs["total"] > budget:
182
+ return f"""Warning: The estimated total cost (${costs['total']:,.2f}) exceeds your budget (${budget:,.2f}).
183
+ Please consider:
184
+ 1. Increasing your budget
185
+ 2. Reducing the number of days
186
+ 3. Choosing a more budget-friendly holiday type
187
+ 4. Selecting different destinations
188
 
189
+ {format_cost_breakdown(costs)}"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
+ # Construct prompt with accurate cost information
192
+ prompt = f"""Create a detailed {num_days}-day travel itinerary for a trip:
193
+ From: {origin}
194
+ To: {destination}
195
+ Budget Breakdown: {format_cost_breakdown(costs)}
196
+ Holiday Type: {holiday_type}
197
+
198
+ Recommended Accommodation:
199
+ {selected_hotel['name']} (${selected_hotel['pricingPerDay']}/night)
200
+ {selected_hotel['description']}
201
+
202
+ Please provide:
203
+ 1. Day-by-day itinerary with specific activities and timing
204
+ 2. Daily budget allocation matching the cost breakdown above
205
+ 3. Specific local transportation recommendations
206
+ 4. Restaurant suggestions within the food budget (${costs['food']/num_days:.2f}/day)
207
+ 5. Activity recommendations within the activities budget (${costs['activities']/num_days:.2f}/day)
208
+
209
+ Format as a clear day-by-day breakdown with budgets for each activity."""
210
 
211
  messages = [
212
  {"role": "system", "content": system_message},
 
214
  ]
215
 
216
  response = ""
 
217
  for message in client.chat_completion(
218
  messages,
219
  max_tokens=max_tokens,
 
225
  response += token
226
  yield response
227
 
228
+ # [Previous Gradio interface code remains the same, just update the button click handler to use the new generate_itinerary function]
229
  # Create the Gradio interface
230
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
231
  gr.Markdown("# 🌎 AI Travel Itinerary Generator ✈️")
232
+ gr.Markdown("Enter your travel details for a customized itinerary with accurate cost calculations!")
233
 
234
  with gr.Row():
235
  with gr.Column():
236
  origin = gr.Textbox(label="Starting Location", placeholder="e.g., New York, USA")
237
  destination = gr.Textbox(label="Destination", placeholder="e.g., Paris, France")
238
+ budget = gr.Slider(minimum=1000, maximum=15000, value=3000, step=100, label="Total Budget (USD)")
239
  num_days = gr.Slider(minimum=1, maximum=14, value=3, step=1, label="Number of Days")
240
  holiday_type = gr.Dropdown(
241
+ choices=list(COST_FACTORS["local_transport_per_day"].keys()),
 
 
 
 
 
 
 
 
242
  label="Type of Holiday",
243
  value="Cultural & Sightseeing"
244
  )
245
 
246
  with gr.Accordion("Advanced Settings", open=False):
247
  system_message = gr.Textbox(
248
+ value="You are an experienced travel planner. Provide detailed itineraries that strictly adhere to the given budget constraints and cost breakdown.",
249
  label="System Message",
250
  lines=3
251
  )
 
254
  top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p")
255
 
256
  with gr.Row():
257
+ generate_button = gr.Button("Generate Itinerary", variant="primary")
258
+ output = gr.Textbox(label="Your Custom Itinerary", lines=20, show_copy_button=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
 
260
  generate_button.click(
261
  fn=generate_itinerary,