pleabargain commited on
Commit
2064073
·
verified ·
1 Parent(s): 0b8a486

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -85
app.py CHANGED
@@ -1,9 +1,12 @@
1
  import gradio as gr
2
  import datetime
3
- from typing import Dict, List, Tuple
4
  import random
5
  from huggingface_hub import InferenceClient
6
 
 
 
 
7
  class TravelPlanner:
8
  def __init__(self):
9
  self.accommodation_types = {
@@ -34,14 +37,6 @@ class TravelPlanner:
34
  budget_level: str) -> List[Dict]:
35
  """
36
  Generate a daily itinerary based on destination and budget level
37
-
38
- Args:
39
- destination: Name of the destination
40
- num_days: Number of days for the trip
41
- budget_level: luxury/mid_range/budget/hostel
42
-
43
- Returns:
44
- List of daily activities and estimated times
45
  """
46
  itinerary = []
47
 
@@ -74,37 +69,24 @@ class TravelPlanner:
74
  num_people: int) -> Dict:
75
  """
76
  Calculate estimated budget based on duration and comfort level
77
-
78
- Args:
79
- num_days: Number of days for the trip
80
- budget_level: luxury/mid_range/budget/hostel
81
- num_people: Number of travelers
82
-
83
- Returns:
84
- Dictionary with budget breakdown
85
  """
86
- # Get cost ranges based on budget level
87
  accommodation_range = self.accommodation_types[budget_level]
88
  meal_range = self.meal_costs[budget_level]
89
 
90
- # Calculate daily costs
91
  daily_accommodation = random.uniform(*accommodation_range)
92
  daily_meals = random.uniform(*meal_range) * 3 # 3 meals per day
93
  daily_activities = random.uniform(30, 100) # Average activity cost
94
  daily_transport = random.uniform(10, 50) # Local transport
95
 
96
- # Calculate total costs
97
  total_accommodation = daily_accommodation * num_days
98
  total_meals = daily_meals * num_days
99
  total_activities = daily_activities * num_days
100
  total_transport = daily_transport * num_days
101
 
102
- # Multiply by number of people (except accommodation which is per room)
103
  total_meals *= num_people
104
  total_activities *= num_people
105
  total_transport *= num_people
106
 
107
- # Add 10% buffer for miscellaneous expenses
108
  buffer = (total_accommodation + total_meals + total_activities + total_transport) * 0.1
109
 
110
  total_cost = total_accommodation + total_meals + total_activities + total_transport + buffer
@@ -124,14 +106,6 @@ class TravelPlanner:
124
  budget: Dict) -> str:
125
  """
126
  Format the itinerary and budget into a readable string
127
-
128
- Args:
129
- destination: Name of the destination
130
- itinerary: List of daily activities
131
- budget: Dictionary of budget breakdown
132
-
133
- Returns:
134
- Formatted string with itinerary and budget
135
  """
136
  output = f"Travel Plan for {destination}\n\n"
137
  output += "=== ITINERARY ===\n\n"
@@ -153,66 +127,75 @@ class TravelPlanner:
153
 
154
  return output
155
 
156
- def generate_travel_plan(destination: str,
157
- num_days: int,
158
- budget_level: str,
159
- num_people: int) -> str:
160
- """
161
- Main function to generate complete travel plan
162
-
163
- Args:
164
- destination: Name of the destination
165
- num_days: Number of days for the trip
166
- budget_level: luxury/mid_range/budget/hostel
167
- num_people: Number of travelers
168
-
169
- Returns:
170
- Formatted string with complete travel plan
171
  """
172
- planner = TravelPlanner()
173
- itinerary = planner.generate_itinerary(destination, num_days, budget_level)
174
- budget = planner.calculate_budget(num_days, budget_level, num_people)
175
- return planner.format_output(destination, itinerary, budget)
176
-
177
- # Integration with your Gradio interface
178
- def respond_with_travel_plan(message: str,
179
- history: List[Tuple[str, str]],
180
- system_message: str,
181
- max_tokens: int,
182
- temperature: float,
183
- top_p: float) -> str:
184
  """
185
- Modified respond function to handle travel planning requests
186
- """
187
- # Parse the input message for travel parameters
188
- # This is a simple example - you might want to add more sophisticated parsing
189
- try:
190
- # Example message format: "Plan a trip to Paris for 5 days, mid_range budget, 2 people"
191
- parts = message.lower().split()
192
- destination_idx = parts.index("to") + 1
193
- days_idx = parts.index("days") - 1
194
- budget_idx = parts.index("budget") - 1
195
- people_idx = parts.index("people") - 1
196
-
197
- destination = parts[destination_idx].capitalize()
198
- num_days = int(parts[days_idx])
199
- budget_level = parts[budget_idx]
200
- num_people = int(parts[people_idx])
201
-
202
- # Generate travel plan
203
- response = generate_travel_plan(destination, num_days, budget_level, num_people)
204
- return response
205
-
206
- except (ValueError, IndexError):
207
- return "I couldn't understand your travel request. Please use the format: 'Plan a trip to [destination] for [X] days, [budget_level] budget, [X] people'"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
- # Update your main Gradio interface
210
  demo = gr.ChatInterface(
211
- respond_with_travel_plan,
212
  additional_inputs=[
213
- gr.Textbox(value="You are a travel planning assistant.", label="System message"),
 
214
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
215
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
216
- gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
 
217
  ],
218
- )
 
 
 
 
 
 
1
  import gradio as gr
