bhavnapatur commited on
Commit
95e130f
·
verified ·
1 Parent(s): d71ed32

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -183
app.py CHANGED
@@ -4,176 +4,42 @@ from huggingface_hub import InferenceClient
4
  import os
5
  import requests
6
  import dateparser
 
7
 
8
- travel_plan_output=""
9
 
10
- def match_europe(scores):
11
- a = scores.count("A")
12
- b = scores.count("B")
13
- c = scores.count("C")
14
- d = scores.count("D")
15
- e = scores.count("E")
16
- if a >= 5:
17
- return "Paris, France"
18
- elif b >=5:
19
- return "Tokyo, Japan"
20
- elif c >= 5:
21
- return "Bali, Indonesia"
22
- elif d >= 5:
23
- return "New York City, USA"
24
- elif e >=5:
25
- return "Barcelona, Spain"
26
- else:
27
- if a > b and a > c and a > d and a > e:
28
- return "Paris, France"
29
- elif b > a and b > c and b > d and b > e:
30
- return "Tokyo, Japan"
31
- elif c > a and c > b and c > d and c > e:
32
- return "Bali, Indonesia"
33
- elif d > a and d > b and d > c and d > e:
34
- return "New York City, USA"
35
- elif e > a and e > b and e > c and e > d:
36
- return "Barcelona, Spain"
37
- else:
38
- return "Sydney, Australia"
39
- questions_europe = [
40
- ("1. What kind of people do you enjoy meeting?", [
41
- ("A", "Locals who know the city's deep history and culture."),
42
- ("B", "Curious travelers and polite locals with cool stories."),
43
- ("C", "Easygoing, spiritual people who live simply."),
44
- ("D", "Bold, confident people chasing big dreams."),
45
- ("E", "Social butterflies who love music and street life.")
46
- ]),
47
- ("2. What type of souvenir do you want to bring home?", [
48
- ("A", "A vintage print from a street artist."),
49
- ("B", "A quirky gadget or handmade oragami."),
50
- ("C", "A handmade bracelet and beach sarong."),
51
- ("D", "A t-shirt from a local streetwear brand."),
52
- ("E", "A flamenco fan or mosaic-tiled trinket.")
53
- ]),
54
- ("3. Choose an activity for your ideal day.", [
55
- ("A", "Browsing a weekend market,then sipping espresso at a corner café."),
56
- ("B", "Eating noodles in a hidden alley, then watching a city sunset from a rooftop temple."),
57
- ("C", "Surfing, spa treatments, or a sunrise hike."),
58
- ("D", "Exploring thrift shops, then catching a pop-up art show downtown."),
59
- ("E", "Dancing on the beach and exploring local street art.")
60
- ]),
61
- ("4. What kind of weather do you prefer?", [
62
- ("A", "Mild and breezy with lots of sunshine."),
63
- ("B", "Cool evenings and warm days."),
64
- ("C", "Hot and tropical with ocean breezes."),
65
- ("D", "Crisp air with clear skies."),
66
- ("E", "Warm with a chance of an evening breeze.")
67
- ]),
68
- ("5. You stumble upon a secret cafe. What do you order?", [
69
- ("A", "A delicate pastry no one else seems to know about."),
70
- ("B", "A spicy noodle dish served with an unusual garnish."),
71
- ("C", "A refreshing tropical drink with exotic fruits."),
72
- ("D", "A hearty bagel sandwich perfect for people on the go."),
73
- ("E", "A colorful shaved ice dessert topped with unexpected flavors.")
74
- ])
75
- ]
76
 
77
- def create_quiz(questions, match_func):
78
- answers = []
79
- with gr.Column():
80
- for q, opts in questions:
81
- choices = [opt[1] for opt in opts]
82
- answers.append(gr.Radio(choices=choices, label=q))
83
- result = gr.Textbox(label="You should travel to...")
84
- btn = gr.Button("Find Ideal Location")
85
 
