Infinity-1995 commited on
Commit
418b0b9
·
verified ·
1 Parent(s): 8bbcaee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -35
app.py CHANGED
@@ -3,7 +3,6 @@ import time
3
  import requests
4
  import re
5
  import gradio as gr
6
- from groq import Groq
7
  from reportlab.pdfgen import canvas
8
  from reportlab.lib.pagesizes import letter
9
  import tempfile
@@ -11,7 +10,6 @@ from textwrap import wrap
11
 
12
  # Load API key securely from environment
13
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
14
- client = Groq(api_key=GROQ_API_KEY)
15
 
16
  MOODS = [
17
  "Adventure",
@@ -48,7 +46,6 @@ def create_leaflet_map(locations):
48
 
49
  html = f"""
50
  <div id="map" style="width: 100%; height: 400px; margin-top: 20px;"></div>
51
-
52
  <link
53
  rel="stylesheet"
54
  href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
@@ -58,14 +55,11 @@ def create_leaflet_map(locations):
58
  src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
59
  crossorigin=""
60
  ></script>
61
-
62
  <script>
63
  var map = L.map('map').setView([{center_lat}, {center_lng}], 6);
64
-
65
  L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png', {{
66
  attribution: '© OpenStreetMap contributors',
67
  }}).addTo(map);
68
-
69
  {markers_js}
70
  </script>
71
  """
@@ -73,14 +67,8 @@ def create_leaflet_map(locations):
73
 
74
  def geocode_location(place_name):
75
  url = "https://nominatim.openstreetmap.org/search"
76
- params = {
77
- "q": place_name,
78
- "format": "json",
79
- "limit": 1
80
- }
81
- headers = {
82
- "User-Agent": "FeelAwayApp/1.0 (mathushawlika1221@gmail.com)"
83
- }
84
  try:
85
  response = requests.get(url, params=params, headers=headers, timeout=5)
86
  if response.status_code == 200:
@@ -97,7 +85,6 @@ def extract_places(itinerary_text):
97
  # Simple heuristic: extract capitalized phrases (names)
98
  pattern = r"\b([A-Z][a-z]+(?:\s[A-Z][a-z]+)*)\b"
99
  matches = re.findall(pattern, itinerary_text)
100
- # Remove common English words that aren't places (can be improved)
101
  blacklist = {"The", "And", "For", "With", "From", "Your", "Day", "Enjoy", "Start", "Begin"}
102
  places = []
103
  for match in matches:
@@ -112,6 +99,29 @@ def extract_places(itinerary_text):
112
  unique_places.append(p)
113
  return unique_places
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  def generate_itinerary(mood, location, budget, days):
116
  mood_text = "any mood" if mood == "Any" else mood
117
  budget_text = "any budget" if budget == "Any" else budget
@@ -122,37 +132,27 @@ def generate_itinerary(mood, location, budget, days):
122
  f"The mood of the traveler is {mood_text} and the budget is {budget_text}. "
123
  f"Use Markdown formatting with **bold headings** for days and time slots."
124
  )
125
-
126
- completion = client.chat.completions.create(
127
- model="gemma2-9b-it",
128
- messages=[
129
- {"role": "system", "content": "You are an expert travel planner."},
130
- {"role": "user", "content": prompt}
131
- ],
132
- temperature=1,
133
- max_completion_tokens=1024,
134
- top_p=1,
135
- stream=False
136
- )
137
-
138
- itinerary_text = completion.choices[0].message.content
139
  image_path = MOOD_IMAGES.get(mood, MOOD_IMAGES["Any"])
140
 
141
- # Extract place names from itinerary text
142
- places = extract_places(itinerary_text)
 
143
 
 
 
144
  locations = []
145
  for place in places:
146
  lat, lng = geocode_location(place)
147
  if lat and lng:
148
  locations.append({"name": place, "lat": lat, "lng": lng})
149
- time.sleep(1) # Respect Nominatim usage policy
150
 
151
  if not locations:
152
  locations = [{"name": "World", "lat": 20, "lng": 0}]
153
 
154
  map_html = create_leaflet_map(locations)
155
-
156
  return itinerary_text, image_path, gr.update(visible=True), map_html, gr.update(visible=True)
157
 
158
  def generate_pdf(itinerary_text):
@@ -167,9 +167,7 @@ def generate_pdf(itinerary_text):
167
  line_height = 12
168
  font_size = 10
169
  c.setFont("Courier", font_size)
170
-
171
  max_chars_per_line = int((width - 2 * margin) / (font_size * 0.6))
172
-
173
  x = margin
174
  y = height - margin
175
 
 
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
 
11
  # Load API key securely from environment
12
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
 
13
 
14
  MOODS = [
15
  "Adventure",
 
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"
 
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
  """
 
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:
 
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:
 
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
  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):
 
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