benjamin5607 commited on
Commit
a8b52b7
ยท
verified ยท
1 Parent(s): 31422b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -36
app.py CHANGED
@@ -32,14 +32,10 @@ try:
32
  response = requests.get(SHEET_URL)
33
  response.encoding = 'utf-8'
34
  df = pd.read_csv(io.StringIO(response.text), on_bad_lines='skip')
35
-
36
- # [์ˆ˜์ •] ๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ ๊ฐ•ํ™”: ๋นˆ ๊ฐ’(NaN)์„ ๋นˆ ๋ฌธ์ž์—ด("")๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ undefined ๋ฐฉ์ง€
37
  df = df.fillna("")
38
  df.columns = df.columns.str.strip()
39
-
40
  for col in df.select_dtypes(include=['object']).columns:
41
  df[col] = df[col].astype(str).str.replace(r'[\r\n\t]+', ' ', regex=True).str.replace('"', '\\"').str.replace("'", "\\'")
42
-
43
  if 'Country' in df.columns:
44
  for country, group in df.groupby('Country'):
45
  PLACE_DB[country] = group.fillna("").to_dict(orient='records')
@@ -55,7 +51,7 @@ db_json_str = json.dumps(PLACE_DB, ensure_ascii=False)
55
  db_base64 = base64.b64encode(db_json_str.encode('utf-8')).decode('utf-8')
56
 
57
  # ==========================================
58
- # 3. ํ†ตํ•ฉ ํ”„๋ก ํŠธ์—”๋“œ (undefined ์™„๋ฒฝ ์ œ๊ฑฐ ๋ฒ„์ „)
59
  # ==========================================
60
  html_template = """
61
  <!DOCTYPE html>
@@ -94,8 +90,8 @@ html_template = """
94
  #world-map-page, #passport-page, #chat-page { background: #000; z-index: 2000; transform: translateY(100%); }
95
  #passport-page { transform: translateX(-100%); background: #0f0f1b; }
96
  #detail-page { background: #0a0a0a; z-index: 4000; transform: translateX(100%); }
97
-
98
  .nav-bar { height: 60px; display: flex; align-items: center; padding: 0 20px; border-bottom: 1px solid #222; background: #111; }
 
99
  .msg { max-width: 85%; padding: 12px 18px; border-radius: 15px; font-size: 14px; line-height: 1.6; margin-bottom: 12px; }
100
  .msg.bot { align-self: flex-start; background: #222; color: #eee; border: 1px solid #333; }
101
  .msg.user { align-self: flex-end; background: var(--gold); color: black; font-weight: bold; }
@@ -197,16 +193,13 @@ html_template = """
197
 
198
  filtered.forEach(p => {
199
  const card = document.createElement('div'); card.className = 'place-card';
200
- // [์ˆ˜์ •] undefined ๋ฐฉ์ง€ ๋กœ์ง (|| "")
201
  const displayLabel = p.label || p.category || "";
202
  const desc = p['desc_'+currentLang.toLowerCase()] || p.desc_ko || "";
203
-
204
  let distHtml = "";
205
  if(userLat && userLon && p.lat && p.lon) {
206
  const dist = getDistanceFromLatLonInKm(userLat, userLon, p.lat, p.lon);
207
  distHtml = `<span class="pc-dist">(๐Ÿ“ ${dist}km)</span>`;
208
  }
209
-
210
  card.innerHTML = `
211
  <div class="pc-header">
212
  <div class="pc-name">${p.name} ${distHtml}</div>
@@ -221,26 +214,28 @@ html_template = """
221
  });
222
  }
223
 
 
224
  async function callGroq(msgs) {
 
 
 
225
  try {
226
  const r = await fetch("https://api.groq.com/openai/v1/chat/completions", {
227
- method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer GROQ_KEY" },
228
- body: JSON.stringify({ model: "llama-3.3-70b-versatile", messages: msgs, temperature: 0.7 })
 
 
229
  });
230
 
231
- // [์ˆ˜์ •] 429 ์—๋Ÿฌ ๋ฐ API ์‹คํŒจ ์ฒ˜๋ฆฌ ๊ฐ•ํ™”
232
  if (!r.ok) {
233
- if (r.status === 429) return "Emily is taking a break. (Too many requests, try again in 1 min)";
234
- return "Emily is busy. (Server Error: " + r.status + ")";
 
235
  }
236
 
237
  const d = await r.json();
238
- if (d && d.choices && d.choices.length > 0) {
239
- return d.choices[0].message.content;
240
- } else {
241
- return "Emily is silent. (No response)";
242
- }
243
- } catch(e) { return "Emily can't reach the server."; }
244
  }
