{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ec529532-5b5f-4f09-b925-6fab408978fe", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: aiofiles in /home/appuser/.local/lib/python3.11/site-packages (23.2.1)\n", "Requirement already satisfied: tqdm in /home/appuser/.local/lib/python3.11/site-packages (4.66.1)\n", "\n", "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.3.1\u001b[0m\n", "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n" ] } ], "source": [ "!pip install aiofiles tqdm" ] }, { "cell_type": "code", "execution_count": 2, "id": "ddfc2d01-6c44-496c-a65b-9a9f44534a2e", "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import json\n", "import os\n", "import re\n", "\n", "import aiofiles\n", "import aiohttp\n", "import pandas as pd\n", "import requests\n", "import tqdm.asyncio\n", "\n", "from restgdf.utils.crawl import fetch_all_data\n", "from restgdf.utils.getinfo import service_metadata, get_metadata\n", "\n", "\n", "api_root = \"http://restgdf_api:8080\"\n", "ms_root = f\"{api_root}/mappingsupport\"\n", "ms_endpoints = {name: f\"{ms_root}/{name}\" for name in ('state', 'county', 'town')} | {\"root\": f\"{api_root}/mappingsupport\"}\n", "\n", "\n", "def get_df() -> pd.DataFrame:\n", " resp = requests.get(ms_endpoints['root'])\n", " data = resp.json()\n", " return pd.DataFrame(data)\n", "\n", "\n", "def get_unique_roots(df: pd.DataFrame) -> pd.Series:\n", " pat = re.compile(r\"(?P^.*/rest/services?).*?$\", re.IGNORECASE)\n", " return (\n", " df\n", " .join(\n", " df['ArcGIS-url']\n", " .dropna()\n", " .str.strip()\n", " .str.extract(pat)\n", " ['root']\n", " .dropna()\n", " )\n", " ['root']\n", " .dropna()\n", " .drop_duplicates()\n", " .sort_values()\n", " )\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "10fb3d81-86a8-44e2-a60f-e909a5836b1d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 34.2 ms, sys: 3.42 ms, total: 37.6 ms\n", "Wall time: 241 ms\n" ] } ], "source": [ "%%time\n", "\n", "df = get_df()\n", "\n", "unique_roots = get_unique_roots(df)" ] }, { "cell_type": "code", "execution_count": 4, "id": "3c66c7b0-f9a6-404e-a353-9457b5c47332", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
urlhash
0http://136.234.13.165/arcgis/rest/services8489457957960488436
1http://216.167.160.20/arcgis107/rest/services4291004727045614516
2http://ags.co.okaloosa.fl.us/arcgis/rest/services10213391155691883489
3http://arcgis.dcnr.nv.gov/arcgis/rest/services8177309747274201625
4http://arcgis2.williamsoncounty-tn.gov/arcgis/...1860738680214392857
\n", "
" ], "text/plain": [ " url hash\n", "0 http://136.234.13.165/arcgis/rest/services 8489457957960488436\n", "1 http://216.167.160.20/arcgis107/rest/services 4291004727045614516\n", "2 http://ags.co.okaloosa.fl.us/arcgis/rest/services 10213391155691883489\n", "3 http://arcgis.dcnr.nv.gov/arcgis/rest/services 8177309747274201625\n", "4 http://arcgis2.williamsoncounty-tn.gov/arcgis/... 1860738680214392857" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "unique_root_hashes = pd.util.hash_pandas_object(unique_roots)\n", "\n", "unique_root_df = pd.DataFrame(zip(unique_roots, unique_root_hashes), columns=['url','hash'])\n", "\n", "unique_root_df.head()" ] }, { "cell_type": "code", "execution_count": 5, "id": "17917509-20e6-458c-8cfd-a0403ed73779", "metadata": {}, "outputs": [], "source": [ "unique_root_df.to_csv('unique_roots.csv', index=False)" ] }, { "cell_type": "code", "execution_count": 6, "id": "9b3ef1af-4cbe-45cd-9986-1b45f8392099", "metadata": {}, "outputs": [], "source": [ "done_dict = {(r.url, r.hash): False for r in unique_root_df.itertuples(index=False)}" ] }, { "cell_type": "code", "execution_count": 7, "id": "2a70822d-e090-40af-b631-0b352e4a6a43", "metadata": {}, "outputs": [], "source": [ "async def scrape_to_files(url_hash_dict: dict[tuple, bool], output_directory: str) -> dict[tuple, bool]:\n", " done_dict = url_hash_dict\n", " async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:\n", "\n", " async def fetch_to_file(url: str, hash: int) -> None:\n", " filepath = os.path.join(output_directory, f\"{hash}.json\")\n", " if os.path.exists(filepath):\n", " return None\n", " try:\n", " data = await fetch_all_data(session, url, return_feature_count=False)\n", " if 'error' in data:\n", " data['error'] = str(data['error'])\n", " async with aiofiles.open(filepath, 'w') as outf:\n", " await outf.write(json.dumps(data))\n", " done_dict[(url, hash)] = True\n", " except Exception as e:\n", " done_dict[(url, hash)] = e\n", " \n", " tasks = [fetch_to_file(url, hash) for url, hash in done_dict.keys()]\n", " results = await tqdm.asyncio.tqdm_asyncio.gather(*tasks)\n", " return done_dict\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "bf720487-a42b-4c39-b6bd-f9ab2e01cd0b", "metadata": {}, "outputs": [], "source": [ "output_dir = os.path.abspath(\"output\")\n", "\n", "if not os.path.exists(output_dir):\n", " os.mkdir(output_dir)" ] }, { "cell_type": "code", "execution_count": 9, "id": "ef74d321-6ef5-40d8-90b3-a990f32c1ea1", "metadata": {}, "outputs": [], "source": [ "import nest_asyncio\n", "\n", "nest_asyncio.apply()" ] }, { "cell_type": "code", "execution_count": 10, "id": "b1859b15-3d0d-4ef7-8ecd-6c57c6e3b600", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " 2%|▏ | 39/2038 [00:06<02:55, 11.41it/s] Can not load response cookies: Illegal key 'Domain=.sherburne.mn.us,AGS_ROLES'\n", "100%|██████████| 2038/2038 [24:38<00:00, 1.38it/s] " ] }, { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 21min 43s, sys: 35.1 s, total: 22min 18s\n", "Wall time: 24min 38s\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "%%time\n", "\n", "results = asyncio.run(scrape_to_files(done_dict, output_dir))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.6" } }, "nbformat": 4, "nbformat_minor": 5 }