home 화면 간격 수정 .

This commit is contained in:
HyeongBaeYang committed 2026-02-10 16:36:33 +09:00
1 parent 793fc645e5
commit 9c975ad36a
6 files changed
+305 -2141

No files matched your search

+5 -15
View File
@@ -3472,25 +3472,15 @@
align-items: center;
justify-content: center;
width: 100%;
padding: 2rem 1rem;
padding: 4rem 1rem 6rem;
position: relative;
}
/* Star Icon - positioned at top center based on Figma (y: 144) */
/* Star Icon - centered above title */
.welcome-star {
position: absolute;
top: 60px;
left: 50%;
transform: translateX(-50%);
width: 40px;
height: 40px;
z-index: 1;
}
@media (min-width: 768px) {
.welcome-star {
top: 80px;
}
margin: 0 auto 12px;
}
.welcome-star img {
@@ -3501,13 +3491,13 @@
.welcome-header {
text-align: center;
margin-bottom: 2rem;
margin-bottom: 3rem;
z-index: 1;
}
@media (min-width: 768px) {
.welcome-header {
margin-bottom: 3rem;
margin-bottom: 4rem;
}
}
-482
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 '정보 없음'}"
)
-178
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)
-717
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>
-749
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>
+300
View File
@@ -0,0 +1,300 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ADO2 Translation Viewer</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0f1117; color: #e0e0e0; }
.header {
position: sticky; top: 0; z-index: 100;
background: #161822; border-bottom: 1px solid #2a2d3a;
padding: 16px 32px;
display: flex; align-items: center; justify-content: space-between;
}
.header h1 { font-size: 18px; font-weight: 700; color: #fff; }
.header h1 span { color: #94FBE0; }
.header-right { display: flex; gap: 12px; align-items: center; }
.stats { font-size: 13px; color: #888; }
.stats b { color: #94FBE0; }
.search-box {
padding: 8px 14px; border-radius: 8px;
background: #1e2030; border: 1px solid #2a2d3a;
color: #e0e0e0; font-size: 13px; width: 240px;
outline: none;
}
.search-box:focus { border-color: #94FBE0; }
.search-box::placeholder { color: #555; }
.btn {
padding: 8px 16px; border-radius: 8px; border: none;
font-size: 13px; font-weight: 600; cursor: pointer; transition: all 0.2s;
}
.btn-primary { background: #94FBE0; color: #000; }
.btn-primary:hover { background: #7ae8cc; }
.btn-secondary { background: #2a2d3a; color: #e0e0e0; }
.btn-secondary:hover { background: #363a4a; }
.filter-bar {
position: sticky; top: 61px; z-index: 99;
background: #12141e; border-bottom: 1px solid #2a2d3a;
padding: 10px 32px;
display: flex; gap: 8px; flex-wrap: wrap;
}
.filter-chip {
padding: 5px 14px; border-radius: 999px;
background: #1e2030; border: 1px solid #2a2d3a;
color: #aaa; font-size: 12px; cursor: pointer; transition: all 0.2s;
}
.filter-chip:hover { border-color: #94FBE0; color: #94FBE0; }
.filter-chip.active { background: #94FBE0; color: #000; border-color: #94FBE0; font-weight: 600; }
.content { padding: 24px 32px; }
.section {
margin-bottom: 32px;
background: #161822; border-radius: 12px; border: 1px solid #2a2d3a;
overflow: hidden;
}
.section-header {
padding: 14px 20px;
background: #1a1d2e; border-bottom: 1px solid #2a2d3a;
display: flex; align-items: center; justify-content: space-between;
cursor: pointer; user-select: none;
}
.section-header:hover { background: #1e2133; }
.section-title { font-size: 15px; font-weight: 700; color: #94FBE0; }
.section-count { font-size: 12px; color: #666; }
.section-toggle { font-size: 12px; color: #666; transition: transform 0.2s; }
.section.collapsed .section-toggle { transform: rotate(-90deg); }
.section.collapsed .section-body { display: none; }
.section-body { padding: 0; }
.row {
display: grid; grid-template-columns: 280px 1fr 1fr;
border-bottom: 1px solid #1e2030; transition: background 0.15s;
}
.row:last-child { border-bottom: none; }
.row:hover { background: #1a1d2e; }
.row.highlight { background: rgba(148, 251, 224, 0.05); }
.cell {
padding: 10px 16px; font-size: 13px; line-height: 1.5;
border-right: 1px solid #1e2030;
}
.cell:last-child { border-right: none; }
.cell-key {
color: #888; font-family: 'SF Mono', 'Fira Code', monospace; font-size: 12px;
word-break: break-all;
}
.cell-ko { color: #e0e0e0; }
.cell-en { color: #c8d0ff; }
.cell-empty { color: #ff6b6b; font-style: italic; }
.row-header {
display: grid; grid-template-columns: 280px 1fr 1fr;
background: #12141e; border-bottom: 1px solid #2a2d3a;
position: sticky; top: 105px; z-index: 50;
}
.row-header .cell {
font-size: 11px; font-weight: 700; text-transform: uppercase;
letter-spacing: 0.05em; color: #666; padding: 8px 16px;
}
.toast {
position: fixed; bottom: 24px; right: 24px;
background: #94FBE0; color: #000; padding: 12px 20px;
border-radius: 8px; font-size: 13px; font-weight: 600;
opacity: 0; transform: translateY(10px);
transition: all 0.3s; pointer-events: none; z-index: 999;
}
.toast.show { opacity: 1; transform: translateY(0); }
@media (max-width: 768px) {
.row, .row-header { grid-template-columns: 1fr; }
.cell-key { background: #12141e; font-weight: 600; }
.header { padding: 12px 16px; flex-direction: column; gap: 8px; }
.filter-bar { padding: 8px 16px; }
.content { padding: 16px; }
}
</style>
</head>
<body>
<div class="header">
<h1><span>ADO2</span> Translation Viewer</h1>
<div class="header-right">
<span class="stats">Total: <b id="totalCount">0</b> keys</span>
<input type="text" class="search-box" id="searchInput" placeholder="Search key or text...">
<button class="btn btn-secondary" onclick="expandAll()">Expand All</button>
<button class="btn btn-secondary" onclick="collapseAll()">Collapse All</button>
<button class="btn btn-primary" onclick="downloadCSV()">Download CSV</button>
</div>
</div>
<div class="filter-bar" id="filterBar"></div>
<div class="row-header">
<div class="cell">KEY</div>
<div class="cell">KO (Korean)</div>
<div class="cell">EN (English)</div>
</div>
<div class="content" id="content"></div>
<div class="toast" id="toast"></div>
<script>
const koData = {"header":{"loginFailedAlert":"로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.","start":"시작하기","loading":"로딩...","login":"로그인"},"sidebar":{"dashboard":"대시보드","newProject":"새 프로젝트 만들기","ado2Contents":"ADO2 콘텐츠","myContents":"내 콘텐츠","myInfo":"내 정보","defaultUser":"사용자","loggingOut":"로그아웃 중...","logout":"로그아웃"},"footer":{"businessNumber":"사업자 등록번호 : 620-87-00810 | 대표 : 안성민","headquarters":"본사 : 41593 대구광역시 북구 옥산로 111, 5층 유니콘랩 대구 A05호","researchCenter":"연구소 : 13453 경기 성남시 수정구 금토로 32 (금토동) (주)KT 판교빌딩 504호~505호 (East)","phone":"전화 : 070-4260-8310 | 010-2755-6463","email":"이메일 : o2oteam@o2o.kr"},"social":{"title":"소셜 미디어 포스팅","postNumber":"게시물 1","videoSpecs":"1080x1920 · 10초","channelLabel":"게시 채널","loadingAccounts":"계정 로딩 중...","noAccounts":"연결된 소셜 계정이 없습니다.","noAccountsHint":"내 정보에서 계정을 연결해주세요.","postTitleLabel":"게시물 제목","postTitlePlaceholder":"게시물 제목을 입력하세요.","postContentLabel":"게시물 내용","postContentPlaceholder":"게시물 내용을 입력하세요.","tagsLabel":"태그","tagsPlaceholder":"태그를 입력하세요. (쉼표로 구분)","privacyLabel":"게시물 공개 범위","privacyPublic":"공개","privacyUnlisted":"미등록 (링크로만 접근)","privacyPrivate":"비공개","publishTimeLabel":"게시 시간","publishNow":"지금 게시","publishSchedule":"시간 설정 (준비 중)","footerNote":"게시는 {link} 후 가능합니다.","footerNoteLink":"요금제 업그레이드","cancel":"취소","posting":"게시 중...","post":"게시","youtubeExpiredAlert":"YouTube 인증이 만료되었습니다. 재연동 페이지로 이동합니다.","channelAndTitleRequired":"채널과 제목을 입력해주세요.","selectChannel":"채널을 선택해주세요.","invalidVideoInfo":"영상 정보가 올바르지 않습니다. (video_id 누락)","uploadStartFailed":"업로드 시작에 실패했습니다.","uploadFailed":"업로드에 실패했습니다."},"upload":{"title":"YouTube 업로드","statusPending":"업로드 준비 중...","statusUploading":"업로드 중...","statusCompleted":"업로드 완료!","statusFailed":"업로드 실패","statusDefault":"처리 중...","videoTitleLabel":"영상 제목","channelLabel":"채널","viewOnYoutube":"YouTube에서 보기","confirm":"확인","close":"닫기","doNotClose":"업로드가 진행 중입니다. 창을 닫지 마세요."},"landing":{"hero":{"searchTypeBusinessName":"업체명","placeholderBusinessName":"업체명을 입력하세요","guideUrl":"URL에서 가져온 정보로 영상이 자동 생성됩니다.","guideBusinessName":"업체명으로 검색하여 정보를 가져옵니다.","errorUrlRequired":"URL을 입력해주세요.","errorNameRequired":"업체명을 입력해주세요.","errorInvalidUrl":"올바른 URL 형식이 아닙니다. (예: https://example.com)","analyzeButton":"브랜드 분석","scrollMore":"스크롤하여 더 보기","testDataLoading":"로딩 중...","testData":"테스트 데이터","testDataLoadFailed":"테스트 데이터를 불러오는데 실패했습니다.","searching":"검색 중..."},"welcome":{"title":"ADO2.AI에 오신 것을 환영합니다.","subtitle":"분석, 제작, 배포까지 콘텐츠 마케팅의 전과정을 자동화","feature1Title":"비즈니스 핵심 정보 분석","feature1Desc":"홈페이지, 네이버 지도, 블로그 등의\nURL을 입력하세요","feature2Title":"홍보 콘텐츠 자동 제작","feature2Desc":"분석된 정보를 바탕으로\n비즈니스에 맞는 음악, 자막, 노래, 영상을\n자동으로 제작해요","feature3Title":"멀티채널 자동 배포","feature3Desc":"완성된 영상은 다운로드하거나\n바로 SNS에 업로드 할 수 있어요"},"display":{"startButton":"시작하기"}},"login":{"back":"뒤로가기","kakaoLoginFailed":"카카오 로그인에 실패했습니다. 다시 시도해주세요.","loginUrlFailed":"로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.","loggingIn":"로그인 중...","kakaoStart":"카카오로 시작하기"},"urlInput":{"searchTypeBusinessName":"업체명","placeholderBusinessName":"업체명을 입력하세요","guideUrl":"URL에서 가져온 정보로 영상이 자동 생성됩니다.","guideBusinessName":"업체명으로 검색하여 정보를 가져옵니다.","searchButton":"검색하기","searching":"검색 중...","testDataLoading":"로딩 중...","testData":"테스트 데이터"},"assetManagement":{"title":"브랜드 에셋","selectedImages":"선택된 이미지","imageAlt":"이미지","uploadBadge":"업로드","imageUpload":"이미지 업로드","dragAndDrop":"이미지를 드래그하여\n업로드","videoRatio":Line truncated
const enData = {"header":{"loginFailedAlert":"Failed to get login URL. Please try again.","start":"Get Started","loading":"Loading...","login":"Log In"},"sidebar":{"dashboard":"Dashboard","newProject":"Create New Project","ado2Contents":"ADO2 Contents","myContents":"My Contents","myInfo":"My Info","defaultUser":"User","loggingOut":"Logging out...","logout":"Log Out"},"footer":{"businessNumber":"Business Registration No. : 620-87-00810 | CEO : Ahn Sungmin","headquarters":"HQ : 41593 Unicorn Lab Daegu A05, 5F, 111 Oksan-ro, Buk-gu, Daegu, Korea","researchCenter":"R&D : 13453 Rooms 504-505 (East), KT Pangyo Bldg, 32 Geumto-ro, Sujeong-gu, Seongnam-si, Gyeonggi-do, Korea","phone":"Tel : 070-4260-8310 | 010-2755-6463","email":"Email : o2oteam@o2o.kr"},"social":{"title":"Social Media Posting","postNumber":"Post 1","videoSpecs":"1080x1920 · 10 sec","channelLabel":"Post Channel","loadingAccounts":"Loading accounts...","noAccounts":"No connected social accounts.","noAccountsHint":"Please connect an account in My Info.","postTitleLabel":"Post Title","postTitlePlaceholder":"Enter a post title.","postContentLabel":"Post Content","postContentPlaceholder":"Enter post content.","tagsLabel":"Tags","tagsPlaceholder":"Enter tags. (separated by commas)","privacyLabel":"Post Visibility","privacyPublic":"Public","privacyUnlisted":"Unlisted (accessible by link only)","privacyPrivate":"Private","publishTimeLabel":"Publish Time","publishNow":"Publish Now","publishSchedule":"Schedule (Coming Soon)","footerNote":"Posting is available after {link}.","footerNoteLink":"plan upgrade","cancel":"Cancel","posting":"Posting...","post":"Post","youtubeExpiredAlert":"YouTube authentication has expired. Redirecting to reconnect page.","channelAndTitleRequired":"Please enter a channel and title.","selectChannel":"Please select a channel.","invalidVideoInfo":"Video information is invalid. (missing video_id)","uploadStartFailed":"Failed to start upload.","uploadFailed":"Upload failed."},"upload":{"title":"YouTube Upload","statusPending":"Preparing upload...","statusUploading":"Uploading...","statusCompleted":"Upload complete!","statusFailed":"Upload failed","statusDefault":"Processing...","videoTitleLabel":"Video Title","channelLabel":"Channel","viewOnYoutube":"View on YouTube","confirm":"OK","close":"Close","doNotClose":"Upload is in progress. Do not close this window."},"landing":{"hero":{"searchTypeBusinessName":"Business Name","placeholderBusinessName":"Enter a business name","guideUrl":"A video will be automatically generated from the information gathered from the URL.","guideBusinessName":"Search by business name to retrieve information.","errorUrlRequired":"Please enter a URL.","errorNameRequired":"Please enter a business name.","errorInvalidUrl":"Invalid URL format. (e.g., https://example.com)","analyzeButton":"Brand Analysis","scrollMore":"Scroll to see more","testDataLoading":"Loading...","testData":"Test Data","testDataLoadFailed":"Failed to load test data.","searching":"Searching..."},"welcome":{"title":"Welcome to ADO2.AI","subtitle":"Automate the entire content marketing process from analysis, creation, to distribution","feature1Title":"Business Core Information Analysis","feature1Desc":"Enter the URL of your homepage,\nNaver Map, blog, etc.","feature2Title":"Automated Promotional Content Creation","feature2Desc":"Based on analyzed information,\nautomatically create music, subtitles, songs,\nand videos tailored to your business","feature3Title":"Multi-Channel Auto Distribution","feature3Desc":"Completed videos can be downloaded\nor uploaded directly to social media"},"display":{"startButton":"Get Started"}},"login":{"back":"Go Back","kakaoLoginFailed":"Kakao login failed. Please try again.","loginUrlFailed":"Failed to get login URL. Please try again.","loggingIn":"Logging in...","kakaoStart":"Start with Kakao"},"urlInput":{"searchTypeBusinessName":"Business Name","placeholderBusinessName":"Enter a business name","guideUrl":"A video will be automatically generated from the information gathered from the URL.","guideBusinessName":"Search by business name to retrieve information.","searchButton":"Search","searching":"Searching...","testDataLoading":"Loading...","testData":"Test Data"},"assetManagement":{"title":"Brand Assets","selectedImages":"Selected Images","imageAlt":"Image","uploadBadge":"Uploaded","imageUpload":"Image Upload","dragAndDrop":"Drag and drop\nimages to upload","videoRatio":"Video Ratio","uploadFailed":"Image upload failed.","uploading":"Uploading...","nextStep":"Next Step"},"soundStudio":{"back":"Go Back","title":"Sound Studio","soundColumn":"Sound","soundTypeLabel":"Select AI Sound Type","soundTypeVocal":"Vocal","soundTypeBGM":"Background Music","soundTypeNarration":"Voice Narration","genreLabel":"Select Genre","genreAuto":"Auto Select","genreBallad":"Ballad","languageLabel":"Language","languageKorean":"Korean","lyricsColumn":"Lyrics","lyricsHint":"Select the lyrics area to edit","lyricsPlaceholder":"Lyrics will be Line truncated
// Flatten nested JSON
function flatten(obj, prefix = '') {
const result = {};
for (const key of Object.keys(obj)) {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null) {
Object.assign(result, flatten(obj[key], fullKey));
} else {
result[fullKey] = obj[key];
}
}
return result;
}
const flatKo = flatten(koData);
const flatEn = flatten(enData);
const allKeys = [...new Set([...Object.keys(flatKo), ...Object.keys(flatEn)])].sort();
// Get top-level sections
const sections = [...new Set(allKeys.map(k => k.split('.')[0]))];
let activeFilter = 'all';
let searchTerm = '';
function getSection(key) { return key.split('.')[0]; }
function escapeHtml(str) {
if (!str) return '';
return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
.replace(/\n/g, '<br>');
}
function showToast(msg) {
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 2000);
}
function renderFilters() {
const bar = document.getElementById('filterBar');
let html = `<div class="filter-chip ${activeFilter === 'all' ? 'active' : ''}" onclick="setFilter('all')">All</div>`;
for (const s of sections) {
html += `<div class="filter-chip ${activeFilter === s ? 'active' : ''}" onclick="setFilter('${s}')">${s}</div>`;
}
bar.innerHTML = html;
}
function setFilter(f) {
activeFilter = f;
renderFilters();
render();
}
function render() {
const content = document.getElementById('content');
let html = '';
let total = 0;
for (const section of sections) {
if (activeFilter !== 'all' && activeFilter !== section) continue;
const sectionKeys = allKeys.filter(k => getSection(k) === section);
const filteredKeys = sectionKeys.filter(k => {
if (!searchTerm) return true;
const term = searchTerm.toLowerCase();
return k.toLowerCase().includes(term)
|| (flatKo[k] || '').toLowerCase().includes(term)
|| (flatEn[k] || '').toLowerCase().includes(term);
});
if (filteredKeys.length === 0) continue;
total += filteredKeys.length;
html += `<div class="section" id="section-${section}">`;
html += `<div class="section-header" onclick="toggleSection('${section}')">
<span class="section-title">${section}</span>
<span><span class="section-count">${filteredKeys.length} keys</span>&nbsp;&nbsp;<span class="section-toggle">&#9660;</span></span>
</div>`;
html += `<div class="section-body">`;
for (const key of filteredKeys) {
const ko = flatKo[key] || '';
const en = flatEn[key] || '';
const shortKey = key.replace(section + '.', '');
const isEmpty = !en;
html += `<div class="row ${isEmpty ? 'highlight' : ''}">`;
html += `<div class="cell cell-key" title="${key}">${escapeHtml(shortKey)}</div>`;
html += `<div class="cell cell-ko">${escapeHtml(ko)}</div>`;
html += `<div class="cell ${isEmpty ? 'cell-empty' : 'cell-en'}">${isEmpty ? '(missing)' : escapeHtml(en)}</div>`;
html += `</div>`;
}
html += `</div></div>`;
}
content.innerHTML = html;
document.getElementById('totalCount').textContent = total;
}
function toggleSection(name) {
const el = document.getElementById('section-' + name);
if (el) el.classList.toggle('collapsed');
}
function expandAll() {
document.querySelectorAll('.section').forEach(el => el.classList.remove('collapsed'));
}
function collapseAll() {
document.querySelectorAll('.section').forEach(el => el.classList.add('collapsed'));
}
function downloadCSV() {
const BOM = '\uFEFF';
let csv = BOM + 'Key,Korean,English\n';
for (const key of allKeys) {
const ko = (flatKo[key] || '').replace(/"/g, '""').replace(/\n/g, '\\n');
const en = (flatEn[key] || '').replace(/"/g, '""').replace(/\n/g, '\\n');
csv += `"${key}","${ko}","${en}"\n`;
}
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'ado2_translations.csv';
a.click();
URL.revokeObjectURL(url);
showToast('CSV downloaded!');
}
// Search
document.getElementById('searchInput').addEventListener('input', (e) => {
searchTerm = e.target.value;
render();
});
// Init
renderFilters();
render();
</script>
</body>
</html>