File size: 32,292 Bytes
1ec47ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0d4d2a
 
 
 
 
 
 
 
 
1ec47ac
c0d4d2a
1ec47ac
 
 
 
 
 
 
c0d4d2a
1ec47ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Idempotent research inventory, complete-event ingest and public Parquet index.

No network calls and no credentials. Full local bytes or an already verified
receipt/DB record are required; only remotely verified complete events export.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import re
import sqlite3
import sys
import uuid
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode

ROOT = Path(__file__).resolve().parents[1]
REPO = 'Jiaxuannn/PAR'
KINDS = ('text', 'video', 'audio', 'metadata')
REMOTE_DONE = ('remote_verified', 'local_removed')
METHODS = {'hub_lfs_sha256_and_size': 'sha256_lfs',
           'remote_full_stream_sha256_and_size': 'sha256_download',
           'sha256_lfs': 'sha256_lfs', 'sha256_download': 'sha256_download'}
INVENTORY_FIELDS = ('record_id','source','geography','record_class','title','date_value',
                    'year_value','date_basis','event_url','index_url','source_csv','final_hq_status','count_unit')


def now():
    return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')


def dumps(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))


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


def uid(prefix, *parts):
    return prefix + uuid.uuid5(uuid.NAMESPACE_URL, '|'.join(map(str, parts))).hex


def public_url(value):
    if not value:
        return None
    u = urlsplit(value)
    if u.scheme not in ('http', 'https') or u.username or u.password:
        raise ValueError('Expected a public HTTP(S) source URL without credentials')
    query = [(k, v) for k, v in parse_qsl(u.query, keep_blank_values=True)
             if not re.search(r'token|signature|credential|password|authorization|cookie|secret', k, re.I)]
    return urlunsplit((u.scheme, u.netloc, u.path, urlencode(query), ''))


def safe_remote_path(value):
    if not isinstance(value, str) or not value or '\\' in value:
        raise ValueError('Invalid remote asset path')
    p = PurePosixPath(value)
    if p.is_absolute() or '..' in p.parts or str(p) != value:
        raise ValueError('Remote asset path must be a normalized relative POSIX path')
    return value


def connect(path):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    con = sqlite3.connect(path, timeout=30)
    con.row_factory = sqlite3.Row
    con.execute('PRAGMA foreign_keys=ON')
    con.execute('PRAGMA busy_timeout=30000')
    return con


def init(con):
    old = con.execute('PRAGMA user_version').fetchone()[0]
    if old not in (0, 1):
        raise ValueError('Unsupported database schema version; use an explicit migration')
    con.executescript((ROOT / 'schema/schema.sql').read_text(encoding='utf-8'))
    return {'schema_version': con.execute('PRAGMA user_version').fetchone()[0]}


def import_inventory(con, inventory, sources):
    definitions = json.loads(Path(sources).read_text(encoding='utf-8-sig'))
    if isinstance(definitions, dict):
        definitions = definitions['sources']
    with con:
        for s in definitions:
            central = s.get('source_id') in {'scio_policy','scio_general','ndrc','mofcom_video'}
            con.execute('''INSERT INTO sources(source_id,name,index_url,geography,level,priority,access_status,collector_name,notes)
                VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(source_id) DO NOTHING''',
                (s['source_id'],s.get('name',s['source_id']),s.get('entry_url',s.get('index_url')),
                 s.get('geography','unknown'),'central' if central else 'provincial',
                 s.get('priority',50),'partial',s.get('collector_name'),s.get('note',s.get('notes'))))
        seen = 0
        with Path(inventory).open(encoding='utf-8-sig', newline='') as f:
            reader = csv.DictReader(f)
            if not set(INVENTORY_FIELDS).issubset(reader.fieldnames or []):
                raise ValueError('Inventory CSV is missing required audited columns')
            for row in reader:
                if not row['record_id'] or not row['source'] or not row['title']:
                    raise ValueError('Inventory record requires id, source and title')
                con.execute('INSERT OR IGNORE INTO sources(source_id,name) VALUES (?,?)', (row['source'],row['source']))
                old = con.execute('SELECT source FROM source_records WHERE record_id=?',(row['record_id'],)).fetchone()
                if old and old['source'] != row['source']:
                    raise ValueError('Immutable source record identity conflict')
                values = [row[k] or None for k in INVENTORY_FIELDS]
                values[11] = values[11] or 'not_assessed'
                values[12] = values[12] or 'source_record'
                con.execute('INSERT INTO source_records('+','.join(INVENTORY_FIELDS)+',raw_record_json) VALUES ('+
                            ','.join('?' for _ in range(14))+') ON CONFLICT(record_id) DO UPDATE SET last_seen_at=excluded.last_seen_at',
                            values+[dumps(row)])
                seen += 1
    return {'input_rows':seen,'source_records':con.execute('SELECT count(*) FROM source_records').fetchone()[0],
            'events':con.execute('SELECT count(*) FROM events').fetchone()[0]}


