File size: 38,286 Bytes
23c46a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc4b924
 
23c46a8
 
 
cd45acb
23c46a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc4b924
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23c46a8
dc4b924
23c46a8
 
 
 
 
 
cd45acb
 
 
23c46a8
 
dc4b924
 
 
 
23c46a8
 
 
 
 
 
 
 
 
 
dc4b924
 
23c46a8
 
 
 
 
dc4b924
 
23c46a8
 
 
 
 
 
 
 
 
 
 
 
 
 
dc4b924
 
 
 
 
 
 
 
 
23c46a8
 
cd45acb
 
 
23c46a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc4b924
 
 
 
 
23c46a8
cd45acb
dc4b924
 
 
 
 
 
 
 
 
 
cd45acb
 
dc4b924
 
 
 
 
 
 
 
 
 
cd45acb
 
 
 
23c46a8
 
 
 
 
 
cd45acb
 
23c46a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc4b924
 
23c46a8
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
#!/usr/bin/env python3
"""Read-only PostgreSQL corpus snapshot and verified monthly media export.

No source mutation, uploads, scheduling, or automatic training. The source DB
transaction closes before slow media copying. Credentials are read at runtime
and never included in output. Use --help and SOURCE_EXPORT.md for operation.
"""
from __future__ import annotations

import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import hashlib
import math
from decimal import Decimal
import json
import os
from pathlib import Path
import re
import shutil
import sys
import time
from uuid import UUID
from urllib.parse import quote, urlsplit
from urllib.request import Request, build_opener, ProxyHandler, HTTPRedirectHandler

VERSION = 'streetshots-source-export-2'
HASH = re.compile(r'[0-9a-f]{64}')
MONTH = re.compile(r'20[0-9]{2}-(0[1-9]|1[0-2])')

DATASET_SQL = """WITH licenses AS MATERIALIZED (
 SELECT dataset_id,revision,manifest->'license' AS license FROM youspeed.crop_dataset_revisions
), memberships AS MATERIALIZED (
 SELECT e.pixel_sha256,jsonb_agg(jsonb_build_object(
  'dataset_id',e.dataset_id,'revision',e.revision,'split',e.split,'member_path',e.member_path,
  'source_label',e.source_label,'original_sha256',e.original_sha256,'provenance',e.provenance,
  'license',r.license) ORDER BY e.dataset_id,e.revision,e.split,e.member_path) AS members
 FROM youspeed.crop_dataset_entries e JOIN licenses r USING(dataset_id,revision) GROUP BY e.pixel_sha256
)
SELECT o.*,NOT EXISTS(SELECT 1 FROM youspeed.crop_dataset_matches m WHERE m.pixel_sha256=o.pixel_sha256) AS active,
 jsonb_build_object('source_memberships',memberships.members) AS metadata
 FROM youspeed.crop_dataset_objects o JOIN memberships USING(pixel_sha256) ORDER BY o.crop_id"""
MOBILE_SQL = '''SELECT m.*,i.active,e.payload->'event' AS observation,
 youspeed.live_crop_exclusion_reason(m.manifest,e.payload->'event') AS live_exclusion,
 (SELECT to_jsonb(r) FROM youspeed.crop_reviews r WHERE r.installation=m.installation
  AND r.epoch=m.epoch AND r.crop_id=m.crop_id ORDER BY r.revision DESC LIMIT 1) AS review
 FROM youspeed.media m JOIN youspeed.crop_corpus_inventory i
 ON i.source='mobile' AND i.crop_id=m.crop_id AND i.installation=m.installation AND i.epoch=m.epoch
 LEFT JOIN youspeed.events e ON e.installation=m.installation AND e.epoch=m.epoch AND e.kind='sighting'
 AND e.event_id::text=m.manifest->>'observation_id'
 ORDER BY m.installation,m.epoch,m.crop_id'''
PANORAMAX_SQL = '''SELECT f.source_id,f.picture_id,f.annotation_id,f.crop_id,f.fingerprint,
 f.metadata AS feature,f.active AS feature_active,f.state,c.digest,c.asset_sha256,c.geometry,
 o.object_key,o.bytes,o.width,o.height,i.active AS item_active,i.visibility,i.geographic_country,
 i.metadata#>>'{picture,ts}' AS capture_at,
 EXISTS(SELECT 1 FROM youspeed.panoramax_suppressions s WHERE s.source_id=f.source_id AND s.picture_id=f.picture_id) AS suppressed,
 COALESCE((SELECT jsonb_agg(l.label ORDER BY l.ordinal) FROM youspeed.panoramax_class_labels l
 WHERE l.crop_id=f.crop_id AND l.fingerprint=f.fingerprint AND l.mapping_sha256=%s),'[]'::jsonb) AS labels,
 (SELECT to_jsonb(r) FROM youspeed.panoramax_crop_reviews r WHERE r.crop_id=f.crop_id
 AND r.fingerprint=f.fingerprint AND r.crop_digest=c.digest ORDER BY r.reviewed_at DESC LIMIT 1) AS review
 FROM youspeed.panoramax_features f JOIN youspeed.panoramax_items i USING(source_id,picture_id)
 LEFT JOIN youspeed.panoramax_crops c ON c.crop_id=f.crop_id AND c.render_key=f.current_render
 LEFT JOIN youspeed.panoramax_crop_objects o ON o.digest=c.digest ORDER BY f.crop_id'''
