import sqlite3 from rapidfuzz import fuzz import shutil from pathlib import Path original_db = Path("data/nasa_data.db") runtime_db = Path("/tmp/nasa_data.db") if not runtime_db.exists(): shutil.copy(original_db, runtime_db) print(f"copied {original_db} → {runtime_db}") else: print(f"using existing runtime DB at {runtime_db}") db_path = str(runtime_db) conn = sqlite3.connect(db_path) cur = conn.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS links ( project_id TEXT, pmc_id TEXT, link_type TEXT, confidence REAL, PRIMARY KEY (project_id, pmc_id, link_type) ); """) def upsert_link(project_id, pmc_id, link_type, confidence): cur.execute(""" SELECT confidence FROM links WHERE project_id=? AND pmc_id=? AND link_type=? """, (project_id, pmc_id, link_type)) row = cur.fetchone() if row is None: cur.execute(""" INSERT INTO links (project_id, pmc_id, link_type, confidence) VALUES (?, ?, ?, ?) """, (project_id, pmc_id, link_type, confidence)) else: existing_conf = row[0] if confidence > existing_conf: cur.execute(""" UPDATE links SET confidence = ? WHERE project_id=? AND pmc_id=? AND link_type=? """, (confidence, project_id, pmc_id, link_type)) cur.execute("SELECT Task_id, PI_Name FROM projects") projects = cur.fetchall() cur.execute("SELECT pmc_id, authors FROM publications") publications = cur.fetchall() pi_author_links = 0 for proj_id, pi_name in projects: if not pi_name: continue for pmc_id, authors in publications: if authors and pi_name.lower() in authors.lower(): upsert_link(proj_id, pmc_id, "pi_author_match", 1.0) pi_author_links += 1 conn.commit() cur.execute(""" SELECT l.project_id, p.[Project Title], pub.title FROM links l JOIN projects p ON l.project_id = p.Task_id JOIN publications pub ON l.pmc_id = pub.pmc_id WHERE l.link_type='pi_author_match' LIMIT 10; """) for r in cur.fetchall(): print("matched (PI→Author):", r) print(f"linked or updated {pi_author_links} PI->Author matches") cur.execute("SELECT Task_id, [Project Title] FROM projects WHERE [Project Title] IS NOT NULL") proj_titles = cur.fetchall() cur.execute("SELECT pmc_id, title FROM publications WHERE title IS NOT NULL") pub_titles = cur.fetchall() THRESHOLD = 85 title_links = 0 for proj_id, pr_title in proj_titles: if not pr_title: continue for pmc_id, pb_title in pub_titles: if not pb_title: continue score = fuzz.token_set_ratio(pr_title, pb_title) if score >= THRESHOLD: conf = score / 100.0 upsert_link(proj_id, pmc_id, "title matching", conf) title_links += 1 conn.commit() cur.execute(""" SELECT l.project_id, p.[Project Title], pub.title, l.confidence FROM links l JOIN projects p ON l.project_id = p.Task_id JOIN publications pub ON l.pmc_id = pub.pmc_id WHERE l.link_type='title matching' ORDER BY l.confidence DESC LIMIT 10 """) for r in cur.fetchall(): print("matched titles:", r) print(f"linked or updated {title_links} TITLE similarity matches") conn.close() print("incremental link matching complete")