-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbp
More file actions
executable file
·2068 lines (1810 loc) · 70.3 KB
/
Copy pathbp
File metadata and controls
executable file
·2068 lines (1810 loc) · 70.3 KB
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
bp — Blue Pearmain command-line interface
Usage:
bp pipeline [--dry-run] [--limit N] Sync-metadata then auto-apply non-conflict proposals
bp stats Show photo counts by privacy state
bp poll [--backfill] [--days N] Poll Flickr for new/updated photos
bp scan [--all] [--days N] Scan Apple Photos library
bp thumbs Populate missing thumbnail paths
bp reconcile [--fix] [--limit N] Check DB state vs actual Flickr state
bp link-orphans [--dry-run] Merge split Photos/Flickr records
bp checkpoint [--mode MODE] Checkpoint the WAL file (default: truncate)
bp sync-album-collections [--dry-run] [--remove [--force]] Sync folder hierarchy → Flickr Collections
bp sync-names-from-flickr [--dry-run] Sync Flickr renames → Apple Photos
bp all [--dry-run] Full maintenance run (scan, poll, thumbs, sync-names-from-flickr, pipeline, reconcile, sync-albums, sync-album-collections, checkpoint)
bp install-daemons [--dry-run] Install launchd agents to ~/Library/LaunchAgents
bp uninstall-daemons [--dry-run] Remove installed launchd agents
bp ui Start the review UI (http://localhost:5173)
bp migrate [--dry-run] [--baseline] Apply pending DB migrations (--baseline: mark applied without running DDL)
bp doctor [--check-flickr] Validate config, environment, and DB state
bp import-contacts-birthdays [--dry-run] [--overwrite] Import birthdays from Apple Contacts
Global options:
--config PATH Path to config.yml (default: config/config.yml)
--verbose Extra logging
Run 'bp <subcommand> --help' for subcommand-specific options.
"""
import argparse
import sys
from pathlib import Path
# Ensure the repo root is on the path regardless of where bp is invoked from.
# Use .resolve().parent (resolve symlink FIRST, then get parent) so that invoking
# bp via a symlink (e.g. ~/bin/bp -> /repo/bp) resolves to the repo root, not the
# symlink's parent directory.
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
def cmd_stats(args):
import yaml
from db.db import Database
with open(args.config) as f:
config = yaml.safe_load(f)
db = Database(Path(config["database"]["path"]).expanduser())
s = db.stats()
by_state = s["by_state"]
total = s["total"]
order = [
("candidate_public", "Candidate public"),
("needs_review", "Needs review"),
("approved_public", "Approved public"),
("already_public", "Already public"),
("keep_private", "Keep private"),
("auto_private", "Auto private"),
("skipped", "Skipped"),
("duplicate_flickr", "Duplicate Flickr"),
]
flickr_linked = db.conn.execute(
"SELECT COUNT(*) AS n FROM photos WHERE flickr_id IS NOT NULL"
).fetchone()["n"]
pushed = db.conn.execute(
"""SELECT COUNT(*) AS n FROM photos
WHERE privacy_state = 'approved_public'
AND perms_pushed_flickr = 1"""
).fetchone()["n"]
approved_pushable = db.conn.execute(
"""SELECT COUNT(*) AS n FROM photos
WHERE privacy_state = 'approved_public'
AND flickr_id IS NOT NULL
AND perms_pushed_flickr = 0"""
).fetchone()["n"]
db.close()
if args.oneliner:
short = {
"candidate_public": "cand",
"needs_review": "review",
"approved_public": "approved",
"already_public": "public",
"keep_private": "private",
"auto_private": "auto",
"skipped": "skip",
"duplicate_flickr": "dup",
}
parts = []
for state, _ in order:
n = by_state.get(state, 0)
if n:
parts.append(f"{short[state]}={n}")
parts.append(f"total={total}")
parts.append(f"flickr={flickr_linked}")
parts.append(f"local={total - flickr_linked}")
parts.append(f"pushed={pushed}")
parts.append(f"pushable={approved_pushable}")
print(" ".join(parts))
return
print()
width = max(len(label) for _, label in order)
for state, label in order:
n = by_state.get(state, 0)
if n:
print(f" {label:<{width}} {n:>8,}")
print(f" {'─' * (width + 11)}")
print(f" {'Total':<{width}} {total:>8,}")
print()
print(f" Flickr-linked records: {flickr_linked:>8,}")
print(f" Photos-only records: {total - flickr_linked:>8,}")
print(f" Approved + pushed: {pushed:>8,}")
print(f" Approved + pushable: {approved_pushable:>8,} (Flickr-linked, not yet pushed)")
print()
def _run(fn, args, pairs):
"""Inject argv, call fn(), propagate non-zero exit codes."""
_inject_argv(args, pairs)
try:
result = fn()
if isinstance(result, int) and result != 0:
sys.exit(result)
except SystemExit:
raise
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
def cmd_poll(args):
from poller.poller import main
_run(
main,
args,
[
("--config", args.config),
("--backfill", args.backfill),
("--days", str(args.days) if args.days else None),
("--verbose", args.verbose),
("--dry-run", args.dry_run),
],
)
def cmd_scan(args):
from poller.scanner import main
_run(
main,
args,
[
("--config", args.config),
("--all", args.all),
("--days", str(args.days) if args.days else None),
("--verbose", args.verbose),
("--dry-run", args.dry_run),
],
)
def cmd_thumbs(args):
from poller.thumbnailer import main
_run(
main,
args,
[
("--config", args.config),
("--verbose", args.verbose),
("--icloud", args.icloud),
("--icloud-limit", args.icloud_limit),
],
)
def cmd_pipeline(args):
"""
Run the full metadata sync pipeline without manual steps:
1. bp sync-metadata — diff cached values, generate proposals
2. bp reconcile --apply-proposals — auto-apply all non-conflict proposals
Collision proposals are left pending for manual review in the UI.
"""
import logging
import yaml
from pathlib import Path as _Path
from poller.bp_logging import configure
configure("pipeline", args.verbose)
log = logging.getLogger("blue-pearmain.pipeline")
with open(args.config) as f:
config = yaml.safe_load(f)
db_path = config["database"]["path"]
library_path = str(_Path(config.get("photos_library", {}).get("path", "")).expanduser())
from db.db import Database
db = Database(db_path)
# Step 1: generate proposals for any photos whose cache has drifted
from flickr.sync_metadata import _select_drift_filtered
from flickr.metadata_puller import run_sync_engine
dry_run = getattr(args, "dry_run", False)
photo_ids = _select_drift_filtered(db, limit=0)
if photo_ids:
log.info(
"pipeline: sync-metadata — %d photos to harmonise%s",
len(photo_ids),
" (dry-run)" if dry_run else "",
)
sync_totals = run_sync_engine(db, photo_ids, dry_run=dry_run, verbose=args.verbose)
log.info(
"pipeline: sync-metadata done — proposals=%d hash_matches=%d skipped=%d failed=%d%s",
sync_totals["proposals"],
sync_totals["hash_matches"],
sync_totals["skipped"],
sync_totals["failed"],
" (dry-run: not written)" if dry_run else "",
)
else:
log.info("pipeline: sync-metadata — nothing to harmonise (all in sync)")
sync_totals = {}
# Step 2: auto-apply non-conflict proposals (both tags and title/description)
if dry_run:
from flickr.proposal_applier import _count_pending
pending = _count_pending(db, conflict_types=["non_conflict"])
log.info(
"pipeline: apply skipped (dry-run) — %d pending non-conflict proposal(s) would be applied",
pending,
)
else:
from flickr.proposal_applier import apply_batch
apply_totals = apply_batch(
db,
library_path,
conflict_types=["non_conflict"],
limit=args.limit or 0,
)
log.info(
"pipeline: apply done — applied=%d failed=%d superseded=%d",
apply_totals["applied"],
apply_totals["failed"],
apply_totals["superseded"],
)
db.close()
def cmd_reconcile(args):
from poller.reconcile import main
_run(
main,
args,
[
("--config", args.config),
("--fix", args.fix),
("--apply-proposals", args.apply_proposals),
("--explain", args.explain),
("--limit", str(args.limit) if args.limit is not None else None),
("--verbose", args.verbose),
],
)
def cmd_tag_writeback(args):
from poller.tag_writeback import main
_run(
main,
args,
[
("--config", args.config),
("--dry-run", args.dry_run),
("--limit", str(args.limit) if args.limit is not None else None),
("--verbose", args.verbose),
("--source", args.source),
],
)
def cmd_ui(args):
from reviewer.app import main
_run(
main,
args,
[
("--config", args.config),
("--port", str(args.port)),
("--host", args.host),
("--debug", args.debug),
],
)
def cmd_sync_albums(args):
from flickr.sync_albums import main
_run(
main,
args,
[
("--config", args.config),
("--dry-run", args.dry_run),
("--album", args.album),
("--limit", str(args.limit) if args.limit is not None else None),
("--coalesce", getattr(args, "coalesce", False)),
("--verbose", args.verbose),
],
)
def cmd_sync_album_collections(args):
from flickr.sync_collections import main
_run(
main,
args,
[
("--config", args.config),
("--dry-run", args.dry_run),
("--remove", getattr(args, "remove", False)),
("--force", getattr(args, "force", False)),
("--verbose", args.verbose),
],
)
def cmd_sync_names_from_flickr(args):
from flickr.sync_names_from_flickr import main
_run(
main,
args,
[
("--config", args.config),
("--dry-run", args.dry_run),
("--verbose", args.verbose),
],
)
def cmd_sync_metadata(args):
from flickr.sync_metadata import main
_run(
main,
args,
[
("--config", args.config),
("--dry-run", args.dry_run),
("--limit", str(args.limit) if args.limit is not None else None),
("--photo-id", str(args.photo_id) if args.photo_id else None),
("--conflicts-only", args.conflicts_only),
("--force", args.force),
("--verbose", args.verbose),
],
)
def cmd_link_orphans(args):
from poller.link_orphans import main
_run(
main,
args,
[
("--config", args.config),
("--dry-run", args.dry_run),
("--limit", str(args.limit) if args.limit is not None else None),
("--verbose", args.verbose),
],
)
def cmd_install_daemons(args):
"""Install launchd plist files to ~/Library/LaunchAgents, substituting template tokens."""
import shutil
home = Path.home()
uv = shutil.which("uv")
if not uv:
print("Error: 'uv' not found on PATH.", file=sys.stderr)
sys.exit(1)
plists = [
"com.blue-pearmain.poller.plist",
"com.blue-pearmain.pipeline.plist",
"com.blue-pearmain.reviewer.plist",
"com.blue-pearmain.reconcile.plist",
"com.blue-pearmain.deduplicator.plist",
]
launch_agents = home / "Library" / "LaunchAgents"
if not args.dry_run:
launch_agents.mkdir(parents=True, exist_ok=True)
for plist_name in plists:
src = ROOT / "config" / plist_name
template = src.read_text()
content = (
template.replace("__REPO__", str(ROOT))
.replace("__UV__", uv)
.replace("__HOME__", str(home))
)
dest = launch_agents / plist_name
if args.dry_run:
print(f" would install: {dest}")
else:
dest.write_text(content)
print(f" installed: {dest}")
if not args.dry_run:
print()
print("To load the daemons, run:")
for plist_name in plists:
print(f" launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/{plist_name}")
print()
print("Or reload an already-loaded daemon:")
print(" launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/<name>.plist")
print(" launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/<name>.plist")
def cmd_uninstall_daemons(args):
"""Remove installed launchd plist files from ~/Library/LaunchAgents."""
home = Path.home()
plists = [
"com.blue-pearmain.poller.plist",
"com.blue-pearmain.pipeline.plist",
"com.blue-pearmain.reviewer.plist",
"com.blue-pearmain.reconcile.plist",
"com.blue-pearmain.deduplicator.plist",
]
launch_agents = home / "Library" / "LaunchAgents"
any_found = False
for plist_name in plists:
dest = launch_agents / plist_name
if dest.exists():
any_found = True
if args.dry_run:
print(f" would remove: {dest}")
else:
dest.unlink()
print(f" removed: {dest}")
else:
print(f" not installed: {dest}")
if any_found and not args.dry_run:
print()
print("If the daemons were loaded, unload them with:")
for plist_name in plists:
print(f" launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/{plist_name}")
print()
print("(Ignore 'No such process' errors for daemons that were not running.)")
def cmd_checkpoint(args):
"""Run a WAL checkpoint and report results."""
import yaml
from db.db import Database
with open(args.config) as f:
config = yaml.safe_load(f)
db = Database(Path(config["database"]["path"]).expanduser())
result = db.checkpoint(mode=args.mode.upper())
db.close()
busy = result["busy"]
log = result["log"]
checkpointed = result["checkpointed"]
if log == 0:
print("WAL is empty — nothing to checkpoint.")
elif busy > 0:
print(
f"Checkpoint incomplete: {checkpointed}/{log} frames moved "
f"({busy} frame(s) blocked by active readers). "
f"Run again when the UI and other readers are stopped for a full truncate."
)
else:
print(f"Checkpoint complete: {checkpointed}/{log} frames moved, WAL truncated.")
def cmd_deduplicator(args):
"""Find and classify duplicate photos; optionally write results to DB."""
import yaml
from poller.deduplicator import main as dedup_main
pairs = [("--config", args.config)]
if args.write:
pairs.append(("--write", True))
if args.dry_run:
pairs.append(("--dry-run", True))
if args.confirm:
pairs.append(("--confirm", True))
if args.flickr:
pairs.append(("--flickr", True))
if args.limit is not None:
pairs.append(("--limit", str(args.limit)))
if args.verbose:
pairs.append(("--verbose", True))
if args.prune:
pairs.append(("--prune", True))
if args.apply:
pairs.append(("--apply", True))
_inject_argv(args, pairs)
dedup_main()
def cmd_prune_proposals(args):
"""Prune resolved metadata proposals and supersede spurious managed-tag proposals."""
import yaml
from db.db import Database
with open(args.config) as f:
config = yaml.safe_load(f)
db = Database(Path(config["database"]["path"]).expanduser())
superseded = db.supersede_managed_tag_proposals(dry_run=args.dry_run)
pruned = db.prune_proposals(older_than_days=args.older_than, dry_run=args.dry_run)
db.close()
prefix = "[dry-run] would " if args.dry_run else ""
print(f"{prefix}supersede={superseded} prune={pruned}")
def _inject_argv(args, pairs):
"""Rebuild sys.argv from parsed args so subcommand main()s parse correctly."""
new_argv = [sys.argv[0]]
for flag, value in pairs:
if value is None or value is False:
continue
if value is True:
new_argv.append(flag)
else:
new_argv.extend([flag, str(value)])
sys.argv = new_argv
def _step_args(base, **overrides):
"""Return a copy of base Namespace with overrides applied."""
import argparse as _ap
d = vars(base).copy()
d.update(overrides)
return _ap.Namespace(**d)
def cmd_status(args):
"""Print operational status: daemon state, queue sizes, pending proposals."""
import yaml
from db.db import Database
from poller.status import collect_status, format_status, status_exit_code
config_path = Path(args.config)
if not config_path.exists():
print(f"Error: config file not found: {config_path}", file=sys.stderr)
sys.exit(2)
try:
with open(config_path) as f:
config = yaml.safe_load(f)
except Exception as e:
print(f"Error reading config: {e}", file=sys.stderr)
sys.exit(2)
try:
db = Database(Path(config["database"]["path"]).expanduser())
except Exception as e:
print(f"Error opening database: {e}", file=sys.stderr)
sys.exit(2)
try:
status = collect_status(config, db)
finally:
db.close()
print(format_status(status))
sys.exit(status_exit_code(status))
def cmd_export(args):
"""Export BP database state to portable NDJSON files."""
import yaml
from datetime import date
from db.db import Database
from poller.exporter import collect_export_data, write_export
config_path = Path(args.config)
if not config_path.exists():
print(f"Error: config file not found: {config_path}", file=sys.stderr)
sys.exit(2)
try:
with open(config_path) as f:
config = yaml.safe_load(f)
except Exception as e:
print(f"Error reading config: {e}", file=sys.stderr)
sys.exit(2)
try:
db = Database(Path(config["database"]["path"]).expanduser())
except Exception as e:
print(f"Error opening database: {e}", file=sys.stderr)
sys.exit(2)
out_dir = Path(args.out) if args.out else Path(f"bp-export-{date.today()}")
try:
data = collect_export_data(db)
finally:
db.close()
write_export(data, out_dir)
photo_count = data["manifest"]["photo_count"]
zone_count = data["manifest"]["zone_count"]
print(f"Exported {photo_count} photos and {zone_count} zones → {out_dir}/")
print(f" photos.ndjson (NDJSON — one object per line)")
print(f" zones.json (JSON array)")
print(f" manifest.json (export metadata)")
# ---------------------------------------------------------------------------
# Migration helpers
# ---------------------------------------------------------------------------
def _pending_migrations(
db_path: str,
migrations_dir: Path,
) -> list[tuple[str, Path]]:
"""
Return (migration_name, file_path) pairs for migrations not yet applied to
db_path, sorted by filename (migrate_NNN_... sorts numerically by NNN).
"""
import re
import sqlite3
_name_re = re.compile(r'^MIGRATION_NAME\s*=\s*["\']([^"\']+)["\']', re.MULTILINE)
try:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
applied = {r["name"] for r in conn.execute("SELECT name FROM schema_migrations").fetchall()}
conn.close()
except sqlite3.OperationalError:
# schema_migrations table doesn't exist yet (fresh DB) — treat all as pending
applied = set()
result: list[tuple[str, Path]] = []
for mf in sorted(migrations_dir.glob("migrate_*.py")):
m = _name_re.search(mf.read_text())
if m and m.group(1) not in applied:
result.append((m.group(1), mf))
return result
def cmd_doctor(args):
"""
Validate config, environment, and DB state before running the pipeline.
Prints a pass/fail checklist and exits non-zero if any required check fails.
"""
import sqlite3
import yaml
OK = "✓"
FAIL = "✗"
WARN = "!"
issues = []
def check(symbol, label, detail=""):
line = f" {symbol} {label}"
if detail:
line += f"\n → {detail}"
print(line)
if symbol == FAIL:
issues.append(label)
print()
print("Blue Pearmain — environment check")
print("─" * 40)
# ── 1. Config file ────────────────────────────────────────────────────────
config_path = Path(args.config)
if not config_path.exists():
check(
FAIL,
f"Config file: {config_path}",
"File not found — copy config/config.example.yml to config/config.yml and fill in your values",
)
print()
print("Cannot continue: config file is required for all other checks.")
sys.exit(1)
try:
with open(config_path) as f:
config = yaml.safe_load(f)
check(OK, f"Config file: {config_path}")
except Exception as e:
check(FAIL, f"Config file: {config_path}", f"YAML parse error: {e}")
sys.exit(1)
# ── 2. Required config keys ───────────────────────────────────────────────
def _cfg(*keys, label=None):
val = config
for k in keys:
val = (val or {}).get(k)
display = label or ".".join(keys)
if not val:
check(FAIL, f"Config key {display}", "Missing or empty — check config.yml")
else:
check(OK, f"Config key {display}")
_cfg("database", "path")
_cfg("photos_library", "path")
_cfg("flickr", "api_key")
_cfg("flickr", "api_secret")
_cfg("flickr", "oauth_token")
_cfg("flickr", "oauth_token_secret")
_cfg("photos_library", "self_name", label="photos_library.self_name")
if "photos_library" in config and not config["photos_library"].get("self_name"):
check(
WARN,
"photos_library.self_name is empty — photos of named people will not be filtered as self",
)
# ── 3. Photos library path ────────────────────────────────────────────────
photos_path_raw = (config.get("photos_library") or {}).get("path", "")
if photos_path_raw:
photos_path = Path(photos_path_raw).expanduser()
if photos_path.exists():
check(OK, f"Photos library: {photos_path}")
else:
check(
FAIL,
f"Photos library: {photos_path}",
"Path not found — check photos_library.path in config.yml",
)
# ── 4. Database ───────────────────────────────────────────────────────────
db_path_raw = (config.get("database") or {}).get("path", "")
db_ok = False
if db_path_raw:
db_path = Path(db_path_raw).expanduser()
if not db_path.exists():
check(WARN, f"Database: {db_path}", "File not found — will be created on first run")
db_ok = False
else:
try:
conn = sqlite3.connect(str(db_path))
conn.execute("SELECT 1")
conn.close()
check(OK, f"Database: {db_path}")
db_ok = True
except Exception as e:
check(FAIL, f"Database: {db_path}", f"Cannot open: {e}")
# ── 5. Migrations ─────────────────────────────────────────────────────────
if db_ok:
try:
pending = _pending_migrations(str(db_path), ROOT / "db" / "migrations")
if pending:
for name, _ in pending:
check(WARN, f"Migration not applied: {name}")
config_flag = (
f" --config {args.config}" if args.config != "config/config.yml" else ""
)
print(f" → Run: bp{config_flag} migrate")
else:
conn = sqlite3.connect(str(db_path))
applied = [
r[0]
for r in conn.execute(
"SELECT name FROM schema_migrations ORDER BY name"
).fetchall()
]
conn.close()
last = applied[-1] if applied else "(none)"
check(OK, f"Migrations: all applied (latest: {last})")
except Exception as e:
check(WARN, "Migrations: could not check", str(e))
# ── 6. photoscript importable ─────────────────────────────────────────────
try:
import photoscript # noqa: F401
check(OK, "photoscript: importable")
except ImportError:
check(FAIL, "photoscript: not found", "Run: uv add photoscript")
# ── 7. Flickr credentials ping (opt-in) ───────────────────────────────────
if args.check_flickr:
try:
from flickr.flickr_client import FlickrClient
fc = config.get("flickr", {})
client = FlickrClient(
api_key=fc.get("api_key", ""),
api_secret=fc.get("api_secret", ""),
oauth_token=fc.get("oauth_token", ""),
oauth_token_secret=fc.get("oauth_token_secret", ""),
)
result = client._call("flickr.test.login")
username = result.get("user", {}).get("username", {}).get("_content", "?")
check(OK, f"Flickr credentials: authenticated as {username}")
except Exception as e:
check(FAIL, "Flickr credentials: API call failed", str(e))
# ── Summary ───────────────────────────────────────────────────────────────
print()
if issues:
print(f" {len(issues)} problem(s) found:")
for i in issues:
print(f" {FAIL} {i}")
print()
sys.exit(1)
else:
print(" All checks passed.")
print()
def cmd_migrate(args: argparse.Namespace) -> None:
"""
Auto-discover and apply all pending DB migrations in order.
Safe to re-run — each migration is idempotent.
"""
import importlib.util
import yaml
with open(args.config) as f:
config = yaml.safe_load(f)
db_path = str(Path(config["database"]["path"]).expanduser())
migrations_dir = ROOT / "db" / "migrations"
pending = _pending_migrations(db_path, migrations_dir)
if not pending:
print("All migrations already applied.")
return
dry_run = getattr(args, "dry_run", False)
baseline = getattr(args, "baseline", False)
if baseline:
_baseline_migrations(db_path, pending, dry_run=dry_run)
return
for name, file_path in pending:
if dry_run:
print(f" [dry-run] Would apply: {name}")
else:
print(f" Applying: {name}…")
spec = importlib.util.spec_from_file_location(name, file_path)
module = importlib.util.module_from_spec(spec) # type: ignore[arg-type]
spec.loader.exec_module(module) # type: ignore[union-attr]
module.run(db_path, dry_run=False)
count = len(pending)
if dry_run:
print(f"\n{count} migration(s) would be applied.")
else:
print(f"\n{count} migration(s) applied.")
def _baseline_migrations(
db_path: str,
pending: list[tuple[str, Path]],
*,
dry_run: bool,
) -> None:
"""Record pending migration names as applied WITHOUT running their DDL.
Use once on a live DB whose schema already exists but whose
schema_migrations table is out of sync — avoids re-running destructive
table-rebuild migrations. Idempotent (INSERT OR IGNORE).
"""
import sqlite3
from datetime import datetime, timezone
if dry_run:
for name, _ in pending:
print(f" [dry-run] Would mark applied (baseline): {name}")
print(f"\n{len(pending)} migration(s) would be marked applied (baseline).")
return
conn = sqlite3.connect(db_path)
try:
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations "
"(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, "
"applied_at TEXT NOT NULL)"
)
now = datetime.now(timezone.utc).isoformat()
for name, _ in pending:
print(f" Marking applied (baseline): {name}")
conn.execute(
"INSERT OR IGNORE INTO schema_migrations (name, applied_at) VALUES (?, ?)",
(name, now),
)
conn.commit()
finally:
conn.close()
print(f"\n{len(pending)} migration(s) marked applied (baseline; no DDL run).")
def _resolve_legacy_library_path(args: argparse.Namespace, config: dict) -> str:
"""--library wins; else fall back to optional config legacy_library.path."""
if getattr(args, "library", None):
return str(Path(args.library).expanduser())
cfg = (config.get("legacy_library") or {}).get("path")
if cfg:
return str(Path(cfg).expanduser())
print(
"Error: no library path. Pass --library <path> or set legacy_library.path in config.",
file=sys.stderr,
)
sys.exit(2)
def cmd_index_legacy(args: argparse.Namespace) -> None:
"""Index a legacy (migrated iPhoto/Photos 4) library into curator.db."""
import yaml
sys.path.insert(0, str(ROOT / "poller"))
from db.db import Database
from legacy_indexer import index_library
from bp_logging import configure
configure("legacy-indexer", args.verbose)
with open(args.config) as f:
config = yaml.safe_load(f)
db_path = str(Path(config["database"]["path"]).expanduser())
thumb_root = Path(config["thumbnails"]["path"]).expanduser()
library_path = _resolve_legacy_library_path(args, config)
if not Path(library_path).exists():
print(f"Error: library not found / not mounted: {library_path}", file=sys.stderr)
sys.exit(1)
db = Database(db_path)
try:
stats = index_library(
library_path,
db,
curator_db_path=db_path,
thumb_root=thumb_root,
copy_thumbnails=not args.no_thumbnails,
limit=args.limit,
use_cache=not args.no_cache,
refresh_cache=args.refresh_cache,
)
finally:
db.close()
print(
f"Indexed {stats['indexed']} assets from library {stats['library_uuid']} "
f"(thumbs ok={stats['thumb_ok']} missing={stats['thumb_missing']} "
f"error={stats['thumb_error']}; "
f"{'authoritative, reconciled ' + str(stats['reconciled']) if stats['authoritative'] else 'non-authoritative (--limit), no deletions'})."
)
def cmd_match_legacy(args: argparse.Namespace) -> None:
"""Match legacy assets to Flickr-only candidate_public photos. Preview by
default (no writes); with --apply, reclassify confident (and all-people
ambiguous) matches out of the review queue."""
import csv
import yaml
from collections import defaultdict
sys.path.insert(0, str(ROOT / "poller"))
from db.db import Database
from legacy_match import normalise_wall_clock, order_rows, preview_rows
from legacy_apply import apply_legacy_matches
from analyzer.privacy import CLASSIFIER_VERSION
with open(args.config) as f:
config = yaml.safe_load(f)
db_path = str(Path(config["database"]["path"]).expanduser())
db = Database(db_path)