benjamin5607 commited on
Commit
a43f3e7
·
verified ·
1 Parent(s): 5decb26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -43
app.py CHANGED
@@ -8,7 +8,7 @@ import requests
8
  import io
9
 
10
  # ==========================================
11
- # 🔐 1. 시크릿 및 설정 로드
12
  # ==========================================
13
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
14
  SHEET_URL = os.environ.get("PRIVATE_SHEET_URL", "")
@@ -24,7 +24,7 @@ st.markdown("""
24
  """, unsafe_allow_html=True)
25
 
26
  # ==========================================
27
- # 2. 데이터 로드 (Google Sheet 연동 및 정제)
28
  # ==========================================
29
  PLACE_DB = {}
30
  try:
@@ -34,7 +34,6 @@ try:
34
  response.raise_for_status()
35
  df = pd.read_csv(io.StringIO(response.text), on_bad_lines='skip')
36
 
37
- # 데이터 클렌징: JS에서 문법 오류를 일으킬 수 있는 줄바꿈 및 특수 따옴표 정제
38
  for col in df.select_dtypes(include=['object']).columns:
39
  df[col] = df[col].astype(str).str.replace(r'[\r\n\t]+', ' ', regex=True).str.replace('"', '\\"').str.replace("'", "\\'")
40
 
@@ -59,7 +58,7 @@ db_json_str = json.dumps(PLACE_DB, ensure_ascii=False)
59
  db_base64 = base64.b64encode(db_json_str.encode('utf-8')).decode('utf-8')
60
 
61
  # ==========================================
62
- # 3. 통합 프론트엔드 (HTML/JS/CSS)
63
  # ==========================================
