ducats 0.2.0__py3-none-any.whl

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.
ducats/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from .catalog import open_catalog, sync_product, sync_products, sync_status
6
+ from .extract import Extractor, PythonExtractor, RegexExtractor
7
+ from .queries import (
8
+ ContiguityBreak,
9
+ ContiguityReport,
10
+ GridGapReport,
11
+ find_contiguity_gaps,
12
+ find_grid_gaps,
13
+ )
14
+ from .registry import PRODUCTS, ProductConfig, register_product
15
+ from .report import format_contiguity_reports, format_grid_reports
16
+
17
+ __all__ = [
18
+ "open_catalog",
19
+ "sync_product",
20
+ "sync_products",
21
+ "sync_status",
22
+ "Extractor",
23
+ "PythonExtractor",
24
+ "RegexExtractor",
25
+ "ContiguityBreak",
26
+ "ContiguityReport",
27
+ "GridGapReport",
28
+ "find_contiguity_gaps",
29
+ "find_grid_gaps",
30
+ "PRODUCTS",
31
+ "ProductConfig",
32
+ "register_product",
33
+ "format_contiguity_reports",
34
+ "format_grid_reports",
35
+ ]
ducats/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.2.0'
22
+ __version_tuple__ = version_tuple = (0, 2, 0)
23
+
24
+ __commit_id__ = commit_id = None
ducats/catalog.py ADDED
@@ -0,0 +1,54 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from __future__ import annotations
6
+
7
+ from datetime import datetime, timezone
8
+ from typing import Iterable
9
+
10
+ import duckdb
11
+
12
+ from .registry import ProductConfig
13
+
14
+
15
+ def open_catalog(db_path: str | None = None) -> duckdb.DuckDBPyConnection:
16
+ return duckdb.connect(db_path) if db_path else duckdb.connect()
17
+
18
+
19
+ def sync_product(con: duckdb.DuckDBPyConnection, product: ProductConfig) -> int:
20
+ product.extractor.build_relation(con, product.base_dir, product.glob)
21
+ con.execute(f"CREATE OR REPLACE TABLE {product.name} AS SELECT * FROM items")
22
+ count = con.execute(f"SELECT count(*) FROM {product.name}").fetchone()[0]
23
+ _record_sync(con, product.name, count)
24
+ return count
25
+
26
+
27
+ def sync_products(con: duckdb.DuckDBPyConnection, products: Iterable[ProductConfig]) -> dict[str, int]:
28
+ return {p.name: sync_product(con, p) for p in products}
29
+
30
+
31
+ def _record_sync(con: duckdb.DuckDBPyConnection, product_name: str, count: int) -> None:
32
+ con.execute("""
33
+ CREATE TABLE IF NOT EXISTS _ducat_sync_log (
34
+ product VARCHAR PRIMARY KEY,
35
+ synced_at TIMESTAMP,
36
+ row_count BIGINT
37
+ )
38
+ """)
39
+ con.execute(
40
+ """
41
+ INSERT INTO _ducat_sync_log VALUES (?, ?, ?)
42
+ ON CONFLICT (product) DO UPDATE SET synced_at = excluded.synced_at, row_count = excluded.row_count
43
+ """,
44
+ [product_name, datetime.now(timezone.utc).replace(tzinfo=None), count],
45
+ )
46
+
47
+
48
+ def sync_status(con: duckdb.DuckDBPyConnection) -> list[tuple]:
49
+ exists = con.execute(
50
+ "SELECT count(*) FROM information_schema.tables WHERE table_name = '_ducat_sync_log'"
51
+ ).fetchone()[0]
52
+ if not exists:
53
+ return []
54
+ return con.execute("SELECT product, synced_at, row_count FROM _ducat_sync_log ORDER BY product").fetchall()
ducats/cli.py ADDED
@@ -0,0 +1,136 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import importlib
9
+ import re
10
+ from datetime import timedelta
11
+
12
+ from .catalog import open_catalog, sync_product, sync_status
13
+ from .queries import find_contiguity_gaps, find_grid_gaps
14
+ from .registry import PRODUCTS
15
+ from .report import format_contiguity_reports, format_grid_reports
16
+
17
+ _DURATION_RE = re.compile(r"^(\d+)(s|m|h|d)$")
18
+ _DURATION_UNITS = {"s": "seconds", "m": "minutes", "h": "hours", "d": "days"}
19
+
20
+
21
+ def _parse_duration(spec: str) -> timedelta:
22
+ m = _DURATION_RE.match(spec)
23
+ if not m:
24
+ raise argparse.ArgumentTypeError(f"duration must look like 30s/5m/1h/2d, got {spec!r}")
25
+ n, unit = m.groups()
26
+ return timedelta(**{_DURATION_UNITS[unit]: int(n)})
27
+
28
+
29
+ def _import_products_modules(modules: list[str]) -> None:
30
+ for mod in modules:
31
+ importlib.import_module(mod)
32
+
33
+
34
+ def _add_products_module_arg(p: argparse.ArgumentParser) -> None:
35
+ p.add_argument(
36
+ "--products-module",
37
+ action="append",
38
+ default=[],
39
+ metavar="MODULE",
40
+ help="Dotted import path of a module that registers ProductConfig(s) via "
41
+ "register_product(); repeatable. e.g. myproject.products",
42
+ )
43
+
44
+
45
+ def _add_catalog_path_arg(p: argparse.ArgumentParser) -> None:
46
+ p.add_argument("--catalog-path", help="DuckDB file to sync into / query. Omit for an in-memory catalog.")
47
+
48
+
49
+ def _cmd_sync(args: argparse.Namespace) -> None:
50
+ _import_products_modules(args.products_module)
51
+ products = [PRODUCTS[args.product]] if args.product else list(PRODUCTS.values())
52
+ if not products:
53
+ raise SystemExit("no products registered — pass --products-module")
54
+
55
+ con = open_catalog(args.catalog_path)
56
+ for product in products:
57
+ count = sync_product(con, product)
58
+ print(f"{product.name}: {count} rows")
59
+
60
+
61
+ def _cmd_query(args: argparse.Namespace) -> None:
62
+ con = open_catalog(args.catalog_path)
63
+ con.sql(args.sql).show(max_rows=args.max_rows)
64
+
65
+
66
+ def _cmd_status(args: argparse.Namespace) -> None:
67
+ con = open_catalog(args.catalog_path)
68
+ rows = sync_status(con)
69
+ if not rows:
70
+ print("no products have been synced against this catalog")
71
+ return
72
+ for product, synced_at, row_count in rows:
73
+ print(f"{product}: {row_count} rows, last synced {synced_at}")
74
+
75
+
76
+ def _cmd_gaps(args: argparse.Namespace) -> None:
77
+ con = open_catalog(args.catalog_path)
78
+ group_cols = args.group_cols.split(",") if args.group_cols else []
79
+
80
+ if args.mode == "grid":
81
+ if args.bucket is None:
82
+ raise SystemExit("--mode grid requires --bucket")
83
+ reports = find_grid_gaps(con, args.table, group_cols, args.bucket)
84
+ print(format_grid_reports(reports))
85
+ else:
86
+ if args.min_gap is None or args.max_gap is None:
87
+ raise SystemExit("--mode contiguity requires --min-gap and --max-gap")
88
+ reports = find_contiguity_gaps(con, args.table, group_cols, args.min_gap, args.max_gap)
89
+ print(format_contiguity_reports(reports))
90
+
91
+
92
+ def main(argv: list[str] | None = None) -> None:
93
+ parser = argparse.ArgumentParser(
94
+ prog="ducats",
95
+ description="Sync a DuckDB catalog of file coverage from disk, then query it "
96
+ "with plain SQL. Products aren't auto-discovered — pass "
97
+ "--products-module (repeatable) to import module(s) that register "
98
+ "them via register_product(). Temporal questions (what covers this "
99
+ "date, which files fall in any January) are plain SQL against a "
100
+ "synced table — there's no subcommand per question.",
101
+ formatter_class=argparse.RawDescriptionHelpFormatter,
102
+ )
103
+ sub = parser.add_subparsers(dest="command", required=True)
104
+
105
+ p_sync = sub.add_parser("sync", help="Sync a product's (or all registered products') catalog table with disk")
106
+ _add_products_module_arg(p_sync)
107
+ _add_catalog_path_arg(p_sync)
108
+ p_sync.add_argument("--product", help="Sync only this product (default: all registered)")
109
+ p_sync.set_defaults(func=_cmd_sync)
110
+
111
+ p_query = sub.add_parser("query", help="Run arbitrary SQL against a catalog")
112
+ _add_catalog_path_arg(p_query)
113
+ p_query.add_argument("--sql", required=True, help="SQL to run, e.g. \"SELECT file FROM resample WHERE sat='B'\"")
114
+ p_query.add_argument("--max-rows", type=int, default=100, help="Cap rows printed (default 100)")
115
+ p_query.set_defaults(func=_cmd_query)
116
+
117
+ p_status = sub.add_parser("status", help="Show last-synced time + row count per product")
118
+ _add_catalog_path_arg(p_status)
119
+ p_status.set_defaults(func=_cmd_status)
120
+
121
+ p_gaps = sub.add_parser("gaps", help="Run one of the built-in computed queries (grid or contiguity gaps)")
122
+ _add_catalog_path_arg(p_gaps)
123
+ p_gaps.add_argument("--table", required=True, help="Catalog table to check (a synced product name)")
124
+ p_gaps.add_argument("--group-cols", default="", help="Comma-separated columns to check independently, e.g. sat,res")
125
+ p_gaps.add_argument("--mode", choices=["grid", "contiguity"], required=True)
126
+ p_gaps.add_argument("--bucket", type=_parse_duration, help="grid mode: cadence, e.g. 1h")
127
+ p_gaps.add_argument("--min-gap", type=_parse_duration, help="contiguity mode: minimum acceptable delta, e.g. 0s")
128
+ p_gaps.add_argument("--max-gap", type=_parse_duration, help="contiguity mode: maximum acceptable delta, e.g. 1s")
129
+ p_gaps.set_defaults(func=_cmd_gaps)
130
+
131
+ args = parser.parse_args(argv)
132
+ args.func(args)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ main()
ducats/extract.py ADDED
@@ -0,0 +1,103 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from dataclasses import dataclass
9
+ from typing import Callable, Protocol
10
+
11
+ import duckdb
12
+
13
+
14
+ class Extractor(Protocol):
15
+ def build_relation(self, con: duckdb.DuckDBPyConnection, base_dir: str, glob: str) -> None: ...
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class RegexExtractor:
20
+ pattern: str
21
+ ts_format: str = "%Y%m%d%H%M%S"
22
+
23
+ def __post_init__(self) -> None:
24
+ groupindex = re.compile(self.pattern).groupindex
25
+ if "start" not in groupindex:
26
+ raise ValueError("pattern must define a named group (?P<start>...)")
27
+ object.__setattr__(self, "_groupindex", groupindex)
28
+
29
+ def build_relation(self, con: duckdb.DuckDBPyConnection, base_dir: str, glob: str) -> None:
30
+ group_exprs = [
31
+ f"regexp_extract(file, '{self.pattern}', {idx}) AS {name}"
32
+ for name, idx in self._groupindex.items()
33
+ if name not in ("start", "end")
34
+ ]
35
+ start_expr = f"strptime(regexp_extract(file, '{self.pattern}', {self._groupindex['start']}), '{self.ts_format}')"
36
+ end_idx = self._groupindex.get("end")
37
+ end_expr = (
38
+ "CAST(NULL AS TIMESTAMP)"
39
+ if end_idx is None
40
+ else f"strptime(regexp_extract(file, '{self.pattern}', {end_idx}), '{self.ts_format}')"
41
+ )
42
+ select_cols = ", ".join([
43
+ "file",
44
+ *group_exprs,
45
+ f"{start_expr} AS start_ts",
46
+ f"{end_expr} AS end_ts",
47
+ ])
48
+ con.execute(f"""
49
+ CREATE OR REPLACE TEMP TABLE items AS
50
+ SELECT {select_cols}
51
+ FROM glob('{base_dir}/{glob}')
52
+ """)
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class PythonExtractor:
57
+ fn: Callable[[str], dict]
58
+ fields: dict[str, str]
59
+ cache_path: str | None = None
60
+
61
+ def build_relation(self, con: duckdb.DuckDBPyConnection, base_dir: str, glob: str) -> None:
62
+ if self.cache_path is None:
63
+ self._build_uncached(con, base_dir, glob)
64
+ else:
65
+ self._build_cached(con, base_dir, glob)
66
+
67
+ def _build_uncached(self, con: duckdb.DuckDBPyConnection, base_dir: str, glob: str) -> None:
68
+ ret_type = duckdb.struct_type(self.fields)
69
+ con.create_function("extract_meta", self.fn, [str], ret_type, side_effects=True)
70
+ struct_cols = ", ".join(f"(m.meta).{name} AS {name}" for name in self.fields)
71
+ con.execute(f"""
72
+ CREATE OR REPLACE TEMP TABLE items AS
73
+ SELECT file, {struct_cols}
74
+ FROM (
75
+ SELECT file, extract_meta(file) AS meta
76
+ FROM glob('{base_dir}/{glob}')
77
+ ) m
78
+ """)
79
+
80
+ def _build_cached(self, con: duckdb.DuckDBPyConnection, base_dir: str, glob: str) -> None:
81
+ field_ddl = ", ".join(f"{name} {ty}" for name, ty in self.fields.items())
82
+ con.execute(f"ATTACH '{self.cache_path}' AS ducat_cache")
83
+ con.execute(f"CREATE TABLE IF NOT EXISTS ducat_cache.extracted (file VARCHAR PRIMARY KEY, {field_ddl})")
84
+ con.execute(f"CREATE OR REPLACE TEMP TABLE _globbed AS SELECT file FROM glob('{base_dir}/{glob}')")
85
+
86
+ ret_type = duckdb.struct_type(self.fields)
87
+ con.create_function("extract_meta", self.fn, [str], ret_type, side_effects=True)
88
+ struct_cols = ", ".join(f"(m.meta).{name} AS {name}" for name in self.fields)
89
+ con.execute(f"""
90
+ INSERT INTO ducat_cache.extracted
91
+ SELECT file, {struct_cols}
92
+ FROM (
93
+ SELECT file, extract_meta(file) AS meta
94
+ FROM _globbed
95
+ WHERE file NOT IN (SELECT file FROM ducat_cache.extracted)
96
+ ) m
97
+ """)
98
+
99
+ con.execute("""
100
+ CREATE OR REPLACE TEMP TABLE items AS
101
+ SELECT e.* FROM ducat_cache.extracted e
102
+ JOIN _globbed g USING (file)
103
+ """)
ducats/queries.py ADDED
@@ -0,0 +1,162 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ from datetime import datetime, timedelta
9
+ from typing import Literal
10
+
11
+ import duckdb
12
+
13
+
14
+ def _group_by_clause(group_cols: list[str]) -> str:
15
+ return ", ".join(group_cols) if group_cols else "1"
16
+
17
+
18
+ def _distinct_groups(con: duckdb.DuckDBPyConnection, table: str, group_cols: list[str]) -> list[tuple]:
19
+ if not group_cols:
20
+ return [()]
21
+ cols = ", ".join(group_cols)
22
+ return con.execute(f"SELECT DISTINCT {cols} FROM {table} ORDER BY {cols}").fetchall()
23
+
24
+
25
+ def _group_where(group_cols: list[str], values: tuple) -> tuple[str, list]:
26
+ if not group_cols:
27
+ return "", []
28
+ clause = " AND ".join(f"{c} = ?" for c in group_cols)
29
+ return f"WHERE {clause}", list(values)
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class GridGapReport:
34
+ group: tuple
35
+ range_start: datetime
36
+ range_end: datetime
37
+ present: int
38
+ expected: int
39
+ bucket: timedelta
40
+ missing_ranges: list[tuple[datetime, datetime]] = field(default_factory=list)
41
+
42
+ @property
43
+ def missing_count(self) -> int:
44
+ return sum(int((end - start) / self.bucket) + 1 for start, end in self.missing_ranges)
45
+
46
+
47
+ def find_grid_gaps(
48
+ con: duckdb.DuckDBPyConnection,
49
+ table: str,
50
+ group_cols: list[str],
51
+ bucket: timedelta,
52
+ ) -> list[GridGapReport]:
53
+ con.execute(f"""
54
+ CREATE OR REPLACE TEMP TABLE _buckets AS
55
+ SELECT DISTINCT {_group_by_clause(group_cols)},
56
+ time_bucket(INTERVAL '{int(bucket.total_seconds())} seconds', start_ts) AS bucket
57
+ FROM {table}
58
+ """)
59
+
60
+ reports = []
61
+ for values in _distinct_groups(con, table, group_cols):
62
+ where, params = _group_where(group_cols, values)
63
+ lo, hi, present = con.execute(
64
+ f"SELECT min(bucket), max(bucket), count(*) FROM _buckets {where}", params
65
+ ).fetchone()
66
+
67
+ group_filter = (" AND " + " AND ".join(f"b.{c} = ?" for c in group_cols)) if group_cols else ""
68
+ gap_rows = con.execute(
69
+ f"""
70
+ WITH expected AS (
71
+ SELECT unnest(generate_series(?, ?, INTERVAL '{int(bucket.total_seconds())} seconds')) AS bucket
72
+ )
73
+ SELECT e.bucket
74
+ FROM expected e
75
+ LEFT JOIN _buckets b ON b.bucket = e.bucket {group_filter}
76
+ WHERE b.bucket IS NULL
77
+ ORDER BY e.bucket
78
+ """,
79
+ [lo, hi, *values],
80
+ ).fetchall()
81
+ gap_ts = [row[0] for row in gap_rows]
82
+
83
+ expected_n = int((hi - lo) / bucket) + 1
84
+ reports.append(GridGapReport(
85
+ group=values,
86
+ range_start=lo,
87
+ range_end=hi,
88
+ present=present,
89
+ expected=expected_n,
90
+ bucket=bucket,
91
+ missing_ranges=_collapse_ranges(gap_ts, bucket),
92
+ ))
93
+ return reports
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class ContiguityBreak:
98
+ group: tuple
99
+ end_ts: datetime
100
+ next_start_ts: datetime
101
+ delta: timedelta
102
+ kind: Literal["gap", "overlap"]
103
+ file: str
104
+ next_file: str
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class ContiguityReport:
109
+ group: tuple
110
+ item_count: int
111
+ breaks: list[ContiguityBreak]
112
+
113
+
114
+ def find_contiguity_gaps(
115
+ con: duckdb.DuckDBPyConnection,
116
+ table: str,
117
+ group_cols: list[str],
118
+ min_gap: timedelta,
119
+ max_gap: timedelta,
120
+ ) -> list[ContiguityReport]:
121
+ reports = []
122
+ for values in _distinct_groups(con, table, group_cols):
123
+ where, params = _group_where(group_cols, values)
124
+ rows = con.execute(
125
+ f"""
126
+ SELECT end_ts,
127
+ lead(start_ts) OVER (ORDER BY start_ts) AS next_start,
128
+ file, lead(file) OVER (ORDER BY start_ts) AS next_file
129
+ FROM {table}
130
+ {where}
131
+ ORDER BY start_ts
132
+ """,
133
+ params,
134
+ ).fetchall()
135
+
136
+ breaks = []
137
+ for end_ts, next_start, file, next_file in rows:
138
+ if next_start is None or end_ts is None:
139
+ continue
140
+ delta = next_start - end_ts
141
+ if min_gap <= delta <= max_gap:
142
+ continue
143
+ kind = "overlap" if delta < min_gap else "gap"
144
+ breaks.append(ContiguityBreak(values, end_ts, next_start, delta, kind, file, next_file))
145
+
146
+ reports.append(ContiguityReport(group=values, item_count=len(rows), breaks=breaks))
147
+ return reports
148
+
149
+
150
+ def _collapse_ranges(ts_list: list, step: timedelta) -> list[tuple]:
151
+ if not ts_list:
152
+ return []
153
+ ranges = []
154
+ start = prev = ts_list[0]
155
+ for t in ts_list[1:]:
156
+ if t - prev == step:
157
+ prev = t
158
+ continue
159
+ ranges.append((start, prev))
160
+ start = prev = t
161
+ ranges.append((start, prev))
162
+ return ranges
ducats/registry.py ADDED
@@ -0,0 +1,26 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass
8
+
9
+ from .extract import Extractor
10
+
11
+ PRODUCTS: dict[str, "ProductConfig"] = {}
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class ProductConfig:
16
+ name: str
17
+ base_dir: str
18
+ glob: str
19
+ extractor: Extractor
20
+
21
+
22
+ def register_product(config: ProductConfig) -> ProductConfig:
23
+ if config.name in PRODUCTS:
24
+ raise ValueError(f"product {config.name!r} is already registered")
25
+ PRODUCTS[config.name] = config
26
+ return config
ducats/report.py ADDED
@@ -0,0 +1,45 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # SPDX-FileCopyrightText: Copyright (c) 2026 TU Wien
3
+ # SPDX-FileContributor: For a full list of authors, see the AUTHORS file.
4
+
5
+ from __future__ import annotations
6
+
7
+ from .queries import ContiguityReport, GridGapReport
8
+
9
+
10
+ def _label(group: tuple) -> str:
11
+ return " ".join(str(v) for v in group) if group else "(all)"
12
+
13
+
14
+ def format_grid_reports(reports: list[GridGapReport]) -> str:
15
+ lines = []
16
+ total_missing = 0
17
+ for r in reports:
18
+ lines.append(
19
+ f"\n=== {_label(r.group)} === range {r.range_start} .. {r.range_end} "
20
+ f"({r.present}/{r.expected} buckets present, {r.missing_count} missing)"
21
+ )
22
+ for start, end in r.missing_ranges:
23
+ if start == end:
24
+ lines.append(f" MISSING {start}")
25
+ else:
26
+ n = int((end - start) / r.bucket) + 1
27
+ lines.append(f" MISSING {start} .. {end} ({n} buckets)")
28
+ total_missing += r.missing_count
29
+ lines.append(f"\nTotal missing buckets across all groups: {total_missing}")
30
+ return "\n".join(lines)
31
+
32
+
33
+ def format_contiguity_reports(reports: list[ContiguityReport]) -> str:
34
+ lines = []
35
+ total_breaks = 0
36
+ for r in reports:
37
+ lines.append(f"\n=== {_label(r.group)} === {r.item_count} items, {len(r.breaks)} contiguity breaks")
38
+ for b in r.breaks:
39
+ lines.append(
40
+ f" {b.kind.upper()} {b.end_ts} -> {b.next_start_ts} (delta={b.delta}) "
41
+ f"[{b.file}] -> [{b.next_file}]"
42
+ )
43
+ total_breaks += len(r.breaks)
44
+ lines.append(f"\nTotal contiguity breaks across all groups: {total_breaks}")
45
+ return "\n".join(lines)
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.5
2
+ Name: ducats
3
+ Version: 0.2.0
4
+ Summary: Sync a queryable DuckDB catalog of file temporal coverage from a file archive on disk
5
+ Project-URL: Repository, https://github.com/TUW-GEO/ducats
6
+ Author-email: TU Wien <remote.sensing@geo.tuwien.ac.at>
7
+ License-Expression: MIT
8
+ License-File: LICENSE.txt
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering
12
+ Requires-Python: >=3.12
13
+ Requires-Dist: duckdb>=1.1
14
+ Requires-Dist: numpy>=1.26
15
+ Description-Content-Type: text/markdown
16
+
17
+ # ducats
18
+
19
+ Maintains a DuckDB catalog of file coverage — sat/product columns + a
20
+ start/end timestamp per file — kept in sync with what's actually on disk.
21
+ The job it does is **sync**; the job it deliberately does *not* do is
22
+ implement every question you might ask ("which file covers this instant",
23
+ "which METOP-B files fall in any January", "where are the gaps") as a
24
+ bespoke function. Once a product is synced, those are plain SQL against a
25
+ table.
26
+
27
+ ## Why
28
+
29
+ `glob()` lists files vectorized; `regexp_extract` pulls fields out of
30
+ filenames vectorized. For archives with tens of thousands of files, syncing
31
+ is fast and the resulting table is small — cheap enough to keep on disk and
32
+ query directly, from this package, another Python process, a notebook, or
33
+ the plain `duckdb` CLI.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install ducats
39
+ ```
40
+
41
+ (Formerly `ducat`; renamed because that name is taken on PyPI. The import
42
+ package and the CLI are `ducats` too.)
43
+
44
+ ## Quickstart
45
+
46
+ Register a product (see [Plugging in a new product](#plugging-in-a-new-product) below), then:
47
+
48
+ ```bash
49
+ uv run ducats sync --products-module myproject.gap_products --catalog-path /data/catalog.duckdb
50
+ uv run ducats status --catalog-path /data/catalog.duckdb
51
+ ```
52
+
53
+ Then just query:
54
+
55
+ ```bash
56
+ # which file covers this instant?
57
+ uv run ducats query --catalog-path /data/catalog.duckdb --sql \
58
+ "SELECT file FROM my_hourly_files WHERE start_ts <= '2026-03-24 10:00:00' AND end_ts >= '2026-03-24 10:00:00'"
59
+
60
+ # which files fall in any January?
61
+ uv run ducats query --catalog-path /data/catalog.duckdb --sql \
62
+ "SELECT file FROM my_hourly_files WHERE month(start_ts) = 1"
63
+ ```
64
+
65
+ Or skip the CLI and open the file directly — it's a normal DuckDB database:
66
+
67
+ ```bash
68
+ duckdb /data/catalog.duckdb -c "SELECT file FROM my_hourly_files WHERE month(start_ts) = 1"
69
+ ```
70
+
71
+ ## Two things worth a real function
72
+
73
+ Most questions are a one-line `WHERE` clause once a table's synced — not
74
+ worth wrapping. Two aren't, because they involve real computation (a
75
+ generated series anti-joined against what's present, or a window function
76
+ over ordered intervals), so `ducats.queries` provides them:
77
+
78
+ | query | for archives where... | flags... |
79
+ |---|---|---|
80
+ | `find_grid_gaps` | files arrive at a fixed cadence (e.g. one per UTC hour) | buckets with zero files |
81
+ | `find_contiguity_gaps` | files are variable-length intervals that should chain end-to-start (e.g. orbit swaths) | adjacent pairs whose `next.start - this.end` falls outside `[min_gap, max_gap]` |
82
+
83
+ ```bash
84
+ uv run ducats gaps --catalog-path /data/catalog.duckdb --table my_hourly_files \
85
+ --mode grid --bucket 1h
86
+
87
+ uv run ducats gaps --catalog-path /data/catalog.duckdb --table my_hourly_files \
88
+ --mode contiguity --min-gap 0s --max-gap 1h
89
+ ```
90
+
91
+ ## Plugging in a new product
92
+
93
+ A product is a `ProductConfig`: where its files live, an `Extractor` that
94
+ reads group columns + a start/end timestamp out of each file.
95
+
96
+ ```python
97
+ from ducats.extract import RegexExtractor
98
+ from ducats.registry import ProductConfig, register_product
99
+
100
+ register_product(ProductConfig(
101
+ name="my_hourly_files",
102
+ base_dir="/data/my_product",
103
+ glob="**/*.nc",
104
+ extractor=RegexExtractor(
105
+ pattern=r"my_product_(\d{14})_(\d{14})\.nc$",
106
+ group_cols={}, # no natural grouping here
107
+ start_group=1,
108
+ end_group=2,
109
+ ),
110
+ group_cols=[],
111
+ ))
112
+ ```
113
+
114
+ Put that in a module (say `myproject/gap_products.py`) and run:
115
+
116
+ ```bash
117
+ uv run ducats sync --products-module myproject.gap_products --catalog-path /data/catalog.duckdb
118
+ ```
119
+
120
+ Nothing is auto-discovered — a product only exists in a given run if its
121
+ module was explicitly imported via `--products-module`. That keeps "what's
122
+ registered" unambiguous instead of depending on import side effects from
123
+ unrelated code.
124
+
125
+ ### Two ways to extract fields
126
+
127
+ - **`RegexExtractor`** — everything needed (timestamps, grouping keys) is in
128
+ the filename. Stays entirely inside SQL; fast even at tens of thousands of
129
+ files. Use this whenever it applies.
130
+ - **`PythonExtractor`** — the info is inside the file (a NetCDF/HDF5 global
131
+ attribute, a sidecar JSON, ...). Registers a Python scalar UDF with DuckDB
132
+ that opens one file and returns a `STRUCT` of the fields you need; DuckDB
133
+ calls it once per row. Slower (one file open per matched file) but the
134
+ same shape comes out, so nothing downstream cares. See the docstring in
135
+ `ducats/extract.py` for a worked example.
136
+
137
+ Either extractor just needs to leave a temp table named `items` with
138
+ columns `file, <group_cols...>, start_ts, end_ts` — write your own if
139
+ neither fits.
140
+
141
+ `PythonExtractor` accepts `cache_path`: point it at a file and extracted
142
+ rows persist across runs, so repeat runs over a mostly-unchanged archive
143
+ only call `fn` for files not already cached. This is a different thing
144
+ from catalog persistence below — it avoids re-*opening files*, not
145
+ re-running Python. No staleness detection — if `fn`'s output for a path or
146
+ the `fields` schema changes, delete the cache file to force a rebuild.
147
+
148
+ ## Catalog persistence
149
+
150
+ `ducats.catalog` is the sync layer:
151
+
152
+ ```python
153
+ from ducats.catalog import open_catalog, sync_product
154
+ from myproject.gap_products import my_hourly_files # a ProductConfig you registered
155
+
156
+ con = open_catalog("/data/catalog.duckdb") # omit the path for in-memory, throwaway
157
+ sync_product(con, my_hourly_files)
158
+ con.sql("SELECT count(*) FROM my_hourly_files").show()
159
+ ```
160
+
161
+ `sync_product` always leaves the table matching the current glob — files
162
+ that disappeared from disk are dropped from it too. Point `open_catalog` at
163
+ a real path and the sync work only has to happen again for files that
164
+ weren't there last time; anything already in the table stays, and other
165
+ processes/tools can open the same file and query it without touching this
166
+ package at all.
167
+
168
+ ## Using the computed queries as a library
169
+
170
+ ```python
171
+ from datetime import timedelta
172
+ from ducats.queries import find_grid_gaps
173
+ from ducats.report import format_grid_reports
174
+
175
+ reports = find_grid_gaps(con, "resample", group_cols=["sat", "res"], bucket=timedelta(hours=1))
176
+ print(format_grid_reports(reports))
177
+ ```
178
+
179
+ `find_grid_gaps`/`find_contiguity_gaps` return dataclasses
180
+ (`GridGapReport`/`ContiguityReport`), not text — `ducats.report` is a
181
+ separate, optional formatting layer, so you can consume the structured
182
+ results directly (e.g. to page on-call, or feed a dashboard) without
183
+ scraping printed text.
184
+
185
+ ## Examples
186
+
187
+ Product-specific config (filename patterns, group wiring, contiguity
188
+ tolerances) lives in the consuming repo, not ducats. For a real-world
189
+ example, see
190
+ [`ascat_szf.yaml`](https://github.com/TUW-GEO/eumdac-store/blob/main/examples/ascat_szf.yaml)
191
+ in [eumdac-store](https://github.com/TUW-GEO/eumdac-store).
192
+
193
+ ## Development
194
+
195
+ ```bash
196
+ uv sync
197
+ uv run pytest
198
+ ```
@@ -0,0 +1,13 @@
1
+ ducats/__init__.py,sha256=bqBP5H8Xgu-dDvynaNw-WwBrEC16YnWtVSZypQ3a3Co,959
2
+ ducats/_version.py,sha256=s9U3X54Pdr-Jlh9GP6LBaa_VRos7qs_wtrVefUHHNIA,520
3
+ ducats/catalog.py,sha256=HBpkfyU5aYMQI95eRApnba9D5duMomgd8Hk0vTC9xCM,1932
4
+ ducats/cli.py,sha256=kI_33_HK8SLgIYzkPCzrPlClZtLiaK3MNJb6ZjK4zr8,5707
5
+ ducats/extract.py,sha256=V6GlpXH6TtPw2IO6Zt3g-3JO4Knuqc46BYQqxxrIgE4,3971
6
+ ducats/queries.py,sha256=O-wg1hG79H2ynvRZ_9WbH-UeEtdIy5dnnWWNblHPtRE,4875
7
+ ducats/registry.py,sha256=YGNe8WsOX8t-uC6nRHkel3SylbRzd_xPiYCGqKx9jbI,646
8
+ ducats/report.py,sha256=xMMYIQUPLuZAf1utjO4K5QV-WsuMSFHjnMvRbQWtSEI,1689
9
+ ducats-0.2.0.dist-info/METADATA,sha256=clpROJXn3kBBexctCWT1j3kxGR4ACO79TwQjplwnOGs,7323
10
+ ducats-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ ducats-0.2.0.dist-info/entry_points.txt,sha256=EyxG-cp1teZH_Iom0uhQVUYKrFb0fDkwmZ7lwbdHuU4,43
12
+ ducats-0.2.0.dist-info/licenses/LICENSE.txt,sha256=TcbxUEcaXgrW-eWznBQ7tGxLiYRTpwYXMuBV51d1Y5k,1074
13
+ ducats-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ducats = ducats.cli:main
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 TU Wien
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.