-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
823 lines (723 loc) · 26.8 KB
/
Copy pathmain.py
File metadata and controls
823 lines (723 loc) · 26.8 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
#!/usr/bin/env python3
"""
main.py — Audiobookshelf Metadata Enricher
Engine that orchestrates:
1. abs.py → fetch books, push updates, track processed
2. utils.py → clean titles, score results, confidence check
3. audible.py → search Audible, get details by ASIN/URL
4. websearch.py → SearXNG fallback when Audible search fails
5. embedding.py → semantic similarity matching (CUDA/CPU)
6. openai_llm.py → LLM picks best match when all else is ambiguous
7. bookinfo.py → Google Books + Open Library fallback for cover/description
Pipeline per book:
Step 1: Search Audible + fuzzy scoring (title/author/narrator/series)
Step 2: LLM picks from Audible results (if LLM_PROVIDER set)
Step 3: Book metadata fallback — Google Books / Open Library (cover + description)
Step 4: Interactive prompt (if -i flag)
.env:
ABS_URL=http://localhost:13378
ABS_TOKEN=your_token
AUDIBLE_REGION=us
SEARXNG_URL=http://localhost:8888 # optional
EMBEDDING_MODEL=all-MiniLM-L6-v2 # optional, set to activate
EMBEDDING_THRESHOLD=0.75 # min cosine similarity
EMBEDDING_DEVICE= # cuda, cpu, or auto
LLM_PROVIDER=openai_llm # optional, set to activate
LLM_BASE_URL=http://localhost:8000/v1
LLM_API_KEY=your_key
LLM_MODEL=your_model_name
Usage:
python main.py # Process all new books
python main.py --force # Reprocess everything
python main.py --author "Tolkien" # Filter by author
python main.py --series "Dune" # Filter by series
python main.py --title "The Hobbit" # Filter by title
python main.py --dry-run # Preview only
python main.py -i # Interactive mode
python main.py -i --force --author "Flanagan"
"""
import argparse
import json
import logging
import os
import re
import sys
import time
from pathlib import Path
try:
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent / ".env")
except ImportError:
pass
import audible
from abs import ABSClient, ProcessedTracker
from utils import clean_title, pick_best, score_result, is_confident
from websearch import find_audible_asins
# ============================================================
# Config
# ============================================================
ABS_URL = os.environ.get("ABS_URL", "")
ABS_TOKEN = os.environ.get("ABS_TOKEN", "")
AUDIBLE_REGION = os.environ.get("AUDIBLE_REGION", "us")
SEARXNG_URL = os.environ.get("SEARXNG_URL", "")
LLM_PROVIDER = os.environ.get("LLM_PROVIDER", "")
LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "")
LLM_API_KEY = os.environ.get("LLM_API_KEY", "")
LLM_MODEL = os.environ.get("LLM_MODEL", "")
LLM_MAX_TOKENS = int(os.environ.get("LLM_MAX_TOKENS", "256"))
LLM_TIMEOUT = int(os.environ.get("LLM_TIMEOUT", "120"))
EMBEDDING_MODEL = os.environ.get("EMBEDDING_MODEL", "")
EMBEDDING_THRESHOLD = float(os.environ.get("EMBEDDING_THRESHOLD", "0.75"))
EMBEDDING_DEVICE = os.environ.get("EMBEDDING_DEVICE", "")
LANGUAGE = os.environ.get("LANGUAGE", "english")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.StreamHandler(),
logging.FileHandler(Path(__file__).parent / "enrich.log"),
],
)
log = logging.getLogger(__name__)
# ============================================================
# LLM Dispatch
# ============================================================
def llm_pick(title: str, author: str, results: list) -> tuple[int | None, str]:
"""
Ask the configured LLM to pick the best match.
Returns (index, reason). index is None on any failure.
"""
provider = LLM_PROVIDER.lower().strip()
if not provider:
return None, "not_configured: LLM_PROVIDER not set"
if provider == "openai_llm":
import openai_llm
return openai_llm.pick_best_match(
title, author, results,
base_url=LLM_BASE_URL,
api_key=LLM_API_KEY,
model=LLM_MODEL,
max_tokens=LLM_MAX_TOKENS,
timeout=LLM_TIMEOUT,
language=LANGUAGE,
)
return None, f"not_configured: unknown LLM_PROVIDER '{provider}'"
def llm_identify(title: str, author: str) -> tuple[str | None, str | None, str]:
"""
Ask the LLM to identify what book a partial/chapter title belongs to.
Returns (book_title, book_author, reason).
"""
provider = LLM_PROVIDER.lower().strip()
if not provider:
return None, None, "not_configured"
if provider == "openai_llm":
import openai_llm
return openai_llm.identify_book(
title, author,
base_url=LLM_BASE_URL,
api_key=LLM_API_KEY,
model=LLM_MODEL,
max_tokens=LLM_MAX_TOKENS,
timeout=LLM_TIMEOUT,
language=LANGUAGE,
)
return None, None, "not_configured"
# ============================================================
# Embedding Dispatch
# ============================================================
def embedding_pick(title: str, author: str, results: list) -> tuple[int | None, float, str]:
"""
Use embedding model to find best match by semantic similarity.
Returns (index, score, reason).
"""
if not EMBEDDING_MODEL:
return None, 0.0, "not_configured"
try:
import embedding
except ImportError:
return None, 0.0, "import_error: sentence-transformers not installed"
try:
idx, score = embedding.pick_best_match(
title, author, results,
model_name=EMBEDDING_MODEL,
threshold=EMBEDDING_THRESHOLD,
device=EMBEDDING_DEVICE,
)
if idx is not None:
return idx, score, "matched"
return None, score, "below_threshold"
except Exception as e:
return None, 0.0, f"error: {e}"
# ============================================================
# Result Merging
# ============================================================
def merge_results(target: list, new: list):
"""Merge new results into target, deduplicating by ASIN."""
seen = {r.get("asin") for r in target if r.get("asin")}
for r in new:
asin = r.get("asin")
if asin and asin not in seen:
target.append(r)
seen.add(asin)
elif not asin:
target.append(r)
# ============================================================
# Search Pipeline
# ============================================================
def search_pipeline(
title: str,
author: str,
regions: list[str],
searxng_url: str = "",
narrator: str = "",
series: str = "",
) -> tuple[list, int | None]:
"""
Run the full search pipeline. Returns (all_results, best_index).
best_index is None if no auto-match found.
"""
all_results = []
cleaned = clean_title(title)
primary = regions[0] if regions else "us"
kw = {"narrator": narrator, "series": series}
# --- Step 1: Full title + author, primary region ---
log.debug(f" Step 1: '{title} {author}' [{primary}]")
results = audible.search(f"{title} {author}", region=primary)
idx = pick_best(title, author, results, **kw)
if idx is not None:
return results, idx
merge_results(all_results, results)
# --- Step 2: Cleaned title + author, primary region ---
if cleaned != title:
log.debug(f" Step 2: '{cleaned} {author}' [{primary}]")
results = audible.search(f"{cleaned} {author}", region=primary)
idx = pick_best(cleaned, author, results, **kw)
if idx is not None:
merge_results(all_results, results)
idx = pick_best(cleaned, author, all_results, **kw)
if idx is not None:
return all_results, idx
else:
merge_results(all_results, results)
# --- Step 3: Cleaned title + author, all regions ---
for region in regions:
if region == primary and cleaned == title:
continue
query = f"{cleaned} {author}" if cleaned != title else f"{title} {author}"
if region == primary:
query = cleaned
log.debug(f" Step 3: '{query}' [{region}]")
results = audible.search(query, region=region)
idx = pick_best(cleaned or title, author, results, **kw)
if idx is not None:
merge_results(all_results, results)
idx = pick_best(cleaned or title, author, all_results, **kw)
if idx is not None:
return all_results, idx
else:
merge_results(all_results, results)
# --- Step 4: SearXNG fallback ---
if searxng_url:
for query in [f"{title} {author} audiobook", f"{cleaned} {author} audiobook"]:
log.debug(f" Step 4: SearXNG '{query}'")
web_hits = find_audible_asins(query, searxng_url=searxng_url)
for hit in web_hits:
existing = {r.get("asin") for r in all_results}
if hit["asin"] in existing:
continue
book = audible.get_by_asin(
hit["asin"], region=hit.get("region", "us"))
if book:
all_results.append(book)
if is_confident(cleaned or title, author, book, **kw):
idx = len(all_results) - 1
return all_results, idx
time.sleep(0.3)
return all_results, None
# ============================================================
# User Interaction
# ============================================================
def show_results(results: list):
"""Display search results."""
if not results:
print(" (no results)")
return
for i, r in enumerate(results):
parts = [f" [{i}] {r.get('title', '?')}"]
if r.get("author"):
parts.append(f"by {r['author']}")
if r.get("narrator"):
parts.append(f"(narr. {r['narrator']})")
if r.get("series"):
seq = r.get("series_sequence", "")
parts.append(f"[{r['series']}{' #' + seq if seq else ''}]")
if r.get("runtime"):
parts.append(f"- {r['runtime']}")
print(" ".join(parts))
def prompt_user(
title: str,
author: str,
results: list,
regions: list[str],
) -> dict | None:
"""Interactive prompt. Returns chosen result dict or None to skip."""
while True:
print(f"\n--- No auto-match for: \"{title}\" by {author} ---")
show_results(results)
print()
print(" [0-9] Pick a result")
print(" [s] Search Audible with custom query")
print(" [a] Enter ASIN directly")
print(" [k] Skip this book")
print(" [q] Quit")
choice = input("\n> ").strip().lower()
if choice == 'q':
sys.exit(0)
elif choice == 'k':
return None
elif choice == 'a':
asin = input(" ASIN: ").strip().upper()
if not re.match(r'^[A-Z0-9]{10}$', asin):
print(" Invalid ASIN (10 alphanumeric chars)")
continue
for region in regions:
book = audible.get_by_asin(asin, region=region)
if book:
print(f" Found: {book.get('title', asin)}")
return book
print(" ASIN not found on any region.")
elif choice == 's':
query = input(" Search: ").strip()
if not query:
continue
region_input = input(f" Region [{regions[0]}]: ").strip().lower()
region = region_input if region_input in audible.REGIONS else regions[0]
new_results = audible.search(query, region=region)
if new_results:
# Replace results with new search
results = new_results
show_results(results)
else:
print(" No results.")
elif choice.isdigit():
idx = int(choice)
if 0 <= idx < len(results):
return results[idx]
print(f" Pick 0-{len(results) - 1}")
else:
print(" Invalid option")
# ============================================================
# Metadata Application
# ============================================================
def build_update(match: dict, details: dict) -> tuple[dict, str | None]:
"""Build ABS metadata dict from match + details."""
merged = {**match, **details}
update = {}
for src, dst in [
("title", "title"),
("author", "authorName"),
("narrator", "narratorName"),
("description", "description"),
("publisher", "publisher"),
("asin", "asin"),
("language", "language"),
]:
if merged.get(src):
update[dst] = merged[src]
if merged.get("genres"):
update["genres"] = merged["genres"]
if merged.get("series"):
update["series"] = [{
"name": merged["series"],
"sequence": merged.get("series_sequence", ""),
}]
return update, merged.get("cover_url")
def apply_to_abs(
abs_client: ABSClient,
item_id: str,
title: str,
match: dict,
dry_run: bool = False,
) -> bool:
"""Fetch details from Audible page and push update to ABS."""
details = {}
if match.get("url"):
details = audible.get_details(match["url"])
time.sleep(0.5)
update, cover_url = build_update(match, details)
if dry_run:
preview = {k: v for k, v in {**match, **details}.items()
if k in ("title", "author", "narrator", "series",
"series_sequence", "asin", "cover_url")}
log.info(f" [DRY RUN] Would update:\n{json.dumps(preview, indent=2)}")
return True
if update:
ok, msg = abs_client.update_metadata(item_id, update)
if ok:
log.info(f" Updated metadata: {title}")
else:
log.error(f" Failed metadata: {msg}")
return False
if cover_url:
if abs_client.set_cover(item_id, cover_url):
log.info(f" Updated cover: {title}")
else:
log.warning(f" Failed cover: {title}")
return True
# ============================================================
# Book Metadata Fallback
# ============================================================
def _book_metadata_fallback(title: str, author: str, narrator: str = "") -> dict | None:
"""
Search Google Books + Open Library for cover/description when Audible fails.
Returns a result dict or None if nothing confident found.
"""
try:
from bookinfo import search_book_metadata
except ImportError:
return None
cleaned = clean_title(title)
query_title = cleaned if cleaned != title else title
results = search_book_metadata(query_title, author)
if not results:
return None
# Use pick_best with a lower threshold — we just want cover + description,
# not a perfect audiobook edition match
idx = pick_best(query_title, author, results,
threshold=8, narrator=narrator)
if idx is not None:
return results[idx]
# If scoring didn't work, just take the first result that has a cover
# and either title or author matches
for r in results:
if not r.get("cover_url"):
continue
from utils import titles_match, names_match
if titles_match(query_title, r.get("title", "")):
if not author or names_match(author, r.get("author", "")):
return r
return None
# ============================================================
# Book Info Extraction & Filtering
# ============================================================
def extract_book_info(item: dict) -> dict:
"""Pull title, author, narrator, series from an ABS library item."""
meta = item.get("media", {}).get("metadata", {})
author = meta.get("authorName", "")
if not author and meta.get("authors"):
author = meta["authors"][0].get("name", "")
narrator = meta.get("narratorName", "")
if not narrator and meta.get("narrators"):
narrators = meta["narrators"]
if isinstance(narrators, list) and narrators:
narrator = narrators[0].get("name", "") if isinstance(
narrators[0], dict) else str(narrators[0])
series = ""
if meta.get("series") and isinstance(meta["series"], list) and meta["series"]:
series = meta["series"][0].get("name", "")
return {
"id": item["id"],
"title": meta.get("title", "Unknown"),
"author": author,
"narrator": narrator,
"series": series,
}
def matches_filter(info: dict, f_author=None, f_series=None, f_title=None) -> bool:
if f_author and f_author.lower() not in info["author"].lower():
return False
if f_series and f_series.lower() not in info["series"].lower():
return False
if f_title and f_title.lower() not in info["title"].lower():
return False
return True
# ============================================================
# Main Engine
# ============================================================
def run(
abs_client: ABSClient,
tracker: ProcessedTracker,
regions: list[str],
searxng_url: str = "",
library: str = None,
f_author: str = None,
f_series: str = None,
f_title: str = None,
dry_run: bool = False,
force: bool = False,
interactive: bool = False,
items: list = None,
delay: float = 1,
):
if items is None:
items = abs_client.get_all_books(library)
log.info(f"Found {len(items)} items")
stats = {"total": 0, "matched": 0,
"skipped": 0, "no_match": 0, "failed": 0}
for item in items:
info = extract_book_info(item)
if not matches_filter(info, f_author, f_series, f_title):
continue
stats["total"] += 1
if not force and tracker.is_done(info["id"]):
log.info(f" Skipping (processed): {info['title']}")
stats["skipped"] += 1
continue
log.info(f"Processing: {info['title']} by {info['author']}")
# Run search pipeline (fuzzy scoring)
all_results, best_idx = search_pipeline(
info["title"], info["author"], regions,
searxng_url=searxng_url,
narrator=info.get("narrator", ""),
series=info.get("series", ""),
)
# Step 1: Got an auto-match from fuzzy scoring
if best_idx is not None:
match = all_results[best_idx]
log.info(
f" Matched: {match.get('title')} by {match.get('author', '?')}")
if apply_to_abs(abs_client, info["id"], info["title"], match, dry_run):
tracker.mark(
info["id"],
"matched" if not dry_run else "dry_run",
match.get("title", ""),
)
stats["matched"] += 1
else:
tracker.mark(info["id"], "failed")
stats["failed"] += 1
time.sleep(delay)
continue
# Step 2: LLM picks from Audible results
if all_results:
llm_idx, llm_reason = llm_pick(
info["title"], info["author"], all_results)
if llm_idx is not None:
match = all_results[llm_idx]
log.info(
f" LLM matched: {match.get('title')} by {match.get('author', '?')}")
if apply_to_abs(abs_client, info["id"], info["title"], match, dry_run):
tracker.mark(
info["id"],
"matched_llm" if not dry_run else "dry_run_llm",
match.get("title", ""),
)
stats["matched"] += 1
else:
tracker.mark(info["id"], "failed")
stats["failed"] += 1
time.sleep(delay)
continue
else:
if llm_reason.startswith("not_configured"):
log.debug(f" LLM skipped: {llm_reason}")
elif llm_reason.startswith("connection_error"):
log.error(f" LLM unreachable: {llm_reason}")
elif llm_reason.startswith("http_"):
log.error(f" LLM API error: {llm_reason}")
elif llm_reason == "none":
log.info(
f" LLM says no match in {len(all_results)} results")
elif llm_reason.startswith("invalid_response"):
log.warning(f" LLM bad response: {llm_reason}")
elif llm_reason.startswith("empty_response"):
log.warning(f" LLM empty response: {llm_reason}")
else:
log.warning(f" LLM failed: {llm_reason}")
# Step 3: LLM identifies the book, then re-search Audible
id_title, id_author, id_reason = llm_identify(
info["title"], info["author"])
if id_title:
log.info(
f" LLM identified as: \"{id_title}\" by {id_author or '?'}")
# Search Audible with the identified title
id_results = []
for region in regions:
r = audible.search(
f"{id_title} {id_author or ''}", region=region)
merge_results(id_results, r)
if id_results:
# Try fuzzy scoring first
idx = pick_best(id_title, id_author or info["author"], id_results,
narrator=info.get("narrator", ""), series=info.get("series", ""))
if idx is not None:
match = id_results[idx]
log.info(
f" Re-search matched: {match.get('title')} by {match.get('author', '?')}")
if apply_to_abs(abs_client, info["id"], info["title"], match, dry_run):
tracker.mark(info["id"],
"matched_identified" if not dry_run else "dry_run_identified",
match.get("title", ""))
stats["matched"] += 1
else:
tracker.mark(info["id"], "failed")
stats["failed"] += 1
time.sleep(delay)
continue
# Try LLM pick on re-search results
llm_idx2, llm_reason2 = llm_pick(
id_title, id_author or info["author"], id_results)
if llm_idx2 is not None:
match = id_results[llm_idx2]
log.info(
f" Re-search LLM matched: {match.get('title')} by {match.get('author', '?')}")
if apply_to_abs(abs_client, info["id"], info["title"], match, dry_run):
tracker.mark(info["id"],
"matched_identified_llm" if not dry_run else "dry_run_identified_llm",
match.get("title", ""))
stats["matched"] += 1
else:
tracker.mark(info["id"], "failed")
stats["failed"] += 1
time.sleep(delay)
continue
else:
log.info(
f" Re-search: LLM still no match in {len(id_results)} results")
elif id_reason == "unknown":
log.info(f" LLM could not identify the book")
elif id_reason != "not_configured":
log.debug(f" LLM identify: {id_reason}")
# Step 4: Book metadata fallback (Google Books / Open Library)
book_fallback = _book_metadata_fallback(
info["title"], info["author"], info.get("narrator", ""),
)
if book_fallback is not None:
log.info(
f" Book metadata fallback: {book_fallback.get('title', '?')} from {book_fallback.get('source', '?')}")
if apply_to_abs(abs_client, info["id"], info["title"], book_fallback, dry_run):
tracker.mark(
info["id"],
"matched_bookinfo" if not dry_run else "dry_run_bookinfo",
book_fallback.get("title", ""),
)
stats["matched"] += 1
else:
tracker.mark(info["id"], "failed")
stats["failed"] += 1
time.sleep(delay)
continue
# No auto-match, LLM failed, no book fallback — try interactive
if interactive:
picked = prompt_user(
info["title"], info["author"], all_results, regions)
if picked:
if apply_to_abs(abs_client, info["id"], info["title"], picked, dry_run):
tracker.mark(
info["id"], "matched_interactive", picked.get("title", ""))
stats["matched"] += 1
else:
tracker.mark(info["id"], "failed")
stats["failed"] += 1
else:
tracker.mark(info["id"], "skipped_interactive")
stats["no_match"] += 1
time.sleep(delay)
continue
# No match, not interactive
log.warning(f" No match: {info['title']}")
tracker.mark(info["id"], "no_match")
stats["no_match"] += 1
time.sleep(delay)
# Summary
log.info("=" * 50)
log.info("Enrichment Complete")
log.info(f" Total: {stats['total']}")
log.info(f" Matched: {stats['matched']}")
log.info(f" Skipped: {stats['skipped']}")
log.info(f" No Match: {stats['no_match']}")
log.info(f" Failed: {stats['failed']}")
log.info("=" * 50)
return stats
# ============================================================
# Test Data Loader
# ============================================================
def load_testdb(path: Path = None) -> list:
"""
Load test database JSON and convert to ABS item format.
Each entry gets the same structure as abs_client.get_all_books() returns.
Test metadata (_test, _difficulty) is preserved for the caller.
"""
if path is None:
path = Path(__file__).parent / "testdb.json"
data = json.loads(path.read_text())
items = []
for book in data["books"]:
meta = {"title": book["title"]}
if book.get("author"):
meta["authorName"] = book["author"]
if book.get("series"):
meta["series"] = [{"name": book["series"], "sequence": ""}]
items.append({
"id": book["id"],
"media": {"metadata": meta},
"_test": book.get("expected", {}),
"_difficulty": book.get("difficulty", ""),
})
return items
# ============================================================
# CLI
# ============================================================
def main():
p = argparse.ArgumentParser(
description="Enrich Audiobookshelf metadata from Audible")
p.add_argument("--abs-url", default=ABS_URL)
p.add_argument("--abs-token", default=ABS_TOKEN)
p.add_argument("--region", default=AUDIBLE_REGION,
help="Primary Audible region (default from env)")
p.add_argument("--searxng-url", default=SEARXNG_URL,
help="SearXNG instance URL (set empty to disable)")
p.add_argument("--library", default=None, help="Process only this library")
p.add_argument("--author", default=None, help="Filter by author (partial)")
p.add_argument("--series", default=None, help="Filter by series (partial)")
p.add_argument("--title", default=None, help="Filter by title (partial)")
p.add_argument("--dry-run", action="store_true",
help="Preview without changes")
p.add_argument("--force", action="store_true", help="Reprocess all")
p.add_argument("--interactive", "-i", action="store_true",
help="Prompt on failures")
p.add_argument("--testing", action="store_true",
help="Use testdb.json instead of ABS. Forces dry-run.")
p.add_argument("--testdb", default=None,
help="Path to test database JSON (default: testdb.json)")
args = p.parse_args()
testing = args.testing
if not testing and (not args.abs_url or not args.abs_token):
print("Error: ABS_URL and ABS_TOKEN required (set in .env or pass as args)")
sys.exit(1)
# Build region list
regions = [args.region]
for r in ["us", "uk"]:
if r not in regions:
regions.append(r)
if testing:
testdb_path = Path(args.testdb) if args.testdb else None
items = load_testdb(testdb_path)
log.info(f"Testing mode: loaded {len(items)} items")
abs_client = None
tracker = ProcessedTracker(
Path(__file__).parent / "processed_test.json")
dry_run = True
delay = 0
else:
items = None
abs_client = ABSClient(args.abs_url, args.abs_token)
tracker = ProcessedTracker(Path(__file__).parent / "processed.json")
dry_run = args.dry_run
delay = 1
run(
abs_client=abs_client,
tracker=tracker,
regions=regions,
searxng_url=args.searxng_url or "",
library=args.library,
f_author=args.author,
f_series=args.series,
f_title=args.title,
dry_run=dry_run,
force=args.force,
interactive=args.interactive,
items=items,
delay=delay,
)
if __name__ == "__main__":
main()