64
  html_code = f"""
65
  <!DOCTYPE html>
@@ -75,13 +74,11 @@ html_code = f"""
75
  :root {{ --gold: #d4af37; --dark: #0a0a0a; --text: #e0e0e0; }}
76
  body {{ margin: 0; padding: 0; background: var(--dark); color: var(--text); font-family: 'Segoe UI', sans-serif; overflow: hidden; }}
77
  .page {{ position: absolute; top: 0; left: 0; width: 100%; height: 100vh; transition: transform 0.5s ease; display: flex; flex-direction: column; }}
78
-
79
  #main-page {{ background: #000; z-index: 100; }}
80
  .place-list-container {{ flex: 1; overflow-y: auto; padding: 20px; padding-bottom: 120px; }}
81
  .place-card {{ background: #1a1a1a; border: 1px solid #333; border-radius: 15px; padding: 18px; margin-bottom: 15px; position: relative; }}
82
  .pc-name {{ font-size: 18px; font-weight: bold; color: var(--gold); }}
83
  .pc-desc {{ font-size: 13px; color: #bbb; margin: 8px 0; line-height: 1.5; }}
84
-
85
  .bartender-btn {{
86
  position: fixed; bottom: 30%; right: 20px; width: 85px; height: 85px; border-radius: 50%;
87
  background: url('data:image/jpeg;base64,{emily_base64}') center/cover;
@@ -89,30 +86,23 @@ html_code = f"""
89
  box-shadow: 0 0 25px rgba(212, 175, 55, 0.6); animation: bounce-float 3s ease-in-out infinite;
90
  }}
91
  @keyframes bounce-float {{ 0%, 100% {{ transform: translateY(0); }} 50% {{ transform: translateY(-15px); }} }}
92
-
93
  #world-map-page {{ background: #111; z-index: 2000; transform: translateY(100%); }}
94
  .map-gps-btn {{
95
  position: absolute; bottom: 30%; right: 20px; z-index: 9999 !important;
96
  width: 60px; height: 60px; border-radius: 50%; background: #222;
97
  border: 3px solid var(--gold); color: var(--gold); font-size: 26px; cursor: pointer;
98
- display: flex; align-items: center; justify-content: center;
99
- box-shadow: 0 4px 15px rgba(0,0,0,0.8);
100
  }}
101
-
102
  #chat-page {{ background: #000; z-index: 3000; transform: translateY(100%); display: flex; flex-direction: column; }}
103
  #detail-page {{ background: #0a0a0a; z-index: 4000; transform: translateX(100%); display: flex; flex-direction: column; }}
104
-
105
  .nav-bar {{ height: 60px; display: flex; align-items: center; padding: 0 20px; border-bottom: 1px solid #222; background: #111; }}
106
  .btn-action {{ padding: 10px 18px; border-radius: 8px; border: none; cursor: pointer; font-weight: bold; margin-right: 8px; font-size: 12px; }}
107
-
108
  .loading-screen {{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 8000; display: none; flex-direction: column; justify-content: center; align-items: center; }}
109
  .loader-ring {{ width: 45px; height: 45px; border: 4px solid #333; border-top: 4px solid var(--gold); border-radius: 50%; animation: spin 1s linear infinite; }}
110
  @keyframes spin {{ 0% {{ transform: rotate(0deg); }} 100% {{ transform: rotate(360deg); }} }}
111
-
112
  .msg {{ max-width: 85%; padding: 12px 18px; border-radius: 15px; font-size: 14px; line-height: 1.6; margin-bottom: 12px; }}
113
  .msg.bot {{ align-self: flex-start; background: #222; color: #eee; border: 1px solid #333; }}
114
  .msg.user {{ align-self: flex-end; background: var(--gold); color: black; font-weight: bold; }}
115
-
116
  .reco-btn {{ display: inline-block; margin-top: 10px; padding: 8px 15px; background: var(--gold); color: black !important; border-radius: 15px; font-weight: bold; text-decoration: none; font-size: 12px; border:none; cursor:pointer; }}
117
  .lang-switcher {{ position: absolute; top: 20px; right: 20px; z-index: 200; display: flex; gap: 8px; }}
118
  .lang-btn {{ background: rgba(0,0,0,0.5); border: 1px solid #555; color: #aaa; padding: 5px 10px; border-radius: 15px; cursor: pointer; font-size: 11px; }}
@@ -147,7 +137,7 @@ html_code = f"""
147
  <div id="chat-messages" style="flex:1; overflow-y:auto; padding:20px; display:flex; flex-direction:column;"></div>
148
  <div style="padding:15px; display:flex; gap:10px; background:#111;">
149
  <input id="chat-input" type="text" style="flex:1; padding:14px; border-radius:10px; border:1px solid #333; background:#222; color:#fff;" placeholder="Whisper to Emily..." onkeydown="if(event.key==='Enter') sendChat()">
150
- <button onclick="sendChat()" style="padding:10px 25px; background:var(--gold); border:none; border-radius:10px; font-weight:bold; cursor:pointer;">SEND</button>
151
  </div>
152
  </div>
153
 
@@ -179,7 +169,7 @@ html_code = f"""
179
  "KO": {{ "ai": "Korean", "greet": "안녕, 자기? 오늘 정말 고생 많았어. 에밀리한테 뭐든 물어봐~" }},
180
  "EN": {{ "ai": "English", "greet": "Hey darling, rough day? Let Emily find you a perfect spot to drink." }},
181
  "JP": {{ "ai": "Japanese", "greet": "あら、ハニー。今日はお疲れ様。エ밀리になんでも聞いて?" }},
182
- "CN": {{ "ai": "Chinese", "greet": "亲爱的,今天辛苦了。想喝点什么?尽管问艾米丽吧。" }}
183
  }};
184
 
185
  window.onload = function() {{
@@ -187,7 +177,7 @@ html_code = f"""
187
  const select = document.getElementById('country-select');
188
  keys.forEach(k => {{ const opt = document.createElement('option'); opt.value = k; opt.text = k; select.appendChild(opt); }});
189
  if(keys.length > 0) selectCountry(keys[0]);
190
- navigator.geolocation.getCurrentPosition(p => {{ userLat = p.coords.latitude; userLon = p.coords.longitude; }}, e => console.log("GPS Denied"));
191
  }};
192
 
193
  function selectCountry(c) {{ selectedCountry = c; renderList(); }}
@@ -198,9 +188,8 @@ html_code = f"""
198
  renderList();
199
  }}
200
 
201
- // [핵심 로직] 한국=네이버 주소 검색 / 해외=구글 좌표 줌인 검색
202
  function getMapUrl(p, country) {{
203
- if (country.includes("Korea") || country.includes("한국") || country.includes("대한민국")) {{
204
  let query = p.address ? p.address : p.name;
205
  return "https://map.naver.com/p/search/" + encodeURIComponent(query);
206
  }} else {{
@@ -216,11 +205,8 @@ html_code = f"""
216
  countryPlaces.forEach(p => {{
217
  const card = document.createElement('div');
218
  card.className = 'place-card';
219
-
220
- // unidentified 방지 Fallback 로직
221
  const descKey = 'desc_' + currentLang.toLowerCase();
222
- let desc = p[descKey] || p.desc_en || p.desc_ko || "Let's explore the heritage of this place.";
223
-
224
  const mapUrl = getMapUrl(p, selectedCountry);
225
 
226
  card.innerHTML = `<div class="pc-name">${{p.name}}</div>
@@ -233,12 +219,11 @@ html_code = f"""
233
  }});
234
  }}
235
 
236
- // 에밀리 상담 기능
237
  function openChat() {{
238
  document.getElementById('chat-page').style.transform = 'translateY(0%)';
239
  if(chatHistory.length === 0) {{
240
  addChatMessage(TRANSLATIONS[currentLang].greet, "bot");
241
- chatHistory.push({{ role: "system", content: "You are Emily, a flirtatious blonde bartender. You must answer ONLY in " + TRANSLATIONS[currentLang].ai + ". Recommending a place from the list? Wrap it in brackets like [Place Name]." }});
242
  }}
243
  }}
244
 
@@ -247,15 +232,13 @@ html_code = f"""
247
  const msg = inp.value.trim(); if(!msg) return;
248
  addChatMessage(msg, 'user'); inp.value = "";
249
  chatHistory.push({{ role: "user", content: msg }});
250
-
251
  const botMsgDiv = addChatMessage("...", "bot");
252
  const res = await callGroq(chatHistory);
253
  botMsgDiv.innerText = res;
254
-
255
  const match = res.match(/\\[(.*?)\\]/);
256
  if(match) {{
257
  const pName = match[1];
258
- botMsgDiv.innerHTML += `<br><button class="reco-btn" onclick="searchAndOpenMap('${{pName.replace(/'/g, "\\\\'")}}')">📍 Open Location Map</button>`;
259
  }}
260
  chatHistory.push({{ role: "assistant", content: res }});
261
  }}
@@ -267,33 +250,25 @@ html_code = f"""
267
  return div;
268
  }}
269
 
270
- // AI 상세 리포트 기능
271
  async function openReview(name, country) {{
272
  const p = PLACE_DB[country].find(x => x.name === name); if(!p) return;
273
  document.getElementById('repo-title').innerText = name;
274
  document.getElementById('detail-page').style.transform = 'translateX(0%)';
275
  document.getElementById('loader').style.display = 'flex';
276
-
277
  if(!miniMap) {{
278
  miniMap = L.map('mini-map');
279
  L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png').addTo(miniMap);
280
  }}
281
- setTimeout(() => {{
282
- miniMap.invalidateSize();
283
- miniMap.setView([p.lat, p.lon], 15);
284
- L.marker([p.lat, p.lon]).addTo(miniMap);
285
- }}, 400);
286
-
287
  const prompt = [
288
- {{ role: "system", content: "Act as Emily. Write a detailed review in " + TRANSLATIONS[currentLang].ai + ". Sections: Vibe, Must Try, Secret Tip." }},
289
- {{ role: "user", content: `Write a review for '${{name}}' in ${{country}}` }}
290
  ];
291
  const res = await callGroq(prompt);
292
  document.getElementById('repo-content').innerText = res;
293
  document.getElementById('loader').style.display = 'none';
294
  }}
295
 
296
- // Groq API 호출 (지능 복구 파라미터 적용)
297
  async function callGroq(messages) {{
298
  try {{
299
  const r = await fetch("https://api.groq.com/openai/v1/chat/completions", {{
@@ -302,11 +277,11 @@ html_code = f"""
302
  body: JSON.stringify({{
303
  model: "llama-3.3-70b-versatile",
304
  messages: messages,
305
- temperature: 0.7, top_p: 0.85, frequency_penalty: 0.7 // 루프 방지 강화
306
  }})
307
  }});
308
  const d = await r.json(); return d.choices[0].message.content;
309
- } catch(e) {{ return "Sweetie, the connection is a bit unstable. Try again!"; }}
310
  }}