def read_manifests(path):
    p = Path(path).resolve()
    raw = p.read_text(encoding='utf-8-sig')
    try:
        parsed = json.loads(raw)
        values = parsed if isinstance(parsed,list) else [parsed]
    except json.JSONDecodeError:
        values = [json.loads(line) for line in raw.splitlines() if line.strip()]
    for m in values:
        yield p,m


def receipt_assets(manifest_path, event_id):
    for p in (manifest_path.parent/'remote_verified.json', manifest_path.parent/(event_id+'.remote_verified.json')):
        if not p.is_file():
            continue
        r = json.loads(p.read_text(encoding='utf-8'))
        if r.get('repo_id') != REPO or r.get('event_id') != event_id or r.get('verified') is not True:
            continue
        result = {}
        for a in r.get('assets',[]):
            commit = a.get('verified_commit') or r.get('commit_sha')
            method = METHODS.get(a.get('verification_method'))
            if commit and re.fullmatch('[0-9a-f]{40,64}',commit) and method and a.get('verified_at'):
                result[a['remote_path']] = dict(a, remote_commit=commit, remote_method=method)
        return result
    return {}


def asset_local_path(asset, manifest_path):
    p = Path(asset['local_path'])
    return p if p.is_absolute() else manifest_path.parent / p


def ingest_one(con, manifest_path, m):
    if str(m.get('schema_version')) != '1' or m.get('quality_status') not in ('full_av_text_verified','hq_verified'):
        raise ValueError('Only complete AV+text manifests version 1 can be ingested')
    event_id = m['event_id']
    if not isinstance(event_id,str) or not re.fullmatch(r'[A-Za-z0-9_-]{8,100}',event_id):
        raise ValueError('Invalid event identifier')
    items = m.get('assets',[])
    by_kind = {a['kind']:a for a in items}
    if not set(KINDS).issubset(by_kind) or len(by_kind) != len(items):
        raise ValueError('Exactly one manifest asset per kind; text/video/audio/metadata are required')
    receipts = receipt_assets(manifest_path,event_id)
    verified = {}
    for a in items:
        safe_remote_path(a['remote_path'])
        if not re.fullmatch('[0-9a-f]{64}',a.get('sha256','')) or not isinstance(a.get('size_bytes'),int) or a['size_bytes'] <= 0:
            raise ValueError('Manifest requires complete SHA-256 and positive byte size')
        old = con.execute('SELECT * FROM assets WHERE remote_path=?',(a['remote_path'],)).fetchone()
        if old and any(old[k] != a[k] for k in ('kind','sha256','size_bytes')):
            raise ValueError('Immutable remote path content conflict; use a versioned new path')
        if old and old['event_id'] != event_id:
            raise ValueError('Remote path already belongs to another event')
        r = receipts.get(a['remote_path'])
        if r and (r.get('sha256') != a['sha256'] or r.get('size_bytes') != a['size_bytes'] or r.get('kind') != a['kind']):
            raise ValueError('Remote receipt conflicts with manifest')
        stored_verified = old is not None and old['state'] in REMOTE_DONE
        p = asset_local_path(a,manifest_path)
        if p.is_file():
            if p.is_symlink() or p.stat().st_size != a['size_bytes']:
                raise ValueError('Local asset size/type mismatch')
            # Existing verified media need not be re-hashed on every resume.
            if not (stored_verified and a['kind'] in ('video','audio')) and digest(p) != a['sha256']:
                raise ValueError('Local asset full checksum mismatch')
        elif not (r or stored_verified):
            raise ValueError('Asset absent without matching verified remote receipt or database evidence')
        if a['kind'] in ('text','metadata') and not p.is_file():
            raise ValueError('Retained text and metadata are required for ingest; restore them from the verified revision')
        verified[a['remote_path']] = (old,r,p)
    metadata = json.loads(asset_local_path(by_kind['metadata'],manifest_path).read_text(encoding='utf-8'))
    transcript = json.loads(asset_local_path(by_kind['text'],manifest_path).read_text(encoding='utf-8'))
    if metadata.get('event_id') != event_id or transcript.get('event_id') != event_id:
        raise ValueError('Metadata, transcript and manifest must identify the same event')
    technical = metadata.get('technical_quality',{})
    required = ('full_source_media_download','full_video_decode','full_audio_decode',
                'official_transcript_open_qa_close','same_official_page_pairing')
    if any(technical.get(k) != 'passed' for k in required):
        raise ValueError('Collector has not recorded all required complete-material checks')
    markers = ('source_published_transcript_complete','opening_marker','qa_marker','closing_marker')
    if any(transcript.get(k) is not True for k in markers) or not transcript.get('text') or not transcript.get('turns'):
        raise ValueError('Published transcript coverage evidence is incomplete')
    source_url = public_url(metadata['primary_url'])
    if public_url(transcript.get('source_url')) != source_url:
        raise ValueError('Transcript and metadata official source mismatch')
    video_probe,audio_probe = metadata.get('video_probe',{}),metadata.get('audio_probe',{})
    if not {'video','audio'}.issubset({s.get('codec_type') for s in video_probe.get('streams',[])}) or not any(s.get('codec_type')=='audio' for s in audio_probe.get('streams',[])):
        raise ValueError('Actual video and audio probe streams are required')
    duration = metadata.get('duration_ms')
    audio_duration = round(float(audio_probe.get('format',{}).get('duration',0))*1000)
    if not isinstance(duration,int) or duration <= 0 or abs(duration-audio_duration)>1000:
        raise ValueError('Audio/video duration evidence mismatch')
    if metadata.get('audio_derivation',{}).get('parent_sha256') != by_kind['video']['sha256']:
        raise ValueError('Derived audio parent hash differs from source video')
    date = metadata.get('event_date')
    if date:
        datetime.strptime(date,'%Y-%m-%d')
    date_basis = metadata.get('date_basis','unknown')
    date_basis = {'official_page_explicit_event_date':'event_page'}.get(date_basis,date_basis)
    if date_basis not in ('event_page','official_transcript','video_content','multiple_sources','unknown'):
        date_basis = 'unknown'
    level = {'central_department':'central'}.get(metadata.get('level'),metadata.get('level','unknown'))
    if level not in ('central','provincial','prefecture','county','other','unknown'):
        level='unknown'
    source_rows = con.execute('SELECT record_id,title FROM source_records WHERE event_url=?',(source_url,)).fetchall()
    event_title = metadata['title'].strip()
    title_basis = 'official_event_heading'
    if event_title in {'商务视频网'}:
        candidates = {row['title'].strip() for row in source_rows if row['title'] and row['title'].strip() not in {'商务视频网'}}
        if len(candidates) != 1:
            raise ValueError('Generic site title requires an unambiguous official catalogue title at the same event URL')
        event_title = candidates.pop()
        title_basis = 'official_catalogue_same_event_url'
    evidence = {'source_url':source_url,'source_page_sha256':metadata.get('source_page_sha256'),
                'raw_metadata_title':metadata['title'],'canonical_title':event_title,'title_basis':title_basis,
                'match_method':'official_same_event_source','alignment_status':'not_aligned',
                'human_review':metadata.get('human_event_coverage_review','pending')}
    with con:
        con.execute('''INSERT INTO events(event_id,title,event_date,date_basis,date_confidence,level,province,event_type,primary_url,status,identity_evidence_json)
            VALUES(?,?,?,?,?,?,?,?,?,'ready',?) ON CONFLICT(event_id) DO UPDATE SET
            title=excluded.title,event_date=excluded.event_date,date_basis=excluded.date_basis,date_confidence=excluded.date_confidence,
            level=excluded.level,province=excluded.province,primary_url=excluded.primary_url,identity_evidence_json=excluded.identity_evidence_json,
            updated_at=?''',(event_id,event_title,date,date_basis,'confirmed' if date and date_basis!='unknown' else 'unknown',
                             level,metadata.get('province'),metadata.get('event_type','unknown'),source_url,dumps(evidence),now()))
        for r in source_rows:
            con.execute('''INSERT INTO event_sources(event_id,record_id,relation,match_status,match_method,evidence_json)
                VALUES(?,?,'primary','confirmed','official_same_event_source',?) ON CONFLICT(event_id,record_id) DO NOTHING''',
                (event_id,r['record_id'],dumps(evidence)))
        ids={a['kind']:uid('ast_',event_id,a['remote_path']) for a in items}
        for a in sorted(items,key=lambda a:({'video':0,'audio':1,'text':2,'metadata':3}.get(a['kind'],4))):
            old,r,p = verified[a['remote_path']]
            asset_id = old['asset_id'] if old else ids[a['kind']]
            ids[a['kind']] = asset_id
            if old:
                # Preserve remote_verified/local_removed; do not regress to locally validated.
                con.execute('UPDATE assets SET local_path=?,updated_at=? WHERE asset_id=?',(str(p),now(),asset_id))
                continue
            previous=con.execute('SELECT coalesce(max(version),0) FROM assets WHERE event_id=? AND kind=? AND variant=?',(event_id,a['kind'],'main')).fetchone()[0]
            con.execute('UPDATE assets SET is_current=0,updated_at=? WHERE event_id=? AND kind=? AND variant=? AND is_current=1',(now(),event_id,a['kind'],'main'))
            state='remote_verified' if r else 'validated'
            probe=video_probe if a['kind']=='video' else audio_probe if a['kind']=='audio' else {}
            mime={'text':'application/json','metadata':'application/json','video':'video/mp4','audio':'audio/flac'}.get(a['kind'])
            con.execute('''INSERT INTO assets(asset_id,event_id,kind,version,source_record_id,source_url,derived_from_asset_id,
                derivation_json,local_path,remote_path,sha256,size_bytes,mime_type,duration_ms,probe_json,downloaded_complete,
                validation_status,state,remote_commit,remote_sha256,remote_verification_method,remote_verified_at)
                VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,'passed',?,?,?,?,?)''',
                (asset_id,event_id,a['kind'],previous+1,source_rows[0]['record_id'] if source_rows else None,source_url,
                 ids['video'] if a['kind']=='audio' else None,dumps(metadata.get('audio_derivation',{}) if a['kind']=='audio' else {}),
                 str(p),a['remote_path'],a['sha256'],a['size_bytes'],mime,duration if a['kind'] in ('video','audio') else None,dumps(probe),
                 state,r['remote_commit'] if r else None,a['sha256'] if r else None,r['remote_method'] if r else None,r['verified_at'] if r else None))
        for turn in transcript['turns']:
            index=turn['turn_index'];label=turn.get('speaker_raw')
            if not isinstance(index,int) or index<0 or not isinstance(turn.get('text'),str):
                raise ValueError('Invalid natural transcript turn')
            participant=uid('par_',event_id,label or 'unknown')
            role='journalist' if turn.get('role')=='reporter' else 'official' if turn.get('role')=='government_speaker' else 'unknown'
            con.execute('''INSERT INTO participants(participant_id,event_id,speaker_label_raw,organization_name_raw,role,source_record_id)
                VALUES(?,?,?,?,?,?) ON CONFLICT(participant_id) DO NOTHING''',
                (participant,event_id,label,'商务部' if role=='official' and urlsplit(source_url).hostname=='video.mofcom.gov.cn' else None,
                 role,source_rows[0]['record_id'] if source_rows else None))
            con.execute('''INSERT INTO utterances(utterance_id,event_id,text_asset_id,participant_id,sequence_index,speaker_label_raw,
                turn_type,text_original,text_source,start_ms,end_ms,timestamp_basis,evidence_json)
                VALUES(?,?,?,?,?,?,? ,?,'official',NULL,NULL,'none',?) ON CONFLICT(utterance_id) DO NOTHING''',
                (uid('utt_',ids['text'],index),event_id,ids['text'],participant,index,label,
                 'question' if role=='journalist' else 'unknown',turn['text'],dumps({'source_url':source_url,'alignment_status':'not_aligned'})))
        checks = [('event_identity','official_same_event_source',None,evidence),
                  ('transcript_coverage','official_transcript_open_qa_close',None,{**{k:transcript[k] for k in markers},'source_url':source_url}),
                  ('cross_modal_match','official_same_event_source',None,evidence),
                  ('full_decode','ffmpeg_complete_video_audio_decode',ids['video'],{'duration_ms':duration,'source_sha256':by_kind['video']['sha256']}),
                  ('audio_usable','full_audio_decode_and_duration_match',ids['audio'],{'duration_ms':audio_duration,'parent_sha256':by_kind['video']['sha256'],'assessment_scope':'decodability_and_duration; acoustic_intelligibility_not_independently_reviewed'})]
        for kind,method,asset_id,ev in checks:
            con.execute('''INSERT INTO quality_checks(check_id,event_id,asset_id,check_type,result,method,reviewer_type,evidence_json)
                VALUES(?,?,?,?,'passed',?,'automatic',?) ON CONFLICT(check_id) DO NOTHING''',
                (uid('chk_',event_id,kind,by_kind['metadata']['sha256']),event_id,asset_id,kind,method,dumps(ev)))
    return event_id


