home 화면 간격 수정 .

main
hbyang 2026-02-10 16:36:33 +09:00
parent 793fc645e5
commit 9c975ad36a
6 changed files with 305 additions and 2141 deletions

View File

@ -3472,25 +3472,15 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 100%; width: 100%;
padding: 2rem 1rem; padding: 4rem 1rem 6rem;
position: relative; position: relative;
} }
/* Star Icon - positioned at top center based on Figma (y: 144) */ /* Star Icon - centered above title */
.welcome-star { .welcome-star {
position: absolute;
top: 60px;
left: 50%;
transform: translateX(-50%);
width: 40px; width: 40px;
height: 40px; height: 40px;
z-index: 1; margin: 0 auto 12px;
}
@media (min-width: 768px) {
.welcome-star {
top: 80px;
}
} }
.welcome-star img { .welcome-star img {
@ -3501,13 +3491,13 @@
.welcome-header { .welcome-header {
text-align: center; text-align: center;
margin-bottom: 2rem; margin-bottom: 3rem;
z-index: 1; z-index: 1;
} }
@media (min-width: 768px) { @media (min-width: 768px) {
.welcome-header { .welcome-header {
margin-bottom: 3rem; margin-bottom: 4rem;
} }
} }

View File

@ -1,482 +0,0 @@
"""
네이버 플레이스 검색 API 모듈
업체명으로 검색하여 place_id를 찾고, 상세정보(사진 포함) 조회
"""
import asyncio
import re
import requests
from dataclasses import dataclass
from typing import Optional, List, Dict, Any
# ============================================================
# Data Classes
# ============================================================
@dataclass
class NaverConfig:
"""네이버 API 설정"""
naver_client_id: str = "cp5MzIsZ8PSQPeQQkVKR"
naver_client_secret: str = "lhdrHgx31G"
naver_local_api_url: str = "https://openapi.naver.com/v1/search/local.json"
@dataclass
class PlaceDetailInfo:
"""네이버 플레이스 상세 정보"""
place_id: str
name: str
category: str
address: str
road_address: str
phone: str
description: str
images: List[str]
business_hours: str
homepage: str
keywords: List[str]
facilities: List[str]
# ============================================================
# Main API Class
# ============================================================
class NaverPlaceAPI:
"""
네이버 플레이스 API 클래스
주요 기능:
- quick_search(): 빠른 자동완성 검색 (place_id 없음)
- autocomplete_search(): place_id 포함 검색 (브라우저 폴백)
- get_place_detail(): place_id로 상세정보 조회
- convert_to_crawling_response(): CrawlingResponse 형식 변환
"""
ACCOMMODATION_CATEGORIES = [
"펜션", "숙박", "호텔", "모텔", "리조트", "게스트하우스",
"민박", "글램핑", "캠핑", "풀빌라", "스테이", "독채"
]
def __init__(self, config: NaverConfig = None):
self.config = config or NaverConfig()
self.search_url = self.config.naver_local_api_url
self.headers = {
"X-Naver-Client-Id": self.config.naver_client_id,
"X-Naver-Client-Secret": self.config.naver_client_secret,
}
self.browser_headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "ko-KR,ko;q=0.9",
"Referer": "https://map.naver.com/",
}
# ============================================================
# Public Methods
# ============================================================
async def quick_search(self, query: str) -> List[Dict[str, Any]]:
"""
빠른 자동완성 검색 (place_id 조회 없음)
Args:
query: 검색어
Returns:
[{"title": "업체명", "category": "카테고리", "address": "주소"}, ...]
"""
try:
response = await asyncio.to_thread(
requests.get,
self.search_url,
headers=self.headers,
params={"query": query, "display": 10},
timeout=5
)
if response.status_code != 200:
return []
items = response.json().get("items", [])
return [
{
"title": self._clean_html(item.get("title", "")),
"category": item.get("category", ""),
"address": item.get("roadAddress") or item.get("address", ""),
}
for item in items
]
except Exception:
return []
async def autocomplete_search(self, query: str) -> List[Dict[str, Any]]:
"""
place_id 포함 검색 (API 실패 브라우저 폴백)
Args:
query: 검색어 또는 네이버 지도 URL
Returns:
[{"place_id": "123", "title": "업체명", "category": "카테고리",
"address": "주소", "is_accommodation": True}, ...]
"""
# URL인 경우 place_id 추출
if query.startswith("http"):
place_id = self._extract_place_id_from_url(query)
if place_id:
detail = await self.get_place_detail(place_id)
if detail:
return [{
"place_id": place_id,
"title": detail.name,
"category": detail.category,
"address": detail.road_address or detail.address,
"is_accommodation": self._is_accommodation(detail.category),
}]
return []
# API로 검색
api_results = await self._search_with_api(query)
if api_results and any(r.get("place_id") for r in api_results):
return api_results
# API 실패 시 브라우저로 검색
print("API에서 place_id를 찾지 못함. 브라우저 검색 시도...")
browser_results = await self._search_with_browser(query)
if browser_results and any(r.get("place_id") for r in browser_results):
# API 결과에 브라우저에서 찾은 place_id 매칭
if api_results:
self._merge_place_ids(api_results, browser_results)
return api_results
return browser_results
return api_results or []
async def get_place_detail(self, place_id: str) -> Optional[PlaceDetailInfo]:
"""
place_id로 상세정보 조회
Args:
place_id: 네이버 플레이스 ID
Returns:
PlaceDetailInfo 또는 None
"""
if not place_id:
return None
try:
response = await asyncio.to_thread(
requests.get,
f"https://map.naver.com/p/api/place/summary/{place_id}",
headers={**self.browser_headers, "Referer": f"https://map.naver.com/p/entry/place/{place_id}"}
)
if response.status_code != 200:
print(f"Detail API Error: {response.status_code}")
return None
pd = response.json().get("data", {}).get("placeDetail", {})
if not pd:
print("No placeDetail in response")
return None
return PlaceDetailInfo(
place_id=place_id,
name=pd.get("name", ""),
category=self._parse_category(pd.get("category")),
address=self._parse_address(pd.get("address"), "address"),
road_address=self._parse_address(pd.get("address"), "roadAddress"),
phone="",
description="",
images=self._parse_images(pd.get("images")),
business_hours=self._parse_business_hours(pd.get("businessHours")),
homepage="",
keywords=self._parse_keywords(pd.get("visitorReviews")),
facilities=self._parse_facilities(pd.get("labels"))
)
except Exception as e:
print(f"Detail fetch error: {e}")
return None
def convert_to_crawling_response(self, detail: PlaceDetailInfo) -> Dict[str, Any]:
"""PlaceDetailInfo를 CrawlingResponse 형식으로 변환"""
address = detail.road_address or detail.address
address_parts = address.split() if address else []
region = address_parts[0] if address_parts else ""
# 태그 생성
tags = []
if region:
tags.append(f"#{region}")
for keyword in detail.keywords[:5]:
tags.append(f"#{keyword}" if not keyword.startswith("#") else keyword)
# 시설 정보
facilities = detail.facilities[:]
if detail.category:
for cat in detail.category.split(">"):
cat = cat.strip()
if cat and cat not in facilities:
facilities.append(cat)
return {
"image_list": detail.images,
"image_count": len(detail.images),
"processed_info": {
"customer_name": detail.name,
"region": region,
"detail_region_info": address
},
"marketing_analysis": {
"report": self._generate_report(detail, address),
"tags": tags,
"facilities": facilities
}
}
# ============================================================
# Private Methods - Search
# ============================================================
async def _search_with_api(self, query: str) -> List[Dict[str, Any]]:
"""Local Search API로 검색 후 좌표로 place_id 조회"""
try:
response = await asyncio.to_thread(
requests.get,
self.search_url,
headers=self.headers,
params={"query": query, "display": 5},
timeout=10
)
if response.status_code != 200:
print(f"Local Search API Error: {response.status_code}")
return []
items = response.json().get("items", [])
results = []
for item in items:
title = self._clean_html(item.get("title", ""))
category = item.get("category", "")
mapx, mapy = item.get("mapx", ""), item.get("mapy", "")
lng = float(mapx) / 10000000 if mapx else 0
lat = float(mapy) / 10000000 if mapy else 0
results.append({
"place_id": "",
"title": title,
"category": category,
"address": item.get("roadAddress") or item.get("address", ""),
"lng": lng,
"lat": lat,
"is_accommodation": self._is_accommodation(category),
})
# 좌표로 place_id 찾기
for result in results:
result["place_id"] = await self._find_place_id_by_coord(
result["title"], result["lng"], result["lat"]
)
return results
except Exception as e:
print(f"Search error: {e}")
return []
async def _find_place_id_by_coord(self, name: str, lng: float, lat: float) -> str:
"""좌표와 업체명으로 place_id 찾기"""
try:
response = await asyncio.to_thread(
requests.get,
"https://map.naver.com/p/api/search/allSearch",
headers=self.browser_headers,
params={"query": name, "type": "place", "searchCoord": f"{lng};{lat}", "displayCount": 1},
timeout=5
)
if response.status_code == 200:
result = response.json().get("result", {})
if "ncaptcha" not in result:
place_list = result.get("place", {}).get("list", [])
if place_list:
return str(place_list[0].get("id", ""))
return ""
except Exception:
return ""
async def _search_with_browser(self, query: str) -> List[Dict[str, Any]]:
"""Playwright 브라우저로 place_id 검색"""
try:
from playwright.async_api import async_playwright
except ImportError:
print("playwright가 설치되지 않았습니다. pip install playwright")
return []
results = []
try:
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
context = await browser.new_context(user_agent=self.browser_headers["User-Agent"])
page = await context.new_page()
await page.goto(f"https://map.naver.com/p/search/{query}", wait_until="domcontentloaded", timeout=20000)
await page.wait_for_timeout(5000)
search_frame = page.frame(name="searchIframe")
if search_frame:
html = await search_frame.content()
text = await search_frame.inner_text('body')
results = self._parse_browser_results(html, text)
await browser.close()
except Exception as e:
print(f"Browser search error: {e}")
return results[:10]
def _parse_browser_results(self, html: str, text: str) -> List[Dict[str, Any]]:
"""브라우저 HTML에서 검색 결과 파싱"""
# place_id 추출
place_ids = []
for pattern in [r'"id":"(\d+)"', r'/place/(\d+)', r'data-id="(\d+)"']:
place_ids.extend(re.findall(pattern, html))
place_ids = list(dict.fromkeys(place_ids)) # 중복 제거
# 텍스트에서 업체 정보 파싱
results = []
lines = text.split('\n')
current_place = {}
place_index = 0
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith('이미지수'):
if current_place.get('title') and place_index < len(place_ids):
current_place['place_id'] = place_ids[place_index]
results.append(current_place)
place_index += 1
current_place = {}
continue
if not current_place.get('title') and len(line) > 1 and not line.isdigit():
if line not in ['네이버페이', '톡톡', '쿠폰', '알림받기']:
current_place['title'] = line
continue
if not current_place.get('category'):
for keyword in self.ACCOMMODATION_CATEGORIES + ['장소대여', '전통숙소']:
if keyword in line:
current_place['category'] = line
current_place['is_accommodation'] = self._is_accommodation(line)
break
# 에라 모르겄다 그냥 전국 다 쳐넣어
if not current_place.get('address'):
regions = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '세종',
'경기', '강원', '충북', '충남', '전북', '전남', '경북', '경남', '제주']
for region in regions:
if line.startswith(region):
current_place['address'] = line
break
if current_place.get('title') and place_index < len(place_ids):
current_place['place_id'] = place_ids[place_index]
results.append(current_place)
return results
def _merge_place_ids(self, api_results: List[Dict], browser_results: List[Dict]):
"""브라우저 결과의 place_id를 API 결과에 매칭"""
for api_r in api_results:
for br_r in browser_results:
if br_r.get("place_id") and api_r.get("title"):
if api_r["title"] in br_r.get("title", "") or br_r.get("title", "") in api_r["title"]:
api_r["place_id"] = br_r["place_id"]
break
# ============================================================
# Private Methods - Parsing
# ============================================================
def _clean_html(self, text: str) -> str:
"""HTML 태그 제거"""
return text.replace("<b>", "").replace("</b>", "")
def _is_accommodation(self, category: str) -> bool:
"""숙박 카테고리 여부"""
return bool(category and any(k in category for k in self.ACCOMMODATION_CATEGORIES))
def _extract_place_id_from_url(self, url: str) -> str:
"""URL에서 place_id 추출"""
for pattern in [r'/place/(\d+)', r'/entry/place/(\d+)', r'place_id=(\d+)']:
match = re.search(pattern, url)
if match:
return match.group(1)
return ""
def _parse_category(self, category_data) -> str:
if isinstance(category_data, dict):
return category_data.get("category", "")
return category_data if isinstance(category_data, str) else ""
def _parse_address(self, address_data, key: str) -> str:
if isinstance(address_data, dict):
return address_data.get(key, "")
return address_data if isinstance(address_data, str) and key == "address" else ""
def _parse_images(self, images_data, limit: int = 20) -> List[str]:
images = []
if isinstance(images_data, dict):
for img in images_data.get("images", [])[:limit]:
if isinstance(img, dict):
url = img.get("origin") or img.get("url") or img.get("thumbnail")
if url:
images.append(url)
elif isinstance(img, str):
images.append(img)
return images
def _parse_business_hours(self, hours_data) -> str:
if isinstance(hours_data, dict):
return hours_data.get("status", "")
return hours_data if isinstance(hours_data, str) else ""
def _parse_keywords(self, reviews_data) -> List[str]:
if isinstance(reviews_data, dict):
display_text = reviews_data.get("displayText", "")
return [display_text] if display_text else []
return []
def _parse_facilities(self, labels_data) -> List[str]:
facilities = []
if isinstance(labels_data, dict):
if labels_data.get("booking"):
facilities.append("예약가능")
if labels_data.get("nPay"):
facilities.append("네이버페이")
if labels_data.get("talktalk"):
facilities.append("톡톡")
return facilities
def _generate_report(self, detail: PlaceDetailInfo, address: str) -> str:
return (
f"## 업체 정보\n{detail.name}은(는) {detail.category} 카테고리에 속한 업체입니다.\n\n"
f"## 위치\n{address}\n\n"
f"## 연락처\n{detail.phone or '정보 없음'}\n\n"
f"## 영업시간\n{detail.business_hours or '정보 없음'}\n\n"
f"## 설명\n{detail.description or '정보 없음'}"
)

