visionhack2018's picture
石川県19市町の公共施設CSV調査 v1.0.0を公開
8d3d527 verified
Raw History Blame Contribute Delete
5.17 kB
"""公共施設CSVの座標欄を測定し、初版の集計を照合する。Python 3.10以降、標準ライブラリのみ。"""
import argparse
import codecs
import csv
import hashlib
import io
import json
import re
import sys
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
from urllib.error import URLError
from urllib.request import Request, urlopen
UNKNOWN = "unverified"
DECIMAL_NUMBER = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)")
DEFAULT_MANIFEST = Path(__file__).with_name("data.csv")
def read_source(data):
if data.startswith(codecs.BOM_UTF8):
return data.decode("utf-8-sig"), "UTF-8 BOMあり"
try:
return data.decode("utf-8"), "UTF-8 BOMなし"
except UnicodeDecodeError:
return data.decode("cp932"), "CP932互換"
def in_degree_range(value, limit):
if not DECIMAL_NUMBER.fullmatch(value):
return False
return -limit <= Decimal(value) <= limit
def measure(data, has_header=True):
text, encoding = read_source(data)
records = [row for row in csv.reader(io.StringIO(text, newline=""), strict=True)
if any(cell.strip() for cell in row)]
if not records:
raise ValueError("空のCSVです。")
first = records[0]
rows = records[1:] if has_header else records
if any(len(row) != len(first) for row in rows):
raise ValueError("列数が不揃いです。元ファイルと比較してください。")
metrics = {
"csv_encoding": encoding,
"header_present": "yes" if has_header else "no",
"data_rows": len(rows),
"column_count": len(first),
"coordinate_pairs_present": UNKNOWN,
"coordinate_pair_pct": UNKNOWN,
"decimal_degree_pairs": UNKNOWN,
}
header = [cell.strip() for cell in first]
if not has_header or header.count("緯度") != 1 or header.count("経度") != 1:
return metrics
latitude = header.index("緯度")
longitude = header.index("経度")
present = 0
within_range = 0
for row in rows:
lat, lon = row[latitude].strip(), row[longitude].strip()
if lat and lon:
present += 1
if in_degree_range(lat, 90) and in_degree_range(lon, 180):
within_range += 1
metrics["coordinate_pairs_present"] = present
metrics["decimal_degree_pairs"] = within_range
if rows:
pct = Decimal(present) * 100 / len(rows)
metrics["coordinate_pair_pct"] = format(pct.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP), "f")
return metrics
def verify_snapshot(manifest, source_dir):
failures = 0
checked = 0
with manifest.open(encoding="utf-8-sig", newline="") as stream:
for entry in csv.DictReader(stream):
code = entry["municipality_code"]
try:
if source_dir:
raw = (source_dir / (code + ".csv")).read_bytes()
else:
request = Request(entry["source_url"], headers={"User-Agent": "VISIONHACK-CSV-audit/1.0"})
with urlopen(request, timeout=30) as response:
raw = response.read()
if hashlib.sha256(raw).hexdigest() != entry["source_sha256"]:
raise ValueError("取得内容のSHA-256が初版と異なります。")
measured = measure(raw, entry["header_present"] == "yes")
differences = [key for key, value in measured.items() if str(value) != entry[key]]
if differences:
raise ValueError("集計値が異なります。" + ", ".join(differences))
except (OSError, URLError, csv.Error, ValueError) as error:
print(f"{code} {entry['municipality']} 確認が必要です。{error}", file=sys.stderr)
failures += 1
continue
checked += 1
print(f"一致 {checked}件 / 要確認 {failures}件")
return 0 if checked and not failures else 1
def main():
parser = argparse.ArgumentParser(description=__doc__)
modes = parser.add_mutually_exclusive_group(required=True)
modes.add_argument("--csv", type=Path, help="手元の公共施設CSVを1件測定する。")
modes.add_argument("--download", action="store_true", help="一覧にある出典のCSVを再取得して照合する。")
modes.add_argument("--source-dir", type=Path, help="5桁の市町コード.csvで保存した元ファイルを照合する。")
parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST, help="比較用の集計CSVの場所。")
parser.add_argument("--no-header", action="store_true", help="単独CSVの先頭行をデータとして数える。")
args = parser.parse_args()
if args.no_header and args.csv is None:
parser.error("--no-header は --csv と一緒に使用してください。")
if args.csv is not None:
print(json.dumps(measure(args.csv.read_bytes(), not args.no_header), ensure_ascii=False, indent=2))
return 0
return verify_snapshot(args.manifest, args.source_dir)
if __name__ == "__main__":
raise SystemExit(main())