"""Backfill verified local extraction results; no model calls and no score changes. Manifest entries identify answer_id, task, step, url and optional existing file_ids. Place .sections.json beside each copied attachment. Sections use TrainingDocumentTextExtractor's JSON shape. Entries without sections are left pending. Dry run by default; --apply requires a new --backup file. """ import argparse import datetime import hashlib import json from pathlib import Path import uuid from migrate_training_step_answers import ROOT, connect def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--directory', type=Path, default=ROOT / 'target/attachment-repair') parser.add_argument('--apply', action='store_true') parser.add_argument('--backup', type=Path) args = parser.parse_args() if args.apply and not args.backup: parser.error('--apply requires --backup') manifest = json.loads((args.directory / 'manifest.json').read_text(encoding='utf-8')) conn = connect(ROOT / 'src/main/resources/application-dev.yml') try: with conn.cursor() as q: q.execute('START TRANSACTION' if args.apply else 'START TRANSACTION READ ONLY') plans, skipped = [], [] backup = {'answers': [], 'files': [], 'chunks': []} for item in manifest: local = args.directory / Path(item['url']).name extracted = local.with_name(local.name + '.sections.json') if not extracted.is_file(): skipped.append(item['url']) continue sections = json.loads(extracted.read_text(encoding='utf-8')) if not sections or any(not str(s.get('text', '')).strip() for s in sections): raise ValueError('Empty extraction: ' + item['url']) q.execute('SELECT * FROM student_training_answer WHERE id=%s' + (' FOR UPDATE' if args.apply else ''), [item['answer_id']]) answer = q.fetchone() if not answer or answer['task_key'] != item['task'] or item['url'] not in (answer['step%d_answer' % item['step']] or '').replace('\\/', '/'): raise ValueError('Attachment no longer belongs to the expected step: ' + item['url']) q.execute('SELECT id,enabled FROM training_task_class_config WHERE teaching_class_id=%s AND task_key=%s LIMIT 1', [answer['teaching_class_id'], answer['task_key']]) config = q.fetchone() effective = config['id'] if config and config['enabled'] else answer['task_id'] q.execute("SELECT * FROM training_knowledge_file WHERE source_type='STUDENT_UPLOAD' AND student_user_id=%s AND task_key=%s AND file_url=%s" + (' FOR UPDATE' if args.apply else ''), [answer['student_user_id'], answer['task_key'], item['url']]) matches = q.fetchall() ids = item.get('file_ids') or [] records = [f for f in matches if f['id'] in ids] if ids else [f for f in matches if f['effective_config_id'] == effective] if ids and {f['id'] for f in records} != set(ids): raise ValueError('Expected file index changed: ' + item['url']) if not records: records = [None] for existing in records: content_hash = hashlib.sha256(local.read_bytes()).hexdigest() if existing and existing['content_hash'] != content_hash: raise ValueError('Local file differs from indexed file: ' + item['url']) if existing and existing['parse_status'] == 'SUCCESS': continue now = datetime.datetime.now() record = dict(existing) if existing else dict(id=str(uuid.uuid4()), source_type='STUDENT_UPLOAD', config_scope='STUDENT', effective_config_id=effective, task_id=answer['task_id'], task_key=answer['task_key'], teaching_class_id=answer['teaching_class_id'], student_user_id=answer['student_user_id'], file_url=item['url'], create_time=now) record.update(step_no=item['step'], file_name=local.name, content_hash=content_hash, parse_status='SUCCESS', parse_message=None, section_count=len(sections), update_time=now) backup['answers'].append(answer) if existing: backup['files'].append(existing) q.execute('SELECT * FROM training_knowledge_chunk WHERE knowledge_file_id=%s', [existing['id']]) backup['chunks'].extend(q.fetchall()) plans.append((existing, record, sections)) print(json.dumps({'mode': 'apply' if args.apply else 'dry-run', 'indexes_to_backfill': len(plans), 'pending_without_extraction': skipped})) if not args.apply: return with args.backup.open('x', encoding='utf-8') as output: json.dump(backup, output, ensure_ascii=False, default=str, indent=2) for existing, record, sections in plans: if existing: q.execute('UPDATE training_knowledge_file SET step_no=%s,file_name=%s,content_hash=%s,parse_status=%s,parse_message=%s,section_count=%s,update_time=%s WHERE id=%s', [record[k] for k in ('step_no', 'file_name', 'content_hash', 'parse_status', 'parse_message', 'section_count', 'update_time', 'id')]) else: q.execute('INSERT INTO training_knowledge_file (' + ','.join(record) + ') VALUES (' + ','.join(['%s'] * len(record)) + ')', list(record.values())) q.execute('DELETE FROM training_knowledge_chunk WHERE knowledge_file_id=%s', [record['id']]) for section in sections: q.execute('INSERT INTO training_knowledge_chunk (id,knowledge_file_id,task_key,effective_config_id,teaching_class_id,student_user_id,step_no,section_type,section_name,section_sequence,content,create_time) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)', [str(uuid.uuid4()), record['id'], record['task_key'], record['effective_config_id'], record['teaching_class_id'], record['student_user_id'], record['step_no'], section['sectionType'], section['sectionName'], section['sequence'], section['text'], record['update_time']]) q.execute('SELECT step_no,content FROM training_knowledge_chunk WHERE knowledge_file_id=%s ORDER BY section_sequence,id', [record['id']]) actual = q.fetchall() if len(actual) != len(sections) or sorted(x['content'] for x in actual) != sorted(s['text'] for s in sections) or any(x['step_no'] != record['step_no'] for x in actual): raise ValueError('Index verification failed: ' + record['id']) for answer in backup['answers']: q.execute('SELECT * FROM student_training_answer WHERE id=%s', [answer['id']]) if q.fetchone() != answer: raise ValueError('An answer or score changed unexpectedly') conn.commit() print(json.dumps({'backfilled': len(plans), 'backup': str(args.backup)})) finally: conn.rollback() conn.close() if __name__ == '__main__': main()