def sync_transfer(con, ledger_path):
    ledger_path=Path(ledger_path).resolve()
    other=sqlite3.connect(ledger_path.as_uri()+'?mode=ro',uri=True)
    other.row_factory=sqlite3.Row
    rows=[dict(r) for r in other.execute('SELECT * FROM transfer_assets WHERE repo_id=?',(REPO,))]
    updated=0; unknown=0
    with con:
        for r in rows:
            a=con.execute('SELECT * FROM assets WHERE remote_path=?',(r['remote_path'],)).fetchone()
            if not a:
                unknown+=1;continue
            if any(a[k]!=r[k] for k in ('event_id','kind','size_bytes','sha256')):
                raise ValueError('Transfer ledger conflicts with immutable research asset')
            if r['state'] not in ('verified','local_removed'):
                continue
            method=METHODS.get(r['verification_method'])
            if not method or not r['verified_commit'] or not r['verified_at']:
                raise ValueError('Verified ledger state lacks checksum verification evidence')
            state='local_removed' if r['state']=='local_removed' or a['state']=='local_removed' else 'remote_verified'
            deleted=r['removed_at'] or a['local_deleted_at']
            if state=='local_removed' and not deleted:
                raise ValueError('Removal state lacks actual removal timestamp')
            con.execute('''UPDATE assets SET state=?,remote_commit=?,remote_sha256=sha256,remote_verification_method=?,
                remote_verified_at=?,local_deleted_at=?,updated_at=? WHERE asset_id=?''',
                (state,r['verified_commit'],method,r['verified_at'],deleted,now(),a['asset_id']))
            updated+=1
    batches=0;unarchived=0
    for b in other.execute('SELECT * FROM transfer_batches WHERE repo_id=?',(REPO,)):
        b=dict(b)
        manifest_path=ledger_path.parent/'upload_receipts'/(b['batch_id']+'.manifest.json')
        if not manifest_path.is_file():
            unarchived+=1;continue
        m=json.loads(manifest_path.read_text(encoding='utf-8'))
        if m.get('repo_id')!=REPO or m.get('batch_id')!=b['batch_id']:
            raise ValueError('Batch manifest identity conflict')
        members=[]
        for item in m['assets']:
            a=con.execute('SELECT * FROM assets WHERE remote_path=?',(item['remote_path'],)).fetchone()
            if not a or any(a[k]!=item[k] for k in ('event_id','kind','sha256','size_bytes')):
                members=[];break
            members.append(a)
        if not members or sum(a['size_bytes'] for a in members)!=m.get('total_bytes'):
            unarchived+=1;continue
        ledger_paths={r[0] for r in other.execute('SELECT remote_path FROM transfer_batch_items WHERE repo_id=? AND batch_id=?',(REPO,b['batch_id']))}
        if ledger_paths!={a['remote_path'] for a in members}:
            raise ValueError('Batch receipt and transfer ledger membership differ')
        verified=b['state']=='verified' and b['commit_sha'] and all(a['state'] in REMOTE_DONE for a in members)
        cleaned=verified and all(a['state']=='local_removed' for a in members if a['kind'] in ('video','audio'))
        state='cleaned' if cleaned else 'remote_verified' if verified else 'failed' if b['state']=='failed' else 'sealed'
        with con:
            con.execute('''INSERT INTO batches(batch_id,repo_id,sealed_bytes,manifest_path,manifest_sha256,state,commit_sha,error_summary,created_at)
                VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(batch_id) DO UPDATE SET state=excluded.state,commit_sha=excluded.commit_sha,
                manifest_sha256=excluded.manifest_sha256,manifest_path=excluded.manifest_path,error_summary=excluded.error_summary,updated_at=?''',
                (b['batch_id'],REPO,m['total_bytes'],str(manifest_path),digest(manifest_path),state,b['commit_sha'],b['last_error_type'],b['created_at'],now()))
            for a in members:
                transfer='verified' if a['state'] in REMOTE_DONE else 'pending'
                cleanup='removed' if a['state']=='local_removed' else 'retained'
                con.execute('''INSERT INTO batch_items(batch_id,asset_id,remote_path,expected_sha256,expected_size_bytes,transfer_status,cleanup_status,verified_at)
                    VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(batch_id,asset_id) DO UPDATE SET transfer_status=excluded.transfer_status,
                    cleanup_status=excluded.cleanup_status,verified_at=excluded.verified_at''',
                    (b['batch_id'],a['asset_id'],a['remote_path'],a['sha256'],a['size_bytes'],transfer,cleanup,a['remote_verified_at']))
        batches+=1
    other.close()
    return {'assets_synchronized':updated,'unmatched_assets_not_imported':unknown,'batches_archived':batches,
            'batches_without_readable_matching_manifest':unarchived,
            'note':'Unarchived batches do not affect verified asset sync; retain upload_receipts beside the ledger for complete batch archival.'}