245
 
246
  async function sendChat() {
@@ -268,8 +263,7 @@ html_template = """
268
 
269
  const sysPrompt = "You are Emily, a bartender. Speak ONLY in " + TRANSLATIONS[currentLang].ai + ". IMPORTANT: If recommending a place, write the name in [Brackets]." + nearbyContext;
270
 
271
- // callGroq๊ฐ€ undefined๋ฅผ ๋ฐ˜ํ™˜ํ•˜์ง€ ์•Š๋„๋ก ๋ณด์žฅ
272
- const botMsg = await callGroq([{ role: "system", content: sysPrompt }, ...chatHistory]) || "Emily is confused.";
273
 
274
  let finalHtml = botMsg;
275
  const regex = /\\[(.*?)\\]/g;
@@ -298,19 +292,7 @@ html_template = """
298
  }
299
 
300
  function markVisited(name) { if(!visitedPlaces.includes(name)) { visitedPlaces.push(name); localStorage.setItem('visitedPlaces', JSON.stringify(visitedPlaces)); } }
301
-
302
- function openPassport() {
303
- document.getElementById('passport-page').style.transform = 'translateX(0%)';
304
- const grid = document.getElementById('stamp-grid'); grid.innerHTML = "";
305
- for(let c in PLACE_DB) {
306
- PLACE_DB[c].forEach(p => {
307
- const active = visitedPlaces.includes(p.name);
308
- const div = document.createElement('div'); div.className = 'stamp' + (active ? ' active' : '');
309
- div.innerHTML = active ? `๐Ÿท<br><b>${p.name}</b>` : `โœˆ๏ธ`;
310
- grid.appendChild(div);
311
- });
312
- }
313
- }
314
  function closePassport() { document.getElementById('passport-page').style.transform = 'translateX(-100%)'; }
315
 
