open-data-philly-downloader 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- open_data_philly_downloader-0.1.0/.github/workflows/ci.yml +17 -0
- open_data_philly_downloader-0.1.0/.github/workflows/publish.yml +18 -0
- open_data_philly_downloader-0.1.0/LICENSE +0 -0
- open_data_philly_downloader-0.1.0/PKG-INFO +17 -0
- open_data_philly_downloader-0.1.0/README.md +1 -0
- open_data_philly_downloader-0.1.0/pyproject.toml +39 -0
- open_data_philly_downloader-0.1.0/src/odp_downloader/__init__.py +0 -0
- open_data_philly_downloader-0.1.0/src/odp_downloader/cli.py +95 -0
- open_data_philly_downloader-0.1.0/src/odp_downloader/client.py +24 -0
- open_data_philly_downloader-0.1.0/src/odp_downloader/download.py +139 -0
- open_data_philly_downloader-0.1.0/src/odp_downloader/geom.py +16 -0
- open_data_philly_downloader-0.1.0/src/odp_downloader/output.py +31 -0
- open_data_philly_downloader-0.1.0/src/odp_downloader/schemas.py +332 -0
- open_data_philly_downloader-0.1.0/tests/test_client.py +34 -0
- open_data_philly_downloader-0.1.0/tests/test_download.py +116 -0
- open_data_philly_downloader-0.1.0/tests/test_geom.py +27 -0
- open_data_philly_downloader-0.1.0/tests/test_output.py +51 -0
- open_data_philly_downloader-0.1.0/uv.lock +995 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
on:
|
|
3
|
+
pull_request:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
jobs:
|
|
7
|
+
test:
|
|
8
|
+
runs-on: ubuntu-latest
|
|
9
|
+
steps:
|
|
10
|
+
- uses: actions/checkout@v4
|
|
11
|
+
- uses: actions/setup-python@v5
|
|
12
|
+
with:
|
|
13
|
+
python-version: '3.10.14'
|
|
14
|
+
- uses: astral-sh/setup-uv@v4
|
|
15
|
+
- run: uv sync
|
|
16
|
+
- run: uv run ruff check .
|
|
17
|
+
- run: uv run pytest
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
on:
|
|
3
|
+
workflow_dispatch:
|
|
4
|
+
push:
|
|
5
|
+
tags: ['v*']
|
|
6
|
+
jobs:
|
|
7
|
+
publish:
|
|
8
|
+
runs-on: ubuntu-latest
|
|
9
|
+
steps:
|
|
10
|
+
- uses: actions/checkout@v4
|
|
11
|
+
- uses: actions/setup-python@v5
|
|
12
|
+
with:
|
|
13
|
+
python-version: '3.10.14'
|
|
14
|
+
- uses: astral-sh/setup-uv@v4
|
|
15
|
+
- run: uv build
|
|
16
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
17
|
+
with:
|
|
18
|
+
password: ${{ secrets.PYPI_API_TOKEN }}
|
|
File without changes
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: open-data-philly-downloader
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Download any table from OpenDataPhilly's CartoDB SQL API.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Police-Accountability-Unit-PHL/open-data-philly-downloader
|
|
6
|
+
Project-URL: Issues, https://github.com/Police-Accountability-Unit-PHL/open-data-philly-downloader/issues
|
|
7
|
+
Author-email: Stephen Suffian <stephen.suffian@pm.me>
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Python: >=3.10.4
|
|
11
|
+
Requires-Dist: click>=8.1.7
|
|
12
|
+
Requires-Dist: pandas>=2.1.1
|
|
13
|
+
Requires-Dist: requests>=2.31.0
|
|
14
|
+
Requires-Dist: sqlmodel>=0.0.16
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# open-data-philly-downloader
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# open-data-philly-downloader
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "open-data-philly-downloader"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Download any table from OpenDataPhilly's CartoDB SQL API."
|
|
5
|
+
authors = [{name = "Stephen Suffian", email = "stephen.suffian@pm.me"}]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
license = {text = "MIT"}
|
|
8
|
+
requires-python = ">=3.10.4"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"click>=8.1.7",
|
|
11
|
+
"pandas>=2.1.1",
|
|
12
|
+
"requests>=2.31.0",
|
|
13
|
+
"sqlmodel>=0.0.16",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://github.com/Police-Accountability-Unit-PHL/open-data-philly-downloader"
|
|
18
|
+
Issues = "https://github.com/Police-Accountability-Unit-PHL/open-data-philly-downloader/issues"
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
odp-download = "odp_downloader.cli:cli"
|
|
22
|
+
|
|
23
|
+
[dependency-groups]
|
|
24
|
+
dev = [
|
|
25
|
+
"pytest>=8.0",
|
|
26
|
+
"pytest-mock>=3.12",
|
|
27
|
+
"ruff>=0.4",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/odp_downloader"]
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["hatchling"]
|
|
35
|
+
build-backend = "hatchling.build"
|
|
36
|
+
|
|
37
|
+
[tool.ruff]
|
|
38
|
+
line-length = 100
|
|
39
|
+
target-version = "py310"
|
|
File without changes
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import click
|
|
2
|
+
|
|
3
|
+
from .client import CartoClient
|
|
4
|
+
from .download import download_by_column, download_by_datetime, download_json_per_row
|
|
5
|
+
from .output import SqliteSink
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@click.group()
|
|
9
|
+
def cli():
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@cli.command()
|
|
14
|
+
@click.option("--db-filepath", default="open_data_philly.db", show_default=True)
|
|
15
|
+
@click.option("--table", required=True)
|
|
16
|
+
@click.option("--csv-split-col", required=True)
|
|
17
|
+
@click.option("--where-str", default=None)
|
|
18
|
+
@click.option("--add-lat-lng/--do-not-add-lat-lng", default=True, show_default=True)
|
|
19
|
+
@click.option("--save-to-csv/--skip-save-to-csv", default=True, show_default=True)
|
|
20
|
+
@click.option("--save-to-sqlite/--skip-save-to-sqlite", default=True, show_default=True)
|
|
21
|
+
@click.option("--debug-mode/--do-not-debug", default=False, show_default=True)
|
|
22
|
+
def by_col(
|
|
23
|
+
table: str,
|
|
24
|
+
csv_split_col: str,
|
|
25
|
+
db_filepath: str,
|
|
26
|
+
save_to_csv: bool,
|
|
27
|
+
save_to_sqlite: bool,
|
|
28
|
+
debug_mode: bool,
|
|
29
|
+
add_lat_lng: bool,
|
|
30
|
+
where_str: str | None,
|
|
31
|
+
):
|
|
32
|
+
"""Download all data from a table, with separate CSVs per split-by column."""
|
|
33
|
+
client = CartoClient()
|
|
34
|
+
sink = SqliteSink(db_filepath=db_filepath) if save_to_sqlite else None
|
|
35
|
+
download_by_column(
|
|
36
|
+
client,
|
|
37
|
+
table,
|
|
38
|
+
csv_split_col,
|
|
39
|
+
sink=sink,
|
|
40
|
+
where=where_str,
|
|
41
|
+
add_lat_lng=add_lat_lng,
|
|
42
|
+
save_to_csv=save_to_csv,
|
|
43
|
+
debug=debug_mode,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@cli.command()
|
|
48
|
+
@click.option("--db-filepath", default="open_data_philly.db", show_default=True)
|
|
49
|
+
@click.option("--table", required=True)
|
|
50
|
+
@click.option("--where-str", default=None)
|
|
51
|
+
@click.option("--add-lat-lng/--do-not-add-lat-lng", default=True, show_default=True)
|
|
52
|
+
@click.option("--save-to-csv/--skip-save-to-csv", default=True, show_default=True)
|
|
53
|
+
@click.option("--save-to-sqlite/--skip-save-to-sqlite", default=True, show_default=True)
|
|
54
|
+
@click.option("--debug-mode/--do-not-debug", default=False, show_default=True)
|
|
55
|
+
@click.option(
|
|
56
|
+
"--split-by",
|
|
57
|
+
required=True,
|
|
58
|
+
type=(str, click.Choice(["year"])),
|
|
59
|
+
help="Column and granularity, e.g. 'initialissuedate year'",
|
|
60
|
+
)
|
|
61
|
+
def by_datetime(
|
|
62
|
+
table: str,
|
|
63
|
+
split_by: tuple[str, str],
|
|
64
|
+
db_filepath: str,
|
|
65
|
+
save_to_csv: bool,
|
|
66
|
+
save_to_sqlite: bool,
|
|
67
|
+
debug_mode: bool,
|
|
68
|
+
add_lat_lng: bool,
|
|
69
|
+
where_str: str | None,
|
|
70
|
+
):
|
|
71
|
+
"""Download all data from a table, split by a datetime column and granularity."""
|
|
72
|
+
datetime_col, granularity = split_by
|
|
73
|
+
client = CartoClient()
|
|
74
|
+
sink = SqliteSink(db_filepath=db_filepath) if save_to_sqlite else None
|
|
75
|
+
download_by_datetime(
|
|
76
|
+
client,
|
|
77
|
+
table,
|
|
78
|
+
datetime_col,
|
|
79
|
+
granularity,
|
|
80
|
+
sink=sink,
|
|
81
|
+
where=where_str,
|
|
82
|
+
add_lat_lng=add_lat_lng,
|
|
83
|
+
save_to_csv=save_to_csv,
|
|
84
|
+
debug=debug_mode,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@cli.command()
|
|
89
|
+
@click.option("--table", required=True)
|
|
90
|
+
@click.option("--column", required=True)
|
|
91
|
+
@click.option("--output-dir", default="json", show_default=True)
|
|
92
|
+
def json_file_per_row(table: str, column: str, output_dir: str):
|
|
93
|
+
"""Download up to 10 rows from a table and write one JSON file per row."""
|
|
94
|
+
client = CartoClient()
|
|
95
|
+
download_json_per_row(client, table, column, output_dir=output_dir)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
CARTO_SQL_URL = "https://phl.carto.com/api/v2/sql"
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CartoError(RuntimeError):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CartoClient:
|
|
12
|
+
def __init__(self, base_url: str = CARTO_SQL_URL, timeout: int = 60):
|
|
13
|
+
self.base_url = base_url
|
|
14
|
+
self.timeout = timeout
|
|
15
|
+
|
|
16
|
+
def query(self, sql: str) -> dict[str, Any]:
|
|
17
|
+
response = requests.post(self.base_url, data={"q": sql}, timeout=self.timeout)
|
|
18
|
+
payload = response.json()
|
|
19
|
+
if "rows" not in payload:
|
|
20
|
+
raise CartoError(f"CartoDB error for SQL:\n{sql}\n\n{payload}")
|
|
21
|
+
return payload
|
|
22
|
+
|
|
23
|
+
def probe(self, table: str) -> list[str]:
|
|
24
|
+
return list(self.query(f"SELECT * FROM {table} LIMIT 0")["fields"].keys())
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
from .client import CartoClient
|
|
6
|
+
from .geom import build_select
|
|
7
|
+
from .output import SqliteSink
|
|
8
|
+
from .schemas import get_schema
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _make_csv_dir(table: str) -> None:
|
|
12
|
+
Path(f"csvs/{table}").mkdir(parents=True, exist_ok=True)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def download_by_column(
|
|
16
|
+
client: CartoClient,
|
|
17
|
+
table: str,
|
|
18
|
+
split_col: str,
|
|
19
|
+
*,
|
|
20
|
+
sink: SqliteSink | None = None,
|
|
21
|
+
where: str | None = None,
|
|
22
|
+
add_lat_lng: bool = True,
|
|
23
|
+
save_to_csv: bool = True,
|
|
24
|
+
debug: bool = False,
|
|
25
|
+
) -> None:
|
|
26
|
+
probe = client.query(f"SELECT * FROM {table} LIMIT 0")
|
|
27
|
+
columns = list(probe["fields"].keys())
|
|
28
|
+
if split_col not in columns:
|
|
29
|
+
raise ValueError(f"Column {split_col} not in {table}. Columns: {columns}")
|
|
30
|
+
|
|
31
|
+
select_clause = build_select(columns, add_lat_lng, table)
|
|
32
|
+
schema = get_schema(table)
|
|
33
|
+
|
|
34
|
+
distinct_sql = f"SELECT DISTINCT({split_col}) AS split_field FROM {table} ORDER BY split_field"
|
|
35
|
+
split_values = [row["split_field"] for row in client.query(distinct_sql)["rows"]]
|
|
36
|
+
|
|
37
|
+
where_sql = f"AND {where}" if where else ""
|
|
38
|
+
|
|
39
|
+
if save_to_csv:
|
|
40
|
+
_make_csv_dir(table)
|
|
41
|
+
|
|
42
|
+
for value in split_values:
|
|
43
|
+
if value is None:
|
|
44
|
+
equiv = "IS NULL"
|
|
45
|
+
else:
|
|
46
|
+
equiv = f"= '{value}'"
|
|
47
|
+
|
|
48
|
+
sql = f"SELECT {select_clause} FROM {table} WHERE {split_col} {equiv} {where_sql}"
|
|
49
|
+
rows = client.query(sql)["rows"]
|
|
50
|
+
print(f"Downloaded {table} {split_col}={value} {where_sql} ({len(rows)} rows)")
|
|
51
|
+
|
|
52
|
+
if save_to_csv:
|
|
53
|
+
pd.DataFrame(rows).to_csv(f"csvs/{table}/{table}_{split_col}_{value}.csv", index=False)
|
|
54
|
+
if sink is not None:
|
|
55
|
+
sink.write(rows, table, schema, debug)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def download_by_datetime(
|
|
59
|
+
client: CartoClient,
|
|
60
|
+
table: str,
|
|
61
|
+
datetime_col: str,
|
|
62
|
+
granularity: str,
|
|
63
|
+
*,
|
|
64
|
+
sink: SqliteSink | None = None,
|
|
65
|
+
where: str | None = None,
|
|
66
|
+
add_lat_lng: bool = True,
|
|
67
|
+
save_to_csv: bool = True,
|
|
68
|
+
debug: bool = False,
|
|
69
|
+
) -> None:
|
|
70
|
+
probe = client.query(f"SELECT * FROM {table} LIMIT 0")
|
|
71
|
+
fields = probe["fields"]
|
|
72
|
+
columns = list(fields.keys())
|
|
73
|
+
|
|
74
|
+
date_columns = [k for k, v in fields.items() if v["type"] == "date"]
|
|
75
|
+
if datetime_col not in date_columns:
|
|
76
|
+
raise ValueError(f"Column {datetime_col} not in date columns for {table}. Columns: {columns}")
|
|
77
|
+
|
|
78
|
+
select_clause = build_select(columns, add_lat_lng, table)
|
|
79
|
+
schema = get_schema(table)
|
|
80
|
+
|
|
81
|
+
distinct_sql = f"EXTRACT({granularity} FROM {datetime_col})"
|
|
82
|
+
first_last = client.query(
|
|
83
|
+
f"SELECT min({datetime_col}) AS first_dt, max({datetime_col}) AS last_dt FROM {table} LIMIT 1"
|
|
84
|
+
)["rows"][0]
|
|
85
|
+
count_by = client.query(
|
|
86
|
+
f"SELECT {distinct_sql} AS dt, count(*) AS num_rows FROM {table} "
|
|
87
|
+
f"GROUP BY {distinct_sql} ORDER BY {distinct_sql} ASC"
|
|
88
|
+
)["rows"]
|
|
89
|
+
|
|
90
|
+
summary = {**first_last, "value_counts": {r["dt"]: r["num_rows"] for r in count_by}}
|
|
91
|
+
print(f"Data ranges from {summary['first_dt']} to {summary['last_dt']}")
|
|
92
|
+
|
|
93
|
+
where_sql = f"AND {where}" if where else ""
|
|
94
|
+
|
|
95
|
+
if save_to_csv:
|
|
96
|
+
_make_csv_dir(table)
|
|
97
|
+
json.dump(summary, open(f"csvs/{table}/summary.json", "w"))
|
|
98
|
+
|
|
99
|
+
split_values = [row["dt"] for row in count_by]
|
|
100
|
+
|
|
101
|
+
for value in split_values:
|
|
102
|
+
if value is None:
|
|
103
|
+
filter_sql = f"{distinct_sql} IS NULL"
|
|
104
|
+
else:
|
|
105
|
+
filter_sql = f"{distinct_sql} = '{value}'"
|
|
106
|
+
|
|
107
|
+
sql = f"SELECT {select_clause} FROM {table} WHERE {filter_sql} {where_sql}"
|
|
108
|
+
rows = client.query(sql)["rows"]
|
|
109
|
+
print(f"Downloaded {table} {datetime_col} {granularity}={value} {where_sql} ({len(rows)} rows)")
|
|
110
|
+
|
|
111
|
+
if save_to_csv:
|
|
112
|
+
pd.DataFrame(rows).to_csv(
|
|
113
|
+
f"csvs/{table}/{table}_{datetime_col}_{granularity}_{value}.csv", index=False
|
|
114
|
+
)
|
|
115
|
+
if sink is not None:
|
|
116
|
+
sink.write(rows, table, schema, debug)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def download_json_per_row(
|
|
120
|
+
client: CartoClient,
|
|
121
|
+
table: str,
|
|
122
|
+
column: str,
|
|
123
|
+
*,
|
|
124
|
+
output_dir: str = "json",
|
|
125
|
+
) -> None:
|
|
126
|
+
probe = client.query(f"SELECT * FROM {table} LIMIT 0")
|
|
127
|
+
columns = list(probe["fields"].keys())
|
|
128
|
+
if column not in columns:
|
|
129
|
+
raise ValueError(f"Column {column} not in {table}. Columns: {columns}")
|
|
130
|
+
|
|
131
|
+
rows = client.query(f"SELECT * FROM {table} LIMIT 10")["rows"]
|
|
132
|
+
|
|
133
|
+
out = Path(output_dir) / table
|
|
134
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
135
|
+
|
|
136
|
+
for row in rows:
|
|
137
|
+
key = str(row.get(column, "unknown"))
|
|
138
|
+
with open(out / f"{key}.json", "w") as f:
|
|
139
|
+
json.dump(row, f)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
log = logging.getLogger(__name__)
|
|
4
|
+
|
|
5
|
+
LAT_EXPR = "st_y(the_geom) as lat"
|
|
6
|
+
LNG_EXPR = "st_x(the_geom) as lng"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def build_select(columns: list[str], add_lat_lng: bool, table: str) -> str:
|
|
10
|
+
has_geom = "the_geom" in columns
|
|
11
|
+
exprs = ["*"]
|
|
12
|
+
if add_lat_lng and has_geom:
|
|
13
|
+
exprs += [LAT_EXPR, LNG_EXPR]
|
|
14
|
+
elif add_lat_lng and not has_geom:
|
|
15
|
+
log.info("%s has no the_geom column; skipping lat/lng injection", table)
|
|
16
|
+
return ", ".join(exprs)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
from sqlmodel import Session, SQLModel, create_engine
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class SqliteSink:
|
|
6
|
+
def __init__(self, db_filepath: str):
|
|
7
|
+
self.engine = create_engine(f"sqlite:///{db_filepath}")
|
|
8
|
+
SQLModel.metadata.create_all(self.engine)
|
|
9
|
+
self.session = Session(self.engine)
|
|
10
|
+
|
|
11
|
+
def write(self, rows: list[dict], table: str, schema: type[SQLModel] | None, debug: bool = False) -> None:
|
|
12
|
+
if schema is not None:
|
|
13
|
+
self._write_typed(rows, schema, debug)
|
|
14
|
+
else:
|
|
15
|
+
self._write_untyped(rows, table)
|
|
16
|
+
|
|
17
|
+
def _write_typed(self, rows: list[dict], schema: type[SQLModel], debug: bool) -> None:
|
|
18
|
+
if debug:
|
|
19
|
+
for row in rows:
|
|
20
|
+
try:
|
|
21
|
+
self.session.add(schema.model_validate(row))
|
|
22
|
+
self.session.commit()
|
|
23
|
+
except Exception as exc:
|
|
24
|
+
print(exc)
|
|
25
|
+
breakpoint()
|
|
26
|
+
else:
|
|
27
|
+
self.session.add_all([schema.model_validate(row) for row in rows])
|
|
28
|
+
self.session.commit()
|
|
29
|
+
|
|
30
|
+
def _write_untyped(self, rows: list[dict], table: str) -> None:
|
|
31
|
+
pd.DataFrame(rows).to_sql(table, self.engine, if_exists="append", index=False)
|