def published_events(con):
    query='''SELECT e.* FROM events e JOIN v_event_readiness r ON e.event_id=r.event_id
        WHERE r.full_av_text_verified=1 AND NOT EXISTS (
        SELECT 1 FROM (SELECT 'text' AS kind UNION ALL SELECT 'video' UNION ALL SELECT 'audio' UNION ALL SELECT 'metadata') required
        WHERE NOT EXISTS (SELECT 1 FROM assets a WHERE a.event_id=e.event_id AND a.kind=required.kind
         AND a.is_current=1 AND a.downloaded_complete=1 AND a.validation_status='passed'
         AND a.state IN ('remote_verified','local_removed'))) ORDER BY e.event_date,e.event_id'''
    return [dict(r) for r in con.execute(query)]


def status(con):
    value=dict(con.execute('SELECT * FROM v_collection_counts').fetchone())
    full=value['full_av_text_verified_count']
    assessed=con.execute("SELECT count(DISTINCT q.event_id) FROM v_latest_quality_checks q JOIN v_event_readiness r ON q.event_id=r.event_id WHERE q.asset_id IS NULL AND q.check_type='final_hq' AND q.result IN ('passed','failed') AND r.full_av_text_verified=1").fetchone()[0]
    value.update(schema_version=1,repo_id=REPO,updated_at=now(),
                 published_full_av_text_count=len(published_events(con)),
                 final_hq_count=value['observed_hq_passed_count'] if full>0 and assessed>=full else None,
                 final_hq_population_total=None,
                 manual_hq_assessment_status='not_assessed' if not assessed else 'partially_assessed' if assessed<full else 'assessed',
                 manual_hq_assessed_events=assessed,
                 count_unit='independent_event; source_record_count is a separate inventory unit')
    return value