316
  function openMap() {
@@ -319,7 +301,6 @@ html_template = """
319
  worldMap = L.map('full-map').setView([20,0],2); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(worldMap);
320
  for(let c in PLACE_DB) PLACE_DB[c].forEach(p => {
321
  if(p.lat && p.lon) {
322
- // [์ˆ˜์ •] ํŒ์—…์—์„œ๋„ undefined ๋ฐฉ์ง€
323
  const lbl = p.label || p.category || "";
324
  L.marker([p.lat,p.lon]).addTo(worldMap).bindPopup(`<b>${p.name}</b><br>${lbl}<br><button class='popup-btn' onclick='window.open("${getMapUrl(p,c)}","_blank")'>MAP</button>`);
325
  }
 
32
  response = requests.get(SHEET_URL)
33
  response.encoding = 'utf-8'
34
  df = pd.read_csv(io.StringIO(response.text), on_bad_lines='skip')
 
 
35
  df = df.fillna("")
36
  df.columns = df.columns.str.strip()
 
37
  for col in df.select_dtypes(include=['object']).columns:
38
  df[col] = df[col].astype(str).str.replace(r'[\r\n\t]+', ' ', regex=True).str.replace('"', '\\"').str.replace("'", "\\'")
 
39
  if 'Country' in df.columns:
40
  for country, group in df.groupby('Country'):
41
  PLACE_DB[country] = group.fillna("").to_dict(orient='records')
 
51
  db_base64 = base64.b64encode(db_json_str.encode('utf-8')).decode('utf-8')
52
 
53
  # ==========================================
54
+ # 3. ํ†ตํ•ฉ ํ”„๋ก ํŠธ์—”๋“œ (๋ชจ๋ธ ๋ณ€๊ฒฝ + ์ƒ์„ธ ์—๋Ÿฌ ์ถœ๋ ฅ)
55
  # ==========================================
56
  html_template = """
57
  <!DOCTYPE html>
 
90
  #world-map-page, #passport-page, #chat-page { background: #000; z-index: 2000; transform: translateY(100%); }
91
  #passport-page { transform: translateX(-100%); background: #0f0f1b; }
92
  #detail-page { background: #0a0a0a; z-index: 4000; transform: translateX(100%); }
 
93
  .nav-bar { height: 60px; display: flex; align-items: center; padding: 0 20px; border-bottom: 1px solid #222; background: #111; }
94
+
95
  .msg { max-width: 85%; padding: 12px 18px; border-radius: 15px; font-size: 14px; line-height: 1.6; margin-bottom: 12px; }
96
  .msg.bot { align-self: flex-start; background: #222; color: #eee; border: 1px solid #333; }
97
  .msg.user { align-self: flex-end; background: var(--gold); color: black; font-weight: bold; }
 
193
 
194
  filtered.forEach(p => {
195
  const card = document.createElement('div'); card.className = 'place-card';
 
196
  const displayLabel = p.label || p.category || "";
197
  const desc = p['desc_'+currentLang.toLowerCase()] || p.desc_ko || "";
 
198
  let distHtml = "";
199
  if(userLat && userLon && p.lat && p.lon) {
200
  const dist = getDistanceFromLatLonInKm(userLat, userLon, p.lat, p.lon);
201
  distHtml = `<span class="pc-dist">(๐Ÿ“ ${dist}km)</span>`;
202
  }
 
203
  card.innerHTML = `
204
  <div class="pc-header">
205
  <div class="pc-name">${p.name} ${distHtml}</div>
 
214
  });
215
  }
216
 
217
+ // [์ค‘์š”] Groq API ํ˜ธ์ถœ ํ•จ์ˆ˜ (์•ˆ์ •์ ์ธ ๋ชจ๋ธ๋กœ ๊ต์ฒด ๋ฐ ์—๋Ÿฌ ์ƒ์„ธํ™”)
218
  async function callGroq(msgs) {
219
+ const apiKey = "GROQ_KEY"; // ํŒŒ์ด์ฌ์—์„œ ์น˜ํ™˜๋จ
220
+ if(!apiKey || apiKey.length < 5) return "Error: API Key is missing. Please check your settings.";
221
+
222
  try {
223
  const r = await fetch("https://api.groq.com/openai/v1/chat/completions", {
224
+ method: "POST",
225
+ headers: { "Content-Type": "application/json", "Authorization": "Bearer " + apiKey },
226
+ // ๋ชจ๋ธ์„ ๊ฐ€์žฅ ์•ˆ์ •์ ์ธ llama-3.1-70b-versatile ๋กœ ๋ณ€๊ฒฝ
227
+ body: JSON.stringify({ model: "llama-3.1-70b-versatile", messages: msgs, temperature: 0.7 })
228
  });
229
 
 
230
  if (!r.ok) {
231
+ const errData = await r.json();
232
+ const errMsg = errData.error ? errData.error.message : r.statusText;
233
+ return "Emily Error: " + r.status + " (" + errMsg + ")";
234
  }
235
 
236
  const d = await r.json();
237
+ return d.choices[0].message.content;
238
+ } catch(e) { return "Emily Network Error: " + e.message; }
 
 
 
 
239
  }
240
 
241
  async function sendChat() {
 
263
 
264
  const sysPrompt = "You are Emily, a bartender. Speak ONLY in " + TRANSLATIONS[currentLang].ai + ". IMPORTANT: If recommending a place, write the name in [Brackets]." + nearbyContext;
265
 
266
+ const botMsg = await callGroq([{ role: "system", content: sysPrompt }, ...chatHistory]);
 
267
 
268
  let finalHtml = botMsg;
269
  const regex = /\\[(.*?)\\]/g;
 
292
  }
293
 
294
  function markVisited(name) { if(!visitedPlaces.includes(name)) { visitedPlaces.push(name); localStorage.setItem('visitedPlaces', JSON.stringify(visitedPlaces)); } }
295
+ function openPassport() { document.getElementById('passport-page').style.transform = 'translateX(0%)'; const grid = document.getElementById('stamp-grid'); grid.innerHTML = ""; for(let c in PLACE_DB) { PLACE_DB[c].forEach(p => { const active = visitedPlaces.includes(p.name); const div = document.createElement('div'); div.className = 'stamp' + (active ? ' active' : ''); div.innerHTML = active ? `๐Ÿท<br><b>${p.name}</b>` : `โœˆ๏ธ`; grid.appendChild(div); }); } }
 
 
 
 
 
 
 
 
 
 
 
 
296
  function closePassport() { document.getElementById('passport-page').style.transform = 'translateX(-100%)'; }
297
 
298
  function openMap() {
 
301
  worldMap = L.map('full-map').setView([20,0],2); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(worldMap);
302
  for(let c in PLACE_DB) PLACE_DB[c].forEach(p => {
303
  if(p.lat && p.lon) {
 
304
  const lbl = p.label || p.category || "";
305
  L.marker([p.lat,p.lon]).addTo(worldMap).bindPopup(`<b>${p.name}</b><br>${lbl}<br><button class='popup-btn' onclick='window.open("${getMapUrl(p,c)}","_blank")'>MAP</button>`);
306
  }