feat(supporters): 회복 일정 플래너를 템플릿·워커에 통합 (/plan·/en/plan), /recovery·/stay 를 /plan 으로 정리

- 템플릿: Planner.astro, lib/plan.ts·tour.ts, styles/plan.css, planStrings, pages plan·en/plan·404. Base 내비 회복 일정 → /plan, 언어 짝 /plan↔/en/plan, 옛 주소 리다이렉트(vercel.json), 사이트맵
- 워커 planner 단계(recovery 다음): scripts/build_planner_data.mjs 가 업종별 기본 규칙표(scripts/template/planner/procedures.plastic|derm.json)에 병원 시술 페이지 원문(recoveryNotes)을 matchKeywords 로 붙이고, 장소는 briefs/<clinic>/planner.places.json(큐레이션) 또는 범용 기본표(관광공사 기준 좌표)로 만든다
- 브리프: viewclinic·oracle 큐레이션 장소. 빈 템플릿(관광 데이터 없음)도 빌드·검증 통과(plan.test 14건)
- 이전 세션의 미커밋 작업(피부과 수집·OCR·게이트·언어 스위치, stay 페이지 제거)도 이 커밋에 함께 들어감. docs/prd 변경은 제외

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Fable 5.1 committed 2026-09-11 11:27:59 +09:00
1 parent 5c08fa97ab
commit aa5b05227f
126 files changed
+12916 -2068

No files matched your search

