-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcliclo.py
More file actions
2298 lines (2063 loc) · 110 KB
/
Copy pathcliclo.py
File metadata and controls
2298 lines (2063 loc) · 110 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
"""
CLICLO v5.1 - Command Line Interface Comic Library Organizer
Automated comic metadata tagging via ComicTagger's CLI.
THE THREE-PASS PIPELINE (v5.1):
Pass 1 (default run) High-confidence auto-tag. The bulk of a library.
Pass 2 (--auto-retry) Automated re-match of the leftover queue: drops the
year, searches by series name, KEEPS the confidence
bar. Recovers files the primary missed on a parse quirk.
Pass 3 (--review) Human-adjudicated. Hands you ComicTagger's native
candidate list per file (-i); you pick a number or skip.
Not data entry; you decide conflicts. Resumable, and it
refuses to run without a real terminal so it cannot hang.
The historical "-i hangs forever" problem was a plumbing bug: capturing output
pipes stdin, so ComicTagger's input() blocks. Pass 3 inherits the real terminal
instead of capturing, which is why it works.
WHAT CHANGED FROM v4.0 (the short version):
- Result parsing no longer greps English log strings. It reads ComicTagger's
structured JSON (-j) and switches on the Status / MatchStatus enums. This is
version-proof; the old approach broke every time ComicTagger reworded a log line.
- Executable discovery falls back to PATH (shutil.which), so a `pip install`
ComicTagger is found, not just a downloaded binary in a fixed folder.
- Database migrates from v3.2 / v4.0 schemas in place, AND backs the old file up
first (db.bak-vN-timestamp) so a botched migration is recoverable.
- Large-network-file copy can no longer hang forever; it runs under a watchdog
timeout instead of a blocking shutil.copy2.
- Resume is correct and cheap: every file ComicTagger has seen lands in the DB
with a status, and each status has its own reprocessing path. The primary scan
skips anything already seen with a single in-memory set, not one query per file.
- Proactive rate-limit pauses now notify Pushover (once per pause), so a throttled
run doesn't look like a silent hang on your phone.
- Credentials are no longer hardcoded. Put them in cliclo.ini (run --init-config)
or in environment variables. Safe to publish.
- tag_format is validated; only CR is a valid --tags-write value in stock 1.6.x.
- -m metadata is YAML-escaped properly (survives apostrophes in series names).
- Pushover stops retrying on 4xx responses (the API says they will never succeed).
Verified against ComicTagger 1.6.0b9 (the 1.6.x line; 1.6.0 is still beta as of
this writing and `pip install comictagger` returns the incompatible 1.5.x CLI).
Requirements:
pip install requests
ComicTagger 1.6.0-beta.x (pip install --pre comictagger, or a 1.6 beta build)
"""
import os
import re
import sys
import time
import json
import shutil
import sqlite3
import logging
import platform
import tempfile
import argparse
import threading
import configparser
import subprocess
import dataclasses
from pathlib import Path
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Set
# ---------------------------------------------------------------------------
# Platform-aware file locking
# ---------------------------------------------------------------------------
if platform.system() == "Windows":
import msvcrt
def _lock_file(fh):
msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
def _unlock_file(fh):
try:
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
except OSError:
pass
else:
import fcntl
def _lock_file(fh):
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
def _unlock_file(fh):
try:
fcntl.flock(fh, fcntl.LOCK_UN)
except OSError:
pass
logger = logging.getLogger("cliclo")
VERSION = "5.1.3"
SCHEMA_VERSION = 6
BANNER_WIDTH = 63
_LETTERS = [
" ██████╗██╗ ██╗ ██████╗██╗ ██████╗",
"██╔════╝██║ ██║██╔════╝██║ ██╔═══██╗",
"██║ ██║ ██║██║ ██║ ██║ ██║",
"██║ ██║ ██║██║ ██║ ██║ ██║",
"╚██████╗███████╗██║╚██████╗███████╗╚██████╔╝",
" ╚═════╝╚══════╝╚═╝ ╚═════╝╚══════╝ ╚═════╝",
]
def _supports_color() -> bool:
"""ANSI color only when it's safe: a real TTY, NO_COLOR unset, and on Windows the
virtual-terminal mode can be switched on. Otherwise we print plain so escape codes
never end up as garbage in a pipe or a dumb console."""
if os.environ.get("NO_COLOR") or os.environ.get("CLICLO_NO_COLOR"):
return False
if not sys.stdout.isatty():
return False
if os.name == "nt":
try:
import ctypes
k = ctypes.windll.kernel32
k.SetConsoleMode(k.GetStdHandle(-11), 7) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
except Exception:
return False
return True
def print_banner():
"""Print the startup banner: centered ANSI-shadow CLICLO, retro color, pulp copy.
Falls back to a plain header if the console can't encode the box-drawing glyphs."""
W = BANNER_WIDTH
color = _supports_color()
def c(s, code):
return f"\033[{code}m{s}\033[0m" if (color and s.strip()) else s
RED, CYAN, BORDER = "38;5;196;1", "38;5;51", "38;5;44"
YELLOW, CREAM, MAGENTA, STAR = "38;5;220;1", "38;5;230", "38;5;205;1", "38;5;226;1"
def ctr(s):
return " " * ((W - len(s)) // 2) + s
def box(s, code):
inner = W - 2
s = s[:inner]
left = (inner - len(s)) // 2
right = inner - len(s) - left
return c("║", BORDER) + " " * left + c(s, code) + " " * right + c("║", BORDER)
top = c("╔" + "═" * (W - 2) + "╗", BORDER)
bot = c("╚" + "═" * (W - 2) + "╝", BORDER)
lines = [""]
for r in _LETTERS:
lines.append(c(ctr(r.ljust(44)), RED))
lines.append(c(ctr(f"v{VERSION} \u00b7 COMMAND-LINE COMIC LIBRARY ORGANIZER"), CYAN))
lines.append(c(ctr("\u2605 ASTOUNDING TALES OF AUTOMATION \u2605"), STAR))
lines.append("")
lines.append(top)
lines.append(box("", CREAM))
lines.append(box('"THIRTY THOUSAND ISSUES LANGUISH IN DIGITAL DARKNESS,', YELLOW))
lines.append(box('AND ONE COMMAND LINE ANSWERS THE CALL!"', YELLOW))
lines.append(box("", CREAM))
lines.append(box("DEVOURS CBR AND CBZ RESUMES FROM ANY CRASH", CREAM))
lines.append(box("BRANDS EACH ISSUE TRUE RESURRECTS THE CORRUPTED", CREAM))
lines.append(box("OUTRUNS THE RATE-LIMITER SUMMONS YOU FOR HARD CALLS", CREAM))
lines.append(box("", CREAM))
lines.append(box("\u2605 WHERE ORDER MEETS RELENTLESS PRECISION \u2605", MAGENTA))
lines.append(bot)
lines.append("")
try:
print("\n".join(lines))
except (UnicodeEncodeError, OSError):
print(f"\n=== CLICLO v{VERSION} - Command Line Interface Comic Library Organizer ===\n")
# ComicTagger 1.6.x result.status values (comictaggerlib/resulttypes.py: Status)
CT_STATUS_SUCCESS = {"success", "existing_tags"}
CT_STATUS_PERMANENT = {"read_failure", "write_permission_failure"}
# ComicTagger MatchStatus values: good_match, no_match, multiple_match, low_confidence_match
# Strings that, in a fetch_data_failure, indicate the velocity / hourly limit.
# These are matched as substrings of ComicTagger's raw output, which includes the
# file path — so they must be specific. A bare "107" or "420" would misclassify any
# fetch failure on a file like "Batman 107.cbz" as a rate limit.
RATE_LIMIT_SIGNALS = ("rate limit", "slow down", "status_code\": 107", "http 420")
# ---------------------------------------------------------------------------
# Defaults. Credentials are intentionally blank: set them in cliclo.ini
# (run --init-config to scaffold one) or via CLICLO_* environment variables.
# ---------------------------------------------------------------------------
DEFAULTS = {
"comictagger_path": "", # blank => discover on PATH via shutil.which
"comics_path": "",
"comicvine_api_key": "",
# EXPERIMENTAL, OFF BY DEFAULT. Comma-separated extra ComicVine keys. When set
# (more than one key total), CLICLO rotates to a key with remaining hourly budget,
# roughly multiplying throughput by the number of keys. This very likely violates
# ComicVine's per-user rate limit and may get your keys AND your IP banned, since
# all requests originate from one machine. Use entirely at your own risk.
"comicvine_api_keys": "",
# ComicVine allows 200 requests PER RESOURCE per hour (volumes and issues are
# separate buckets) plus velocity detection (~1 req/sec). One auto-tag makes
# several requests. We budget hourly conservatively; ComicTagger paces sub-second
# internally and caches series data on disk, so real consumption is usually lower.
"safe_invocations_per_hour": "50",
"api_calls_per_invocation": "4",
"max_retries": "3",
"tag_format": "CR", # CR is the only valid --tags-write value in stock 1.6.x
# When a normal conversion fails on a recoverable problem (corrupt per-file timestamp,
# a container ComicTagger won't identify), try a tolerant repack: extract the pages with
# independent tooling and write a fresh CBZ with reset metadata. All-or-nothing; never
# produces a comic missing pages. Set false to disable and just skip failed files.
"repair_failed_archives": "true",
# Optional HTTP/HTTPS proxy for ComicTagger's ComicVine requests, e.g.
# http://192.168.1.10:8118. Routes online calls through the proxy via the standard
# HTTP(S)_PROXY env vars. NOTE: a proxy on your own LAN egresses through the same
# internet connection, so ComicVine still sees your same public IP; it changes
# nothing about rate limits unless the proxy is chained upstream to a VPN/Tor/etc.
"proxy": "",
# EXPERIMENTAL, OFF BY DEFAULT. With a proxy set and more than one key, bind each key
# to its own egress (key 1 -> direct, key 2 -> proxy, ...) so each key always exits the
# same IP and looks like a separate user. Only meaningful if the proxy is a genuinely
# different public IP (chained to a VPN/Tor); verify with `curl -x <proxy> ifconfig.me`.
# This is deliberate IP rotation to get around a per-user limit; own the ban risk.
"rotate_egress": "false",
"db_path": "cliclo_progress.db",
"pushover_api_token": "",
"pushover_user_key": "",
"pushover_device": "",
"pushover_enabled": "true",
}
CONFIG_FILE = "cliclo.ini"
CONFIG_DIR_LOG = "cliclo.log"
CONFIG_DIR_DB = "cliclo_progress.db"
def default_state_dir() -> str:
"""Return the platform-appropriate per-user state directory for CLICLO.
Follows the XDG Base Directory spec on Linux, the OS-native locations on
macOS and Windows, and falls back to a dotfile in $HOME if none of the
usual env vars are set (e.g. stripped container). Created-on-demand by the
caller; this function does NOT mkdir.
"""
# XDG_CONFIG_HOME wins if set, even on macOS/Windows — explicit is explicit.
xdg = os.environ.get("XDG_CONFIG_HOME")
if xdg:
return os.path.join(xdg, "cliclo")
if sys.platform == "darwin":
return os.path.expanduser("~/Library/Application Support/CLICLO")
if sys.platform == "win32":
local = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~")
return os.path.join(local, "CLICLO")
# Linux/BSD/etc.: ~/.config/cliclo
return os.path.expanduser("~/.config/cliclo")
def resolve_state_dir(args) -> str:
"""Pick the state directory for this run.
Resolution order:
1. Explicit --config-dir (highest priority).
2. CWD if any legacy state file (`cliclo.ini`, `cliclo_progress.db`,
`comic_tagger_progress.db`) already lives there — preserves the
pre-v5.1.2 behavior for users upgrading in place.
3. The platform default (see ``default_state_dir``).
"""
if getattr(args, "config_dir", None):
return os.path.abspath(args.config_dir)
for legacy in (CONFIG_FILE, CONFIG_DIR_DB, "comic_tagger_progress.db"):
if os.path.exists(legacy):
return os.getcwd()
return default_state_dir()
def resolve_config_path(args, state_dir: str) -> str:
"""Pick the cliclo.ini path: --config wins, else state_dir/cliclo.ini.
Falls back to legacy CWD ``cliclo.ini`` when present (existing users
upgrading in place) so we never silently strand an existing config.
"""
explicit = getattr(args, "config", None)
# argparse default is CONFIG_FILE (which is the bare filename "cliclo.ini"),
# so a None-or-equal-to-default means "not set on the command line".
if explicit and explicit != CONFIG_FILE:
return explicit
legacy_cwd = os.path.join(os.getcwd(), CONFIG_FILE)
if os.path.exists(legacy_cwd):
return legacy_cwd
return os.path.join(state_dir, CONFIG_FILE)
def resolve_db_path(args, config: dict, state_dir: str) -> str:
"""Pick the progress DB path: explicit --db-path wins, else config, else state-dir default.
``config["db_path"]`` is the value loaded from cliclo.ini — if the user set
``db_path`` there we honor it; otherwise we use ``state_dir/cliclo_progress.db``
unless a legacy DB lives in CWD (in which case CWD wins for back-compat).
"""
explicit = getattr(args, "db_path", None)
if explicit:
return explicit
cfg_db = config.get("db_path", "").strip()
if cfg_db and cfg_db != CONFIG_DIR_DB:
return cfg_db
for legacy in (CONFIG_DIR_DB, "comic_tagger_progress.db"):
if os.path.exists(legacy):
return os.path.abspath(legacy)
return os.path.join(state_dir, CONFIG_DIR_DB)
def load_config(config_file: str = CONFIG_FILE) -> Dict[str, str]:
"""defaults -> config file -> environment variables (CLICLO_<KEY>)."""
# interpolation=None: secrets, proxy URLs and percent-encoded tokens often contain '%'
# (e.g. a key with a '%' in it, or a URL with query-string encoding). The default
# configparser would raise InterpolationSyntaxError on the first such value and abort
# startup. None disables %(name)s expansion entirely; we don't rely on it.
config = dict(DEFAULTS)
if os.path.exists(config_file):
cp = configparser.ConfigParser(interpolation=None)
cp.read(config_file, encoding="utf-8")
if cp.has_section("cliclo"):
for key in config:
if cp.has_option("cliclo", key):
config[key] = cp.get("cliclo", key)
for key in config:
env_key = f"CLICLO_{key.upper()}"
if env_key in os.environ:
config[key] = os.environ[env_key]
return config
def write_default_config(path: str):
# Match load_config: never let '%' in defaults round-trip through interpolation.
cp = configparser.ConfigParser(interpolation=None)
cp.add_section("cliclo")
for k, v in DEFAULTS.items():
cp.set("cliclo", k, v)
with open(path, "w", encoding="utf-8") as f:
f.write("; CLICLO configuration. Fill in the blanks below.\n")
f.write("; Required to do anything useful: comicvine_api_key and comics_path.\n")
f.write("; comictagger_path may be left blank to auto-discover on PATH.\n")
f.write("; To resume an earlier run, set db_path to that run's database file.\n")
f.write("; comicvine_api_keys is EXPERIMENTAL key rotation: likely violates ComicVine's\n")
f.write("; rate limit and risks key/IP bans. Leave blank unless you accept that.\n")
f.write("; proxy routes ComicVine calls through an HTTP(S) proxy; same public IP unless\n")
f.write("; the proxy is chained to a VPN/Tor upstream.\n")
f.write("; rotate_egress (with proxy + 2+ keys) binds each key to its own IP, key 1 direct\n")
f.write("; and key 2 via proxy. EXPERIMENTAL IP rotation; verify the proxy is a different\n")
f.write("; public IP first and own the ban risk.\n")
f.write("; Keep this file out of version control (add it to .gitignore).\n\n")
cp.write(f)
# ---------------------------------------------------------------------------
# Pushover
# ---------------------------------------------------------------------------
class PushoverNotifier:
def __init__(self, api_token: str, user_key: str,
device: str = "", enabled: bool = True):
self.api_token = (api_token or "").strip()
self.user_key = (user_key or "").strip()
self.device = (device or "").strip() or None
self.enabled = enabled
self.api_url = "https://api.pushover.net/1/messages.json"
self.notified_milestones: Set[int] = set()
if self.enabled and (not self.api_token or not self.user_key):
logger.warning("Pushover credentials missing; notifications disabled")
self.enabled = False
def send(self, message: str, title: str = "CLICLO", priority: int = 0,
sound: str = "pushover", retry: int = 60, expire: int = 600,
max_retries: int = 2) -> bool:
if not self.enabled:
return False
try:
import requests
except ImportError:
logger.warning("requests not installed; Pushover disabled")
self.enabled = False
return False
data = {
"token": self.api_token,
"user": self.user_key,
"message": message[:1024], # API hard limit
"title": title[:250],
"priority": priority,
"sound": sound,
"html": 1,
}
if self.device:
data["device"] = self.device
if priority == 2:
# Emergency priority REQUIRES retry + expire. retry >= 30, expire <= 10800.
data["retry"] = max(retry, 30)
data["expire"] = min(expire, 10800)
for attempt in range(max_retries + 1):
try:
resp = requests.post(self.api_url, data=data, timeout=10)
if resp.status_code == 200:
if resp.json().get("status") == 1:
return True
logger.warning(f"Pushover API error: {resp.json().get('errors')}")
return False
# 4xx means the input is invalid; retrying will never help (per API docs).
if 400 <= resp.status_code < 500:
logger.warning(f"Pushover HTTP {resp.status_code} (not retrying): {resp.text[:120]}")
return False
logger.warning(f"Pushover HTTP {resp.status_code}: {resp.text[:120]}")
except Exception as e:
logger.warning(f"Pushover attempt {attempt + 1} failed: {e}")
if attempt < max_retries:
time.sleep(2 ** attempt)
return False
# -- semantic notifications --------------------------------------------
def notify_startup(self, total_files: int):
msg = (f"\U0001f680 <b>Starting comic tagging</b>\n"
f"\U0001f4da {total_files:,} files to process\n"
f"\u23f0 Started {datetime.now().strftime('%H:%M')}")
self.send(msg, title="CLICLO Started", sound="bike")
def notify_milestone(self, processed: int, total: int,
stats: Dict[str, int], elapsed_hours: float):
if processed in self.notified_milestones or processed not in self._milestones(total):
return
self.notified_milestones.add(processed)
sc = stats.get("success", 0)
sr = (sc / processed * 100) if processed else 0
rph = processed / elapsed_hours if elapsed_hours > 0 else 0
eta = (total - processed) / rph if rph > 0 else 0
prio = 1 if processed >= 10000 else 0
snd = "magic" if processed >= 20000 else "cashregister" if processed >= 10000 else "bike"
msg = (f"\U0001f4ca <b>Milestone: {processed:,}/{total:,}</b>\n"
f"Success: <b>{sc:,}</b> ({sr:.1f}%)\n"
f"Errors: {stats.get('error', 0):,}\n"
f"Needs review: {stats.get('needs_followup', 0):,}\n"
f"CBR converted: {stats.get('cbr_converted', 0):,}\n"
f"Rate: {rph:.1f}/hr, ETA: {eta:.1f}h")
self.send(msg, title=f"Progress: {processed / total * 100:.1f}%", priority=prio, sound=snd)
def notify_rate_pause(self, wait_minutes: int, reason: str = "hourly budget"):
resume_at = (datetime.now() + timedelta(minutes=wait_minutes)).strftime("%H:%M")
msg = (f"\u23f8\ufe0f <b>Pausing for rate limit</b>\n"
f"Reason: {reason}\n"
f"Waiting ~{wait_minutes} min, resuming around {resume_at}")
self.send(msg, title="Rate Limited", priority=0, sound="falling")
def notify_errors(self, count: int, sample: str):
msg = (f"\u26a0\ufe0f <b>{count} consecutive API errors</b>\n"
f"Likely rate limited or a ComicVine hiccup\n"
f"Sample: {sample[:80]}")
self.send(msg, title="API Errors", priority=1, sound="siren")
def notify_completion(self, total: int, stats: Dict[str, int], hours: float):
sc = stats.get("success", 0)
sr = (sc / total * 100) if total else 0
icon = "\U0001f389" if sr >= 90 else "\u2705" if sr >= 75 else "\u26a0\ufe0f"
rate = f"{total / hours:.1f}/hr" if hours > 0 else "N/A"
msg = (f"{icon} <b>Tagging complete</b>\n"
f"Processed: <b>{total:,}</b>\n"
f"Success: <b>{sc:,}</b> ({sr:.1f}%)\n"
f"Errors: {stats.get('error', 0):,}\n"
f"Needs review: {stats.get('needs_followup', 0):,}\n"
f"CBR converted: {stats.get('cbr_converted', 0):,}\n"
f"Duration: {hours:.1f}h, Rate: {rate}")
self.send(msg, title="CLICLO Complete", priority=1, sound="magic")
def notify_crash(self, error_msg: str):
self.send(f"\U0001f4a5 <b>Fatal error</b>\n{error_msg[:200]}",
title="CLICLO Crashed", priority=2, sound="siren", retry=60, expire=600)
def notify_interrupted(self):
self.send("\u23f9\ufe0f <b>Processing interrupted</b>\nProgress saved, resume anytime",
title="CLICLO Stopped", priority=1, sound="falling")
@staticmethod
def _milestones(total: int) -> List[int]:
ms = [m for m in (100, 500, 1000, 2500, 5000, 10000, 15000, 20000, 25000) if m < total]
c = 30000
while c < total:
ms.append(c)
c += 5000
return ms
# ---------------------------------------------------------------------------
# Database (with migration + pre-migration backup)
# ---------------------------------------------------------------------------
class CLICLODatabase:
"""SQLite progress / rate-limit / stats store.
Migrates v3.2 and v4.0 databases in place and backs the old file up first.
Schema version is tracked with PRAGMA user_version.
"""
def __init__(self, db_path: str = "cliclo_progress.db"):
self.db_path = db_path
self._lock_path = db_path + ".lock"
self._lock_fh = None
self._acquire_lock()
self._backup_if_legacy()
self.conn = sqlite3.connect(db_path)
self.conn.execute("PRAGMA journal_mode=WAL")
self._init_schema()
def _acquire_lock(self):
try:
self._lock_fh = open(self._lock_path, "w")
_lock_file(self._lock_fh)
except (OSError, IOError):
logger.error(f"Another CLICLO instance appears to be running (lock: {self._lock_path}). "
"If that's wrong, delete the .lock file and retry.")
sys.exit(1)
def _backup_if_legacy(self):
"""If an older-schema DB exists, copy it aside before we migrate it."""
if not os.path.exists(self.db_path):
return
try:
peek = sqlite3.connect(self.db_path)
uv = peek.execute("PRAGMA user_version").fetchone()[0]
has_pf = peek.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='processed_files'"
).fetchone()
peek.close()
except Exception as e:
logger.warning(f"Could not inspect existing DB for migration backup: {e}")
return
if has_pf and uv < SCHEMA_VERSION:
bak = f"{self.db_path}.bak-v{uv}-{datetime.now():%Y%m%d%H%M%S}"
try:
shutil.copy2(self.db_path, bak)
logger.info(f"Existing DB (schema v{uv}) backed up to {bak} before migration")
except Exception as e:
logger.warning(f"Backup before migration failed (continuing): {e}")
def _init_schema(self):
cur = self.conn.cursor()
existed = cur.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='processed_files'"
).fetchone() is not None
start_uv = cur.execute("PRAGMA user_version").fetchone()[0]
cur.execute("""
CREATE TABLE IF NOT EXISTS processed_files (
filepath TEXT PRIMARY KEY,
status TEXT NOT NULL,
ct_status TEXT,
match_status TEXT,
processed_at TEXT,
error_message TEXT,
retry_count INTEGER DEFAULT 0,
converted_from_cbr INTEGER DEFAULT 0,
file_size_mb REAL,
tags_written TEXT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS api_calls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
called_at TEXT NOT NULL,
estimated_calls INTEGER DEFAULT 1,
key_id TEXT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS statistics (
key TEXT PRIMARY KEY,
value INTEGER DEFAULT 0
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS low_confidence (
filepath TEXT PRIMARY KEY,
added_at TEXT,
reason TEXT
)
""")
if existed and start_uv < SCHEMA_VERSION:
logger.info(f"Migrating database schema v{start_uv} -> v{SCHEMA_VERSION}")
self._migrate(cur)
cur.execute("CREATE INDEX IF NOT EXISTS idx_pf_status ON processed_files(status)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_api_called ON api_calls(called_at)")
cur.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
self.conn.commit()
def _migrate(self, cur):
# 1. Add any columns introduced after the existing DB was created.
self._ensure_columns(cur, "processed_files", {
"ct_status": "TEXT",
"match_status": "TEXT",
"error_message": "TEXT",
"processed_at": "TEXT",
"retry_count": "INTEGER DEFAULT 0",
"converted_from_cbr": "INTEGER DEFAULT 0",
"file_size_mb": "REAL",
"tags_written": "TEXT",
})
self._ensure_columns(cur, "api_calls", {"estimated_calls": "INTEGER DEFAULT 1",
"key_id": "TEXT"})
# 2. v3.2 named the queue table "low_confidence_matches". Carry its rows over.
legacy = cur.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='low_confidence_matches'"
).fetchone()
if legacy:
cols = {r[1] for r in cur.execute("PRAGMA table_info(low_confidence_matches)")}
if "filepath" in cols:
reason_col = "reason" if "reason" in cols else "''"
if "added_at" in cols:
added_col = "added_at"
elif "processed_at" in cols: # v3.2 used this name
added_col = "processed_at"
else:
added_col = "NULL"
moved = cur.execute(f"""
INSERT OR IGNORE INTO low_confidence (filepath, added_at, reason)
SELECT filepath, COALESCE({added_col}, ?), {reason_col}
FROM low_confidence_matches
""", (datetime.now().isoformat(),)).rowcount
logger.info(f" migrated: moved {moved} rows from low_confidence_matches")
# v3.2 queued low-confidence files WITHOUT marking them processed, so a fresh
# pass-1 run would re-tag them and waste API budget. Native v5.x marks them
# 'needs_followup' (and thus skips them in pass 1). Backfill that here so the
# resumed run behaves identically: queued for --review, skipped by pass 1.
backfilled = cur.execute("""
INSERT OR IGNORE INTO processed_files (filepath, status, match_status, processed_at)
SELECT filepath, 'needs_followup', 'low_confidence_match', ?
FROM low_confidence
""", (datetime.now().isoformat(),)).rowcount
if backfilled:
logger.info(f" migrated: marked {backfilled} queued files 'needs_followup'")
def _ensure_columns(self, cur, table: str, cols: Dict[str, str]):
existing = {r[1] for r in cur.execute(f"PRAGMA table_info({table})")}
for name, decl in cols.items():
if name not in existing:
cur.execute(f"ALTER TABLE {table} ADD COLUMN {name} {decl}")
logger.info(f" migrated: added {table}.{name}")
# -- processed files ---------------------------------------------------
def seen_paths(self) -> Set[str]:
"""Every filepath ComicTagger has already touched, any status.
The primary scan skips these; each status has its own reprocessing path."""
return {r[0] for r in self.conn.execute("SELECT filepath FROM processed_files")}
def mark_processed(self, filepath: str, status: str, error_message: str = None,
ct_status: str = None, match_status: str = None,
converted_from_cbr: bool = False, file_size_mb: float = None,
tags_written: str = None):
"""Upsert that preserves retry_count (a separate counter)."""
self.conn.execute("""
INSERT INTO processed_files
(filepath, status, ct_status, match_status, processed_at, error_message,
converted_from_cbr, file_size_mb, tags_written, retry_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
ON CONFLICT(filepath) DO UPDATE SET
status = excluded.status,
ct_status = excluded.ct_status,
match_status = excluded.match_status,
processed_at = excluded.processed_at,
error_message = excluded.error_message,
converted_from_cbr = CASE WHEN excluded.converted_from_cbr THEN 1 ELSE converted_from_cbr END,
file_size_mb = COALESCE(excluded.file_size_mb, file_size_mb),
tags_written = COALESCE(excluded.tags_written, tags_written)
""", (filepath, status, ct_status, match_status, datetime.now().isoformat(),
error_message, int(converted_from_cbr), file_size_mb, tags_written))
self.conn.commit()
def get_retry_count(self, filepath: str) -> int:
row = self.conn.execute(
"SELECT retry_count FROM processed_files WHERE filepath = ?", (filepath,)
).fetchone()
return row[0] if row else 0
def increment_retry(self, filepath: str):
self.conn.execute(
"UPDATE processed_files SET retry_count = retry_count + 1 WHERE filepath = ?", (filepath,)
)
self.conn.commit()
# -- follow-up queue ---------------------------------------------------
def add_low_confidence(self, filepath: str, reason: str):
self.conn.execute(
"INSERT OR REPLACE INTO low_confidence (filepath, added_at, reason) VALUES (?, ?, ?)",
(filepath, datetime.now().isoformat(), reason)
)
self.conn.commit()
def get_low_confidence_files(self) -> List[Tuple[str, str]]:
return self.conn.execute(
"SELECT filepath, reason FROM low_confidence ORDER BY added_at"
).fetchall()
def remove_low_confidence(self, filepath: str):
self.conn.execute("DELETE FROM low_confidence WHERE filepath = ?", (filepath,))
self.conn.commit()
def remove_path(self, filepath: str):
"""Drop a file from the progress tables (used when deleting duplicates)."""
self.conn.execute("DELETE FROM processed_files WHERE filepath = ?", (filepath,))
self.conn.execute("DELETE FROM low_confidence WHERE filepath = ?", (filepath,))
self.conn.commit()
# -- failed files ------------------------------------------------------
def get_failed_files(self):
return self.conn.execute("""
SELECT filepath, status, retry_count, error_message
FROM processed_files WHERE status IN ('error', 'permanent_error')
ORDER BY processed_at DESC
""").fetchall()
def get_retryable_paths(self, max_retries: int) -> List[str]:
return [r[0] for r in self.conn.execute(
"SELECT filepath FROM processed_files WHERE status = 'error' AND retry_count < ?",
(max_retries,)
).fetchall()]
# -- rate limiting -----------------------------------------------------
def record_api_invocation(self, estimated_calls: int = 4, key_id: str = None):
self.conn.execute(
"INSERT INTO api_calls (called_at, estimated_calls, key_id) VALUES (?, ?, ?)",
(datetime.now().isoformat(), estimated_calls, key_id)
)
self.conn.commit()
def estimated_calls_last_hour(self, key_id: str = None) -> int:
cutoff = (datetime.now() - timedelta(hours=1)).isoformat()
if key_id is None:
return self.conn.execute(
"SELECT COALESCE(SUM(estimated_calls), 0) FROM api_calls WHERE called_at > ?",
(cutoff,)).fetchone()[0]
return self.conn.execute(
"SELECT COALESCE(SUM(estimated_calls), 0) FROM api_calls "
"WHERE called_at > ? AND key_id = ?", (cutoff, key_id)).fetchone()[0]
def cleanup_old_api_calls(self):
cutoff = (datetime.now() - timedelta(hours=1)).isoformat()
self.conn.execute("DELETE FROM api_calls WHERE called_at <= ?", (cutoff,))
self.conn.commit()
# -- statistics --------------------------------------------------------
def increment_stat(self, key: str, amount: int = 1):
self.conn.execute("""
INSERT INTO statistics (key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = value + ?
""", (key, amount, amount))
self.conn.commit()
def get_stats(self) -> Dict[str, int]:
return dict(self.conn.execute("SELECT key, value FROM statistics").fetchall())
def status_summary(self) -> Dict[str, int]:
return dict(self.conn.execute(
"SELECT status, COUNT(*) FROM processed_files GROUP BY status"
).fetchall())
def schema_version(self) -> int:
return self.conn.execute("PRAGMA user_version").fetchone()[0]
def close(self):
self.conn.close()
if self._lock_fh:
_unlock_file(self._lock_fh)
self._lock_fh.close()
try:
os.unlink(self._lock_path)
except OSError:
pass
# ---------------------------------------------------------------------------
# ComicTagger result
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class CTResult:
returncode: int
status: Optional[str] # ComicTagger Status enum, or None if unparsed
match_status: Optional[str] # ComicTagger MatchStatus enum, or None
tags_written: List[str]
raw: str # combined stdout+stderr, for diagnostics
def _extract_json(stdout: str) -> Optional[dict]:
"""Pull ComicTagger's -j result object out of stdout, ignoring any
human-readable prefix/suffix lines. Returns the first dict that has a 'status' key."""
decoder = json.JSONDecoder()
idx = stdout.find("{")
while idx != -1:
try:
obj, _ = decoder.raw_decode(stdout, idx)
if isinstance(obj, dict) and "status" in obj:
return obj
except json.JSONDecodeError:
pass
idx = stdout.find("{", idx + 1)
return None
# ---------------------------------------------------------------------------
# Core tagger
# ---------------------------------------------------------------------------
class CLICLOTagger:
def __init__(self, config: Dict[str, str], pushover: PushoverNotifier):
self.comics_path = Path(config["comics_path"]) if config["comics_path"] else None
self.comictagger_path = config["comictagger_path"].strip()
# Effective key list: the single key plus any comma-separated extras, deduped,
# order preserved. With one key this behaves exactly as before (no rotation).
keys = [config.get("comicvine_api_key", "").strip()]
keys += [k.strip() for k in config.get("comicvine_api_keys", "").split(",")]
seen_k: Set[str] = set()
self.api_keys = [k for k in keys if k and not (k in seen_k or seen_k.add(k))]
self.api_key = self.api_keys[0] if self.api_keys else "" # default / single-key path
self._key_cooldowns: Dict[str, datetime] = {} # fingerprint -> cooldown-until
self.safe_invocations = int(config["safe_invocations_per_hour"])
self.calls_per_invocation = int(config["api_calls_per_invocation"])
self.max_retries = int(config["max_retries"])
self.tag_format = self._validate_tag_format(config["tag_format"])
self.repair_failed = config.get("repair_failed_archives", "true").strip().lower() == "true"
# Egress: a "direct" env (proxy vars stripped) and, if a proxy is set, a "proxy" env.
self.proxy = config.get("proxy", "").strip()
self.rotate_egress = config.get("rotate_egress", "false").strip().lower() == "true"
_PROXY_VARS = ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy")
base = {k: v for k, v in os.environ.items() if k not in _PROXY_VARS}
self._env_direct = dict(base)
self._env_proxy = dict(base)
if self.proxy:
for var in _PROXY_VARS:
self._env_proxy[var] = self.proxy
# Routes for rotation: direct first, then proxy. Each key binds to one route by
# index, so a given key always exits from the same IP (looks like a stable user).
self.routes: List[Tuple[str, Dict[str, str]]] = [("direct", self._env_direct)]
if self.proxy and self.rotate_egress:
self.routes.append(("proxy", self._env_proxy))
# Env used when NOT rotating: all calls via proxy if one is set, else direct.
self._env = self._env_proxy if (self.proxy and not self.rotate_egress) else self._env_direct
self.db = CLICLODatabase(config["db_path"])
self.pushover = pushover
self.exe = self._find_executable()
self.converted_this_session: Set[str] = set()
self._consecutive_api_errors = 0
self.dry_run = False
self.accept_low_confidence = False # opt-in blind low-confidence accept in --auto-retry
# Resolve flag names that drift between ComicTagger betas, then version-check.
self._flag_abort = "--abort"
self._flag_accept = "--no-abort"
self._has_no_year = True
self._resolve_flags()
if len(self.api_keys) > 1:
fps = ", ".join(self._key_fp(k) for k in self.api_keys)
logger.warning(f"EXPERIMENTAL multi-key rotation ON: {len(self.api_keys)} keys "
f"(…{fps}). This likely violates ComicVine's per-user rate limit and "
f"can get your keys and IP banned. All traffic is from one machine, so "
f"rotation may not even raise your effective ceiling. You accepted this.")
if self.proxy and self.rotate_egress and len(self.routes) > 1:
binding = ", ".join(f"…{self._key_fp(k)}→{self.routes[i % len(self.routes)][0]}"
for i, k in enumerate(self.api_keys))
logger.warning(f"EXPERIMENTAL egress rotation ON: keys bound to routes [{binding}]. "
f"This is deliberate IP rotation on top of key rotation to get around a "
f"per-user limit; VPN/Tor exit IPs can be flagged faster, not slower.")
elif self.proxy:
logger.info(f"Routing ComicVine requests through proxy {self.proxy} (same public IP "
f"unless this proxy is chained to a VPN/Tor upstream).")
if not self.api_key:
logger.warning("No ComicVine API key set. Online tagging will fail. "
"Run --init-config and edit cliclo.ini, or set CLICLO_COMICVINE_API_KEY.")
self._check_version()
@staticmethod
def _validate_tag_format(raw: str) -> str:
fmt = (raw or "CR").strip().upper()
valid = {f for f in fmt.split(",") if f}
if valid - {"CR", "CBL", "COMET"}:
logger.warning(f"tag_format '{raw}' contains values stock ComicTagger 1.6.x rejects. "
"CR is the standard target (CIX/ComicInfo.xml is written under CR; "
"toggle it with --cr/--no-cr). Falling back to CR.")
return "CR"
return fmt
def _find_executable(self) -> Path:
# 1. Explicit path: a file, or a directory containing the binary.
if self.comictagger_path:
p = Path(self.comictagger_path)
if p.is_file():
return p
for name in ("comictagger.exe", "comictagger"):
cand = p / name
if cand.exists():
return cand
# 2. On PATH (covers pip installs).
found = shutil.which("comictagger") or shutil.which("comictagger.exe")
if found:
return Path(found)
raise FileNotFoundError(
"ComicTagger executable not found. Set comictagger_path in cliclo.ini to the "
"install directory or binary, or ensure 'comictagger' is on your PATH "
"(pip install --pre comictagger)."
)
def _check_version(self):
try:
out = subprocess.run([str(self.exe), "--version"],
capture_output=True, text=True, timeout=15)
lines = [l.strip() for l in (out.stdout + out.stderr).splitlines() if l.strip()]
# The version sits on a line like "ComicTagger 1.6.0b11.dev0: ...", not on the
# trailing Apache-license line. Find the line that actually names a version.
ver_line = next((l for l in lines if re.search(r"comictagger\s+v?\d+\.\d+", l, re.I)), "")
if not ver_line:
ver_line = next((l for l in lines if re.search(r"\bv?\d+\.\d+\.\d+", l)
and "apache" not in l.lower()), "")
logger.info(f"ComicTagger: {ver_line or (lines[0] if lines else 'unknown')}")
m = re.search(r"(\d+\.\d+\.\d+[A-Za-z0-9.]*)", ver_line)
ver_num = m.group(1) if m else ""
if ver_num.startswith("1.5"):
logger.warning("This looks like ComicTagger 1.5.x, whose CLI is INCOMPATIBLE "
"with CLICLO. Install the 1.6.x line: pip install --pre comictagger")
except Exception as e:
logger.warning(f"Could not determine ComicTagger version: {e}")
def _resolve_flags(self):
"""ComicTagger's low-confidence flag was renamed between betas:
1.6.0b9 and earlier : --abort / --no-abort
1.6.0b11+ : --no-save-on-low-confidence / --save-on-low-confidence
Hardcoding either breaks on the other, and argparse prefix-matching makes it
worse: passing --abort to a b11 build silently resolves to the unrelated
--abort-on-conflict. So probe --help once and use the names that actually exist."""
help_text = ""
try:
h = subprocess.run([str(self.exe), "--help"], capture_output=True, text=True, timeout=15)
help_text = h.stdout + h.stderr
except Exception as e: # noqa: BLE001
logger.warning(f"Could not read ComicTagger --help for flag detection: {e}")
if "--no-save-on-low-confidence" in help_text: # b11+
self._flag_abort = "--no-save-on-low-confidence"
self._flag_accept = "--save-on-low-confidence"
elif "--no-abort" in help_text: # b9 and earlier
self._flag_abort = "--abort"
self._flag_accept = "--no-abort"
logger.warning(
"ComicTagger looks like a pre-b11 beta. Ambiguous matches (multiple / "
"low-confidence) can crash this build with an AssertionError instead of "
"being handled cleanly, and --review may not reach its prompt. This is a "
"ComicTagger bug, not CLICLO. Upgrade to 1.6.0b11+ for reliable pass-2 and "
"pass-3 behaviour: pip install --pre comictagger")
elif help_text:
self._flag_abort = None
self._flag_accept = None
logger.warning("No low-confidence flag found in ComicTagger's help; relying on "
"its default match-confidence behaviour.")
self._has_no_year = (not help_text) or ("--no-use-year-when-identifying" in help_text)
# -- rate limiting -----------------------------------------------------
@staticmethod
def _key_fp(key: str) -> str:
"""Short, log-safe fingerprint of a key (last 4 chars). Never log full keys."""
return key[-4:] if key else "none"
def _route_for_key(self, key: str) -> Tuple[str, Dict[str, str]]:
"""Bind each key to one egress route by index, so a key always exits the same IP.
With rotation off (or no proxy) every key uses the single default env."""
if not (self.rotate_egress and len(self.routes) > 1):
return ("proxy" if (self.proxy and not self.rotate_egress) else "direct", self._env)
try:
ki = self.api_keys.index(key)
except ValueError:
ki = 0
return self.routes[ki % len(self.routes)]
def _select_and_wait_key(self) -> str:
"""Return a key with remaining hourly budget, waiting if necessary.
Single-key setups just enforce the one budget (old behaviour). Multi-key
setups pick the first key that is both under budget and not in a velocity
cooldown; if none qualifies, wait until the soonest one frees up. The budget
is per key because ComicVine's limit is per user/key."""