{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b30a3d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "### WKB_to_LatLong.py\n",
    "### Version: 7/27/2022\n",
    "### Author: Khem So, khem_so@fws.gov, (503) 231-6839\n",
    "### Abstract: This Python 3 script opens a CSV file and converts geometry stored as well-known binary (WKB) into decimal latitude and longitude coordinates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2762bb4a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import shapely"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "043e7166",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Replace with path to your source CSV file\n",
    "df = pd.read_csv(r\"C:\\Users\\kso\\Documents\\WORKSPACE\\Scratch\\NABatDetectorPtsWKT2022.csv\")\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21bc03ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_lat(wkb_text):\n",
    "    from shapely import wkb\n",
    "    latitude = shapely.wkb.loads(wkb_text, hex=True).y\n",
    "    return latitude\n",
    "\n",
    "def convert_long(wkb_text):\n",
    "    from shapely import wkb\n",
    "    longitude = shapely.wkb.loads(wkb_text, hex=True).x\n",
    "    return longitude"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33845020",
   "metadata": {},
   "outputs": [],
   "source": [
    "# If needed, replace 'location_geometry' with the name of the field containing WKB\n",
    "df['latitude'] = df['location_geometry'].apply(convert_lat)\n",
    "df['longitude'] = df['location_geometry'].apply(convert_long)\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ade68359",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Replace with path to your destination CSV file\n",
    "df.to_csv(os.path.join(r\"C:\\Users\\kso\\Documents\\WORKSPACE\\Scratch\\NABatDetectorPtsWKT2022-2.csv\"), index= False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