86
- def evaluate(*vals):
87
- codes = []
88
- for i, val in enumerate(vals):
89
- if val is None:
90
- codes.append("C")
91
- else:
92
- codes.append(next(opt[0] for opt in questions[i][1] if opt[1] == val))
93
- return match_func(codes)
94
 
95
- btn.click(evaluate, inputs=answers, outputs=result)
96
- return answers, result, btn
97
-
98
- with gr.Blocks() as demo:
99
- gr.Markdown("Quiz")
100
-
101
- with gr.Tabs():
102
- with gr.TabItem("Quiz"):
103
- create_quiz(questions_europe, match_europe)
104
-
105
-
106
- client = InferenceClient("gemini-1.5-flash")
107
- # change the LLM
108
-
109
- def parse_date(date_str):
110
- if not date_str:
111
- return None
112
- parsed_date = dateparser.parse(date_str, settings={'PREFER_DATES_FROM': 'future'})
113
- return parsed_date if parsed_date else None
114
 
115
  def respond(your_location, destination, transportation, date, preference, include_options):
116
  global travel_guide_output
117
-
118
- if not GOOGLE_API_KEY:
119
- return "Error: Google Gemini API key not configured."
120
-
121
  latitude, longitude = get_coordinates(destination)
122
  weather_info = ""
123
  travel_date = parse_date(date)
124
-
125
- if latitude and longitude and travel_date:
126
- weather_data = get_weather_forecast(latitude, longitude)
127
- if weather_data and 'list' in weather_data:
128
- for forecast in weather_data['list']:
129
- forecast_date = datetime.fromtimestamp(forecast['dt'])
130
- if forecast_date.date() == travel_date.date() and forecast_date.hour == 12:
131
- weather_info = f" The weather forecast for {travel_date.strftime('%B %d')} is {forecast['weather'][0]['description']} with a temperature of {forecast['main']['temp']}°C."
132
- break
133
-
134
- prompt = f"""
135
- **Travel Plan Details:**
136
- - **From:** {your_location}
137
- - **To:** {destination}
138
- - **Transportation:** {transportation}
139
- - **Travel Date:** {date}
140
- - **Budget Preference:** {preference}
141
- - **Additional Info:** {', '.join(include_options) if include_options else 'None'}
142
  {weather_info}
143
- Provide a detailed travel guide based on these details.
144
- """
145
 
146
  try:
147
- response = model.generate_content([{"role": "user", "parts": [{"text": prompt}]}])
148
- travel_guide_output = response.text
149
- return response.text
150
  except Exception as e:
151
- return f"An error occurred: {e}"
152
 
153
- def chatbot_respond(message, chat_history):
154
- global travel_guide_output
155
- if not travel_guide_output:
156
- return "No travel guide has been generated yet. Please enter your travel details first."
157
-
158
- prompt = f"""
159
- You are an AI travel assistant. The user has already generated a travel guide. Use the following details to assist them:
160
-
161
- {travel_guide_output}
162
-
163
- If the user asks a question related to their trip, provide an answer based on this guide.
164
- If the user asks general travel questions, respond accordingly.
165
- If they make casual conversation, respond naturally.
166
-
167
- User's message: {message}
168
- """
169
-
170
- try:
171
- response = model.generate_content([{"role": "user", "parts": [{"text": prompt}]}])
172
- return response.text
173
- except Exception as e:
174
- return f"An error occurred: {e}"
175
-
176
-
177
  with gr.Blocks() as app:
178
  gr.Markdown("# 🌍 Where Should I Travel?")
179
 
@@ -185,33 +51,19 @@ with gr.Blocks() as app:
185
  with gr.Row():
186
  with gr.Column(scale=1):
187
  your_location_input = gr.Textbox(label="Your Current Location")