311
 
312
  function openMap() {{
@@ -324,8 +299,8 @@ html_code = f"""
324
  function flyToUser() {{
325
  if(userLat && userLon) {{
326
  worldMap.flyTo([userLat, userLon], 15);
327
- L.marker([userLat, userLon]).addTo(worldMap).bindPopup("📍 I'm Here!").openPopup();
328
- }} else alert("Darling, I can't find your location. Check your GPS!");
329
  }}
330
 
331
  function searchAndOpenMap(pName) {{
 
8
  import io
9
 
10
  # ==========================================
11
+ # 🔐 1. 시크릿 로드
12
  # ==========================================
13
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
14
  SHEET_URL = os.environ.get("PRIVATE_SHEET_URL", "")
 
24
  """, unsafe_allow_html=True)
25
 
26
  # ==========================================
27
+ # 2. 데이터 로드 (Google Sheet 연동)
28
  # ==========================================
29
  PLACE_DB = {}
30
  try:
 
34
  response.raise_for_status()
35
  df = pd.read_csv(io.StringIO(response.text), on_bad_lines='skip')
36
 
 
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
 
 
58
  db_base64 = base64.b64encode(db_json_str.encode('utf-8')).decode('utf-8')
59
 
60
  # ==========================================
61
+ # 3. 통합 프론트엔드 (중괄호 완벽 이스케이프)
62
  # ==========================================
63
  html_code = f"""
64
  <!DOCTYPE html>
 
74
  :root {{ --gold: #d4af37; --dark: #0a0a0a; --text: #e0e0e0; }}
75
  body {{ margin: 0; padding: 0; background: var(--dark); color: var(--text); font-family: 'Segoe UI', sans-serif; overflow: hidden; }}
76
  .page {{ position: absolute; top: 0; left: 0; width: 100%; height: 100vh; transition: transform 0.5s ease; display: flex; flex-direction: column; }}
 
77
  #main-page {{ background: #000; z-index: 100; }}
78
  .place-list-container {{ flex: 1; overflow-y: auto; padding: 20px; padding-bottom: 120px; }}
79
  .place-card {{ background: #1a1a1a; border: 1px solid #333; border-radius: 15px; padding: 18px; margin-bottom: 15px; position: relative; }}
80
  .pc-name {{ font-size: 18px; font-weight: bold; color: var(--gold); }}
81
  .pc-desc {{ font-size: 13px; color: #bbb; margin: 8px 0; line-height: 1.5; }}
 
82
  .bartender-btn {{
83
  position: fixed; bottom: 30%; right: 20px; width: 85px; height: 85px; border-radius: 50%;
84
  background: url('data:image/jpeg;base64,{emily_base64}') center/cover;
 
86
  box-shadow: 0 0 25px rgba(212, 175, 55, 0.6); animation: bounce-float 3s ease-in-out infinite;
87
  }}
88
  @keyframes bounce-float {{ 0%, 100% {{ transform: translateY(0); }} 50% {{ transform: translateY(-15px); }} }}
 
89
  #world-map-page {{ background: #111; z-index: 2000; transform: translateY(100%); }}
90
  .map-gps-btn {{
91
  position: absolute; bottom: 30%; right: 20px; z-index: 9999 !important;
92
  width: 60px; height: 60px; border-radius: 50%; background: #222;
93
  border: 3px solid var(--gold); color: var(--gold); font-size: 26px; cursor: pointer;
94
+ display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(0,0,0,0.8);
 
95
  }}
 
96
  #chat-page {{ background: #000; z-index: 3000; transform: translateY(100%); display: flex; flex-direction: column; }}
97
  #detail-page {{ background: #0a0a0a; z-index: 4000; transform: translateX(100%); display: flex; flex-direction: column; }}
 
98
  .nav-bar {{ height: 60px; display: flex; align-items: center; padding: 0 20px; border-bottom: 1px solid #222; background: #111; }}
99
  .btn-action {{ padding: 10px 18px; border-radius: 8px; border: none; cursor: pointer; font-weight: bold; margin-right: 8px; font-size: 12px; }}
 
100
  .loading-screen {{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 8000; display: none; flex-direction: column; justify-content: center; align-items: center; }}
101
  .loader-ring {{ width: 45px; height: 45px; border: 4px solid #333; border-top: 4px solid var(--gold); border-radius: 50%; animation: spin 1s linear infinite; }}
102
  @keyframes spin {{ 0% {{ transform: rotate(0deg); }} 100% {{ transform: rotate(360deg); }} }}
 
103
  .msg {{ max-width: 85%; padding: 12px 18px; border-radius: 15px; font-size: 14px; line-height: 1.6; margin-bottom: 12px; }}
104
  .msg.bot {{ align-self: flex-start; background: #222; color: #eee; border: 1px solid #333; }}
105
  .msg.user {{ align-self: flex-end; background: var(--gold); color: black; font-weight: bold; }}
 
106
  .reco-btn {{ display: inline-block; margin-top: 10px; padding: 8px 15px; background: var(--gold); color: black !important; border-radius: 15px; font-weight: bold; text-decoration: none; font-size: 12px; border:none; cursor:pointer; }}
107
  .lang-switcher {{ position: absolute; top: 20px; right: 20px; z-index: 200; display: flex; gap: 8px; }}
108
  .lang-btn {{ background: rgba(0,0,0,0.5); border: 1px solid #555; color: #aaa; padding: 5px 10px; border-radius: 15px; cursor: pointer; font-size: 11px; }}
 
137
  <div id="chat-messages" style="flex:1; overflow-y:auto; padding:20px; display:flex; flex-direction:column;"></div>
138
  <div style="padding:15px; display:flex; gap:10px; background:#111;">
139
  <input id="chat-input" type="text" style="flex:1; padding:14px; border-radius:10px; border:1px solid #333; background:#222; color:#fff;" placeholder="Whisper to Emily..." onkeydown="if(event.key==='Enter') sendChat()">
140
+ <button onclick="sendChat()" style="padding:10px 20px; background:var(--gold); border:none; border-radius:10px; font-weight:bold; cursor:pointer;">SEND</button>
141
  </div>
142
  </div>
143
 
 
169
  "KO": {{ "ai": "Korean", "greet": "안녕, 자기? 오늘 정말 고생 많았어. 에밀리한테 뭐든 물어봐~" }},
170
  "EN": {{ "ai": "English", "greet": "Hey darling, rough day? Let Emily find you a perfect spot to drink." }},
171
  "JP": {{ "ai": "Japanese", "greet": "あら、ハニー。今日はお疲れ様。エ밀리になんでも聞いて?" }},
172
+ "CN": {{ "ai": "Chinese", "greet": "亲爱的,今天辛苦了. 想喝点什么?" }}
173
  }};
174
 
175
  window.onload = function() {{
 
177
  const select = document.getElementById('country-select');
178
  keys.forEach(k => {{ const opt = document.createElement('option'); opt.value = k; opt.text = k; select.appendChild(opt); }});
179
  if(keys.length > 0) selectCountry(keys[0]);
180
+ navigator.geolocation.getCurrentPosition(p => {{ userLat = p.coords.latitude; userLon = p.coords.longitude; }});
181
  }};
182
 
183
  function selectCountry(c) {{ selectedCountry = c; renderList(); }}
 
188
  renderList();
189
  }}
190
 
 
191
  function getMapUrl(p, country) {{
192
+ if (country.includes("Korea") || country.includes("한국")) {{
193
  let query = p.address ? p.address : p.name;
194
  return "https://map.naver.com/p/search/" + encodeURIComponent(query);
195
  }} else {{
 
205
  countryPlaces.forEach(p => {{
206
  const card = document.createElement('div');
207
  card.className = 'place-card';
 
 
208
  const descKey = 'desc_' + currentLang.toLowerCase();
209
+ let desc = p[descKey] || p.desc_en || p.desc_ko || "Exploring the taste of heritage...";
 
210
  const mapUrl = getMapUrl(p, selectedCountry);
211
 
212
  card.innerHTML = `<div class="pc-name">${{p.name}}</div>
 
219
  }});
220
  }}
221
 
 
222
  function openChat() {{
223
  document.getElementById('chat-page').style.transform = 'translateY(0%)';
224
  if(chatHistory.length === 0) {{
225
  addChatMessage(TRANSLATIONS[currentLang].greet, "bot");
226
+ chatHistory.push({{ role: "system", content: "You are Emily, a flirtatious blonde bartender. Recommending a place? Wrap name in brackets like [Place Name]." }});
227
  }}
228
  }}
229
 
 
232
  const msg = inp.value.trim(); if(!msg) return;
233
  addChatMessage(msg, 'user'); inp.value = "";
234
  chatHistory.push({{ role: "user", content: msg }});
 
235
  const botMsgDiv = addChatMessage("...", "bot");
236
  const res = await callGroq(chatHistory);
237
  botMsgDiv.innerText = res;
 
238
  const match = res.match(/\\[(.*?)\\]/);
239
  if(match) {{
240
  const pName = match[1];
241
+ botMsgDiv.innerHTML += `<br><button class="reco-btn" onclick="searchAndOpenMap('${{pName.replace(/'/g, "\\\\'")}}')">📍 View on Map</button>`;
242
  }}
243
  chatHistory.push({{ role: "assistant", content: res }});
244
  }}
 
250
  return div;
251
  }}
252
 
 
253
  async function openReview(name, country) {{
254
  const p = PLACE_DB[country].find(x => x.name === name); if(!p) return;
255
  document.getElementById('repo-title').innerText = name;
256
  document.getElementById('detail-page').style.transform = 'translateX(0%)';
257
  document.getElementById('loader').style.display = 'flex';
 
258
  if(!miniMap) {{
259
  miniMap = L.map('mini-map');
260
  L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png').addTo(miniMap);
261
  }}
262
+ setTimeout(() => {{ miniMap.invalidateSize(); miniMap.setView([p.lat, p.lon], 15); L.marker([p.lat, p.lon]).addTo(miniMap); }}, 400);
 
 
 
 
 
263
  const prompt = [
264
+ {{ role: "system", content: "Act as Emily. Write review in " + TRANSLATIONS[currentLang].ai + ". Sections: Vibe, Must Try, Secret Tip." }},
265
+ {{ role: "user", content: "Write review for " + name + " in " + country }}
266
  ];
267
  const res = await callGroq(prompt);
268
  document.getElementById('repo-content').innerText = res;
269
  document.getElementById('loader').style.display = 'none';
270
  }}
271
 
 
272
  async function callGroq(messages) {{
273
  try {{
274
  const r = await fetch("https://api.groq.com/openai/v1/chat/completions", {{
 
277
  body: JSON.stringify({{
278
  model: "llama-3.3-70b-versatile",
279
  messages: messages,
280
+ temperature: 0.7, top_p: 0.85, frequency_penalty: 0.7
281
  }})
282
  }});
283
  const d = await r.json(); return d.choices[0].message.content;
284
+ } catch(e) {{ return "Sweetie, the connection is a bit unstable."; }}
285
  }}
286
 
287
  function openMap() {{
 
299
  function flyToUser() {{
300
  if(userLat && userLon) {{
301
  worldMap.flyTo([userLat, userLon], 15);
302
+ L.marker([userLat, userLon]).addTo(worldMap).bindPopup("📍 My Spot").openPopup();
303
+ }} else alert("GPS off, honey!");
304
  }}
305
 
306
  function searchAndOpenMap(pName) {{