Infinity-1995 commited on
Commit
d422ea8
·
verified ·
1 Parent(s): 0ecf707

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -116
app.py CHANGED
@@ -1,8 +1,6 @@
1
  import os
2
- import time
3
- import requests
4
- import re
5
  import gradio as gr
 
6
  from reportlab.pdfgen import canvas
7
  from reportlab.lib.pagesizes import letter
8
  import tempfile
@@ -10,6 +8,7 @@ from textwrap import wrap
10
 
11
  # Load API key securely from environment
12
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
 
13
 
14
  MOODS = [
15
  "Adventure",
@@ -33,95 +32,6 @@ MOOD_IMAGES = {
33
  "Any": "images/default.png"
34
  }
35
 
36
- def create_leaflet_map(locations):
37
- markers_js = ""
38
- for loc in locations:
39
- markers_js += f"""
40
- L.marker([{loc['lat']}, {loc['lng']}]).addTo(map)
41
- .bindPopup("<b>{loc['name']}</b>");
42
- """
43
-
44
- center_lat = locations[0]['lat'] if locations else 20
45
- center_lng = locations[0]['lng'] if locations else 0
46
-
47
- html = f"""
48
- <div id="map" style="width: 100%; height: 400px; margin-top: 20px;"></div>
49
- <link
50
- rel="stylesheet"
51
- href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
52
- crossorigin=""
53
- />
54
- <script
55
- src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
56
- crossorigin=""
57
- ></script>
58
- <script>
59
- var map = L.map('map').setView([{center_lat}, {center_lng}], 6);
60
- L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png', {{
61
- attribution: '© OpenStreetMap contributors',
62
- }}).addTo(map);
63
- {markers_js}
64
- </script>
65
- """
66
- return html
67
-
68
- def geocode_location(place_name):
69
- url = "https://nominatim.openstreetmap.org/search"
70
- params = {"q": place_name, "format": "json", "limit": 1}
71
- headers = {"User-Agent": "FeelAwayApp/1.0 (mathushawlika1221@gmail.com)"}
72
- try:
73
- response = requests.get(url, params=params, headers=headers, timeout=5)
74
- if response.status_code == 200:
75
- data = response.json()
76
- if data:
77
- lat = float(data[0]["lat"])
78
- lon = float(data[0]["lon"])
79
- return lat, lon
80
- except Exception:
81
- pass
82
- return None, None
83
-
84
- def extract_places(itinerary_text):
85
- # Simple heuristic: extract capitalized phrases (names)
86
- pattern = r"\b([A-Z][a-z]+(?:\s[A-Z][a-z]+)*)\b"
87
- matches = re.findall(pattern, itinerary_text)
88
- blacklist = {"The", "And", "For", "With", "From", "Your", "Day", "Enjoy", "Start", "Begin"}
89
- places = []
90
- for match in matches:
91
- if match not in blacklist and len(match) > 2:
92
- places.append(match)
93
- # Remove duplicates preserving order
94
- seen = set()
95
- unique_places = []
96
- for p in places:
97
- if p not in seen:
98
- seen.add(p)
99
- unique_places.append(p)
100
- return unique_places
101
-
102
- def call_groq_model(prompt):
103
- if not GROQ_API_KEY:
104
- return "**Error:** Missing GROQ_API_KEY in environment settings."
105
-
106
- url = "https://api.groq.com/openai/v1/chat/completions"
107
- headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
108
- payload = {
109
- "model": "gemma2-9b-it",
110
- "messages": [
111
- {"role": "system", "content": "You are an expert travel planner."},
112
- {"role": "user", "content": prompt}
113
- ],
114
- "temperature": 1,
115
- "max_tokens": 1024
116
- }
117
- try:
118
- response = requests.post(url, headers=headers, json=payload, timeout=30)
119
- response.raise_for_status()
120
- data = response.json()
121
- return data["choices"][0]["message"]["content"]
122
- except Exception as e:
123
- return f"**Error calling model:** {e}"
124
-
125
  def generate_itinerary(mood, location, budget, days):
126
  mood_text = "any mood" if mood == "Any" else mood
127
  budget_text = "any budget" if budget == "Any" else budget
@@ -132,28 +42,22 @@ def generate_itinerary(mood, location, budget, days):
132
  f"The mood of the traveler is {mood_text} and the budget is {budget_text}. "
133
  f"Use Markdown formatting with **bold headings** for days and time slots."
134
  )