def public_json_check(rows):
    content=dumps(rows)
    if re.search(r'hf_[A-Za-z0-9]{15,}',content) or re.search(r'(?i)(?:authorization|password|cookie|access_token)"\s*:',content):
        raise ValueError('Potential credential in public export; review source data')
    return content


def export(con,out):
    import pyarrow as pa
    import pyarrow.parquet as pq
    out=Path(out);out.mkdir(parents=True,exist_ok=True)
    events=published_events(con)
    erows=[];arows=[];urows=[];qrows=[]
    for event in events:
        eid=event['event_id']
        assets=[dict(r) for r in con.execute("SELECT * FROM assets WHERE event_id=? AND is_current=1 AND state IN ('remote_verified','local_removed') ORDER BY kind,variant",(eid,))]
        by_kind={a['kind']:a for a in assets if a['kind'] in KINDS}
        readiness=dict(con.execute('SELECT * FROM v_event_readiness WHERE event_id=?',(eid,)).fetchone())
        final=con.execute("SELECT result FROM v_latest_quality_checks WHERE event_id=? AND asset_id IS NULL AND check_type='final_hq'",(eid,)).fetchone()
        erows.append({'event_id':eid,'title':event['title'],'date':event['event_date'],'level':event['level'],
                      'province':event['province'],'source_url':public_url(event['primary_url']),
                      'duration_ms':by_kind['video']['duration_ms'],**{k+'_path':by_kind[k]['remote_path'] for k in KINDS},
                      'quality_status':'full_av_text_verified','manual_hq_status':final['result'] if final else 'not_assessed',
                      'alignment_status':'not_aligned','asset_total_bytes':sum(a['size_bytes'] for a in assets)})
        for a in assets:
            arows.append({k:a[k] for k in ('asset_id','event_id','kind','remote_path','sha256','size_bytes','duration_ms','mime_type',
                                          'source_url','derived_from_asset_id','remote_commit','remote_verification_method','remote_verified_at','license_status')})
        for r in con.execute('SELECT * FROM utterances WHERE event_id=? AND text_asset_id=? ORDER BY sequence_index',(eid,by_kind['text']['asset_id'])):
            urows.append({k:r[k] for k in ('utterance_id','event_id','participant_id','sequence_index','speaker_label_raw','turn_type',
                                         'text_original','text_source','start_ms','end_ms','timestamp_basis')})
        current_ids={a['asset_id'] for a in assets}
        for r in con.execute('SELECT * FROM v_latest_quality_checks WHERE event_id=? ORDER BY check_type',(eid,)):
            if r['asset_id'] is not None and r['asset_id'] not in current_ids:
                continue
            qrows.append({k:r[k] for k in ('check_id','event_id','asset_id','check_type','result','method','reviewer_type','rule_version','evidence_json','checked_at')})
    fields={
      'events': [('event_id','s'),('title','s'),('date','s'),('level','s'),('province','s'),('source_url','s'),('duration_ms','i'),
                 ('text_path','s'),('video_path','s'),('audio_path','s'),('metadata_path','s'),('quality_status','s'),('manual_hq_status','s'),('alignment_status','s'),('asset_total_bytes','i')],
      'assets': [(k,'i' if k in ('size_bytes','duration_ms') else 's') for k in ('asset_id','event_id','kind','remote_path','sha256','size_bytes','duration_ms','mime_type','source_url','derived_from_asset_id','remote_commit','remote_verification_method','remote_verified_at','license_status')],
      'utterances': [(k,'i' if k in ('sequence_index','start_ms','end_ms') else 's') for k in ('utterance_id','event_id','participant_id','sequence_index','speaker_label_raw','turn_type','text_original','text_source','start_ms','end_ms','timestamp_basis')],
      'quality_checks': [(k,'s') for k in ('check_id','event_id','asset_id','check_type','result','method','reviewer_type','rule_version','evidence_json','checked_at')]
    }
    tables={'events':erows,'assets':arows,'utterances':urows,'quality_checks':qrows}
    for name,rows in tables.items():
        public_json_check(rows)
        schema=pa.schema([(k,pa.int64() if t=='i' else pa.string()) for k,t in fields[name]])
        p=out/(name+'.parquet');tmp=out/(name+'.parquet.tmp')
        pq.write_table(pa.Table.from_pylist(rows,schema=schema),tmp,compression='zstd')
        tmp.replace(p)
    info=status(con)
    info['exported_tables']={k:len(v) for k,v in tables.items()}
    info['public_export_rule']='Only full AV+text verified events with text/video/audio/metadata all remotely SHA-256 verified.'
    tmp=out/'dataset_status.json.tmp';tmp.write_text(json.dumps(info,ensure_ascii=False,indent=2)+'\n',encoding='utf-8');tmp.replace(out/'dataset_status.json')
    return info


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--db',type=Path,default=Path('state/collection.sqlite'))
    sub=p.add_subparsers(dest='command',required=True)
    sub.add_parser('init')
    q=sub.add_parser('import-inventory');q.add_argument('--inventory',type=Path,required=True);q.add_argument('--sources',type=Path,required=True)
    q=sub.add_parser('ingest');q.add_argument('--manifest',type=Path,action='append',required=True)
    q=sub.add_parser('sync-transfer');q.add_argument('--ledger',type=Path,required=True)
    q=sub.add_parser('export');q.add_argument('--out',type=Path,default=Path('data/index'))
    sub.add_parser('status')
    args=p.parse_args()
    if args.command!='init' and not args.db.is_file():
        p.error('Initialize the database first with init')
    con=connect(args.db)
    try:
        if args.command=='init':result=init(con)
        elif args.command=='import-inventory':result=import_inventory(con,args.inventory,args.sources)
        elif args.command=='ingest':
            ids=[]
            for path in args.manifest:
                for mp,m in read_manifests(path):ids.append(ingest_one(con,mp,m))
            result={'ingested_manifests':len(ids),'distinct_event_ids':len(set(ids)),**status(con)}
        elif args.command=='sync-transfer':result=sync_transfer(con,args.ledger)
        elif args.command=='export':result=export(con,args.out)
        else:result=status(con)
        print(json.dumps(result,ensure_ascii=False,indent=2))
    finally:
        con.close()


if __name__=='__main__':
    try:main()
    except (ValueError,OSError,sqlite3.Error) as exc:
        # Never dump raw metadata or credential-bearing request objects.
        print(json.dumps({'error_type':type(exc).__name__,'message':re.sub(r'hf_[A-Za-z0-9]+','[REDACTED]',str(exc))},ensure_ascii=False),file=sys.stderr)
        sys.exit(1)