FRAME_SQL = '''SELECT i.source_id,i.picture_id,i.fingerprint,i.active,i.visibility,i.geographic_country,i.metadata,
 EXISTS(SELECT 1 FROM youspeed.panoramax_suppressions s WHERE s.source_id=i.source_id AND s.picture_id=i.picture_id) AS suppressed
 FROM youspeed.panoramax_items i ORDER BY i.source_id,i.picture_id'''


def canonical(value):
    return (json.dumps(value,ensure_ascii=False,sort_keys=True,separators=(',', ':'),default=str,allow_nan=False)+'\n').encode()


# Copied semantic-json-v1 implementation from the existing source contract.
def source_canonical(value) -> bytes:
    """YouSpeed semantic-json-v1 (provisional; pinned vectors are normative).

    UTF-8, sorted Unicode keys, no whitespace, finite binary64 input numbers
    serialized from shortest decimal repr with integral and negative-zero
    normalization. Expand exponents in [1e-6,1e21); normalize others.
    Does not advertise RFC8785 compatibility. Clients must run golden vectors.
    """

    def encode(item):
        if item is None or isinstance(item, (str, bool)):
            return json.dumps(item, ensure_ascii=False, separators=(",", ":"))
        if isinstance(item, (int, float)):
            if isinstance(item, int) and abs(item) > 9007199254740991:
                raise ValueError("unsafe_integer")
            if not math.isfinite(item):
                raise ValueError("nonfinite")
            if item == 0:
                return "0"
            number = Decimal(str(item)).normalize()
            if Decimal("1e-6") <= abs(number) < Decimal("1e21"):
                return format(number, "f")
            mantissa, exponent = format(number, "e").split("e")
            return (
                mantissa
                + "e"
                + ("+" if int(exponent) >= 0 else "-")
                + str(abs(int(exponent)))
            )
        if isinstance(item, list):
            return "[" + ",".join(encode(x) for x in item) + "]"
        if isinstance(item, dict) and all(isinstance(k, str) for k in item):
            return (
                "{"
                + ",".join(encode(k) + ":" + encode(item[k]) for k in sorted(item))
                + "}"
            )
        raise ValueError("invalid_json")

    return encode(value).encode("utf-8")


def source_digest(value):
    return hashlib.sha256(source_canonical(value)).hexdigest()


