Fourteen Fenton Bluffs subdivision wells (1988-1992) from the DCP scanned archive plus three 2023 reports from the DCP online dataset, transcribed in evidence/wells/neighbor-wells.json with the page images. tools/dcp_wells.py downloads, splits, OCRs and greps the town-year TIFFs.
137 lines
5.4 KiB
Python
137 lines
5.4 KiB
Python
#!/usr/bin/env -S uv run --no-project --with pillow python3 -I
|
|
"""Search Connecticut DCP scanned well completion reports (1970-2020) for a town.
|
|
|
|
The Department of Consumer Protection keeps the pre-2021 well completion reports as one
|
|
multi-page TIFF per town per year in a public S3 bucket (linked from the DCP Well Drilling page
|
|
as "Statewide Well Drilling Reports, 1970 - Present"). Each report is two pages: the well
|
|
drilling permit (with a lot sketch) followed by the well completion report (casing, yield,
|
|
static level, formation log). Reports are filed by town and year of drilling and usually give
|
|
the subdivision lot number rather than a house number, so grep for road names and lot numbers.
|
|
|
|
Usage:
|
|
tools/dcp_wells.py --town Willington --years 1986-1992 --grep "fenton|potter|balaz" --out wells/
|
|
tools/dcp_wells.py --list-towns
|
|
|
|
Needs `tesseract` on PATH. OCR runs one thread per process (OMP_THREAD_LIMIT=1); running
|
|
tesseract with its default threading on a 16-core box thrashed badly.
|
|
"""
|
|
import argparse, os, re, subprocess, sys, urllib.parse, urllib.request
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from xml.etree import ElementTree as ET
|
|
|
|
from PIL import Image, ImageSequence
|
|
|
|
BUCKET = "http://s3-dcp-01.s3.amazonaws.com"
|
|
NS = "{http://s3.amazonaws.com/doc/2006-03-01/}"
|
|
|
|
|
|
def list_keys(prefix):
|
|
url = f"{BUCKET}/?prefix={urllib.parse.quote(prefix)}"
|
|
with urllib.request.urlopen(url, timeout=60) as r:
|
|
root = ET.fromstring(r.read())
|
|
return [c.find(NS + "Key").text for c in root.iter(NS + "Contents")]
|
|
|
|
|
|
def list_towns():
|
|
url = f"{BUCKET}/?prefix=data/&delimiter=/"
|
|
with urllib.request.urlopen(url, timeout=60) as r:
|
|
root = ET.fromstring(r.read())
|
|
return [p.find(NS + "Prefix").text[5:-1] for p in root.iter(NS + "CommonPrefixes")]
|
|
|
|
|
|
def fetch(key, dest):
|
|
if os.path.exists(dest) and os.path.getsize(dest) > 0:
|
|
return dest
|
|
url = f"{BUCKET}/{urllib.parse.quote(key)}"
|
|
with urllib.request.urlopen(url, timeout=300) as r, open(dest, "wb") as f:
|
|
f.write(r.read())
|
|
return dest
|
|
|
|
|
|
def split_pages(path, outdir, tag):
|
|
os.makedirs(outdir, exist_ok=True)
|
|
pages = []
|
|
with Image.open(path) as im:
|
|
for i, pg in enumerate(ImageSequence.Iterator(im)):
|
|
p = os.path.join(outdir, f"{tag}_{i:03d}.png")
|
|
if not os.path.exists(p):
|
|
pg.convert("L").save(p)
|
|
pages.append(p)
|
|
return pages
|
|
|
|
|
|
def ocr(page, txtdir):
|
|
base = os.path.splitext(os.path.basename(page))[0]
|
|
out = os.path.join(txtdir, base)
|
|
if os.path.exists(out + ".txt"):
|
|
return out + ".txt"
|
|
env = dict(os.environ, OMP_THREAD_LIMIT="1")
|
|
subprocess.run(["tesseract", page, out, "--psm", "6"], env=env,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
|
|
return out + ".txt"
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("--town")
|
|
ap.add_argument("--years", help="e.g. 1988 or 1986-1992")
|
|
ap.add_argument("--grep", help="case-insensitive regex to find in OCR text")
|
|
ap.add_argument("--out", default="dcp-wells")
|
|
ap.add_argument("--jobs", type=int, default=max(2, (os.cpu_count() or 4) - 2))
|
|
ap.add_argument("--view-width", type=int, default=1300, help="width of JPEG copies of matching pages")
|
|
ap.add_argument("--list-towns", action="store_true")
|
|
a = ap.parse_args()
|
|
|
|
if a.list_towns:
|
|
print("\n".join(list_towns()))
|
|
return
|
|
if not (a.town and a.years):
|
|
ap.error("--town and --years are required")
|
|
|
|
y0, _, y1 = a.years.partition("-")
|
|
years = range(int(y0), int(y1 or y0) + 1)
|
|
keys = list_keys(f"data/{a.town}/")
|
|
os.makedirs(a.out, exist_ok=True)
|
|
pages = []
|
|
for y in years:
|
|
cand = [k for k in keys if re.search(rf"/{re.escape(a.town)} {y}/.*\.tiff?$", k, re.I)]
|
|
if not cand:
|
|
print(f"{y}: no TIFF in bucket (keys: {[k for k in keys if str(y) in k]})", file=sys.stderr)
|
|
continue
|
|
tif = fetch(cand[0], os.path.join(a.out, f"{a.town}_{y}.tif"))
|
|
pg = split_pages(tif, os.path.join(a.out, "pages"), str(y))
|
|
print(f"{y}: {len(pg)} pages", file=sys.stderr)
|
|
pages += pg
|
|
|
|
txtdir = os.path.join(a.out, "ocr")
|
|
os.makedirs(txtdir, exist_ok=True)
|
|
with ThreadPoolExecutor(a.jobs) as ex:
|
|
txts = list(ex.map(lambda p: ocr(p, txtdir), pages))
|
|
|
|
if not a.grep:
|
|
return
|
|
rx = re.compile(a.grep, re.I)
|
|
viewdir = os.path.join(a.out, "matches")
|
|
os.makedirs(viewdir, exist_ok=True)
|
|
hits = []
|
|
for page, txt in zip(pages, txts):
|
|
text = open(txt, errors="replace").read()
|
|
if rx.search(text):
|
|
hits.append(page)
|
|
line = next((l.strip() for l in text.splitlines() if rx.search(l)), "")
|
|
print(f"{os.path.basename(page)}: {line[:140]}")
|
|
# Save matching pages plus the page after each (permit sketch is followed by the report).
|
|
want = set()
|
|
for h in hits:
|
|
i = pages.index(h)
|
|
want.update(pages[i:i + 2])
|
|
for p in sorted(want):
|
|
with Image.open(p) as im:
|
|
s = a.view_width / im.width
|
|
im.resize((a.view_width, int(im.height * s)), Image.LANCZOS).save(
|
|
os.path.join(viewdir, os.path.basename(p)[:-4] + ".jpg"), quality=72, optimize=True)
|
|
print(f"{len(hits)} matching pages; {len(want)} page images in {viewdir}", file=sys.stderr)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|