View File

@ -1,178 +0,0 @@
"""
네이버 플레이스 검색 테스트 서버
Flask를 사용하여 검색 상세정보 조회 API 제공
"""
import asyncio
import sys
from io import StringIO
from flask import Flask, render_template, request, jsonify
from main import NaverPlaceAPI
app = Flask(__name__)
place_api = NaverPlaceAPI()
# ============================================================
# Utilities
# ============================================================
class LogCapture:
"""콘솔 출력을 캡처하는 컨텍스트 매니저"""
def __init__(self):
self.logs = []
self._stdout = None
self._capture = None
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._capture = StringIO()
return self
def __exit__(self, *args):
self.logs = [log for log in self._capture.getvalue().split('\n') if log.strip()]
sys.stdout = self._stdout
def get_logs(self):
return self.logs
def run_async(coro):
"""비동기 함수를 동기적으로 실행"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
loop.close()
# ============================================================
# Routes - Pages
# ============================================================
@app.route('/')
def index():
"""검색 페이지"""
return render_template('search.html')
@app.route('/result')
def result():
"""결과 페이지"""
return render_template('result.html')
# ============================================================
# Routes - API
# ============================================================
@app.route('/api/autocomplete', methods=['POST'])
def api_autocomplete():
"""
빠른 자동완성 API (place_id 없음)
Request: {"query": "스테이"}
Response: {"results": [{"title": "...", "category": "...", "address": "..."}], "count": 10}
"""
try:
data = request.get_json()
query = data.get('query', '').strip()
if not query or len(query) < 2:
return jsonify({'results': []})
results = run_async(place_api.quick_search(query))
return jsonify({'results': results, 'count': len(results)})
except Exception as e:
return jsonify({'results': [], 'error': str(e)})
@app.route('/api/search', methods=['POST'])
def api_search():
"""
검색 API (place_id 포함)
Request: {"query": "스테이 머뭄"}
Response: {"results": [{"place_id": "123", "title": "...", ...}], "count": 5, "logs": [...]}
"""
try:
data = request.get_json()
query = data.get('query', '').strip()
if not query:
return jsonify({'error': '검색어를 입력해주세요.'}), 400
with LogCapture() as log_capture:
results = run_async(place_api.autocomplete_search(query))
return jsonify({
'results': results,
'count': len(results),
'logs': log_capture.get_logs(),
'query': query
})
except Exception as e:
import traceback
return jsonify({'error': str(e), 'trace': traceback.format_exc()}), 500
@app.route('/api/detail', methods=['POST'])
def api_detail():
"""
상세정보 API
Request: {"place_id": "1133638931"}
Response: {"detail": {...}, "crawling_response": {...}, "logs": [...]}
"""
try:
data = request.get_json()
place_id = data.get('place_id', '').strip()
if not place_id:
return jsonify({'error': 'place_id를 입력해주세요.'}), 400
with LogCapture() as log_capture:
detail = run_async(place_api.get_place_detail(place_id))
if not detail:
return jsonify({'error': '상세 정보를 찾을 수 없습니다.', 'logs': log_capture.get_logs()}), 404
return jsonify({
'detail': {
'place_id': detail.place_id,
'name': detail.name,
'category': detail.category,
'address': detail.address,
'road_address': detail.road_address,
'phone': detail.phone,
'description': detail.description,
'images': detail.images,
'business_hours': detail.business_hours,
'homepage': detail.homepage,
'keywords': detail.keywords,
'facilities': detail.facilities,
},
'crawling_response': place_api.convert_to_crawling_response(detail),
'logs': log_capture.get_logs()
})
except Exception as e:
import traceback
return jsonify({'error': str(e), 'trace': traceback.format_exc()}), 500
# ============================================================
# Entry Point
# ============================================================
if __name__ == '__main__':
print("=" * 60)
print("네이버 플레이스 검색 테스트 서버")
print("=" * 60)
print("브라우저에서 http://localhost:5001 으로 접속하세요")
print("=" * 60)
app.run(debug=True, port=5001, use_reloader=False)

View File

@ -1,717 +0,0 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>크롤링 결과</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
min-height: 100vh;
color: #fff;
}
.container {
max-width: 1000px;
margin: 0 auto;
padding: 40px 20px;
}
.back-btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 12px 20px;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 10px;
color: #fff;
font-size: 1rem;
cursor: pointer;
transition: all 0.3s ease;
margin-bottom: 30px;
}
.back-btn:hover {
background: rgba(255, 255, 255, 0.2);
}
.loading {
text-align: center;
padding: 80px;
}
.spinner {
width: 60px;
height: 60px;
border: 4px solid rgba(255, 255, 255, 0.1);
border-top-color: #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 20px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.result-container {
display: none;
}
.result-container.active {
display: block;
}
.business-header {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 20px;
padding: 32px;
margin-bottom: 24px;
}
.business-name {
font-size: 2.2rem;
font-weight: 700;
margin-bottom: 8px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.business-category {
font-size: 1.1rem;
color: #a0aec0;
margin-bottom: 16px;
}
.business-address {
display: flex;
align-items: center;
gap: 8px;
color: #718096;
}
.info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 24px;
margin-bottom: 24px;
}
.info-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 24px;
}
.info-card h3 {
font-size: 1.1rem;
color: #667eea;
margin-bottom: 16px;
display: flex;
align-items: center;
gap: 8px;
}
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.tag {
padding: 8px 16px;
background: rgba(102, 126, 234, 0.2);
border-radius: 20px;
font-size: 0.9rem;
color: #a78bfa;
}
.facility-tag {
background: rgba(72, 187, 120, 0.2);
color: #68d391;
}
.images-section {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 24px;
margin-bottom: 24px;
}
.images-section h3 {
font-size: 1.1rem;
color: #667eea;
margin-bottom: 16px;
}
.images-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
}
.image-item {
aspect-ratio: 4/3;
border-radius: 12px;
overflow: hidden;
background: rgba(0, 0, 0, 0.3);
}
.image-item img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.image-item:hover img {
transform: scale(1.05);
}
.report-section {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 24px;
margin-bottom: 24px;
}
.report-section h3 {
font-size: 1.1rem;
color: #667eea;
margin-bottom: 16px;
}
.report-content {
line-height: 1.8;
color: #e2e8f0;
}
.report-content h4 {
color: #a78bfa;
margin: 20px 0 10px;
font-size: 1rem;
}
.json-section {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 24px;
}
.json-section h3 {
font-size: 1.1rem;
color: #667eea;
margin-bottom: 16px;
display: flex;
align-items: center;
justify-content: space-between;
}
.copy-btn {
padding: 8px 16px;
background: rgba(102, 126, 234, 0.3);
border: none;
border-radius: 8px;
color: #fff;
font-size: 0.85rem;
cursor: pointer;
transition: all 0.3s ease;
}
.copy-btn:hover {
background: rgba(102, 126, 234, 0.5);
}
.json-content {
background: rgba(0, 0, 0, 0.3);
border-radius: 12px;
padding: 20px;
overflow-x: auto;
font-family: 'Fira Code', 'Monaco', monospace;
font-size: 0.85rem;
line-height: 1.6;
color: #a0aec0;
max-height: 400px;
overflow-y: auto;
}
.log-section {
background: rgba(0, 0, 0, 0.3);
border-radius: 12px;
padding: 16px;
margin-bottom: 24px;
}
.log-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.log-title {
font-size: 0.9rem;
color: #a0aec0;
display: flex;
align-items: center;
gap: 8px;
}
.log-toggle {
background: none;
border: none;
color: #667eea;
cursor: pointer;
font-size: 0.85rem;
}
.log-content {
background: rgba(0, 0, 0, 0.4);
border-radius: 8px;
padding: 12px;
font-family: 'Fira Code', monospace;
font-size: 0.8rem;
color: #68d391;
max-height: 150px;
overflow-y: auto;
}
.log-line {
margin-bottom: 4px;
padding: 2px 0;
}
.log-line.info { color: #68d391; }
.log-line.warn { color: #fbd38d; }
.log-line.error { color: #fc8181; }
.detail-info-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 24px;
margin-bottom: 24px;
}
.detail-info-card h3 {
font-size: 1.1rem;
color: #667eea;
margin-bottom: 16px;
}
.detail-row {
display: flex;
padding: 10px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.detail-row:last-child {
border-bottom: none;
}
.detail-label {
width: 140px;
color: #a0aec0;
flex-shrink: 0;
}
.detail-value {
color: #e2e8f0;
flex: 1;
}
.detail-value a {
color: #667eea;
text-decoration: none;
}
.detail-value a:hover {
text-decoration: underline;
}
.tab-container {
margin-bottom: 24px;
}
.tab-buttons {
display: flex;
gap: 8px;
margin-bottom: 16px;
}
.tab-btn {
padding: 10px 20px;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 8px;
color: #a0aec0;
cursor: pointer;
transition: all 0.3s ease;
}
.tab-btn.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.error-container {
text-align: center;
padding: 60px;
display: none;
}
.error-container.active {
display: block;
}
.error-icon {
font-size: 4rem;
margin-bottom: 20px;
}
.error-message {
font-size: 1.2rem;
color: #fca5a5;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
<button class="back-btn" onclick="goBack()">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M15 18l-6-6 6-6"/>
</svg>
검색으로 돌아가기
</button>
<div class="loading" id="loading">
<div class="spinner"></div>
<p>상세 정보를 불러오는 중...</p>
</div>
<div class="error-container" id="errorContainer">
<div class="error-icon">⚠️</div>
<p class="error-message" id="errorMessage"></p>
<button class="back-btn" onclick="goBack()">다시 검색하기</button>
</div>
<div class="result-container" id="resultContainer">
<!-- 로그 섹션 -->
<div class="log-section" id="logSection" style="display: none;">
<div class="log-header">
<span class="log-title">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
</svg>
API 호출 로그
</span>
<button class="log-toggle" onclick="toggleLog()">접기/펼치기</button>
</div>
<div class="log-content" id="logContent"></div>
</div>
<!-- Business Header -->
<div class="business-header">
<h1 class="business-name" id="businessName"></h1>
<p class="business-category" id="businessCategory"></p>
<p class="business-address">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
<circle cx="12" cy="10" r="3"/>
</svg>
<span id="businessAddress"></span>
</p>
</div>
<!-- 원본 상세 정보 -->
<div class="detail-info-card">
<h3>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display: inline-block; vertical-align: middle; margin-right: 8px;">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="16" x2="12" y2="12"/>
<line x1="12" y1="8" x2="12.01" y2="8"/>
</svg>
원본 상세 정보
</h3>
<div id="rawDetailInfo"></div>
</div>
<!-- Info Grid -->
<div class="info-grid">
<div class="info-card">
<h3>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/>
<line x1="7" y1="7" x2="7.01" y2="7"/>
</svg>
추천 타겟 키워드
</h3>
<div class="tag-list" id="tagList"></div>
</div>
<div class="info-card">
<h3>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
<line x1="9" y1="9" x2="15" y2="9"/>
<line x1="9" y1="15" x2="15" y2="15"/>
</svg>
시설 및 서비스
</h3>
<div class="tag-list" id="facilityList"></div>
</div>
</div>
<!-- Images Section -->
<div class="images-section" id="imagesSection">
<h3>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display: inline-block; vertical-align: middle; margin-right: 8px;">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
<circle cx="8.5" cy="8.5" r="1.5"/>
<polyline points="21,15 16,10 5,21"/>
</svg>
수집된 이미지 (<span id="imageCount">0</span>장)
</h3>
<div class="images-grid" id="imagesGrid"></div>
</div>
<!-- Report Section -->
<div class="report-section">
<h3>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display: inline-block; vertical-align: middle; margin-right: 8px;">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14,2 14,8 20,8"/>
<line x1="16" y1="13" x2="8" y2="13"/>
<line x1="16" y1="17" x2="8" y2="17"/>
</svg>
마케팅 분석 리포트
</h3>
<div class="report-content" id="reportContent"></div>
</div>
<!-- JSON Section -->
<div class="json-section">
<h3>
CrawlingResponse JSON
<button class="copy-btn" onclick="copyJson()">복사</button>
</h3>
<pre class="json-content" id="jsonContent"></pre>
</div>
</div>
</div>
<script>
let crawlingData = null;
let rawDetailData = null;
let logVisible = true;
function goBack() {
window.location.href = '/';
}
function toggleLog() {
const logContent = document.getElementById('logContent');
logVisible = !logVisible;
logContent.style.display = logVisible ? 'block' : 'none';
}
function displayLogs(logs) {
const logSection = document.getElementById('logSection');
const logContent = document.getElementById('logContent');
if (!logs || logs.length === 0) {
logSection.style.display = 'none';
return;
}
let html = '';
logs.forEach(log => {
let className = 'info';
if (log.includes('error') || log.includes('Error') || log.includes('실패')) {
className = 'error';
} else if (log.includes('시도') || log.includes('찾지 못함')) {
className = 'warn';
}
html += `<div class="log-line ${className}">${log}</div>`;
});
logContent.innerHTML = html;
logSection.style.display = 'block';
}
function displayRawDetail(detail) {
const container = document.getElementById('rawDetailInfo');
if (!detail) {
container.innerHTML = '<p style="color: #718096;">상세 정보 없음</p>';
return;
}
const rows = [
{ label: 'place_id', value: detail.place_id },
{ label: '업체명', value: detail.name },
{ label: '카테고리', value: detail.category },
{ label: '지번 주소', value: detail.address },
{ label: '도로명 주소', value: detail.road_address },
{ label: '전화번호', value: detail.phone },
{ label: '설명', value: detail.description },
{ label: '영업시간', value: detail.business_hours },
{ label: '홈페이지', value: detail.homepage, isLink: true },
{ label: '키워드', value: detail.keywords ? detail.keywords.join(', ') : null },
{ label: '시설', value: detail.facilities ? detail.facilities.join(', ') : null },
{ label: '이미지 수', value: detail.images ? detail.images.length + '개' : '0개' },
];
let html = '';
rows.forEach(row => {
const value = row.value || '-';
let displayValue = value;
if (row.isLink && row.value) {
displayValue = `<a href="${row.value}" target="_blank">${row.value}</a>`;
}
html += `
<div class="detail-row">
<span class="detail-label">${row.label}</span>
<span class="detail-value">${displayValue}</span>
</div>
`;
});
container.innerHTML = html;
}
async function loadDetail() {
const urlParams = new URLSearchParams(window.location.search);
const placeId = urlParams.get('place_id');
const title = decodeURIComponent(urlParams.get('title') || '');
if (!placeId) {
showError('place_id가 없습니다.');
return;
}
try {
const response = await fetch('/api/detail', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ place_id: placeId }),
});
const data = await response.json();
// 로그 표시
displayLogs(data.logs);
if (data.error) {
showError(data.error);
return;
}
crawlingData = data.crawling_response;
rawDetailData = data.detail;
// 원본 상세 정보 표시
displayRawDetail(data.detail);
// 크롤링 응답 표시
displayResult(data.crawling_response);
} catch (error) {
showError('상세 정보를 불러오는 중 오류가 발생했습니다: ' + error.message);
}
}
function showError(message) {
document.getElementById('loading').style.display = 'none';
document.getElementById('errorMessage').textContent = message;
document.getElementById('errorContainer').classList.add('active');
}
function displayResult(data) {
document.getElementById('loading').style.display = 'none';
document.getElementById('resultContainer').classList.add('active');
// Business Info
document.getElementById('businessName').textContent = data.processed_info.customer_name;
document.getElementById('businessCategory').textContent = data.marketing_analysis.facilities.join(' · ') || '정보 없음';
document.getElementById('businessAddress').textContent = data.processed_info.detail_region_info;
// Tags
const tagList = document.getElementById('tagList');
tagList.innerHTML = data.marketing_analysis.tags.map(tag =>
`<span class="tag">${tag}</span>`
).join('');
// Facilities
const facilityList = document.getElementById('facilityList');
facilityList.innerHTML = data.marketing_analysis.facilities.map(facility =>
`<span class="tag facility-tag">${facility}</span>`
).join('');
// Images
const imageCount = data.image_count || 0;
document.getElementById('imageCount').textContent = imageCount;
if (imageCount > 0) {
const imagesGrid = document.getElementById('imagesGrid');
imagesGrid.innerHTML = data.image_list.map(url =>
`<div class="image-item">
<img src="${url}" alt="업체 이미지" loading="lazy" onerror="this.src='https://via.placeholder.com/400x300?text=Image+Not+Found'">
</div>`
).join('');
} else {
document.getElementById('imagesSection').style.display = 'none';
}
// Report
const reportContent = document.getElementById('reportContent');
const report = data.marketing_analysis.report;
reportContent.innerHTML = report
.replace(/## (.*)/g, '<h4>$1</h4>')
.replace(/\n/g, '<br>');
// JSON
document.getElementById('jsonContent').textContent = JSON.stringify(data, null, 2);
}
function copyJson() {
if (crawlingData) {
navigator.clipboard.writeText(JSON.stringify(crawlingData, null, 2))
.then(() => {
alert('JSON이 클립보드에 복사되었습니다.');
})
.catch(err => {
console.error('복사 실패:', err);
});
}
}
// 페이지 로드 시 상세 정보 불러오기
window.onload = loadDetail;
</script>
</body>
</html>

View File

@ -1,749 +0,0 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>네이버 플레이스 검색</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
min-height: 100vh;
color: #fff;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 40px 20px;
}
.header {
text-align: center;
margin-bottom: 40px;
}
.header h1 {
font-size: 2.5rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin-bottom: 10px;
}
.header p {
color: #a0aec0;
font-size: 1.1rem;
}
.search-box {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 30px;
margin-bottom: 30px;
}
.search-input-wrapper {
display: flex;
gap: 12px;
position: relative;
}
.search-input-container {
flex: 1;
position: relative;
}
.search-input {
width: 100%;
padding: 16px 20px;
font-size: 1.1rem;
border: 2px solid rgba(255, 255, 255, 0.2);
border-radius: 12px;
background: rgba(255, 255, 255, 0.05);
color: #fff;
outline: none;
transition: all 0.3s ease;
}
.search-input:focus {
border-color: #667eea;
background: rgba(255, 255, 255, 0.1);
}
.search-input::placeholder {
color: #718096;
}
/* 자동완성 드롭다운 스타일 */
.autocomplete-dropdown {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: rgba(30, 30, 50, 0.98);
border: 2px solid rgba(102, 126, 234, 0.5);
border-top: none;
border-radius: 0 0 12px 12px;
max-height: 300px;
overflow-y: auto;
z-index: 1000;
display: none;
}
.autocomplete-dropdown.active {
display: block;
}
.autocomplete-item {
padding: 12px 16px;
cursor: pointer;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
transition: background 0.2s ease;
}
.autocomplete-item:last-child {
border-bottom: none;
}
.autocomplete-item:hover {
background: rgba(102, 126, 234, 0.2);
}
.autocomplete-item.selected {
background: rgba(102, 126, 234, 0.3);
}
.autocomplete-title {
font-size: 1rem;
font-weight: 500;
color: #fff;
margin-bottom: 4px;
}
.autocomplete-meta {
font-size: 0.85rem;
color: #a0aec0;
}
.autocomplete-loading {
padding: 16px;
text-align: center;
color: #a0aec0;
}
.autocomplete-loading .mini-spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid rgba(255, 255, 255, 0.1);
border-top-color: #667eea;
border-radius: 50%;
animation: spin 0.8s linear infinite;
margin-right: 8px;
vertical-align: middle;
}
.search-btn {
padding: 16px 32px;
font-size: 1.1rem;
font-weight: 600;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
border: none;
border-radius: 12px;
cursor: pointer;
transition: all 0.3s ease;
}
.search-btn:hover {
transform: translateY(-2px);
box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
}
.search-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.loading {
text-align: center;
padding: 40px;
display: none;
}
.loading.active {
display: block;
}
.spinner {
width: 50px;
height: 50px;
border: 4px solid rgba(255, 255, 255, 0.1);
border-top-color: #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 20px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.results {
display: none;
}
.results.active {
display: block;
}
.result-item {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 24px;
margin-bottom: 16px;
cursor: pointer;
transition: all 0.3s ease;
border: 2px solid transparent;
}
.result-item:hover {
background: rgba(255, 255, 255, 0.15);
border-color: #667eea;
transform: translateX(8px);
}
.result-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 12px;
}
.result-title {
font-size: 1.3rem;
font-weight: 600;
}
.result-badge {
padding: 4px 12px;
background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
border-radius: 20px;
font-size: 0.85rem;
font-weight: 500;
}
.result-badge.accommodation {
background: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
}
.result-category {
color: #a0aec0;
font-size: 0.95rem;
margin-bottom: 8px;
}
.result-address {
color: #718096;
font-size: 0.9rem;
}
.result-place-id {
color: #667eea;
font-size: 0.85rem;
margin-top: 8px;
font-family: monospace;
}
.no-results {
text-align: center;
padding: 40px;
color: #a0aec0;
}
.error-message {
background: rgba(239, 68, 68, 0.2);
border: 1px solid rgba(239, 68, 68, 0.5);
border-radius: 12px;
padding: 16px;
color: #fca5a5;
margin-top: 20px;
display: none;
}
.error-message.active {
display: block;
}
.info-text {
text-align: center;
color: #718096;
font-size: 0.9rem;
margin-top: 20px;
}
.log-section {
background: rgba(0, 0, 0, 0.3);
border-radius: 12px;
padding: 16px;
margin-top: 20px;
display: none;
}
.log-section.active {
display: block;
}
.log-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.log-title {
font-size: 0.9rem;
color: #a0aec0;
display: flex;
align-items: center;
gap: 8px;
}
.log-toggle {
background: none;
border: none;
color: #667eea;
cursor: pointer;
font-size: 0.85rem;
}
.log-content {
background: rgba(0, 0, 0, 0.4);
border-radius: 8px;
padding: 12px;
font-family: 'Fira Code', monospace;
font-size: 0.8rem;
color: #68d391;
max-height: 200px;
overflow-y: auto;
}
.log-line {
margin-bottom: 4px;
padding: 2px 0;
}
.log-line.info {
color: #68d391;
}
.log-line.warn {
color: #fbd38d;
}
.log-line.error {
color: #fc8181;
}
.search-stats {
display: flex;
gap: 16px;
margin-bottom: 16px;
padding: 12px 16px;
background: rgba(102, 126, 234, 0.1);
border-radius: 10px;
font-size: 0.9rem;
}
.stat-item {
display: flex;
align-items: center;
gap: 6px;
color: #a0aec0;
}
.stat-value {
color: #667eea;
font-weight: 600;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>네이버 플레이스 검색</h1>
<p>숙박/펜션 업체를 검색하고 상세 정보를 확인하세요</p>
</div>
<div class="search-box">
<div class="search-input-wrapper">
<div class="search-input-container">
<input
type="text"
class="search-input"
id="searchInput"
placeholder="업체명을 입력하세요 (예: 스테이 머뭄)"
oninput="handleInput(event)"
onkeydown="handleKeyDown(event)"
onfocus="showAutocomplete()"
autocomplete="off"
>
<div class="autocomplete-dropdown" id="autocompleteDropdown"></div>
</div>
<button class="search-btn" id="searchBtn" onclick="search()">검색</button>
</div>
<div class="error-message" id="errorMessage"></div>
</div>
<div class="loading" id="loading">
<div class="spinner"></div>
<p>검색 중입니다... (브라우저 검색은 5-7초 소요)</p>
</div>
<div class="results" id="results"></div>
<!-- 로그 섹션 -->
<div class="log-section" id="logSection">
<div class="log-header">
<span class="log-title">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
</svg>
검색 로그
</span>
<button class="log-toggle" onclick="toggleLog()">접기/펼치기</button>
</div>
<div class="log-content" id="logContent"></div>
</div>
<p class="info-text">
검색 결과에서 업체를 클릭하면 상세 정보 페이지로 이동합니다.
</p>
</div>
<script>
let logVisible = true;
let autocompleteTimeout = null;
let autocompleteResults = [];
let selectedIndex = -1;
// 자동완성 입력 처리
function handleInput(event) {
const query = event.target.value.trim();
// 이전 타임아웃 취소
if (autocompleteTimeout) {
clearTimeout(autocompleteTimeout);
}
if (query.length < 2) {
hideAutocomplete();
return;
}
// 300ms 디바운스
autocompleteTimeout = setTimeout(() => {
fetchAutocomplete(query);
}, 300);
}
// 키보드 네비게이션
function handleKeyDown(event) {
const dropdown = document.getElementById('autocompleteDropdown');
if (!dropdown.classList.contains('active')) {
if (event.key === 'Enter') {
search();
}
return;
}
const items = dropdown.querySelectorAll('.autocomplete-item');
switch(event.key) {
case 'ArrowDown':
event.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
updateSelection(items);
break;
case 'ArrowUp':
event.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, -1);
updateSelection(items);
break;
case 'Enter':
event.preventDefault();
if (selectedIndex >= 0 && autocompleteResults[selectedIndex]) {
selectAutocompleteItem(autocompleteResults[selectedIndex]);
} else {
hideAutocomplete();
search();
}
break;
case 'Escape':
hideAutocomplete();
break;
}
}
function updateSelection(items) {
items.forEach((item, index) => {
if (index === selectedIndex) {
item.classList.add('selected');
item.scrollIntoView({ block: 'nearest' });
} else {
item.classList.remove('selected');
}
});
}
// 자동완성 API 호출
async function fetchAutocomplete(query) {
const dropdown = document.getElementById('autocompleteDropdown');
// 로딩 표시
dropdown.innerHTML = '<div class="autocomplete-loading"><span class="mini-spinner"></span>검색 중...</div>';
dropdown.classList.add('active');
try {
const response = await fetch('/api/autocomplete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query })
});
const data = await response.json();
if (data.results && data.results.length > 0) {
autocompleteResults = data.results;
selectedIndex = -1;
renderAutocomplete(data.results);
} else {
dropdown.innerHTML = '<div class="autocomplete-loading">검색 결과가 없습니다</div>';
}
} catch (error) {
dropdown.innerHTML = '<div class="autocomplete-loading">자동완성 오류</div>';
}
}
// 자동완성 결과 렌더링
function renderAutocomplete(results) {
const dropdown = document.getElementById('autocompleteDropdown');
let html = '';
results.forEach((item, index) => {
const category = item.category || '';
const address = item.address || '';
html += `
<div class="autocomplete-item" onclick="selectAutocompleteItem(autocompleteResults[${index}])">
<div class="autocomplete-title">${item.title}</div>
<div class="autocomplete-meta">${category}${category && address ? ' · ' : ''}${address}</div>
</div>
`;
});
dropdown.innerHTML = html;
}
// 자동완성 항목 선택
function selectAutocompleteItem(item) {
// 주소에서 시/군/구 정보만 추출하여 검색어에 추가
// 예: "전북 군산시 나운동" -> "군산"
let locationKeyword = '';
if (item.address) {
// 주소에서 시/군/구 추출 (예: 군산시, 대구광역시, 강남구 등)
const match = item.address.match(/([가-힣]+(?:시|군|구))/);
if (match) {
locationKeyword = match[1].replace(/시$|군$|구$/, ''); // 시/군/구 제거
}
}
// 검색어: "업체명 지역" 형식으로 구성
const searchQuery = locationKeyword ? `${item.title} ${locationKeyword}` : item.title;
document.getElementById('searchInput').value = searchQuery;
hideAutocomplete();
search(); // 바로 검색 실행
}
function showAutocomplete() {
const query = document.getElementById('searchInput').value.trim();
if (query.length >= 2 && autocompleteResults.length > 0) {
document.getElementById('autocompleteDropdown').classList.add('active');
}
}
function hideAutocomplete() {
document.getElementById('autocompleteDropdown').classList.remove('active');
selectedIndex = -1;
}
// 외부 클릭 시 자동완성 숨기기
document.addEventListener('click', function(event) {
const container = document.querySelector('.search-input-container');
if (!container.contains(event.target)) {
hideAutocomplete();
}
});
function toggleLog() {
const logContent = document.getElementById('logContent');
logVisible = !logVisible;
logContent.style.display = logVisible ? 'block' : 'none';
}
function displayLogs(logs) {
const logSection = document.getElementById('logSection');
const logContent = document.getElementById('logContent');
if (!logs || logs.length === 0) {
logSection.classList.remove('active');
return;
}
let html = '';
logs.forEach(log => {
let className = 'info';
if (log.includes('error') || log.includes('Error')) {
className = 'error';
} else if (log.includes('찾지 못함') || log.includes('시도')) {
className = 'warn';
}
html += `<div class="log-line ${className}">${log}</div>`;
});
logContent.innerHTML = html;
logSection.classList.add('active');
}
async function search() {
const query = document.getElementById('searchInput').value.trim();
const searchBtn = document.getElementById('searchBtn');
const loading = document.getElementById('loading');
const results = document.getElementById('results');
const errorMessage = document.getElementById('errorMessage');
const logSection = document.getElementById('logSection');
if (!query) {
showError('검색어를 입력해주세요.');
return;
}
// UI 상태 변경
searchBtn.disabled = true;
loading.classList.add('active');
results.classList.remove('active');
errorMessage.classList.remove('active');
logSection.classList.remove('active');
try {
const response = await fetch('/api/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
const data = await response.json();
// 로그 표시
displayLogs(data.logs);
if (data.error) {
showError(data.error);
return;
}
displayResults(data.results, data.query, data.count);
} catch (error) {
showError('검색 중 오류가 발생했습니다: ' + error.message);
} finally {
searchBtn.disabled = false;
loading.classList.remove('active');
}
}
function showError(message) {
const errorMessage = document.getElementById('errorMessage');
errorMessage.textContent = message;
errorMessage.classList.add('active');
}
function displayResults(items, query, count) {
const results = document.getElementById('results');
if (!items || items.length === 0) {
results.innerHTML = '<div class="no-results">검색 결과가 없습니다.</div>';
results.classList.add('active');
return;
}
// 통계 정보
const accommodationCount = items.filter(i => i.is_accommodation).length;
const withPlaceIdCount = items.filter(i => i.place_id).length;
let html = `
<div class="search-stats">
<div class="stat-item">
<span>검색어:</span>
<span class="stat-value">"${query}"</span>
</div>
<div class="stat-item">
<span>총 결과:</span>
<span class="stat-value">${count}개</span>
</div>
<div class="stat-item">
<span>숙박업체:</span>
<span class="stat-value">${accommodationCount}개</span>
</div>
<div class="stat-item">
<span>place_id 있음:</span>
<span class="stat-value">${withPlaceIdCount}개</span>
</div>
</div>
`;
items.forEach((item, index) => {
const isAccommodation = item.is_accommodation;
const badgeClass = isAccommodation ? 'accommodation' : '';
const badgeText = isAccommodation ? '숙박업체' : '일반';
const hasPlaceId = item.place_id ? '' : 'style="opacity: 0.6"';
html += `
<div class="result-item" onclick="selectPlace('${item.place_id}', '${encodeURIComponent(item.title)}')" ${hasPlaceId}>
<div class="result-header">
<span class="result-title">${item.title}</span>
<span class="result-badge ${badgeClass}">${badgeText}</span>
</div>
<div class="result-category">${item.category || '카테고리 없음'}</div>
<div class="result-address">${item.address || '주소 정보 없음'}</div>
<div class="result-place-id">place_id: ${item.place_id || '❌ 없음 (상세조회 불가)'}</div>
</div>
`;
});
results.innerHTML = html;
results.classList.add('active');
}
function selectPlace(placeId, title) {
if (!placeId) {
alert('place_id가 없어 상세 정보를 조회할 수 없습니다.');
return;
}
window.location.href = `/result?place_id=${placeId}&title=${title}`;
}
</script>
</body>
</html>

File diff suppressed because one or more lines are too long