{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ec83871e",
   "metadata": {},
   "source": [
    "# 서울시 강북구 미아동 건물 층수 지도\n",
    "\n",
    "VWorld `buldFloorCoList`로 건물 층 정보를 수집하고, `getBldgisSpceWFS` 건물 도형에 결합해 대화형 지도를 만듭니다. 대상은 **법정동 미아동**(PNU 앞 8자리 `11305101`)입니다.\n",
    "\n",
    "- 인증키: 프로젝트 루트 `.env`의 `vworld_key`\n",
    "- 선택 설정: 키 발급 시 도메인을 등록했다면 `.env`에 `vworld_domain=등록한_URL` 추가\n",
    "- 결과: `mia_height_map.html`, `mia_building_floors.csv`\n",
    "- API: [건물층수조회](https://api.vworld.kr/ned/data/buldFloorCoList), [VWorld 국가중점데이터 안내](https://www.vworld.kr/dtna/dtna_apiSvcList_s001.do)\n",
    "\n",
    "> 층수는 지상층 번호의 최댓값으로 계산합니다. 건물 도형과 층 자료에 공통 건물 일련번호가 없으면 해당 필지(PNU)의 최대 층수를 표시합니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2d805389",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Could not find platform independent libraries <prefix>\n",
      "\n",
      "[notice] A new release of pip is available: 26.2.1 -> 26.3\n",
      "[notice] To update, run: python.exe -m pip install --upgrade pip\n"
     ]
    }
   ],
   "source": [
    "%pip install -q requests pandas folium python-dotenv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "18b71b62",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "설정 완료 — API 키는 출력하지 않습니다.\n"
     ]
    }
   ],
   "source": [
    "from __future__ import annotations\n",
    "\n",
    "import hashlib\n",
    "import json\n",
    "import math\n",
    "import re\n",
    "import time\n",
    "from pathlib import Path\n",
    "from typing import Any\n",
    "\n",
    "import folium\n",
    "import pandas as pd\n",
    "import requests\n",
    "from dotenv import load_dotenv\n",
    "from folium.plugins import Fullscreen\n",
    "from branca.colormap import linear\n",
    "\n",
    "load_dotenv(Path('.env'))\n",
    "import os\n",
    "\n",
    "VWORLD_KEY = os.getenv('vworld_key', '').strip()\n",
    "VWORLD_DOMAIN = os.getenv('vworld_domain', '').strip()\n",
    "if not VWORLD_KEY:\n",
    "    raise RuntimeError(\".env에 vworld_key=발급키를 설정하세요.\")\n",
    "\n",
    "BASE_URL = 'https://api.vworld.kr'\n",
    "MIA_PNU_PREFIX = '11305101'  # 서울특별시 강북구 미아동(법정동, 8자리)\n",
    "PAGE_SIZE = 1000\n",
    "TIMEOUT = 60\n",
    "session = requests.Session()\n",
    "session.headers.update({'User-Agent': 'mia-height-notebook/1.0'})\n",
    "print('설정 완료 — API 키는 출력하지 않습니다.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a75367fc",
   "metadata": {},
   "source": [
    "## 1. API 도우미와 인증 확인\n",
    "\n",
    "VWorld는 오류도 HTTP 200으로 반환할 수 있어 응답 본문의 오류 코드를 별도로 검사합니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "08518739",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "VWorld 인증 및 buldFloorCoList 접근 확인 완료\n"
     ]
    }
   ],
   "source": [
    "class VWorldError(RuntimeError):\n",
    "    pass\n",
    "\n",
    "\n",
    "def _find_error(obj: Any) -> tuple[str, str] | None:\n",
    "    if isinstance(obj, dict):\n",
    "        normalized = {str(k).lower(): v for k, v in obj.items()}\n",
    "        code = normalized.get('error') or normalized.get('resultcode')\n",
    "        message = normalized.get('message') or normalized.get('resultmsg') or ''\n",
    "        if code and str(code).upper() not in {'SUCCESS', 'OK', '0', '00'}:\n",
    "            return str(code), str(message)\n",
    "        for value in obj.values():\n",
    "            found = _find_error(value)\n",
    "            if found:\n",
    "                return found\n",
    "    elif isinstance(obj, list):\n",
    "        for value in obj:\n",
    "            found = _find_error(value)\n",
    "            if found:\n",
    "                return found\n",
    "    return None\n",
    "\n",
    "\n",
    "def vworld_get(path: str, params: dict[str, Any], retries: int = 3) -> dict[str, Any]:\n",
    "    query = {**params, 'key': VWORLD_KEY}\n",
    "    if VWORLD_DOMAIN:\n",
    "        query['domain'] = VWORLD_DOMAIN\n",
    "    for attempt in range(retries):\n",
    "        try:\n",
    "            response = session.get(BASE_URL + path, params=query, timeout=TIMEOUT)\n",
    "            response.raise_for_status()\n",
    "            data = response.json()\n",
    "            error = _find_error(data)\n",
    "            if error:\n",
    "                code, message = error\n",
    "                hint = ''\n",
    "                if code.upper() == 'INCORRECT_KEY':\n",
    "                    hint = ' VWorld에서 키의 활성 상태와 국가중점데이터 API 활용신청을 확인하세요.'\n",
    "                raise VWorldError(f'{code}: {message}{hint}')\n",
    "            return data\n",
    "        except (requests.RequestException, ValueError) as exc:\n",
    "            if attempt == retries - 1:\n",
    "                raise VWorldError(f'VWorld 요청 실패: {type(exc).__name__}') from exc\n",
    "            time.sleep(2 ** attempt)\n",
    "    raise AssertionError('unreachable')\n",
    "\n",
    "\n",
    "def first_list_of_dicts(obj: Any) -> list[dict[str, Any]]:\n",
    "    \"\"\"응답 버전에 따른 field/items/rows 차이를 흡수합니다.\"\"\"\n",
    "    if isinstance(obj, dict):\n",
    "        for key in ('field', 'items', 'rows', 'row', 'item'):\n",
    "            value = obj.get(key)\n",
    "            if isinstance(value, list) and (not value or isinstance(value[0], dict)):\n",
    "                return value\n",
    "            if isinstance(value, dict):\n",
    "                return [value]\n",
    "        for value in obj.values():\n",
    "            result = first_list_of_dicts(value)\n",
    "            if result:\n",
    "                return result\n",
    "    elif isinstance(obj, list) and (not obj or isinstance(obj[0], dict)):\n",
    "        return obj\n",
    "    return []\n",
    "\n",
    "\n",
    "def find_number(obj: Any, names=('totalcount', 'totalfeatures', 'numbermatched')) -> int | None:\n",
    "    if isinstance(obj, dict):\n",
    "        for key, value in obj.items():\n",
    "            if str(key).lower() in names:\n",
    "                try:\n",
    "                    return int(value)\n",
    "                except (TypeError, ValueError):\n",
    "                    pass\n",
    "        for value in obj.values():\n",
    "            found = find_number(value, names)\n",
    "            if found is not None:\n",
    "                return found\n",
    "    return None\n",
    "\n",
    "\n",
    "# 작은 요청으로 인증/활용 권한을 먼저 확인\n",
    "test = vworld_get('/ned/data/buldFloorCoList', {\n",
    "    'pnu': MIA_PNU_PREFIX, 'format': 'json', 'numOfRows': 1, 'pageNo': 1\n",
    "})\n",
    "print('VWorld 인증 및 buldFloorCoList 접근 확인 완료')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f6ddd45",
   "metadata": {},
   "source": [
    "## 2. 미아동 층 자료 수집\n",
    "\n",
    "8자리 법정동 PNU 접두어로 `buldFloorCoList`를 페이지 끝까지 조회합니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1543a00e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "층 자료 65,774 / 65,774건\n",
      "원본 층 레코드: 65,774건 / 컬럼: ['agbldgSn', 'buldFloorNm', 'liCodeNm', 'buldDongNm', 'ldaQotaRate', 'clsSeCodeNm', 'buldHoNm', 'buldRoomNm', 'mnnmSlno', 'buldNm', 'pnu', 'lastUpdtDt', 'liCode', 'regstrSeCodeNm', 'relateLdEmdLiCode', 'regstrSeCode', 'clsSeCode']\n"
     ]
    },
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "agbldgSn",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "buldFloorNm",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "liCodeNm",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "buldDongNm",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "ldaQotaRate",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "clsSeCodeNm",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "buldHoNm",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "buldRoomNm",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "mnnmSlno",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "buldNm",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "pnu",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "lastUpdtDt",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "liCode",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "regstrSeCodeNm",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "relateLdEmdLiCode",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "regstrSeCode",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "clsSeCode",
         "rawType": "str",
         "type": "string"
        }
       ],
       "ref": "f5df029d-c16e-4f67-8bf4-dfc2f62f55eb",
       "rows": [
        [
         "0",
         "0922",
         "5",
         "서울특별시 강북구 미아동",
         "0000",
         "38.39/370",
         "현재",
         "502",
         "0000",
         "3-9",
         "다세대주택",
         "1130510100100030009",
         "2026-11-06",
         "1130510100",
         "토지대장",
         "10100",
         "1",
         "0"
        ],
        [
         "1",
         "0922",
         "5",
         "서울특별시 강북구 미아동",
         "0000",
         "38.39/370",
         "현재",
         "501",
         "0000",
         "3-9",
         "다세대주택",
         "1130510100100030009",
         "2026-11-06",
         "1130510100",
         "토지대장",
         "10100",
         "1",
         "0"
        ],
        [
         "2",
         "0922",
         "4",
         "서울특별시 강북구 미아동",
         "0000",
         "34.37/370",
         "현재",
         "402",
         "0000",
         "3-9",
         "다세대주택",
         "1130510100100030009",
         "2026-11-06",
         "1130510100",
         "토지대장",
         "10100",
         "1",
         "0"
        ],
        [
         "3",
         "0922",
         "4",
         "서울특별시 강북구 미아동",
         "0000",
         "26.05/370",
         "현재",
         "403",
         "0000",
         "3-9",
         "다세대주택",
         "1130510100100030009",
         "2026-11-06",
         "1130510100",
         "토지대장",
         "10100",
         "1",
         "0"
        ],
        [
         "4",
         "0922",
         "3",
         "서울특별시 강북구 미아동",
         "0000",
         "26.05/370",
         "현재",
         "303",
         "0000",
         "3-9",
         "다세대주택",
         "1130510100100030009",
         "2026-11-06",
         "1130510100",
         "토지대장",
         "10100",
         "1",
         "0"
        ]
       ],
       "shape": {
        "columns": 17,
        "rows": 5
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>agbldgSn</th>\n",
       "      <th>buldFloorNm</th>\n",
       "      <th>liCodeNm</th>\n",
       "      <th>buldDongNm</th>\n",
       "      <th>ldaQotaRate</th>\n",
       "      <th>clsSeCodeNm</th>\n",
       "      <th>buldHoNm</th>\n",
       "      <th>buldRoomNm</th>\n",
       "      <th>mnnmSlno</th>\n",
       "      <th>buldNm</th>\n",
       "      <th>pnu</th>\n",
       "      <th>lastUpdtDt</th>\n",
       "      <th>liCode</th>\n",
       "      <th>regstrSeCodeNm</th>\n",
       "      <th>relateLdEmdLiCode</th>\n",
       "      <th>regstrSeCode</th>\n",
       "      <th>clsSeCode</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0922</td>\n",
       "      <td>5</td>\n",
       "      <td>서울특별시 강북구 미아동</td>\n",
       "      <td>0000</td>\n",
       "      <td>38.39/370</td>\n",
       "      <td>현재</td>\n",
       "      <td>502</td>\n",
       "      <td>0000</td>\n",
       "      <td>3-9</td>\n",
       "      <td>다세대주택</td>\n",
       "      <td>1130510100100030009</td>\n",
       "      <td>2026-11-06</td>\n",
       "      <td>1130510100</td>\n",
       "      <td>토지대장</td>\n",
       "      <td>10100</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0922</td>\n",
       "      <td>5</td>\n",
       "      <td>서울특별시 강북구 미아동</td>\n",
       "      <td>0000</td>\n",
       "      <td>38.39/370</td>\n",
       "      <td>현재</td>\n",
       "      <td>501</td>\n",
       "      <td>0000</td>\n",
       "      <td>3-9</td>\n",
       "      <td>다세대주택</td>\n",
       "      <td>1130510100100030009</td>\n",
       "      <td>2026-11-06</td>\n",
       "      <td>1130510100</td>\n",
       "      <td>토지대장</td>\n",
       "      <td>10100</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0922</td>\n",
       "      <td>4</td>\n",
       "      <td>서울특별시 강북구 미아동</td>\n",
       "      <td>0000</td>\n",
       "      <td>34.37/370</td>\n",
       "      <td>현재</td>\n",
       "      <td>402</td>\n",
       "      <td>0000</td>\n",
       "      <td>3-9</td>\n",
       "      <td>다세대주택</td>\n",
       "      <td>1130510100100030009</td>\n",
       "      <td>2026-11-06</td>\n",
       "      <td>1130510100</td>\n",
       "      <td>토지대장</td>\n",
       "      <td>10100</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0922</td>\n",
       "      <td>4</td>\n",
       "      <td>서울특별시 강북구 미아동</td>\n",
       "      <td>0000</td>\n",
       "      <td>26.05/370</td>\n",
       "      <td>현재</td>\n",
       "      <td>403</td>\n",
       "      <td>0000</td>\n",
       "      <td>3-9</td>\n",
       "      <td>다세대주택</td>\n",
       "      <td>1130510100100030009</td>\n",
       "      <td>2026-11-06</td>\n",
       "      <td>1130510100</td>\n",
       "      <td>토지대장</td>\n",
       "      <td>10100</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0922</td>\n",
       "      <td>3</td>\n",
       "      <td>서울특별시 강북구 미아동</td>\n",
       "      <td>0000</td>\n",
       "      <td>26.05/370</td>\n",
       "      <td>현재</td>\n",
       "      <td>303</td>\n",
       "      <td>0000</td>\n",
       "      <td>3-9</td>\n",
       "      <td>다세대주택</td>\n",
       "      <td>1130510100100030009</td>\n",
       "      <td>2026-11-06</td>\n",
       "      <td>1130510100</td>\n",
       "      <td>토지대장</td>\n",
       "      <td>10100</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  agbldgSn buldFloorNm       liCodeNm buldDongNm ldaQotaRate clsSeCodeNm  \\\n",
       "0     0922           5  서울특별시 강북구 미아동       0000   38.39/370          현재   \n",
       "1     0922           5  서울특별시 강북구 미아동       0000   38.39/370          현재   \n",
       "2     0922           4  서울특별시 강북구 미아동       0000   34.37/370          현재   \n",
       "3     0922           4  서울특별시 강북구 미아동       0000   26.05/370          현재   \n",
       "4     0922           3  서울특별시 강북구 미아동       0000   26.05/370          현재   \n",
       "\n",
       "  buldHoNm buldRoomNm mnnmSlno buldNm                  pnu  lastUpdtDt  \\\n",
       "0      502       0000      3-9  다세대주택  1130510100100030009  2026-11-06   \n",
       "1      501       0000      3-9  다세대주택  1130510100100030009  2026-11-06   \n",
       "2      402       0000      3-9  다세대주택  1130510100100030009  2026-11-06   \n",
       "3      403       0000      3-9  다세대주택  1130510100100030009  2026-11-06   \n",
       "4      303       0000      3-9  다세대주택  1130510100100030009  2026-11-06   \n",
       "\n",
       "       liCode regstrSeCodeNm relateLdEmdLiCode regstrSeCode clsSeCode  \n",
       "0  1130510100           토지대장             10100            1         0  \n",
       "1  1130510100           토지대장             10100            1         0  \n",
       "2  1130510100           토지대장             10100            1         0  \n",
       "3  1130510100           토지대장             10100            1         0  \n",
       "4  1130510100           토지대장             10100            1         0  "
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def fetch_all_floor_rows(pnu_prefix: str) -> list[dict[str, Any]]:\n",
    "    all_rows: list[dict[str, Any]] = []\n",
    "    page = 1\n",
    "    while True:\n",
    "        data = vworld_get('/ned/data/buldFloorCoList', {\n",
    "            'pnu': pnu_prefix, 'format': 'json',\n",
    "            'numOfRows': PAGE_SIZE, 'pageNo': page,\n",
    "        })\n",
    "        rows = first_list_of_dicts(data)\n",
    "        total = find_number(data)\n",
    "        all_rows.extend(rows)\n",
    "        print(f'층 자료 {len(all_rows):,}' + (f' / {total:,}' if total is not None else '') + '건', end='\\r')\n",
    "        if not rows or len(rows) < PAGE_SIZE or (total is not None and len(all_rows) >= total):\n",
    "            break\n",
    "        page += 1\n",
    "    print()\n",
    "    return all_rows\n",
    "\n",
    "\n",
    "floor_rows = fetch_all_floor_rows(MIA_PNU_PREFIX)\n",
    "if not floor_rows:\n",
    "    raise RuntimeError('미아동 층 자료가 0건입니다. PNU 범위 조회 권한/응답을 확인하세요.')\n",
    "floor_raw = pd.DataFrame(floor_rows)\n",
    "print(f'원본 층 레코드: {len(floor_raw):,}건 / 컬럼: {list(floor_raw.columns)}')\n",
    "floor_raw.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7ab7a7f1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "_pnu",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "_sn",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "_dong",
         "rawType": "str",
         "type": "string"
        },
        {
         "name": "지상층수",
         "rawType": "Int64",
         "type": "integer"
        },
        {
         "name": "층레코드수",
         "rawType": "int64",
         "type": "integer"
        }
       ],
       "ref": "1de94994-d0dd-4366-b1cd-07850f7ff5d7",
       "rows": [
        [
         "0",
         "1130510100100030009",
         "0922",
         "0000",
         "5",
         "5"
        ],
        [
         "1",
         "1130510100100030010",
         "0599",
         "0000",
         "4",
         "6"
        ],
        [
         "2",
         "1130510100100030011",
         "1831",
         "0000",
         "4",
         "5"
        ],
        [
         "3",
         "1130510100100030012",
         "1840",
         "0000",
         "4",
         "6"
        ],
        [
         "4",
         "1130510100100030036",
         "1854",
         "0000",
         "4",
         "5"
        ]
       ],
       "shape": {
        "columns": 5,
        "rows": 5
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>_pnu</th>\n",
       "      <th>_sn</th>\n",
       "      <th>_dong</th>\n",
       "      <th>지상층수</th>\n",
       "      <th>층레코드수</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1130510100100030009</td>\n",
       "      <td>0922</td>\n",
       "      <td>0000</td>\n",
       "      <td>5</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1130510100100030010</td>\n",
       "      <td>0599</td>\n",
       "      <td>0000</td>\n",
       "      <td>4</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1130510100100030011</td>\n",
       "      <td>1831</td>\n",
       "      <td>0000</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1130510100100030012</td>\n",
       "      <td>1840</td>\n",
       "      <td>0000</td>\n",
       "      <td>4</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1130510100100030036</td>\n",
       "      <td>1854</td>\n",
       "      <td>0000</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                  _pnu   _sn _dong  지상층수  층레코드수\n",
       "0  1130510100100030009  0922  0000     5      5\n",
       "1  1130510100100030010  0599  0000     4      6\n",
       "2  1130510100100030011  1831  0000     4      5\n",
       "3  1130510100100030012  1840  0000     4      6\n",
       "4  1130510100100030036  1854  0000     4      5"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "건물/동 단위 집계: 3,192건\n"
     ]
    }
   ],
   "source": [
    "def norm(text: Any) -> str:\n",
    "    return re.sub(r'[^a-z0-9]', '', str(text).lower())\n",
    "\n",
    "\n",
    "def find_col(df: pd.DataFrame, candidates: list[str], required=True) -> str | None:\n",
    "    lookup = {norm(col): col for col in df.columns}\n",
    "    for candidate in candidates:\n",
    "        if norm(candidate) in lookup:\n",
    "            return lookup[norm(candidate)]\n",
    "    if required:\n",
    "        raise KeyError(f'필요 컬럼을 찾지 못했습니다: {candidates}; 실제 컬럼={list(df.columns)}')\n",
    "    return None\n",
    "\n",
    "\n",
    "pnu_col = find_col(floor_raw, ['pnu'])\n",
    "sn_col = find_col(floor_raw, ['agbldgSn', 'buldSn', 'ldaregSn'], required=False)\n",
    "dong_col = find_col(floor_raw, ['buldDongNm'], required=False)\n",
    "floor_col = find_col(floor_raw, ['buldFloorNm', 'floorNm', 'floorNo', 'floor'])\n",
    "\n",
    "def above_ground_number(value: Any) -> float:\n",
    "    text = str(value).strip()\n",
    "    if not text or text.lower() == 'nan' or any(token in text for token in ('지하', 'B', 'b')):\n",
    "        return math.nan\n",
    "    match = re.search(r'-?\\d+', text.replace(',', ''))\n",
    "    if not match:\n",
    "        return math.nan\n",
    "    number = int(match.group())\n",
    "    return float(number) if number > 0 else math.nan\n",
    "\n",
    "floor_raw['_pnu'] = floor_raw[pnu_col].astype(str).str.replace(r'\\.0$', '', regex=True).str.zfill(19)\n",
    "floor_raw['_sn'] = floor_raw[sn_col].astype(str).str.strip() if sn_col else ''\n",
    "floor_raw['_dong'] = floor_raw[dong_col].fillna('').astype(str).str.strip() if dong_col else ''\n",
    "floor_raw['_above_floor'] = floor_raw[floor_col].map(above_ground_number)\n",
    "\n",
    "building_floors = (\n",
    "    floor_raw.groupby(['_pnu', '_sn', '_dong'], dropna=False)\n",
    "    .agg(지상층수=('_above_floor', 'max'), 층레코드수=(floor_col, 'nunique'))\n",
    "    .reset_index()\n",
    ")\n",
    "building_floors['지상층수'] = building_floors['지상층수'].fillna(building_floors['층레코드수']).astype('Int64')\n",
    "building_floors.to_csv('mia_building_floors.csv', index=False, encoding='utf-8-sig')\n",
    "display(building_floors.head())\n",
    "print(f'건물/동 단위 집계: {len(building_floors):,}건')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15bb14d0",
   "metadata": {},
   "source": [
    "## 3. 건물 도형 수집\n",
    "\n",
    "WFS의 1,000건 제한을 피하기 위해 결과가 한도에 닿는 PNU 접두어만 숫자 0–9로 재귀 분할합니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "71a6476c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "중복 제거 후 건물 도형: 13,600건\n",
      "도형 속성 예시: ['src_objectid', 'gis_idntfc_no', 'pnu', 'ld_cpsg_code', 'mnnm', 'slno', 'regstr_se_code', 'buld_prpos_code', 'strct_code', 'ar', 'use_confm_de', 'totar', 'plot_ar', 'hg', 'btl_rt', 'measrmt_rt', 'buld_idntfc_no', 'violt_bild', 'refrn_systm_cntc_no', 'last_updt_dt', 'src_signgu_code', 'buld_nm', 'dong_nm', 'ground_floor_co', 'undgrnd_floor_co', 'data_creat_change_de']\n"
     ]
    }
   ],
   "source": [
    "def fetch_wfs(prefix: str) -> tuple[list[dict[str, Any]], int | None]:\n",
    "    data = vworld_get('/ned/wfs/getBldgisSpceWFS', {\n",
    "        'pnu': prefix, 'maxFeatures': PAGE_SIZE, 'resultType': 'results',\n",
    "        'srsName': 'EPSG:4326', 'output': 'application/json',\n",
    "    })\n",
    "    features = data.get('features', [])\n",
    "    return features, find_number(data)\n",
    "\n",
    "\n",
    "def collect_wfs_by_prefix(prefix: str) -> list[dict[str, Any]]:\n",
    "    features, total = fetch_wfs(prefix)\n",
    "    truncated = len(features) >= PAGE_SIZE or (total is not None and total > len(features))\n",
    "    if truncated and len(prefix) < 19:\n",
    "        children: list[dict[str, Any]] = []\n",
    "        for digit in '0123456789':\n",
    "            children.extend(collect_wfs_by_prefix(prefix + digit))\n",
    "        return children\n",
    "    return features\n",
    "\n",
    "\n",
    "features = collect_wfs_by_prefix(MIA_PNU_PREFIX)\n",
    "unique = {}\n",
    "for feature in features:\n",
    "    fingerprint = hashlib.sha1(json.dumps(feature, sort_keys=True, ensure_ascii=False).encode()).hexdigest()\n",
    "    unique[fingerprint] = feature\n",
    "features = list(unique.values())\n",
    "if not features:\n",
    "    raise RuntimeError('건물 도형이 0건입니다.')\n",
    "print(f'중복 제거 후 건물 도형: {len(features):,}건')\n",
    "print('도형 속성 예시:', list(features[0].get('properties', {}).keys()))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e04cd4a4",
   "metadata": {},
   "source": [
    "## 4. 층수 결합 및 지도 작성"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9543fa96",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "층수 결합: 11,607/13,600 (WFS 11,383, 일련번호 0, PNU 대체 224)\n"
     ]
    }
   ],
   "source": [
    "def prop_value(props: dict[str, Any], candidates: list[str]) -> str:\n",
    "    lookup = {norm(k): v for k, v in props.items()}\n",
    "    for candidate in candidates:\n",
    "        value = lookup.get(norm(candidate))\n",
    "        if value is not None:\n",
    "            return str(value).strip().removesuffix('.0')\n",
    "    return ''\n",
    "\n",
    "\n",
    "def positive_floor_count(value: Any) -> int | None:\n",
    "    \"\"\"VWorld WFS의 지상층수 값을 양의 정수로 변환합니다.\"\"\"\n",
    "    if value is None:\n",
    "        return None\n",
    "    text = str(value).strip()\n",
    "    if not text or text.lower() in {'nan', 'none', 'null'}:\n",
    "        return None\n",
    "    match = re.search(r'\\d+', text.replace(',', ''))\n",
    "    if not match:\n",
    "        return None\n",
    "    number = int(match.group())\n",
    "    return number if number > 0 else None\n",
    "\n",
    "\n",
    "floor_count_col = building_floors.columns[3]\n",
    "exact_lookup = building_floors.groupby(['_pnu', '_sn'])[floor_count_col].max().astype(int).to_dict()\n",
    "pnu_lookup = building_floors.groupby('_pnu')[floor_count_col].max().astype(int).to_dict()\n",
    "\n",
    "matched_wfs = matched_exact = matched_pnu = 0\n",
    "for feature in features:\n",
    "    props = feature.setdefault('properties', {})\n",
    "    pnu = prop_value(props, ['pnu']).zfill(19)\n",
    "    # WFS ?? ?? ??? ?? ????? ?? ???? ????.\n",
    "    floors = positive_floor_count(prop_value(props, ['ground_floor_co']))\n",
    "    method = 'WFS 지상층수'\n",
    "    if floors is not None:\n",
    "        matched_wfs += 1\n",
    "    else:\n",
    "        # ?? ???? ???? ?? ?? ????? ?? ?? ??? ?????.\n",
    "        sn = prop_value(props, ['agbldgSn', 'buldSn', 'ldaregSn', 'buld_idntfc_no', 'gis_idntfc_no'])\n",
    "        floors = exact_lookup.get((pnu, sn)) if sn else None\n",
    "        method = '건물 일련번호 일치'\n",
    "        if floors is not None:\n",
    "            matched_exact += 1\n",
    "        else:\n",
    "            floors = pnu_lookup.get(pnu)\n",
    "            method = '필지 내 최대값'\n",
    "            if floors is not None:\n",
    "                matched_pnu += 1\n",
    "    props['PNU'] = pnu\n",
    "    props['ground_floor_count'] = floors\n",
    "    props['match_method'] = method if floors is not None else '층 자료 없음'\n",
    "\n",
    "mapped = [f for f in features if f['properties'].get('ground_floor_count') is not None]\n",
    "print(f'층수 결합: {len(mapped):,}/{len(features):,} (WFS {matched_wfs:,}, 일련번호 {matched_exact:,}, PNU 대체 {matched_pnu:,})')\n",
    "if not mapped:\n",
    "    raise RuntimeError('층수와 건물 도형이 결합되지 않았습니다. 위 셀의 실제 컬럼과 속성을 확인하세요.')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a457f6b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def iter_lonlat(coords: Any):\n",
    "    if isinstance(coords, (list, tuple)) and len(coords) >= 2 and all(isinstance(v, (int, float)) for v in coords[:2]):\n",
    "        yield float(coords[0]), float(coords[1])\n",
    "    elif isinstance(coords, (list, tuple)):\n",
    "        for child in coords:\n",
    "            yield from iter_lonlat(child)\n",
    "\n",
    "points = [pt for feature in mapped for pt in iter_lonlat(feature.get('geometry', {}).get('coordinates', []))]\n",
    "if not points:\n",
    "    raise RuntimeError('No building geometry coordinates were found.')\n",
    "min_lon, max_lon = min(x for x, _ in points), max(x for x, _ in points)\n",
    "min_lat, max_lat = min(y for _, y in points), max(y for _, y in points)\n",
    "values = [f['properties']['ground_floor_count'] for f in mapped]\n",
    "vmax = max(values)\n",
    "colormap = linear.YlOrRd_09.scale(1, max(vmax, 2))\n",
    "colormap.caption = 'Above-ground floors'\n",
    "\n",
    "m = folium.Map(\n",
    "    location=[(min_lat + max_lat) / 2, (min_lon + max_lon) / 2],\n",
    "    zoom_start=14, tiles=None, control_scale=True,\n",
    ")\n",
    "folium.TileLayer(tiles='OpenStreetMap', name='OpenStreetMap', show=True, control=True).add_to(m)\n",
    "Fullscreen().add_to(m)\n",
    "folium.GeoJson(\n",
    "    {'type': 'FeatureCollection', 'features': mapped},\n",
    "    name='Buildings by floor count',\n",
    "    style_function=lambda f: {\n",
    "        'fillColor': colormap(f['properties']['ground_floor_count']),\n",
    "        'color': '#555', 'weight': 0.45, 'fillOpacity': 0.78,\n",
    "    },\n",
    "    highlight_function=lambda f: {'weight': 2, 'color': '#111', 'fillOpacity': 0.95},\n",
    "    tooltip=folium.GeoJsonTooltip(\n",
    "        fields=['ground_floor_count', 'PNU', 'match_method'],\n",
    "        aliases=['Floors', 'PNU', 'Match method'], localize=True, sticky=False,\n",
    "    ),\n",
    ").add_to(m)\n",
    "colormap.add_to(m)\n",
    "folium.LayerControl(collapsed=False).add_to(m)\n",
    "m.fit_bounds([[min_lat, min_lon], [max_lat, max_lon]])\n",
    "m.save('mia_height_map.html')\n",
    "map_path = Path('mia_height_map.html')\n",
    "interaction_js = Path('map_interactions.js').read_text(encoding='utf-8')\n",
    "map_html = map_path.read_text(encoding='utf-8')\n",
    "selection_assets = '''\n",
    "<!-- mia-selection-controls-assets -->\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css\">\n<style>\n.mia-selection-status,\n.mia-basemap-toggle {\n  background: rgba(255, 255, 255, .96);\n  border: 1px solid rgba(15, 23, 42, .18);\n  border-radius: 7px;\n  box-shadow: 0 1px 5px rgba(15, 23, 42, .22);\n  color: #172033;\n  font: 700 12px/1.3 system-ui, -apple-system, \"Segoe UI\", sans-serif;\n  padding: 8px 10px;\n}\n.mia-basemap-toggle label { display: flex; align-items: center; gap: 5px; cursor: pointer; }\n.mia-basemap-toggle input { accent-color: #155eef; width: 15px; height: 15px; }\n.mia-floor-label { background: transparent !important; border: 0 !important; }\n.mia-floor-label span {\n  display: inline-block;\n  transform: translate(-50%, -50%);\n  white-space: nowrap;\n  padding: 2px 5px;\n  border: 1px solid rgba(15, 23, 42, .72);\n  border-radius: 5px;\n  background: rgba(255, 255, 255, .94);\n  color: #101828;\n  box-shadow: 0 1px 3px rgba(15, 23, 42, .28);\n  font: 800 11px/1.2 system-ui, -apple-system, \"Segoe UI\", sans-serif;\n  pointer-events: none;\n}\n@media (max-width: 640px) {\n  .mia-selection-status, .mia-basemap-toggle { font-size: 11px; padding: 6px 8px; }\n}\n</style>\n",
    "'''\n",
    "if 'mia-selection-controls-assets' not in map_html:\n",
    "    map_html = map_html.replace('</head>', selection_assets + '\\n</head>', 1)\n",
    "if 'mia-selection-controls-script' not in map_html:\n",
    "    selection_scripts = (\n",
    "        '<script src=\"https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js\"></script>\\n'\n",
    "        '<script id=\"mia-selection-controls-script\">\\n' + interaction_js + '\\n</script>\\n'\n",
    "    )\n",
    "    map_html = map_html.replace('</html>', selection_scripts + '</html>', 1)\n",
    "map_path.write_text(map_html, encoding='utf-8')\n",
    "print('Saved: mia_height_map.html, mia_building_floors.csv')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3348b9ee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"100%\"\n",
       "            height=\"800\"\n",
       "            src=\"mia_height_map.html\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x22afd8ce990>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "지도가 보이지 않으면 새 창에서 열기: <a href='mia_height_map.html' target='_blank'>mia_height_map.html</a><br>"
      ],
      "text/plain": [
       "c:\\Users\\User\\Desktop\\mia\\mia\\mia_height_map.html"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from pathlib import Path\n",
    "from IPython.display import FileLink, IFrame, display\n",
    "\n",
    "map_file = Path('mia_height_map.html')\n",
    "if not map_file.exists():\n",
    "    raise FileNotFoundError('mia_height_map.html이 없습니다. 바로 위 지도 생성 셀을 먼저 실행하세요.')\n",
    "\n",
    "display(IFrame(src=str(map_file), width='100%', height=800))\n",
    "display(FileLink(map_file, result_html_prefix='지도가 보이지 않으면 새 창에서 열기: '))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv (3.14.7)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.14.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