def sha_file(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as f:
        for block in iter(lambda:f.read(1024*1024),b''): h.update(block)
    return h.hexdigest()


def write_json(path,value):
    path=Path(path); path.parent.mkdir(parents=True,exist_ok=True)
    path.write_bytes(canonical(value))


def safe_part(value):
    """Reversible path encoding. Exact labels stay in metadata."""
    if value is None or value=='': return '_unknown'
    value=str(value)
    encoded=quote(value,safe='-_')
    if encoded in ('.','..'): encoded=encoded.replace('.', '%2E')
    return encoded


def rooted(root,relative):
    path=(Path(root)/relative).resolve()
    if not path.is_relative_to(Path(root).resolve()): raise ValueError('unsafe_path')
    return path


def unique_label(labels):
    identities=set()
    unresolved=False
    for label in labels:
        parsed=label.get('parsed') or {}
        if parsed.get('code')=='yes': continue
        country=label.get('target_classifier_country') or parsed.get('namespace_country')
        selected=label.get('selected_yolo') or {}
        if label.get('yolo_mapping_status')=='unique' and selected.get('label'):
            identities.add((country,selected['label']))
        elif label.get('semantic_mapping_status')=='unique':
            candidates={x.get('label') for x in label.get('semantic_candidates',[]) if x.get('label')}
            if len(candidates)==1: identities.add((country,next(iter(candidates))))
            else: unresolved=True
        elif parsed.get('national_code') and country and not str(label.get('country_resolution_state','')).startswith('country_'):
            # Preserve exact source identities even when the deployed model has no output.
            identities.add((country,parsed['national_code']))
        else: unresolved=True
    if len(identities)==1 and not unresolved: return next(iter(identities))
    return None,None


def base_row(sample,task,source,observed):
    return dict(schema_version=1,sample_id=sample,task=task,source=source,observed_at=observed,
                group_status='provisional',status='active',eligible=False)


def classifier_path(month,country,label,sample,encoding='PNG'):
    extension='jpg' if str(encoding).upper() in ('JPEG','JPG') else 'png'
    return f'data/{month}/classificator/{safe_part(country)}/{safe_part(label or "_unresolved")}/{safe_part(sample)}.{extension}'


def normalize_dataset(row,month,observed):
    memberships=row['metadata'].get('source_memberships') or []
    labels={x.get('source_label') for x in memberships}
    label=next(iter(labels)) if len(labels)==1 else None
    sample='dataset-'+str(row['crop_id'])
    result=base_row(sample,'classificator','dataset',observed)
    result.update(country='DE',label=label,label_origin='source_dataset',sha256=row['digest'],
        pixel_sha256=row['pixel_sha256'],group_id='pixels:'+row['pixel_sha256'],
        path=classifier_path(month,'DE',label,sample),source_revision=hashlib.sha256(canonical(memberships)).hexdigest(),
        eligible=bool(row['active'] and label),status='active' if row['active'] else 'withdrawn',
        source_memberships=memberships,dimensions=[row['width'],row['height']])
    return dict(row=result,media=dict(kind='dataset',object_key=row['object_key'],bytes=row['bytes']))


def normalize_mobile(row,month,observed):
    m=row['manifest']; event=row.get('observation') or {}; classification=event.get('classification') or {}
    country=classification.get('country') or (m.get('classification') or {}).get('country')
    label=classification.get('model_label'); origin='model'; review=row.get('review') or {}
    # Apply only reviews bound to these exact source bytes and observation/manifest.
    review_valid=bool(review and review.get('crop_digest')==row['digest']
        and review.get('observation_sha256')==source_digest(event)
        and review.get('manifest_sha256')==source_digest(m))
    if review_valid:
        verdict=review.get('verdict')
        if verdict=='wrong_class':
            replacement=review.get('corrected_classification') or {}
            country=replacement.get('country') or country
            label=replacement.get('model_label') or replacement.get('class_id') or replacement.get('canonical_code'); origin='manual'
        elif verdict=='confirmed': origin='manual'
        elif verdict=='not_a_sign': label='bad'; origin='manual'
        elif verdict=='uncertain': label=None; origin='unknown'
    sample=f'mobile-{row["installation"]}-{row["epoch"]}-{row["crop_id"]}'
    result=base_row(sample,'classificator','mobile',observed)
    result.update(country=country,label=label,label_origin=origin,sha256=row['digest'],
        path=classifier_path(month,country,label,sample,m.get('encoding')),
        group_id='mobile-session:'+str(event.get('collection_session_id') or f'{row["installation"]}:{row["epoch"]}'),
        sighting_id=m.get('observation_id'),source_revision=hashlib.sha256(canonical(dict(manifest=m,event=event,review=review))).hexdigest(),
        eligible=bool(row['active'] and label and country),status='active' if row['active'] else 'withdrawn',
        dimensions=[m.get('decoded_width'),m.get('decoded_height')],capture_at=m.get('source_frame_at'),
        installation=str(row['installation']),epoch=row['epoch'],
        expires_at=row.get('expires'),live_exclusion=row.get('live_exclusion'),manifest=m,observation=event,
        review=review or None,review_binding_valid=review_valid)
    return dict(row=result,media=dict(kind='mobile',object_key=row['object_path'],bytes=m.get('byte_length'),
        installation=str(row['installation']),epoch=row['epoch'],crop_id=str(row['crop_id'])))


def normalize_panoramax(row,month,observed):
    country,label=unique_label(row.get('labels') or [])
    tags=(row.get('feature') or {}).get('semantics') or []
    origin='model' if any(str(x.get('key','')).startswith('classification_model') for x in tags) else 'source_annotation'
    review=row.get('review') or {}
    if review:
        verdict=review.get('verdict')
        if verdict=='confirmed': origin='manual'
        elif verdict=='not_a_sign': label='bad'; origin='manual'
        elif verdict in ('uncertain','unreviewed'): label=None; origin='unknown'
        elif verdict=='wrong_class':
            derived=review.get('derived') or {}
            replacement=derived.get('corrected_classification') or derived.get('classification') or derived
            country=replacement.get('country') or country
            label=replacement.get('model_label') or replacement.get('class_id') or replacement.get('canonical_code')
            origin='manual'
    admitted=bool(row['feature_active'] and row['item_active'] and not row['suppressed'])
    sample='panoramax-'+str(row['crop_id'])
    result=base_row(sample,'classificator','panoramax',observed)
    result.update(country=country or row.get('geographic_country'),label=label,label_origin=origin,
        sha256=row.get('digest'),path=classifier_path(month,country or row.get('geographic_country'),label,sample),
        group_id='panoramax-picture:'+str(row['picture_id']),parent_sample_id='panoramax-frame-'+str(row['picture_id']),parent_image_id='panoramax-frame-'+str(row['picture_id']),
        source_id=row['source_id'],picture_id=str(row['picture_id']),annotation_id=row['annotation_id'],
        source_revision=row['fingerprint'],capture_at=row['capture_at'],visibility=row['visibility'],
        eligible=bool(admitted and row['state']=='ready' and label and (not review or review.get('downstream_eligible'))),status='active' if admitted else 'withdrawn',
        dimensions=[row.get('width'),row.get('height')],source_state=row['state'],geometry=row.get('geometry'),
        feature=row.get('feature'),source_labels=row.get('labels'),review=row.get('review'),
        label_review_status='verified_review' if origin=='manual' else 'unverified_source_authorship' if origin=='source_annotation' else 'prediction',
        source_asset_sha256=row.get('asset_sha256'))
    return dict(row=result,media=dict(kind='panoramax',object_key=row.get('object_key'),bytes=row.get('bytes'),crop_id=str(row['crop_id'])))


def detector_annotations(item):
    boxes=[]
    metadata=(item.get('picture') or {}).get('metadata') or {}
    width,height=metadata.get('width'),metadata.get('height')
    panorama=metadata.get('type')=='equirectangular'
    for annotation in item.get('annotations',[]):
        tags=annotation.get('semantics') or []
        classes=set()
        for tag in tags:
            key,value=tag.get('key'),tag.get('value')
            if key=='osm|traffic_sign': classes.add('sign')
            elif key=='blur|type' and value in ('face','plate','license_plate'):
                classes.add('plate' if value=='license_plate' else value)
        shape=annotation.get('shape') or {}
        if shape.get('type')!='Polygon' or shape.get('wrap') or len(classes)!=1: continue
        if not isinstance(width,(int,float)) or not isinstance(height,(int,float)) or width<=0 or height<=0: continue
        try:
            if len(shape['coordinates'])!=1: continue
            points=shape['coordinates'][0]
            if len(points)<4 or points[0]!=points[-1] or any(len(p)!=2 for p in points): continue
            xs=[float(p[0]) for p in points]; ys=[float(p[1]) for p in points]
            box=[min(xs),min(ys),max(xs),max(ys)]
            if not all(math.isfinite(x) for x in box) or box[0]>=box[2] or box[1]>=box[3]: continue
            if box[0]<0 or box[1]<0 or box[2]>width or box[3]>height or (panorama and box[2]-box[0]>width/2): continue
        except (KeyError,TypeError,ValueError,IndexError): continue
        category=next(iter(classes))
        boxes.append(dict(annotation_id=annotation.get('id'),class_id={'sign':0,'plate':1,'face':2}[category],
            label=category,box_xyxy=box,geometry_status='valid_nonwrapping_polygon',shape=shape,semantics=tags,
            label_origin='model' if any(str(t.get('key','')).startswith('detection_model') for t in tags) else 'source_annotation'))
    return boxes


def normalize_frame(row,month,observed):
    item=row['metadata']; asset=item.get('asset') or {}; picture=item.get('picture') or {}; meta=picture.get('metadata') or {}
    sample='panoramax-frame-'+str(row['picture_id'])
    # Hash bucket prevents >10k files in a single detector directory.
    bucket=hashlib.sha256(sample.encode()).hexdigest()[:2]
    path=f'data/{month}/detector/{bucket}/{sample}.jpg'
    active=bool(row['active'] and not row['suppressed'])
    result=base_row(sample,'detector','panoramax',observed)
    result.update(path=path,sha256=asset.get('sha256'),annotation_path=path[:-4]+'.json',
        group_id='panoramax-picture:'+str(row['picture_id']),parent_image_id=sample,source_id=row['source_id'],picture_id=str(row['picture_id']),
        source_revision=row['fingerprint'],capture_at=picture.get('ts'),visibility=row['visibility'],
        dimensions=[meta.get('width'),meta.get('height')],status='active' if active else 'withdrawn',
        eligible=False,label_origin='source_annotation',exclusion_reason='annotation_completeness_unverified')
    annotation=dict(schema_version=1,sample_id=sample,image_sha256=asset.get('sha256'),
        dimensions=result['dimensions'],coordinates='registered-raster-pixel-xyxy',
        classes={'0':'sign','1':'plate','2':'face'},annotations=detector_annotations(item),
        annotation_complete={'sign':False,'plate':False,'face':False},
        annotation_completeness_reason='source annotations are not exhaustive reviewed ground truth',
        geometry_conversion='Only bounded nonwrapping single-ring closed polygons are normalized; all other raw annotations remain in source_metadata.',
        source_metadata=item)
    return dict(row=result,media=dict(kind='frame',object_key=asset.get('relative_path'),rendition=asset.get('rendition'),
        public_url=(item.get('runtime_configuration') or {}).get('media_url','').rstrip('/')+'/'+str(asset.get('relative_path','')),
        visibility=row['visibility']),annotation=annotation)


def snapshot(args):
    if not MONTH.fullmatch(args.month): raise ValueError('invalid_month')
    import psycopg
    from psycopg.rows import dict_row
    dsn=sys.stdin.read().strip() if args.database_stdin else ''
    if args.database_file:
        if args.database_file.stat().st_mode & 0o077: raise ValueError('dsn_must_be_private')
        dsn=args.database_file.read_text().strip()
    mapping=json.loads(args.mapping_file.read_text())
    mapping_sha=mapping['sha256']
    if not HASH.fullmatch(mapping_sha): raise ValueError('mapping_digest_invalid')
    mapping_content={k:v for k,v in mapping.items() if k!='sha256'}
    if hashlib.sha256(json.dumps(mapping_content,sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest()!=mapping_sha:
        raise ValueError('mapping_content_digest_mismatch')
    folder=args.output_root/f'data/{args.month}'
    if (folder/'source-plan.jsonl').exists(): raise ValueError('snapshot_already_exists_use_materialize')
    folder.mkdir(parents=True,exist_ok=True)
    options=dict(user='youspeed_report',dbname='youspeed',row_factory=dict_row,connect_timeout=20,
                 keepalives=1,keepalives_idle=15,keepalives_interval=10,keepalives_count=3,tcp_user_timeout=60000,
                 options='-c default_transaction_read_only=on -c statement_timeout=120000')
    if args.db_host: options['host']=args.db_host
    if args.db_port: options['port']=args.db_port
    counts=Counter(); records=[]
    with psycopg.connect(dsn,**options) as db:
        db.execute('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY')
        identity=db.execute("SELECT current_database() AS database,current_user AS role,transaction_timestamp() AS cutoff,current_setting('transaction_read_only') AS read_only,current_setting('transaction_isolation') AS isolation").fetchone()
        if identity['role']!='youspeed_report' or identity['read_only']!='on' or identity['isolation']!='repeatable read':
            raise ValueError('unexpected_source_identity')
        observed=str(identity['cutoff'])
        for name,sql,params,normalizer in [('dataset',DATASET_SQL,(),normalize_dataset),('mobile',MOBILE_SQL,(),normalize_mobile),
                ('panoramax',PANORAMAX_SQL,(mapping_sha,),normalize_panoramax),('frame',FRAME_SQL,(),normalize_frame)]:
            with db.cursor(name='streetshots_'+name) as cursor:
                cursor.itersize=1000
                cursor.execute(sql,params)
                for row in cursor:
                    record=normalizer(row,args.month,observed)
                    records.append(record); counts[name]+=1
            print(json.dumps(dict(source=name,records=counts[name])),flush=True)
        controls=dict(observed_at=observed,tombstones=db.execute('SELECT installation,deleted_through FROM youspeed.tombstones').fetchall(),
            authorizations=db.execute("SELECT installation,epoch,scope,state FROM youspeed.authorizations WHERE scope IN ('sign_metadata','crop_storage')").fetchall())
    # No live DB transaction is held during filesystem/network copying.
    with (folder/'source-plan.jsonl').open('wb') as stream:
        for record in records: stream.write(canonical(record))
    write_json(folder/'source-controls.json',controls)
    shutil.copyfile(__file__,folder/'source-exporter.py')
    write_json(folder/'source-snapshot.json',dict(exporter=VERSION,exporter_source_sha256=sha_file(__file__),
        exporter_source=dict(path=f'data/{args.month}/source-exporter.py',sha256=sha_file(__file__)),
        python_version=sys.version,psycopg_version=psycopg.__version__,identity=identity,source_counts=dict(counts),
        controls=dict(path=f'data/{args.month}/source-controls.json',sha256=sha_file(folder/'source-controls.json')),
        mapping_sha256=mapping_sha,source_plan_sha256=sha_file(folder/'source-plan.jsonl')))
    write_json(folder/'manifest.json',dict(schema_version=1,month=args.month,exporter=VERSION,status='partial',
        stage='metadata_frozen',source_counts=dict(counts),cutoff=observed,
        source_plan_sha256=sha_file(folder/'source-plan.jsonl'),expected_records=len(records),verified_records=0))
    print(json.dumps(dict(stage='metadata_frozen',source_counts=dict(counts),records=len(records))))


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self,*args): return None


def fetch_url(url,max_bytes):
    # Credentials never come from metadata URLs; authenticated private storage should be mounted.
    p=urlsplit(url)
    if p.username or p.password or p.query or p.fragment: raise ValueError('unsafe_source_url')
    if p.scheme!='https' and not (p.scheme=='http' and p.hostname in ('127.0.0.1','localhost')): raise ValueError('unsafe_source_url')
    opener=build_opener(ProxyHandler({}),NoRedirect())
    with opener.open(Request(url,headers={'Accept':'image/png,image/jpeg'}),timeout=60) as response:
        data=response.read(max_bytes+1)
    if len(data)>max_bytes: raise ValueError('source_too_large')
    return data


def reconstruct_panoramax(record,args):
    """Render with the existing backend code, bound to verified frozen pixels."""
    from PIL import Image
    from panoramax_geometry import render
    row=record['row']
    if row.get('visibility')!='anyone' and not args.frame_root: raise ValueError('owner_only_source_access_required')
    frame=getattr(args,'frame_index',{}).get((row['source_id'],row['picture_id']))
    if not frame: raise ValueError('parent_frame_absent_from_snapshot')
    if frame['row']['status']=='withdrawn': raise ValueError('parent_frame_withdrawn')
    parent=rooted(args.output_root,frame['row']['path'])
    if not parent.exists(): raise ValueError('verified_parent_frame_unavailable')
    if sha_file(parent)!=row['source_asset_sha256'] or frame['row']['sha256']!=row['source_asset_sha256']:
        raise ValueError('parent_asset_hash_mismatch')
    metadata=frame['annotation']['source_metadata']['picture']['metadata']
    with Image.open(parent) as image:
        data,geometry=render(image,row['feature']['shape'],metadata)
    # Geometry is verified independently from the strict output byte hash below.
    old=row.get('geometry') or {}
    for key,value in geometry.items():
        if key in old and old[key]!=value: raise ValueError('reconstructed_geometry_mismatch')
    return data


def hd_relative(picture_id):
    # Exact existing source adapter function (panoramax_source.hd_relative).
    value = str(UUID(str(picture_id)))
    return Path(value[:2], value[2:4], value[4:6], value[6:8], value[9:] + ".jpg")


def bind_unhashed_frame(row,media,args):
    """Persist first filesystem observation, never revise it during a retry."""
    from PIL import Image
    from io import BytesIO
    sample=row['sample_id']; bucket=hashlib.sha256(sample.encode()).hexdigest()[:2]
    relative=f'data/{args.month}/source-bindings/{bucket}/{safe_part(sample)}.json'
    path=rooted(args.output_root,relative)
    if path.exists():
        binding=json.loads(path.read_text())
        if binding['sample_id']!=sample or binding['picture_id']!=row['picture_id']: raise ValueError('source_binding_identity_mismatch')
    else:
        if not args.frame_root: raise ValueError('unhashed_frame_requires_mounted_source')
        source_relative=str(hd_relative(row['picture_id']))
        source=rooted(args.frame_root,source_relative)
        if source.stat().st_size>args.max_image_bytes: raise ValueError('source_too_large')
        data=source.read_bytes()
        with Image.open(BytesIO(data)) as image:
            dimensions=list(image.size);image.verify()
        binding=dict(schema_version=1,sample_id=sample,picture_id=row['picture_id'],source_id=row['source_id'],
            sha256=hashlib.sha256(data).hexdigest(),bytes=len(data),dimensions=dimensions,object_key=source_relative,
            method='first_observed_registered_hd_filesystem',previous_asset_sha256=None,
            observed_at=datetime.now(timezone.utc).isoformat(),metadata_cutoff=row.get('observed_at'))
        path.parent.mkdir(parents=True,exist_ok=True)
        # An interrupted write fails closed; an existing binding is never overwritten.
        with path.open('xb') as out: out.write(canonical(binding));out.flush();os.fsync(out.fileno())
        fd=os.open(path.parent,os.O_RDONLY)
        try: os.fsync(fd)
        finally: os.close(fd)
    row.update(sha256=binding['sha256'],source_expected_sha256=None,
        source_declared_dimensions=row.get('dimensions'),dimensions=binding['dimensions'],
        source_binding=dict(path=relative,sha256=sha_file(path)),source_bytes_observed_at=binding['observed_at'])
    media['object_key']=binding['object_key']


def materialize_one(record,args):
    row=dict(record['row']); media=dict(record['media']); path=rooted(args.output_root,row['path'])
    if row['status']=='withdrawn': return row,None
    if media['kind']=='panoramax' and row.get('source_state') not in (None,'ready'):
        row.update(status='pending',eligible=False,media_required=False,media_verified=False,
                   exclusion_reason='source_crop_not_ready:'+row['source_state'])
        return row,None
    row['media_required']=True
    if media['kind']=='panoramax':
        from panoramax_classifier_crop import context_path
        path=rooted(args.output_root,context_path(row['path']))
    expected=row.get('sha256')
    try:
        if not isinstance(expected,str) or not HASH.fullmatch(expected):
            if media['kind']=='frame' and getattr(args,'bind_unhashed_frames',False):
                bind_unhashed_frame(row,media,args);expected=row['sha256']
            else: raise ValueError('source_digest_missing')
        if not path.exists() or sha_file(path)!=expected:
            kind=media['kind']; source_root=getattr(args,kind+'_root')
            if source_root and media.get('object_key'):
                source=rooted(source_root,media['object_key'])
                if source.stat().st_size>args.max_image_bytes: raise ValueError('source_too_large')
                data=source.read_bytes()
            elif kind=='mobile' and args.mobile_proxy:
                data=fetch_url(args.mobile_proxy.rstrip('/')+f'/inspector/api/crops/{media["installation"]}/{media["epoch"]}/{media["crop_id"]}/image',args.max_image_bytes)
            elif kind=='panoramax' and args.panoramax_proxy:
                data=fetch_url(args.panoramax_proxy.rstrip('/')+f'/inspector/api/panoramax/crops/{media["crop_id"]}/image',args.max_image_bytes)
            elif kind=='panoramax' and getattr(args,'reconstruct_panoramax',False):
                data=reconstruct_panoramax(record,args)
            elif kind=='frame' and args.public_frames and media['visibility']=='anyone':
                url=urlsplit(media['public_url'])
                if url.hostname!=row.get('source_id') or not url.path.startswith('/permanent/'):
                    raise ValueError('frame_origin_binding_mismatch')
                data=fetch_url(media['public_url'],args.max_image_bytes)
            elif kind=='frame' and media.get('visibility')!='anyone':
                raise ValueError('owner_only_source_access_required')
            else: raise ValueError('source_media_access_not_configured')
            if hashlib.sha256(data).hexdigest()!=expected: raise ValueError('source_hash_mismatch')
            if not (data.startswith(b'\x89PNG\r\n\x1a\n') or data.startswith(b'\xff\xd8\xff')): raise ValueError('not_image_bytes')
            from PIL import Image
            from io import BytesIO
            with Image.open(BytesIO(data)) as image:
                if row.get('dimensions') and all(row['dimensions']) and list(image.size)!=row['dimensions']:
                    raise ValueError('image_dimensions_mismatch')
                image.verify()
            path.parent.mkdir(parents=True,exist_ok=True)
            temporary=path.with_suffix(path.suffix+'.part')
            temporary.write_bytes(data); os.replace(temporary,path)
        if 'annotation' in record:
            annotation_path=rooted(args.output_root,row['annotation_path'])
            annotation=dict(record['annotation'])
            annotation.update(image_sha256=row['sha256'],dimensions=row['dimensions'])
            if row.get('source_binding'):
                annotation['source_binding']=row['source_binding']
                # Bounds must use the registered image raster, never EXIF dimensions.
                normalized=json.loads(json.dumps(annotation['source_metadata']))
                normalized.setdefault('picture',{}).setdefault('metadata',{}).update(width=row['dimensions'][0],height=row['dimensions'][1])
                annotation['annotations']=detector_annotations(normalized)
            write_json(annotation_path,annotation)
            row['annotation_sha256']=sha_file(annotation_path)
        row['bytes']=path.stat().st_size
        if media['kind']=='panoramax':
            from panoramax_classifier_crop import tighten
            row=tighten(row,args.output_root)
        row['media_verified']=True
        return row,None
    except Exception as error:
        # No exception bodies: external libraries can echo credentials/request bodies.
        row.update(status='pending',eligible=False,media_verified=False)
        reason=str(error) if type(error) is ValueError else type(error).__name__
        return row,dict(sample_id=row['sample_id'],error=reason)


def materialize(args):
    folder=args.output_root/f'data/{args.month}'
    source=json.loads((folder/'source-snapshot.json').read_text())
    if sha_file(folder/'source-plan.jsonl')!=source['source_plan_sha256']: raise ValueError('source_plan_changed')
    controls=source.get('controls')
    if controls and sha_file(rooted(args.output_root,controls['path']))!=controls['sha256']: raise ValueError('source_controls_changed')
    with (folder/'source-plan.jsonl').open() as stream:
        records=[json.loads(line) for line in stream]
    frames=[r for r in records if r['media']['kind']=='frame']
    others=[r for r in records if r['media']['kind']!='frame']
    args.frame_index={(r['row']['source_id'],r['row']['picture_id']):r for r in frames}
    errors=[]; counts=Counter(); verified=0; total_bytes=0; metadata_only=0
    processed=0; started=time.time(); last_progress=0; context_count=0; context_bytes=0
    with (folder/'metadata.jsonl.part').open('wb') as out,(folder/'errors.jsonl.part').open('wb') as errout:
        # A complete frame phase is a barrier: crop workers never race a parent
        # still being downloaded. The same frozen plan supplies both phases.
        for phase,batch in (('frames',frames),('crops',others)):
            with ThreadPoolExecutor(max_workers=args.workers) as pool:
                for row,error in pool.map(lambda r:materialize_one(r,args),batch):
                    if phase=='frames' and row.get('media_verified'):
                        args.frame_index[(row['source_id'],row['picture_id'])]['row']=row
                    out.write(canonical(row)); counts[row['status']]+=1; processed+=1
                    if row.get('media_verified'): verified+=1; total_bytes+=row['bytes']
                    if row.get('source_context'):
                        context_count+=1; context_bytes+=row['source_context']['bytes']
                    if row.get('media_required') is False: metadata_only+=1
                    if error: errors.append(error); errout.write(canonical(error)); errout.flush()
                    if time.time()-last_progress>=30 or processed==len(records):
                        progress=dict(stage='materializing',phase=phase,processed=processed,total=len(records),
                            verified=verified,errors=len(errors),bytes=total_bytes,elapsed_seconds=round(time.time()-started),
                            updated_at=datetime.now(timezone.utc).isoformat())
                        write_json(folder/'progress.json.part',progress); os.replace(folder/'progress.json.part',folder/'progress.json')
                        print(json.dumps(progress,sort_keys=True),flush=True); last_progress=time.time(); out.flush()
    os.replace(folder/'metadata.jsonl.part',folder/'metadata.jsonl')
    os.replace(folder/'errors.jsonl.part',folder/'errors.jsonl')
    renderer_source=Path(__file__).with_name('panoramax_classifier_crop.py')
    renderer_target=folder/'classifier-crop-renderer.py'
    if renderer_target.exists() and sha_file(renderer_target)!=sha_file(renderer_source): raise ValueError('classifier_crop_renderer_changed')
    if not renderer_target.exists(): shutil.copyfile(renderer_source,renderer_target)
    manifest=dict(schema_version=1,month=args.month,exporter=VERSION,status='partial' if errors else 'complete',
        stage='media_verified' if not errors else 'media_incomplete',cutoff=str(source['identity']['cutoff']),
        exporter_source_sha256=source.get('exporter_source_sha256'),exporter_source=source.get('exporter_source'),
        materializer_source_sha256=sha_file(__file__),
        source_counts=source['source_counts'],controls=source.get('controls'),expected_records=len(records),verified_records=verified,
        record_status_counts=dict(counts),metadata_only_records=metadata_only,bytes=total_bytes,error_count=len(errors),
        context_records=context_count,context_bytes=context_bytes,classifier_crop_policy='annotated-sign-1',
        classifier_crop_renderer=dict(path=f'data/{args.month}/classifier-crop-renderer.py',sha256=sha_file(renderer_target)),
        metadata=dict(path=f'data/{args.month}/metadata.jsonl',sha256=sha_file(folder/'metadata.jsonl'),rows=len(records)),
        source_plan_sha256=source['source_plan_sha256'],
        training_note='Export completeness does not establish annotation completeness, training eligibility or reviewed split groups.')
    write_json(folder/'manifest.json',manifest)
    print(json.dumps(manifest,sort_keys=True))
    return 1 if errors else 0


def main(argv=None):
    parser=argparse.ArgumentParser(description=__doc__)
    sub=parser.add_subparsers(dest='command',required=True)
    for command in ('snapshot','materialize'):
        p=sub.add_parser(command)
        p.add_argument('--output-root',type=Path,required=True,help='Staging repository root, never production media root')
        p.add_argument('--month',required=True)
        if command=='snapshot':
            credentials=p.add_mutually_exclusive_group()
            credentials.add_argument('--database-file',type=Path)
            credentials.add_argument('--database-stdin',action='store_true',help='Read existing report DSN securely from stdin; never writes it')
            p.add_argument('--db-host'); p.add_argument('--db-port',type=int)
            p.add_argument('--mapping-file',type=Path,required=True)
        else:
            for kind in ('dataset','mobile','panoramax','frame'): p.add_argument('--'+kind+'-root',type=Path)
            p.add_argument('--mobile-proxy'); p.add_argument('--panoramax-proxy')
            p.add_argument('--public-frames',action='store_true')
            p.add_argument('--reconstruct-panoramax',action='store_true',help='Use exact backend renderer on verified archived public parent frames; enforce original crop hash')
            p.add_argument('--bind-unhashed-frames',action='store_true',help='Bind missing frame asset hashes once using mounted registered HD rasters, with an immutable first-observation ledger')
            p.add_argument('--workers',type=int,default=4)
            p.add_argument('--max-image-bytes',type=int,default=128*1024**2)
    args=parser.parse_args(argv)
    os.umask(0o077)
    if not MONTH.fullmatch(args.month): parser.error('month must be YYYY-MM')
    if args.command=='materialize' and not 1<=args.workers<=16: parser.error('workers must be 1..16')
    try:
        return snapshot(args) if args.command=='snapshot' else materialize(args)
    except Exception as error:
        print(json.dumps(dict(error=type(error).__name__,detail=str(error) if type(error) is ValueError else 'operation failed; credentials suppressed')),file=sys.stderr)
        return 1


if __name__=='__main__': sys.exit(main())