aboutsummaryrefslogtreecommitdiffstats
path: root/squashr-tags-integration
blob: b8469b4fb9e24e8356e4514c8eec22aa5dddcda1 (plain) (blame)
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
#!/usr/bin/env python3
"""squashr-tags-integration — Integrate MedMan tags into squashr container dir."""
import argparse, json, os, sqlite3
from datetime import datetime, timezone

def main():
    p = argparse.ArgumentParser(description="Integrate MedMan tags into squashr container")
    p.add_argument("--db", required=True, help="Path to medman.db")
    p.add_argument("--dat", required=True, help="Comma-separated data dirs")
    p.add_argument("--container-dir", required=True, help="Container directory")
    p.add_argument("--output", default="tags.json")
    p.add_argument("--output-path")
    a = p.parse_args()

    if not os.path.isfile(a.db):
        exp = {"ts":datetime.now(timezone.utc).isoformat(),"tags":[],"files":{}}
    else:
        db = sqlite3.connect(a.db); db.row_factory = sqlite3.Row
        rows = db.execute("""SELECT ft.hash,f.didx,f.rel,t.name AS tn FROM ftags ft JOIN tags t ON t.id=ft.tid JOIN files f ON f.hash=ft.hash ORDER BY ft.hash,t.name""").fetchall()
        atags = db.execute("SELECT id,name FROM tags ORDER BY name").fetchall()
        db.close()

        cf = set()
        for dp,_,fns in os.walk(a.container_dir):
            for fn in fns: cf.add(os.path.relpath(os.path.join(dp,fn), a.container_dir))

        ft = {}; matched = 0
        for r in rows:
            if r["rel"] not in cf: continue
            h = r["hash"]
            if h not in ft: ft[h] = {"didx":r["didx"],"tags":[]}; matched += 1
            ft[h]["tags"].append(r["tn"])
        exp = {"ts":datetime.now(timezone.utc).isoformat(),"tags":[dict(t) for t in atags],"files":ft}

    op = a.output_path or os.path.join(a.container_dir, a.output)
    os.makedirs(os.path.dirname(op) or ".", exist_ok=True)
    with open(op,"w") as f: json.dump(exp, f, indent=2)
    print(f"Tags export written to {op}")

if __name__ == "__main__": main()