135
-
136
- itinerary_text = call_groq_model(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
137
  image_path = MOOD_IMAGES.get(mood, MOOD_IMAGES["Any"])
138
-
139
- # If API failed, don't proceed to map
140
- if itinerary_text.startswith("**Error"):
141
- return itinerary_text, None, gr.update(visible=False), "", gr.update(visible=False)
142
-
143
- # Extract place names
144
- places = extract_places(itinerary_text)
145
- locations = []
146
- for place in places:
147
- lat, lng = geocode_location(place)
148
- if lat and lng:
149
- locations.append({"name": place, "lat": lat, "lng": lng})
150
- time.sleep(1)
151
-
152
- if not locations:
153
- locations = [{"name": "World", "lat": 20, "lng": 0}]
154
-
155
- map_html = create_leaflet_map(locations)
156
- return itinerary_text, image_path, gr.update(visible=True), map_html, gr.update(visible=True)
157
 
158
  def generate_pdf(itinerary_text):
159
  if not itinerary_text.strip():
@@ -167,7 +71,9 @@ def generate_pdf(itinerary_text):
167
  line_height = 12
168
  font_size = 10
169
  c.setFont("Courier", font_size)
 
170
  max_chars_per_line = int((width - 2 * margin) / (font_size * 0.6))
 
171
  x = margin
172
  y = height - margin
173
 
@@ -188,6 +94,7 @@ def generate_pdf(itinerary_text):
188
  return temp_pdf.name
189
 
190
  with gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")) as demo:
 
191
  header_html = """
192
  <style>
193
  @keyframes colorCycle {
@@ -205,7 +112,6 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")
205
  color: #007777;
206
  font-size: 18px;
207
  margin-top: 4px;
208
- font-weight:bold;
209
  }
210
  </style>
211
  <div style='text-align: center;'>
@@ -216,6 +122,7 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")
216
  with gr.Row():
217
  gr.HTML(header_html)
218
 
 
219
  with gr.Row():
220
  mood = gr.Dropdown(MOODS, label="Mood", value="Any", info="Select the mood of your trip")
221
  location = gr.Textbox(label="Destination", placeholder="e.g., India, Japan, France (leave blank for Any)", info="Where do you want to go?")
@@ -229,7 +136,6 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")
229
  with gr.Column():
230
  itinerary_output = gr.Markdown(label="Generated Itinerary")
231
  image_output = gr.Image(label="Travel Mood Image", type="filepath", visible=False)
232
- map_output = gr.HTML(visible=False)
233
 
234
  with gr.Column():
235
  download_btn = gr.Button("📥 Download Itinerary as PDF", variant="secondary")
@@ -238,7 +144,7 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")
238
  generate_btn.click(
239
  generate_itinerary,
240
  inputs=[mood, location, budget, days],
241
- outputs=[itinerary_output, image_output, image_output, map_output, map_output]
242
  )
243
 
244
  download_btn.click(
@@ -249,3 +155,4 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")
249
 
250
  demo.launch()
251
 
 
 
1
  import os
 
 
 
2
  import gradio as gr
3
+ from groq import Groq
4
  from reportlab.pdfgen import canvas
5
  from reportlab.lib.pagesizes import letter
6
  import tempfile
 
8
 
9
  # Load API key securely from environment
10
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
11
+ client = Groq(api_key=GROQ_API_KEY)
12
 
13
  MOODS = [
14
  "Adventure",
 
32
  "Any": "images/default.png"
33
  }
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def generate_itinerary(mood, location, budget, days):
36
  mood_text = "any mood" if mood == "Any" else mood
37
  budget_text = "any budget" if budget == "Any" else budget
 
42
  f"The mood of the traveler is {mood_text} and the budget is {budget_text}. "
43
  f"Use Markdown formatting with **bold headings** for days and time slots."
44
  )
45
+
46
+ completion = client.chat.completions.create(
47
+ model="gemma2-9b-it",
48
+ messages=[
49
+ {"role": "system", "content": "You are an expert travel planner."},
50
+ {"role": "user", "content": prompt}
51
+ ],
52
+ temperature=1,
53
+ max_completion_tokens=1024,
54
+ top_p=1,
55
+ stream=False
56
+ )
57
+
58
+ itinerary_text = completion.choices[0].message.content
59
  image_path = MOOD_IMAGES.get(mood, MOOD_IMAGES["Any"])
60
+ return itinerary_text, image_path, gr.update(visible=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  def generate_pdf(itinerary_text):
63
  if not itinerary_text.strip():
 
71
  line_height = 12
72
  font_size = 10
73
  c.setFont("Courier", font_size)
74
+
75
  max_chars_per_line = int((width - 2 * margin) / (font_size * 0.6))
76
+
77
  x = margin
78
  y = height - margin
79
 
 
94
  return temp_pdf.name
95
 
96
  with gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")) as demo:
97
+ # Header with gr.HTML for styles and animation
98
  header_html = """
99
  <style>
100
  @keyframes colorCycle {
 
112
  color: #007777;
113
  font-size: 18px;
114
  margin-top: 4px;
 
115
  }
116
  </style>
117
  <div style='text-align: center;'>
 
122
  with gr.Row():
123
  gr.HTML(header_html)
124
 
125
+ # Inputs
126
  with gr.Row():
127
  mood = gr.Dropdown(MOODS, label="Mood", value="Any", info="Select the mood of your trip")
128
  location = gr.Textbox(label="Destination", placeholder="e.g., India, Japan, France (leave blank for Any)", info="Where do you want to go?")
 
136
  with gr.Column():
137
  itinerary_output = gr.Markdown(label="Generated Itinerary")
138
  image_output = gr.Image(label="Travel Mood Image", type="filepath", visible=False)
 
139
 
140
  with gr.Column():
141
  download_btn = gr.Button("📥 Download Itinerary as PDF", variant="secondary")
 
144
  generate_btn.click(
145
  generate_itinerary,
146
  inputs=[mood, location, budget, days],
147
+ outputs=[itinerary_output, image_output, image_output]
148
  )
149
 
150
  download_btn.click(
 
155
 
156
  demo.launch()
157
 
158
+