2
  import datetime
3
+ from typing import Dict, List
4
  import random
5
  from huggingface_hub import InferenceClient
6
 
7
+ # Initialize the Hugging Face client
8
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
9
+
10
  class TravelPlanner:
11
  def __init__(self):
12
  self.accommodation_types = {
 
37
  budget_level: str) -> List[Dict]:
38
  """
39
  Generate a daily itinerary based on destination and budget level
 
 
 
 
 
 
 
 
40
  """
41
  itinerary = []
42
 
 
69
  num_people: int) -> Dict:
70
  """
71
  Calculate estimated budget based on duration and comfort level
 
 
 
 
 
 
 
 
72
  """
 
73
  accommodation_range = self.accommodation_types[budget_level]
74
  meal_range = self.meal_costs[budget_level]
75
 
 
76
  daily_accommodation = random.uniform(*accommodation_range)
77
  daily_meals = random.uniform(*meal_range) * 3 # 3 meals per day
78
  daily_activities = random.uniform(30, 100) # Average activity cost
79
  daily_transport = random.uniform(10, 50) # Local transport
80
 
 
81
  total_accommodation = daily_accommodation * num_days
82
  total_meals = daily_meals * num_days
83
  total_activities = daily_activities * num_days
84
  total_transport = daily_transport * num_days
85
 
 
86
  total_meals *= num_people
87
  total_activities *= num_people
88
  total_transport *= num_people
89
 
 
90
  buffer = (total_accommodation + total_meals + total_activities + total_transport) * 0.1
91
 
92
  total_cost = total_accommodation + total_meals + total_activities + total_transport + buffer
 
106
  budget: Dict) -> str:
107
  """
108
  Format the itinerary and budget into a readable string
 
 
 
 
 
 
 
 
109
  """
110
  output = f"Travel Plan for {destination}\n\n"
111
  output += "=== ITINERARY ===\n\n"
 
127
 
128
  return output
129
 
130
+ def respond(
131
+ message: str,
132
+ history: List[Dict[str, str]], # Updated to use dict format
133
+ system_message: str,
134
+ max_tokens: int,
135
+ temperature: float,
136
+ top_p: float
137
+ ) -> str:
 
 
 
 
 
 
 
138
  """
139
+ Process chat message and generate travel plan if requested
 
 
 
 
 
 
 
 
 
 
 
140
  """
141
+ # Check if this is a travel planning request
142
+ if "plan a trip" in message.lower():
143
+ try:
144
+ # Parse the message
145
+ parts = message.lower().split()
146
+ destination_idx = parts.index("to") + 1
147
+ days_idx = parts.index("days") - 1
148
+ budget_idx = parts.index("budget") - 1
149
+ people_idx = parts.index("people") - 1
150
+
151
+ destination = parts[destination_idx].capitalize()
152
+ num_days = int(parts[days_idx])
153
+ budget_level = parts[budget_idx]
154
+ num_people = int(parts[people_idx])
155
+
156
+ # Generate travel plan
157
+ planner = TravelPlanner()
158
+ itinerary = planner.generate_itinerary(destination, num_days, budget_level)
159
+ budget = planner.calculate_budget(num_days, budget_level, num_people)
160
+ return planner.format_output(destination, itinerary, budget)
161
+
162
+ except (ValueError, IndexError):
163
+ return "I couldn't understand your travel request. Please use the format: 'Plan a trip to [destination] for [X] days, [budget_level] budget, [X] people'"
164
+
165
+ # If not a travel request, use the Hugging Face model
166
+ messages = [{"role": "system", "content": system_message}]
167
+
168
+ # Convert history to the correct format
169
+ for msg in history:
170
+ messages.append({"role": msg["role"], "content": msg["content"]})
171
+
172
+ messages.append({"role": "user", "content": message})
173
+
174
+ response = ""
175
+ for token in client.chat_completion(
176
+ messages,
177
+ max_tokens=max_tokens,
178
+ stream=True,
179
+ temperature=temperature,
180
+ top_p=top_p,
181
+ ):
182
+ response += token.choices[0].delta.content
183
+ return response
184
 
185
+ # Create the Gradio interface with updated message format
186
  demo = gr.ChatInterface(
187
+ respond,
188
  additional_inputs=[
189
+ gr.Textbox(value="You are a travel planning assistant who can also chat about other topics.",
190
+ label="System message"),
191
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
192
  gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
193
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05,
194
+ label="Top-p (nucleus sampling)"),
195
  ],
196
+ message_history=True, # Enable message history
197
+ )
198
+
199
+ # Launch the application
200
+ if __name__ == "__main__":
201
+ demo.launch()