feat(supporters): /en/stay 를 참고 사이트 수준으로 다시 지음 — 설명문·이동시간·계절축제·동선·날씨
haewon 이 준 참고 사이트(스테이,머뭄)의 연동 범위에 맞춰 다시 만들었다. 앞서 만든 것은 거리순 표였고, 실제로 필요한 것은 설명문과 이동 시간이 붙은 카드, 계절로 묶은 축제, 시간표가 있는 동선이었다. 수집 (scripts/fetch_medical_tourism.py) - detailCommon2 의 overview 를 가져온다. locationBasedList2 는 설명문을 주지 않아 카드에 이름과 주소만 남았다. 123/125 건 확보. - 이동 시간을 낸다. 참고 사이트 표기를 역산해 도보는 max(1, round(m/80)), 차는 직선거리 km x 1.2 로 맞췄다(135m→2분, 566m→7분, 25km→30분). 2km 까지 도보로 보고, 짧은 거리의 차 시간은 주차·신호 때문에 의미가 없어 최소 5분으로 둔다. - 축제를 계절로 분류하고, 도보 시간 구간별 건수를 누적으로 집계한다. 사진 (125/125, 전부 실제로 열리는 것 확인) 목록 API 의 firstimage 만 쓰면 38건이 비었다. 폴백을 넷으로 걸었다. 1) detailImage2 — 이미지 전용 오퍼레이션. 15건 회수(도산공원 7장이 여기 있었다) 2) 국문 서비스 KorService2 — 영문 항목에 없어도 국문 항목에 있다. 10건 3) 업체 공식 홈페이지 og:image — 2건 4) Naver 이미지 검색 API — 11건 og:image 는 실제로 열어 보고 쓴다. 이미지가 아니거나 인스타 CDN 처럼 핫링크를 403 으로 막으면 화면에서 빈 칸이 되기 때문이다. imageSource 를 항목마다 남겼다. naver 출처는 제3자 저작물이므로 내부 시연 범위이며, 공개 배포 전에는 걷어내거나 라이선스 있는 사진으로 교체해야 한다(haewon 판단). 화면 (supporters/src/pages/en/stay.astro) - Around the clinic: 도보 시간 누적 필터, 범주별 카드, 사진 위 이동시간 배지, 설명문, 공식 홈페이지가 있으면 링크하고 없으면 검색으로 보낸다. - Festivals: 계절 탭. - Shaping your days: 좌표로 그린 인라인 SVG 지도와 시간표. 외부 지도 라이브러리를 부르지 않는다. 시각은 가정이며 화면에 그렇게 적었다. - 오늘 날씨: Open-Meteo, 키 불필요. 빌드가 아니라 브라우저에서 받는다. 정적 빌드에 넣으면 배포 시각의 날씨가 굳는다. 못 받으면 블록을 통째로 숨긴다. 문구는 이 페이지의 목록에만 연결한다. 무엇을 해도 되는지는 의학 판단이라 말하지 않는다. - 섹션 점프 바(글래스, 스티키) + IntersectionObserver 스크롤 스파이. 고친 것 - 항목마다 붙던 KO 태그를 헤더 언어 스위치 하나로 바꿨다. 짝이 있는 페이지는 서로 잇고 없으면 그 언어의 입구로 보낸다. 영문 페이지가 늘면 PAIRS 표에 줄만 추가한다. - .chip 클래스가 이미 있어 홈·뉴스룸·영상 페이지를 덮어쓰고 있었다. 새 스타일을 .stay 아래로 모두 가뒀다. - factSheet 에 영문 주소(fullEn)와 우편번호를 넣었다. 근거는 뷰성형외과 자신의 한국관광공사 등재 항목(contentid 3364779)이며 fullEnSource 에 적었다. 템플릿은 같은 코드에 빈 데이터 스캐폴드를 둔다. 뷰성형외과 데이터가 새 병원 빌드로 새면 안 된다. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
a807d5dd9c
commit
e32633e9a6
11 files changed
+2495
-232
No files matched your search
@@ -20,7 +20,7 @@ INFINITH 제품 화면(/discovery)이 아니라 병원 서포터즈 사이트에
|
||||
python3 scripts/fetch_medical_tourism.py
|
||||
python3 scripts/fetch_medical_tourism.py --out supporters/src/data/medicalTourism.json
|
||||
"""
|
||||
import argparse, io, json, math, os, ssl, sys, time, urllib.parse, urllib.request
|
||||
import argparse, io, json, math, os, re, ssl, sys, time, urllib.parse, urllib.request
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
@@ -33,6 +33,9 @@ CAT_WELLNESS = ("A02020300", "A02020400") # Hot Springs & Spa, Jjimjilbang
|
||||
|
||||
# 다국어 ContentTypeId. 국문과 코드가 다르다.
|
||||
# 반경은 목적에 따라 다르다. 회복기에 매일 가는 곳(숙박·식사·스파)은 가깝게, 관광은 넓게 본다.
|
||||
SEASON = {3: "spring", 4: "spring", 5: "spring", 6: "summer", 7: "summer", 8: "summer",
|
||||
9: "autumn", 10: "autumn", 11: "autumn", 12: "winter", 1: "winter", 2: "winter"}
|
||||
|
||||
TYPES = {
|
||||
"76": ("attraction", "10000"),
|
||||
"78": ("culture", "10000"),
|
||||
@@ -98,6 +101,164 @@ def call_all(env, op, extra, max_pages=6, rows=100):
|
||||
return total, got
|
||||
|
||||
|
||||
def walk_min(m):
|
||||
"""도보 분. 80m/분(4.8km/h) 기준. 참고 사이트의 표기를 역산해 맞춘 값이다
|
||||
(135m→2분, 248m→3분, 297m→4분, 566m→7분)."""
|
||||
return max(1, round(m / 80))
|
||||
|
||||
|
||||
def drive_min(km):
|
||||
"""차 이동 분. 직선거리 km x 1.2. 역시 역산값이다(25km→30분, 33km→40분)."""
|
||||
return max(1, round(km * 1.2))
|
||||
|
||||
|
||||
def travel(m):
|
||||
"""이동 수단과 소요 시간.
|
||||
2km 까지는 걸을 수 있는 거리로 본다(약 25분). 그 위는 차·지하철이다.
|
||||
짧은 거리의 차 시간은 주차와 신호 때문에 의미가 없으므로 최소 5분으로 둔다."""
|
||||
if m is None: return None
|
||||
if m <= 2000: return {"mode": "walk", "minutes": walk_min(m), "label": f"{walk_min(m)} min walk"}
|
||||
mins = max(5, drive_min(m / 1000))
|
||||
return {"mode": "drive", "minutes": mins, "label": f"{mins} min by car"}
|
||||
|
||||
|
||||
def fetch_overview(env, content_id, cache):
|
||||
"""detailCommon2 의 overview(설명문)와 homepage. locationBasedList2 는 주지 않는다.
|
||||
설명문이 없으면 카드가 이름과 주소뿐이라 사람이 고를 수 없다."""
|
||||
if content_id in cache: return cache[content_id]
|
||||
try:
|
||||
_, rows = call(env, "detailCommon2", {"contentId": content_id}, rows=1)
|
||||
except Exception:
|
||||
cache[content_id] = ("", ""); return cache[content_id]
|
||||
if not rows: cache[content_id] = ("", ""); return cache[content_id]
|
||||
r = rows[0]
|
||||
ov = re.sub(r"<[^>]+>", " ", r.get("overview") or "")
|
||||
ov = re.sub(r"\s+", " ", ov).strip()
|
||||
hp = re.sub(r"<[^>]+>", " ", r.get("homepage") or "").strip()
|
||||
hp = (re.search(r"https?://\S+", hp) or [None])[0] if hp else ""
|
||||
cache[content_id] = (ov, hp or "")
|
||||
return cache[content_id]
|
||||
|
||||
|
||||
def fetch_image(env, content_id, cache):
|
||||
"""locationBasedList2 의 firstimage 가 비어 있을 때 detailImage2 로 한 번 더 찾는다.
|
||||
이미지 전용 오퍼레이션이라 목록 API 에 없는 사진이 여기 있다(도산공원 7장, 몽마르뜨공원 5장).
|
||||
실측: 사진 없던 38건 중 15건을 여기서 살렸다. 나머지 23건은 TourAPI 에 사진이 없다."""
|
||||
key = ("img", content_id)
|
||||
if key in cache: return cache[key]
|
||||
try:
|
||||
_, rows = call(env, "detailImage2", {"contentId": content_id, "imageYN": "Y"}, rows=5)
|
||||
except Exception:
|
||||
cache[key] = ""; return ""
|
||||
url = ""
|
||||
for r in rows or []:
|
||||
u = (r.get("originimgurl") or r.get("smallimageurl") or "").strip()
|
||||
if u: url = u.replace("http://", "https://", 1); break
|
||||
cache[key] = url
|
||||
return url
|
||||
|
||||
|
||||
def call_kor(env, op, extra, rows=10):
|
||||
"""국문 서비스(KorService2). 영문 항목에 사진이 없어도 국문 항목에는 있는 경우가 있다.
|
||||
같은 한국관광공사 사진이라 출처가 달라지지 않는다."""
|
||||
p = {"MobileOS": "ETC", "MobileApp": "INFINITH", "_type": "json",
|
||||
"numOfRows": str(rows), "pageNo": "1", **extra}
|
||||
url = f"{env['TOUR_API_BASE']}/KorService2/{op}?serviceKey={env['TOUR_API_KEY']}&" + urllib.parse.urlencode(p)
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=25, context=ssl_ctx()) as r:
|
||||
body = r.read().decode("utf-8", "replace")
|
||||
if body.lstrip().startswith("<"): return []
|
||||
j = json.loads(body)["response"]
|
||||
if j["header"].get("resultCode") != "0000": return []
|
||||
it = j["body"].get("items")
|
||||
return [] if not it or it == "" else it["item"]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def korean_name(title):
|
||||
m = re.search(r"\(([^)]+)\)\s*$", title or "")
|
||||
return (m.group(1) if m else (title or "")).strip()
|
||||
|
||||
|
||||
def fetch_image_kor(env, p):
|
||||
"""국문 서비스에서 같은 이름의 항목을 찾아 사진을 가져온다. 실측 23건 중 10건이 여기서 나왔다."""
|
||||
ko = korean_name(p.get("title"))
|
||||
if not re.search(r"[가-힣]", ko): return ""
|
||||
rows = []
|
||||
if p.get("lat"):
|
||||
rows = call_kor(env, "locationBasedList2",
|
||||
{"mapX": str(p["lng"]), "mapY": str(p["lat"]), "radius": "300", "keyword": ko})
|
||||
if not rows: rows = call_kor(env, "searchKeyword2", {"keyword": ko})
|
||||
key = ko.replace(" ", "")
|
||||
for r in rows:
|
||||
if key in (r.get("title") or "").replace(" ", ""):
|
||||
u = (r.get("firstimage") or r.get("firstimage2") or "").strip()
|
||||
if u: return u.replace("http://", "https://", 1)
|
||||
return ""
|
||||
|
||||
|
||||
def fetch_image_og(url):
|
||||
"""업체 공식 홈페이지의 대표 이미지(og:image). 업체가 스스로 올린 사진이라 목록에 쓰기에 무리가 없다.
|
||||
검색 결과 이미지를 긁어 쓰면 식당·블로그·언론사의 저작물이라 환자용 페이지에 올릴 수 없다."""
|
||||
if not url or not url.startswith("http"): return ""
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=12, context=ssl_ctx()) as r:
|
||||
head = r.read(120000).decode("utf-8", "replace")
|
||||
base = r.geturl()
|
||||
except Exception:
|
||||
return ""
|
||||
m = re.search(r'<meta[^>]+(?:property|name)=["\']og:image["\'][^>]*content=["\']([^"\']+)', head, re.I) \
|
||||
or re.search(r'<meta[^>]+content=["\']([^"\']+)["\'][^>]+(?:property|name)=["\']og:image', head, re.I)
|
||||
if not m: return ""
|
||||
u = m.group(1).strip()
|
||||
if u.startswith("//"): u = "https:" + u
|
||||
elif u.startswith("/"):
|
||||
from urllib.parse import urlparse
|
||||
pr = urlparse(base); u = f"{pr.scheme}://{pr.netloc}{u}"
|
||||
return u if u.startswith("https://") else ""
|
||||
|
||||
|
||||
def usable_image(url):
|
||||
"""실제로 이미지가 오는지 열어 본다. og:image 가 이미지가 아니거나(빈 content-type)
|
||||
인스타 CDN 처럼 핫링크를 403 으로 막는 경우가 있어 화면에서 빈 칸이 된다."""
|
||||
if not url: return False
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||||
with urllib.request.urlopen(req, timeout=10, context=ssl_ctx()) as r:
|
||||
return r.status == 200 and (r.headers.get("content-type") or "").startswith("image")
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def fetch_image_naver(env, p):
|
||||
"""마지막 폴백. Naver 이미지 검색 API.
|
||||
주의: 결과는 제3자 저작물이다. 내부 시연 목적으로만 쓰고, 공개 배포 전에는
|
||||
imageSource 가 'naver' 인 항목을 걷어내거나 라이선스가 있는 사진으로 교체한다.
|
||||
구글 HTML 크롤링 대신 이걸 쓰는 이유는 공식 API 라 차단되지 않고 결과가 일정해서다."""
|
||||
cid, sec = env.get("NAVER_CLIENT_ID"), env.get("NAVER_CLIENT_SECRET")
|
||||
if not (cid and sec): return ""
|
||||
ko = korean_name(p.get("title"))
|
||||
if not ko: return ""
|
||||
# 지역을 붙이면 정확도가 오르지만 결과가 아예 없는 경우가 있다. 넓혀 가며 시도한다.
|
||||
plain = re.sub(r"\s*\(.*\)\s*", "", p.get("title") or "").strip()
|
||||
for q in (f"{ko} 서울", ko, plain):
|
||||
if not q: continue
|
||||
qs = urllib.parse.urlencode({"query": q, "display": "3", "sort": "sim"})
|
||||
req = urllib.request.Request("https://openapi.naver.com/v1/search/image.json?" + qs,
|
||||
headers={"X-Naver-Client-Id": cid, "X-Naver-Client-Secret": sec})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15, context=ssl_ctx()) as r:
|
||||
items = json.loads(r.read().decode()).get("items", [])
|
||||
except Exception:
|
||||
continue
|
||||
for it in items:
|
||||
u = (it.get("link") or "").strip()
|
||||
if u.startswith("https://"): return u
|
||||
return ""
|
||||
|
||||
|
||||
def bucket(it):
|
||||
"""분류코드로 범주를 정한다. None 이면 버린다."""
|
||||
cat3 = (it.get("cat3") or "").strip()
|
||||
@@ -121,10 +282,15 @@ def clean(it, lat, lng):
|
||||
# tong.visitkorea.or.kr 은 https 로도 같은 파일을 준다(실측 확인).
|
||||
"image": (lambda u: u.replace("http://", "https://", 1) if u else None)(
|
||||
it.get("firstimage") or it.get("firstimage2") or None),
|
||||
"imageSource": "tourapi" if (it.get("firstimage") or it.get("firstimage2")) else "",
|
||||
"tel": (it.get("tel") or "").strip() or None,
|
||||
"lat": ilat or None, "lng": ilng or None,
|
||||
"distanceM": round(float(dist)) if dist else (
|
||||
round(haversine_km(lat, lng, ilat, ilng) * 1000) if ilat and ilng else None),
|
||||
"travel": travel(round(float(dist)) if dist else (
|
||||
round(haversine_km(lat, lng, ilat, ilng) * 1000) if ilat and ilng else None)),
|
||||
# detailCommon2 로 따로 채운다(locationBasedList2 는 설명문을 주지 않는다).
|
||||
"overview": "", "homepage": "",
|
||||
# TourAPI 가 주지 않는 값. Google Places 승인 후 채운다. 지금은 비워 둔다.
|
||||
"rating": None, "reviewCount": None, "openingHours": None,
|
||||
}
|
||||
@@ -176,13 +342,59 @@ def main():
|
||||
if c["lat"] is None: nocoord += 1; continue
|
||||
km = haversine_km(lat, lng, c["lat"], c["lng"])
|
||||
if km > a.festival_km: continue
|
||||
c.update(startDate=it.get("eventstartdate"), endDate=it.get("eventenddate"),
|
||||
distanceKm=round(km, 1))
|
||||
sd = it.get("eventstartdate") or ""
|
||||
c.update(startDate=sd, endDate=it.get("eventenddate"),
|
||||
distanceKm=round(km, 1), month=(int(sd[4:6]) if len(sd) == 8 else None),
|
||||
season=SEASON.get(int(sd[4:6]), "") if len(sd) == 8 else "")
|
||||
near.append(c)
|
||||
near.sort(key=lambda x: x["startDate"] or "")
|
||||
out["festivals"] = near[:a.per_type]
|
||||
print(f" festival API {total:>4}건 · 받음 {len(rows):>3} · 좌표없음 {nocoord} · {a.festival_km:.0f}km 이내 {len(near)}")
|
||||
|
||||
# 설명문은 항목마다 detailCommon2 를 한 번씩 부른다. 카드에 이름과 주소만 있으면 고를 수 없다.
|
||||
cache: dict = {}
|
||||
targets = [p for v in out["places"].values() for p in v] + out["festivals"]
|
||||
print(f"\n 설명문 수집 {len(targets)}건", end="", flush=True)
|
||||
for i, p in enumerate(targets):
|
||||
if not p.get("id"): continue
|
||||
ov, hp = fetch_overview(env, p["id"], cache)
|
||||
p["overview"] = ov[:600]
|
||||
p["homepage"] = hp
|
||||
if not p.get("image"):
|
||||
# 1) 영문 detailImage2 → 2) 국문 서비스 → 3) 업체 공식 홈페이지 og:image
|
||||
# 1) 영문 detailImage2 → 2) 국문 서비스 → 3) 업체 홈페이지 og:image → 4) Naver 이미지 검색
|
||||
src = ""
|
||||
img = fetch_image(env, p["id"], cache)
|
||||
if img: src = "tourapi"
|
||||
if not img:
|
||||
img = fetch_image_kor(env, p); src = "tourapi-kor" if img else src
|
||||
if not img:
|
||||
cand = fetch_image_og(p.get("homepage") or "")
|
||||
if cand and usable_image(cand): img, src = cand, "homepage"
|
||||
if not img:
|
||||
img = fetch_image_naver(env, p); src = "naver" if img else src
|
||||
p["image"] = img or None
|
||||
p["imageSource"] = src
|
||||
if i % 20 == 0: print(".", end="", flush=True)
|
||||
time.sleep(0.12)
|
||||
got = sum(1 for p in targets if p["overview"])
|
||||
pic = sum(1 for p in targets if p.get("image"))
|
||||
print(f" 완료 · 설명문 {got}/{len(targets)} · 사진 {pic}/{len(targets)}")
|
||||
|
||||
# 도보 시간 구간별 건수. 화면의 필터 칩이 이 수를 쓴다.
|
||||
allp = [p for v in out["places"].values() for p in v]
|
||||
# 누적 기준이다. "15분 이내"는 5분 이내도 포함한다. 사람이 고르는 방식에 맞춘다.
|
||||
def walk_upto(mins):
|
||||
return sum(1 for p in allp if p.get("travel") and p["travel"]["mode"] == "walk"
|
||||
and p["travel"]["minutes"] <= mins)
|
||||
out["filters"] = {
|
||||
"total": len(allp),
|
||||
"walk5": walk_upto(5),
|
||||
"walk15": walk_upto(15),
|
||||
"walkAll": sum(1 for p in allp if p.get("travel") and p["travel"]["mode"] == "walk"),
|
||||
"drive": sum(1 for p in allp if not p.get("travel") or p["travel"]["mode"] != "walk"),
|
||||
}
|
||||
|
||||
out["meta"] = {
|
||||
"source": "한국관광공사 TourAPI " + env["TOUR_API_SERVICE"],
|
||||
"fetchedAt": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
|
||||
Reference in new issue
Block a user