188
- destination_input = gr.Textbox(label="Travel Destination")
189
- transportation_dropdown = gr.Dropdown(["Bus", "Plane", "Train"], label="Preferred Transportation")
190
- date_input = gr.Textbox(label="Travel Date (e.g., tomorrow, March 15)")
191
- preference_dropdown = gr.Dropdown(["Luxurious", "Cheap", "Balanced"], label="Budget Preferences")
192
- include_checkboxes = gr.CheckboxGroup([
193
- "Restaurant recommendations", "Hotel suggestions", "Nearby attractions", "Local tips", "Packing guides"], label="Include in Chat")
194
-
195
- with gr.Column(scale=1):
196
- output_box = gr.Markdown(label="AI Travel Plan", value="Fill out previous form and press the create button")
197
-
198
- with gr.Column(scale=1):
199
- gr.ChatInterface(
200
- respond,
201
- type="messages",
202
- title="Travia",
203
- examples=[
204
- "I would like to travel to a place, but I don't know how to plan it",
205
- "I need to budget for my trip.",
206
- "I want to learn more about the language, food, and culture of the place I'm traveling to."
207
- ]
208
- )
209
- send_button.click(
210
- respond_plan,
211
- inputs=[your_location_input, destination_input, transportation_dropdown, date_input, preference_dropdown, include_checkboxes],
212
- outputs=[output_box]
213
- )
214
-
215
-
216
-
217
  app.launch(debug=True)
 
4
  import os
5
  import requests
6
  import dateparser
7
+ from datetime import datetime
8
 
9
+ travel_guide_output = ""
10
 
11
+ # Your existing `match_europe`, `questions_europe`, `create_quiz`, `parse_date` functions...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ client = InferenceClient("HuggingFace-model-name") # Replace with your actual model
 
 
 
 
 
 
 
14
 
15
+ def get_coordinates(location):
16
+ return 40.7128, -74.0060 # dummy coordinates
 
 
 
 
 
 
17
 
18
+ def get_weather_forecast(lat, lon):
19
+ return None # dummy data or implement actual API
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  def respond(your_location, destination, transportation, date, preference, include_options):
22
  global travel_guide_output
 
 
 
 
23
  latitude, longitude = get_coordinates(destination)
24
  weather_info = ""
25
  travel_date = parse_date(date)
26
+ prompt = f"""Your travel details:
27
+ - From: {your_location}
28
+ - To: {destination}
29
+ - Transportation: {transportation}
30
+ - Date: {date}
31
+ - Preference: {preference}
32
+ - Extras: {include_options}
 
 
 
 
 
 
 
 
 
 
 
33
  {weather_info}
34
+ Provide a travel guide based on these."""
 
35
 
36
  try:
37
+ response = client.text_generation(prompt)
38
+ travel_guide_output = response.generated_text
39
+ return travel_guide_output
40
  except Exception as e:
41
+ return f"Error: {e}"
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  with gr.Blocks() as app:
44
  gr.Markdown("# 🌍 Where Should I Travel?")
45
 
 
51
  with gr.Row():
52
  with gr.Column(scale=1):
53
  your_location_input = gr.Textbox(label="Your Current Location")
54
+ destination_input = gr.Textbox(label="Travel Destination")
55
+ transportation_dropdown = gr.Dropdown(["Bus", "Plane", "Train"], label="Transportation")
56
+ date_input = gr.Textbox(label="Travel Date (e.g., tomorrow, June 15)")
57
+ preference_dropdown = gr.Dropdown(["Luxurious", "Cheap", "Balanced"], label="Budget")
58
+ include_checkboxes = gr.CheckboxGroup([
59
+ "Restaurant recommendations", "Hotel suggestions", "Nearby attractions", "Local tips", "Packing guides"], label="Include")
60
+ send_button = gr.Button("Create Travel Plan")
61
+ output_box = gr.Markdown(value="Fill out the form and press 'Create Travel Plan'")
62
+
63
+ send_button.click(
64
+ respond,
65
+ inputs=[your_location_input, destination_input, transportation_dropdown, date_input, preference_dropdown, include_checkboxes],
66
+ outputs=output_box
67
+ )
68
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  app.launch(debug=True)