+197 -52
View File
@@ -1,24 +1,40 @@
#!/usr/bin/env python3
"""의료관광 연결 데이터 수집 (한국관광공사 TourAPI 다국어).
"""의료관광 연결 데이터 수집 (한국관광공사 TourAPI 다국어). 병원별로 돈다.
병원 좌표를 중심으로 숙박·음식점·관광지·문화시설·쇼핑을 모으고, 진행 중인 축제를
거리와 함께 붙여 프론트가 쓸 JSON 하나로 낸다.
거리와 함께 붙여 프론트가 쓸 JSON 으로 낸다. 영문(EngService2)과 국문(KorService2)을
한 번에 만들 수 있다.
왜 사전 수집인가
영문 서비스는 강남 일대 커버리지가 얇고(5km 음식점 18건, 국문은 338건) 관광지의
79%가 의료기관이라 필터링이 많이 필요하다. 그 처리를 수집 시점에 끝내고 프론트는
정제된 결과만 그린다. 미팅 데모 중 외부 API 상태에 화면이 종속되지도 않는다.
영문 서비스는 도심 커버리지가 얇고 관광지 항목의 대부분이 의료기관이라 필터링이 많이
필요하다. 그 처리를 수집 시점에 끝내고 프론트는 정제된 결과만 그린다. 미팅 데모 중
외부 API 상태에 화면이 종속되지도 않는다.
무엇을 만들지 않는가
없는 값을 채우지 않는다. 평점·리뷰·영업시간은 TourAPI 가 주지 않으므로 비워 두고,
Google Places 승인 후 별도 단계에서 붙인다. 식이 적합성은 병원 입력이며 여기서
판정하지 않는다.
판정하지 않는다. 좌표도 지어내지 않는다. 주소를 좌표로 바꾸지 못하면 종료 코드 1 로 멈춘다.
출력은 서포터즈 사이트(Astro)의 데이터다. 화면은 supporters/src/pages/en/stay.astro 다.
INFINITH 제품 화면(/discovery)이 아니라 병원 서포터즈 사이트에 실린다. 외국인 환자가 보는 곳이다.
기준 좌표를 정하는 순서
1. --lat --lng 를 직접 주면 그대로 쓴다 (coordSource: 명령 인자).
2. --address 와 --name 을 주면 네이버 지역검색(NAVER_CLIENT_ID/SECRET)으로 상호를 찾고,
결과의 도로명 주소가 준 주소의 도로명·번지와 같을 때만 그 좌표를 쓴다.
네이버가 못 찾으면 TourAPI 키워드 검색(국문·영문)으로 한 번 더 찾는다.
3. 아무 인자도 없으면 .env 의 TOUR_API_ORIGIN_LAT/LNG (초기 샘플 사이트용).
어느 경우든 meta.origin.coordSource 에 출처와 날짜를 적는다.
python3 scripts/fetch_medical_tourism.py
python3 scripts/fetch_medical_tourism.py --out supporters/src/data/medicalTourism.json
출력은 서포터즈 사이트(Astro)의 데이터다. 화면은 src/pages/stay.astro(국문)와
src/pages/en/stay.astro(영문)다. 외국인 환자와 보호자가 보는 곳이다.
# 워커가 부르는 형태 (팩트 시트 주소 기준, 영문·국문 동시)
python3 scripts/fetch_medical_tourism.py --clinic oracle --name "오라클피부과" \
--address "서울 강남구 선릉로 612 한일빌딩" --label "오라클피부과 (선릉로 612)" \
--out-en ~/supporters-builds/oracle/tourism/medicalTourism.json \
--out-ko ~/supporters-builds/oracle/tourism/medicalTourismKo.json
# 좌표를 직접 줄 때
python3 scripts/fetch_medical_tourism.py --lat 37.5049823 --lng 127.0254182 --label "..." --out-en a.json --out-ko b.json
# 이전 방식 (.env 좌표, 언어 하나)
python3 scripts/fetch_medical_tourism.py --lang ko --out supporters/src/data/medicalTourismKo.json
"""
import argparse, io, json, math, os, re, ssl, sys, time, urllib.parse, urllib.request
@@ -51,7 +67,7 @@ TYPES_KO = {
"32": ("stay", "5000"),
"39": ("restaurant", "5000"),
}
TYPES = TYPES_EN # main() 에서 --lang 에 맞게 바꾼다
# 언어별 타입 표는 collect() 가 lang 에 맞게 고른다.
def ssl_ctx():
@@ -62,11 +78,17 @@ def ssl_ctx():
def load_env(path):
""".env 파일을 읽고, 같은 이름의 환경변수가 있으면 그 값을 우선한다.
워커(run.mjs)나 클라우드 실행은 파일 없이 환경변수만 줄 수 있다."""
d = {}
for line in io.open(path, encoding="utf-8"):
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, v = line.split("=", 1); d[k.strip()] = v.strip()
if os.path.exists(path):
for line in io.open(path, encoding="utf-8"):
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, v = line.split("=", 1); d[k.strip()] = v.strip().strip('"').strip("'")
for k, v in os.environ.items():
if k.startswith(("TOUR_API_", "NAVER_CLIENT_")) and v:
d[k] = v
return d
@@ -305,32 +327,119 @@ def clean(it, lat, lng):
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--festival-km", type=float, default=60.0, help="이 거리 안의 축제만 담는다")
ap.add_argument("--per-type", type=int, default=24, help="타입별 최대 건수")
ap.add_argument("--lang", choices=["en", "ko"], default="en",
help="en 은 EngService2(외국인 환자용 /en/stay), ko 는 KorService2(/stay)")
ap.add_argument("--out", default="")
a = ap.parse_args()
# ---------- 기준 좌표 ----------
global TYPES
env = load_env(os.path.join(ROOT, ".env"))
if a.lang == "ko":
TYPES = TYPES_KO
env = dict(env, TOUR_API_SERVICE="KorService2")
if not a.out:
a.out = ("supporters/src/data/medicalTourism.json" if a.lang == "en"
else "supporters/src/data/medicalTourismKo.json")
for k in ("TOUR_API_KEY", "TOUR_API_BASE", "TOUR_API_SERVICE", "TOUR_API_ORIGIN_LAT", "TOUR_API_ORIGIN_LNG"):
if not env.get(k): sys.exit(f".env 에 {k} 가 비어 있습니다")
lat, lng = float(env["TOUR_API_ORIGIN_LAT"]), float(env["TOUR_API_ORIGIN_LNG"])
def road_key(address):
"""주소에서 도로명과 건물번호를 뽑는다. "서울 강남구 선릉로 612 한일빌딩" → ("선릉로", "612").
비교에만 쓴다. 없으면 (None, None)."""
m = re.search(r"([가-힣A-Za-z0-9]*?(?:대로|로|길))\s*(\d+(?:-\d+)?)(?!\s*길)", address or "")
return (m.group(1), m.group(2)) if m else (None, None)
out = {"places": {}, "festivals": [], "meta": {}}
def addr_match(want, got):
"""검색 결과 주소가 준 주소와 같은 도로명·번지인지. 도로명과 번지 사이 공백은 무시하고,
번지 바로 뒤에 숫자나 '-' 가 붙으면(612 와 6120, 612-1) 다른 곳으로 본다.
"봉은사로 107 1, 3-5층" 처럼 공백 뒤에 층이 오는 것은 같은 곳이다."""
road, num = road_key(want)
if not road: return False
return re.search(re.escape(road) + r"\s*" + re.escape(num) + r"(?![\d-])", got or "") is not None
def strip_tags(s):
return re.sub(r"<[^>]+>", "", s or "").strip()
def geocode_naver(env, name, address):
"""네이버 지역검색으로 상호를 찾아 좌표를 얻는다. mapx/mapy 는 WGS84 경위도 x 10^7 이다.
주소만으로는 결과가 없다(실측). 상호를 넣고, 결과의 도로명 주소가 준 주소와 같을 때만 받는다."""
cid, sec = env.get("NAVER_CLIENT_ID"), env.get("NAVER_CLIENT_SECRET")
if not (cid and sec): return None, "NAVER_CLIENT_ID/SECRET 없음"
road, num = road_key(address)
queries = []
if road: queries.append(f"{name} {road} {num}")
queries += [f"{name} {address}", name]
tried = []
for q in queries:
qs = urllib.parse.urlencode({"query": q, "display": "5", "sort": "random"})
req = urllib.request.Request("https://openapi.naver.com/v1/search/local.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 as e:
tried.append(f"'{q}': 요청 실패 {e}"); continue
for it in items:
got = it.get("roadAddress") or it.get("address") or ""
if not addr_match(address, got): continue
try:
lng, lat = int(it["mapx"]) / 1e7, int(it["mapy"]) / 1e7
except (KeyError, ValueError):
continue
if not (33 <= lat <= 39 and 124 <= lng <= 132): continue
return {"lat": lat, "lng": lng, "matched": strip_tags(it.get("title")), "matchedAddress": got,
"coordSource": f"네이버 지역검색 '{strip_tags(it.get('title'))}' ({got}) {time.strftime('%Y-%m-%d')}"}, ""
tried.append(f"'{q}': {len(items)}건, 주소 일치 없음")
return None, "; ".join(tried)
def geocode_tourapi(env, name, address):
"""TourAPI 키워드 검색(국문·영문)으로 병원 항목을 찾는다. 등재된 병원만 나오므로 보조 수단이다."""
tried = []
for svc in ("KorService2", "EngService2"):
e = dict(env, TOUR_API_SERVICE=svc)
try:
_, rows = call(e, "searchKeyword2", {"keyword": name}, rows=20, retries=1)
except Exception as ex:
tried.append(f"{svc}: 요청 실패 {ex}"); continue
for it in rows:
got = it.get("addr1") or ""
if not addr_match(address, got): continue
try:
lng, lat = float(it.get("mapx") or 0), float(it.get("mapy") or 0)
except ValueError:
continue
if not (33 <= lat <= 39 and 124 <= lng <= 132): continue
return {"lat": lat, "lng": lng, "matched": (it.get("title") or "").strip(), "matchedAddress": got,
"coordSource": f"한국관광공사 TourAPI {svc} contentid {it.get('contentid')} ({got}) {time.strftime('%Y-%m-%d')}"}, ""
tried.append(f"{svc}: {len(rows)}건, 주소 일치 없음")
return None, "; ".join(tried)
def resolve_origin(env, a):
"""기준 좌표와 출처. 못 정하면 (None, 이유)."""
if a.lat is not None or a.lng is not None:
if a.lat is None or a.lng is None: return None, "--lat 와 --lng 는 함께 줘야 합니다"
return {"lat": a.lat, "lng": a.lng, "address": a.address or "",
"coordSource": f"명령 인자 --lat/--lng {time.strftime('%Y-%m-%d')}"}, ""
if a.address:
if not a.name: return None, "--address 에는 --name(검색할 상호)이 필요합니다. 주소만으로는 지역검색 결과가 없습니다"
road, num = road_key(a.address)
if not road: return None, f"주소에서 도로명·번지를 찾지 못했습니다: {a.address}"
found, why1 = geocode_naver(env, a.name, a.address)
if found: return dict(found, address=a.address), ""
found, why2 = geocode_tourapi(env, a.name, a.address)
if found: return dict(found, address=a.address), ""
return None, f"주소를 좌표로 바꾸지 못했습니다. 네이버 지역검색: {why1} / TourAPI: {why2}"
lat, lng = env.get("TOUR_API_ORIGIN_LAT"), env.get("TOUR_API_ORIGIN_LNG")
if not (lat and lng): return None, "기준 좌표가 없습니다. --address --name 또는 --lat --lng 를 주거나 .env 의 TOUR_API_ORIGIN_LAT/LNG 를 채우세요"
return {"lat": float(lat), "lng": float(lng), "address": "",
"coordSource": f".env TOUR_API_ORIGIN_LAT/LNG {time.strftime('%Y-%m-%d')}"}, ""
# ---------- 수집 ----------
def collect(env, lang, origin, a):
"""한 언어의 데이터를 모아 dict 로 돌려준다. 파일은 쓰지 않는다."""
types = TYPES_KO if lang == "ko" else TYPES_EN
env = dict(env, TOUR_API_SERVICE="KorService2" if lang == "ko" else "EngService2")
lat, lng = origin["lat"], origin["lng"]
print(f"\n[{lang}] {env['TOUR_API_SERVICE']} · 기준 {lat}, {lng}")
out = {"places": {}, "festivals": [], "filters": {}, "meta": {}}
filtered_log = {}
wellness = []
for ct, (name, radius) in TYPES.items():
for ct, (name, radius) in types.items():
total, rows = call_all(env, "locationBasedList2",
{"mapX": str(lng), "mapY": str(lat), "radius": radius,
"contentTypeId": ct, "arrange": "E"})
@@ -348,7 +457,7 @@ def main():
print(f" {name:<11} r={radius:>5}m · API {total:>4} · 받음 {len(rows):>3} · 의료관광업소 제외 {len(dropped):>3} · 담음 {len(out['places'][name])}")
wellness.sort(key=lambda x: x["distanceM"] if x["distanceM"] is not None else 10 ** 9)
out["places"]["wellness"] = wellness[:a.per_type]
filtered_log["wellness"] = {"note": "관광지(76)에서 스파·찜질방 분류만 분리", "shown": len(out["places"]["wellness"])}
filtered_log["wellness"] = {"note": "관광지에서 스파·찜질방 분류만 분리", "shown": len(out["places"]["wellness"])}
print(f" {'wellness':<11} 스파·찜질방 분리 · 담음 {len(out['places']['wellness'])}")
# 영문 축제는 areacode 필드가 비어 있어 지역 필터를 쓸 수 없다. 좌표로 거리를 계산해 거른다.
@@ -372,24 +481,23 @@ def main():
# 설명문은 항목마다 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)
print(f" 설명문 수집 {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 이미지 검색
# 1) 같은 언어 detailImage2 → 2) 국문 서비스 → 3) 업체 홈페이지 og:image → 4) Naver 이미지 검색
src = ""
img = fetch_image(env, p["id"], cache)
if img: src = "tourapi"
if not img and a.lang == "en":
if not img and lang == "en":
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:
if not img and not a.no_naver_images:
img = fetch_image_naver(env, p); src = "naver" if img else src
p["image"] = img or None
p["imageSource"] = src
@@ -414,26 +522,63 @@ def main():
}
out["meta"] = {
"lang": a.lang,
"lang": lang,
"clinic": a.clinic or "",
"source": "한국관광공사 TourAPI " + env["TOUR_API_SERVICE"],
"fetchedAt": time.strftime("%Y-%m-%dT%H:%M:%S"),
"origin": {"lat": lat, "lng": lng, "label": "뷰성형외과의원 (봉은사로 107)",
"coordSource": "Naver 지역검색 실측 2026-09-09"},
"radiusByType": {n: int(r) for n, r in TYPES.values()}, "festivalRadiusKm": a.festival_km,
"origin": {"lat": lat, "lng": lng, "label": a.label or origin.get("matched") or origin.get("address") or "",
"address": origin.get("address", ""), "coordSource": origin["coordSource"]},
"radiusByType": {n: int(r) for n, r in types.values()}, "festivalRadiusKm": a.festival_km,
"counts": filtered_log,
# 화면이 한계를 그대로 표시할 수 있게 데이터에 적어 둔다. 없는 값을 채우지 않는다.
"limits": [
"영문 서비스는 강남 일대 숙박·음식점 커버리지가 얇다(반경 5km 숙박 4건·음식점 18건, 국문은 43건·338건).",
"관광지 항목의 대부분(반경 5km 100건 중 92건)이 분류코드 A02020500 \"Medical Tourism Sites\" 였고 제외했다.",
"영문 서비스는 도심 숙박·음식점 커버리지가 국문보다 얇다.",
"관광지 항목 중 분류코드 A02020500 \"Medical Tourism Sites\"(병원·유치업체)는 제외했다.",
"평점·리뷰·영업시간은 TourAPI 가 제공하지 않는다. Google Places 승인 후 채운다.",
"영문 축제는 areacode 필드가 비어 있어 좌표 거리로 걸렀다.",
"수술 전후 식이 적합성은 병원이 입력한 가이드로만 표시한다. 이 파일에는 없다.",
],
}
p = os.path.join(ROOT, a.out)
os.makedirs(os.path.dirname(p), exist_ok=True)
io.open(p, "w", encoding="utf-8").write(json.dumps(out, ensure_ascii=False, indent=2))
print(f"\n→ {a.out}")
return out
def main():
ap = argparse.ArgumentParser(description="병원 주변 관광 데이터 수집 (TourAPI)")
ap.add_argument("--clinic", default="", help="병원 id (meta.clinic)")
ap.add_argument("--name", default="", help="지역검색에 쓸 상호. --address 와 함께 준다")
ap.add_argument("--address", default="", help="병원 주소. 네이버 지역검색으로 좌표를 찾는다")
ap.add_argument("--lat", type=float, default=None); ap.add_argument("--lng", type=float, default=None)
ap.add_argument("--label", default="", help="화면에 보일 기준점 이름 (meta.origin.label)")
ap.add_argument("--out-en", default="", help="영문 JSON 경로 (절대 또는 현재 폴더 기준)")
ap.add_argument("--out-ko", default="", help="국문 JSON 경로")
ap.add_argument("--festival-km", type=float, default=60.0, help="이 거리 안의 축제만 담는다")
ap.add_argument("--per-type", type=int, default=24, help="타입별 최대 건수")
ap.add_argument("--no-naver-images", action="store_true", help="네이버 이미지 검색 폴백을 끈다 (공개 배포용)")
ap.add_argument("--lang", choices=["en", "ko"], default="en", help="(이전 방식) --out 하나만 낼 때의 언어")
ap.add_argument("--out", default="", help="(이전 방식) 저장소 루트 기준 경로")
a = ap.parse_args()
env = load_env(os.path.join(ROOT, ".env"))
for k in ("TOUR_API_KEY", "TOUR_API_BASE"):
if not env.get(k): sys.exit(f"{k} 가 비어 있습니다 (.env 또는 환경변수)")
origin, why = resolve_origin(env, a)
if not origin:
print(f"기준 좌표 실패: {why}", file=sys.stderr); sys.exit(1)
print(f"기준 좌표 {origin['lat']}, {origin['lng']} · {origin['coordSource']}")
jobs = []
if a.out_en: jobs.append(("en", os.path.abspath(a.out_en)))
if a.out_ko: jobs.append(("ko", os.path.abspath(a.out_ko)))
if not jobs:
rel = a.out or ("supporters/src/data/medicalTourism.json" if a.lang == "en" else "supporters/src/data/medicalTourismKo.json")
jobs.append((a.lang, os.path.join(ROOT, rel)))
for lang, path in jobs:
out = collect(env, lang, origin, a)
os.makedirs(os.path.dirname(path), exist_ok=True)
io.open(path, "w", encoding="utf-8").write(json.dumps(out, ensure_ascii=False, indent=2))
print(f"→ {path} · 장소 {out['filters']['total']} · 축제 {len(out['festivals'])}")
if __name__ == "__main__":