Explorer
/tmp/aa043-staging/modify_post.py
← Zurück ↓ Download
import sys
import os

def replace_post(content):
    lines = content.splitlines(keepends=True)
    start = None
    for i, line in enumerate(lines):
        if line.strip().startswith('def post(row):'):
            start = i
            break
    if start is None:
        return content
    end = None
    for i in range(start+1, len(lines)):
        if lines[i].startswith('def ') and not lines[i].startswith('    def '):
            end = i
            break
    if end is None:
        end = len(lines)
    new_post = '''def post(row):
    # Write to graphiti_import_queue instead of HTTP POST
    import hashlib, json, sqlite3
    from datetime import datetime, timezone
    p = Path(row['absolute_path'])
    raw = p.read_text(encoding='utf-8', errors='ignore')
    title = re.search(r'(?m)^#\s+(.+)$', raw)
    title = title.group(1).strip() if title else p.stem
    meta = json.loads(row['metadata_json'] or '{}')
    run_id = os.getenv('OBSIDIAN_IMPORT_RUN_ID') or ('run-' + datetime.now(timezone.utc).isoformat())
    request_id = 'req-' + hashlib.sha256((run_id + str(row['id']) + datetime.now(timezone.utc).isoformat()).encode()).hexdigest()[:24]
    source_identity = row['source_identity'] or ('obsidian:' + row['relative_path'])
    version_hash = row['content_version_hash'] or row['content_hash']
    formal_identity = row['import_identity'] or formal_import_identity(source_identity, version_hash)
    provenance = {
        'import_identity': formal_identity,
        'identity_version': 'v1',
        'source_identity': source_identity,
        'content_version_hash': version_hash,
        'canonical_obsidian_path': row['relative_path'],
        'reconciliation_record_id': 'legacy-queue-' + str(row['id']),
        'source_system': 'obsidian-general',
        'source_type': 'markdown',
        'request_id': request_id,
        'run_id': run_id,
        'import_key': row['import_key'],
        'obsidian_path': row['relative_path'],
        'document_title': title,
        'document_type': row['document_type'],
        'content_hash': row['content_hash'],
        'source_area': row['source_area'],
        'queue_id': row['id'],
        'importer_name': 'obsidian-graphiti-single-writer',
        'importer_version': CFG['importer_version'],
        'imported_at': datetime.now(timezone.utc).isoformat(),
        'metadata': meta
    }
    payload = {
        'content': raw[:8000],
        'source': 'obsidian',
        'actor': 'obsidian-single-writer',
        'name': 'aa043_' + formal_identity,
        'context': json.dumps(provenance, ensure_ascii=False, sort_keys=True),
        'timestamp': datetime.now(timezone.utc).isoformat()
    }
    payload_json = json.dumps(payload, ensure_ascii=False, sort_keys=True)
    payload_hash = hashlib.sha256(payload_json.encode()).hexdigest()
    if source_identity.startswith('youtube:'):
        source_type_db = 'youtube'
        video_id = source_identity.split(':', 1)[1]
    else:
        source_type_db = 'obsidian'
        video_id = None
    db_path = str(Path(CFG['db']))
    conn = sqlite3.connect(db_path)
    try:
        conn.execute('''
            INSERT INTO graphiti_import_queue (
                source_type, video_id, obsidian_path, content_hash, file_modified_at,
                graphiti_status, graphiti_attempts, graphiti_last_attempt_at,
                created_at, updated_at, attempt_count, reconciliation_record_id,
                source_version_id, import_identity, knowledge_unit_identity, action,
                payload_hash, payload_json, post_request_id
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''', (
            source_type_db,
            video_id,
            row['relative_path'],
            row['content_hash'],
            row.get('modified_at'),
            'pending',
            0,
            datetime.now(timezone.utc).isoformat(),
            datetime.now(timezone.utc).isoformat(),
            datetime.now(timezone.utc).isoformat(),
            0,
            provenance['reconciliation_record_id'],
            None,
            formal_identity,
            '__source__',
            'CREATE',
            payload_hash,
            payload_json,
            request_id
        ))
        conn.commit()
    finally:
        conn.close()
    return {'status': 'queued', 'queue_id': row['id']}
'''
    new_lines = lines[:start] + new_post.splitlines(keepends=True) + lines[end:]
    return ''.join(new_lines)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('Usage: modify_post.py <filename>')
        sys.exit(1)
    filename = sys.argv[1]
    with open(filename, 'r', encoding='utf-8') as f:
        content = f.read()
    new_content = replace_post(content)
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(new_content)