Coverage for downtify/doctor_ai_sections.py: 85%

397 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""The AI helper's tools for the Doctor's other sections. 

2 

3:mod:`downtify.doctor_ai` holds the helper itself and the duplicate 

4playlists. This module adds, the same way (read, compare, suggest with a 

5reason, the user applies): 

6 

7* **Duplicate songs** - the Doctor's groups, a search over the whole 

8 library (a remix or a live version is never in a group: its length 

9 differs), each file's details, an audio comparison and a MusicBrainz 

10 lookup, then "keep this copy" or "these are different songs". 

11* **Downloaded again under a new Spotify ID** - the full list; the extra 

12 files are fixed with the same "keep this copy". 

13* **slskd leftovers** - run the check and suggest deleting the copies it 

14 verified identical to a library file. 

15* **Navidrome** - the problems found and the page's own plan, and a 

16 suggestion of which flagged Navidrome playlists to delete. 

17 

18Every repair still runs through :mod:`downtify.doctor_routes`, with its 

19checks, the music trash, backups and the "check again first" locks. 

20""" 

21 

22from __future__ import annotations 

23 

24import asyncio 

25from pathlib import Path 

26from typing import Any, Optional 

27 

28from fastapi import HTTPException 

29from loguru import logger 

30 

31from . import api, doctor_ai, isrc, musicbrainz, trash_routes 

32from .doctor import STATUS_VERIFIED, norm, relinked_tracks 

33from .doctor_ai import ( 

34 ToolError, 

35 _doctor, 

36 _http_error, 

37 _int_arg, 

38 _last_health, 

39 _reason_arg, 

40 helper, 

41) 

42from .duplicate_merge import MergeError, plan_merge 

43from .library_catalog import resolve_library_file 

44from .library_trash import TrashError, identity_keys 

45from .library_upgrade import has_lyrics 

46from .library_usage import provider_of 

47 

48#: At most this many copies in one "keep" suggestion (the Doctor's own 

49#: merge limit, plus the kept one). 

50MAX_COPIES = 21 

51 

52_MERGE_CODES = { 

53 'dedupe_invalid': 'Pick one copy to keep and at least one other copy.', 

54 'dedupe_missing': 'One of these files is not in the library', 

55 'dedupe_replacement_pending': ( 

56 'Replace audio is still working on one of these files' 

57 ), 

58} 

59 

60 

61# --------------------------------------------------------------------------- 

62# Library helpers 

63# --------------------------------------------------------------------------- 

64 

65 

66def _inputs() -> dict[str, Any]: 

67 return api._usage_library_inputs(api.library_context()) 

68 

69 

70def _playlists_by_file() -> dict[str, list[str]]: 

71 dr = _doctor() 

72 out: dict[str, list[str]] = {} 

73 for info in dr._m3u_infos(dr._ctx()): 

74 for stored in info.entries: 

75 names = out.setdefault(norm(stored), []) 

76 if info.name not in names: 

77 names.append(info.name) 

78 return out 

79 

80 

81def _row(entry: dict[str, Any], providers: dict[str, str]) -> dict[str, Any]: 

82 name = norm(entry.get('file')) 

83 try: 

84 size = max(0, int(entry.get('size') or 0)) 

85 except (TypeError, ValueError): 

86 size = 0 

87 try: 

88 duration = float(entry.get('duration') or 0) 

89 except (TypeError, ValueError): 

90 duration = 0.0 

91 return { 

92 'file': name, 

93 'bytes': size, 

94 'provider': provider_of(name, providers), 

95 'codec': str(entry.get('codec') or ''), 

96 'bitrate': int(entry.get('bitrate') or 0), 

97 'title': str(entry.get('title') or ''), 

98 'artist': str(entry.get('artist') or ''), 

99 'album': str(entry.get('album') or ''), 

100 'duration': duration, 

101 } 

102 

103 

104def _rows_for(files: list[str]) -> list[dict[str, Any]]: 

105 """The Doctor's card rows of *files*, in that order, with the 

106 playlists each is in. Raises :class:`ToolError` for a stranger.""" 

107 

108 inputs = _inputs() 

109 by_file = {norm(e.get('file')): e for e in inputs['entries']} 

110 playlists = _playlists_by_file() 

111 rows = [] 

112 for name in files: 

113 entry = by_file.get(norm(name)) 

114 if entry is None: 

115 raise ToolError( 

116 f'{name!r} is not a library file (use search_library).' 

117 ) 

118 row = _row(entry, inputs['providers']) 

119 row['playlists'] = sorted(playlists.get(row['file'], [])) 

120 rows.append(row) 

121 return rows 

122 

123 

124def _full_path(stored: str) -> Optional[Path]: 

125 try: 

126 return resolve_library_file(stored, api.library_context()) 

127 except Exception: 

128 return None 

129 

130 

131def _files_arg( 

132 args: dict[str, Any], name: str = 'files', least: int = 1 

133) -> list[str]: 

134 raw = args.get(name) 

135 if not isinstance(raw, list): 

136 raise ToolError(f'"{name}" must be a list of library file paths.') 

137 files = list(dict.fromkeys(norm(f) for f in raw if norm(f))) 

138 if len(files) < least: 

139 raise ToolError(f'Give at least {least} different file(s).') 

140 if len(files) > MAX_COPIES: 

141 raise ToolError(f'At most {MAX_COPIES} files at a time.') 

142 return files 

143 

144 

145def _grouped(files: list[str]) -> bool: 

146 """Whether the last health check put all *files* in one group.""" 

147 

148 groups = _doctor()._state.get('duplicates') or {} 

149 found = {groups.get(norm(f)) for f in files} 

150 return None not in found and len(found) == 1 

151 

152 

153def _check_fresh(section: str) -> None: 

154 if section in _doctor()._stale: 

155 raise ToolError( 

156 f'The {section} section is out of date after a repair: call ' 

157 'run_health_check before suggesting more there.' 

158 ) 

159 

160 

161def _add(suggestion: dict[str, Any]) -> dict[str, Any]: 

162 try: 

163 return helper.add(suggestion) 

164 except ValueError as exc: 

165 code = str(exc) 

166 if code.startswith('already_suggested:'): 

167 raise ToolError( 

168 f'{code.split(":", 1)[1]!r} is already in a waiting ' 

169 'suggestion; withdraw that one first.' 

170 ) from None 

171 raise ToolError('Too many waiting suggestions.') from None 

172 

173 

174#: Why the music trash would refuse a copy, in words for the assistant. 

175TRASH_REASONS = { 

176 'identity_uncertain': ( 

177 'it has no Spotify, Deezer or YouTube id, no ISRC, and its title, ' 

178 'artist and album tags are not all filled in, so the trash could ' 

179 'not be sure to restore the right song' 

180 ), 

181 'unsupported_collection': "its folder isn't covered by the music trash", 

182 'item_not_found': 'it is not in the library any more', 

183 'track_is_playing': 'it is playing right now (try again after)', 

184 'library_task_active': ( 

185 'a library upgrade is running (try again when it is done)' 

186 ), 

187} 

188 

189 

190def trash_check(files: list[str]) -> dict[str, str]: 

191 """``{file: reason}`` for each copy the music trash would refuse 

192 (empty when it takes them all, or is off: then nothing is checked). 

193 

194 The same lookup as the trash's own preview, file by file and without 

195 reserving anything: a merge whose copy the trash refuses stops 

196 before anything changes, so this says so before the user applies. 

197 """ 

198 

199 if api.state.library_trash is None: 

200 return {} 

201 refused: dict[str, str] = {} 

202 for name in files: 

203 try: 

204 tracks = trash_routes._selection( 

205 trash_routes.Selection(files=[name]) 

206 ) 

207 except TrashError as exc: 

208 refused[name] = str(exc) or 'unknown' 

209 continue 

210 except Exception: 

211 # Only a heads-up: the trash checks again when applying. 

212 logger.opt(exception=True).debug('doctor ai: trash check') 

213 continue 

214 if not any(identity_keys(t.get('metadata') or {}) for t in tracks): 

215 refused[name] = 'identity_uncertain' 

216 return refused 

217 

218 

219def _trash_words(reason: str) -> str: 

220 return TRASH_REASONS.get(reason, reason) 

221 

222 

223# --------------------------------------------------------------------------- 

224# Duplicate songs 

225# --------------------------------------------------------------------------- 

226 

227 

228async def tool_list_duplicate_songs(args: dict[str, Any]) -> dict[str, Any]: 

229 last = _last_health() 

230 if not last['at']: 

231 raise ToolError('No health check yet: call run_health_check.') 

232 review = last['result'].get('duplicates') or {} 

233 groups = review.get('groups') or [] 

234 kind = str(args.get('kind') or '') 

235 if kind in {'exact', 'likely'}: 

236 groups = [g for g in groups if g.get('kind') == kind] 

237 offset = _int_arg(args, 'offset', 0, 100_000) 

238 limit = _int_arg(args, 'limit', 25, 100) or 25 

239 return { 

240 'health_check_at': last['at'], 

241 'total_groups': len(groups), 

242 'offset': offset, 

243 'music_trash_on': bool(review.get('trash')), 

244 'groups': [ 

245 { 

246 'kind': g.get('kind'), 

247 'artist': g.get('artist'), 

248 'title': g.get('title'), 

249 'files': [ 

250 { 

251 'file': f['file'], 

252 'format': f.get('codec'), 

253 'kbps': round((f.get('bitrate') or 0) / 1000), 

254 'seconds': round(f.get('duration') or 0, 1), 

255 'bytes': f.get('bytes'), 

256 'source': f.get('provider'), 

257 'tags': { 

258 'title': f.get('title'), 

259 'artist': f.get('artist'), 

260 'album': f.get('album'), 

261 }, 

262 'playlists': f.get('playlists') or [], 

263 } 

264 for f in g.get('files') or [] 

265 ], 

266 } 

267 for g in groups[offset : offset + limit] 

268 ], 

269 'out_of_date': 'duplicates' in _doctor()._stale, 

270 } 

271 

272 

273async def tool_search_library(args: dict[str, Any]) -> dict[str, Any]: 

274 words = str(args.get('query') or '').casefold().split() 

275 if not words: 

276 raise ToolError('Give a "query": words from the artist or title.') 

277 limit = _int_arg(args, 'limit', 50, 200) or 50 

278 inputs = await asyncio.to_thread(_inputs) 

279 found = [] 

280 for entry in inputs['entries']: 

281 text = ' '.join( 

282 str(entry.get(k) or '') 

283 for k in ('artist', 'title', 'album', 'file') 

284 ).casefold() 

285 if all(w in text for w in words): 

286 row = _row(entry, inputs['providers']) 

287 found.append({ 

288 'file': row['file'], 

289 'artist': row['artist'], 

290 'title': row['title'], 

291 'album': row['album'], 

292 'seconds': round(row['duration'], 1), 

293 'format': row['codec'], 

294 'kbps': round(row['bitrate'] / 1000), 

295 'source': row['provider'], 

296 }) 

297 found.sort(key=lambda r: (r['artist'].casefold(), r['title'].casefold())) 

298 return {'total': len(found), 'files': found[:limit]} 

299 

300 

301def _file_details(stored: str) -> dict[str, Any]: 

302 path = _full_path(stored) 

303 if path is None or not path.is_file(): 

304 return {'file': stored, 'exists': False} 

305 details: dict[str, Any] = {'file': stored, 'exists': True} 

306 try: 

307 details['isrc'] = isrc.read(path) or None 

308 except Exception: 

309 details['isrc'] = None 

310 try: 

311 details['lyrics'] = ( 

312 'synced' 

313 if has_lyrics(path, synced_only=True) 

314 else ('plain' if has_lyrics(path) else 'none') 

315 ) 

316 except Exception: 

317 details['lyrics'] = 'unknown' 

318 try: 

319 import mutagen # noqa: PLC0415 # only when asked 

320 

321 audio = mutagen.File(str(path), easy=True) 

322 tags = dict(audio.tags or {}) if audio is not None else {} 

323 details['tags'] = { 

324 key: (value[0] if isinstance(value, list) and value else value) 

325 for key, value in tags.items() 

326 if key 

327 in { 

328 'title', 

329 'artist', 

330 'album', 

331 'albumartist', 

332 'date', 

333 'tracknumber', 

334 'genre', 

335 'version', 

336 } 

337 } 

338 except Exception: 

339 details['tags'] = {} 

340 return details 

341 

342 

343async def tool_song_details(args: dict[str, Any]) -> dict[str, Any]: 

344 files = _files_arg(args) 

345 if len(files) > 10: 

346 raise ToolError('At most 10 files at a time.') 

347 rows = await asyncio.to_thread(_rows_for, files) 

348 extra = await asyncio.to_thread(lambda: [_file_details(f) for f in files]) 

349 trash_on = api.state.library_trash is not None 

350 refused = await asyncio.to_thread(trash_check, files) if trash_on else {} 

351 return { 

352 'files': [ 

353 { 

354 **{k: row[k] for k in ('file', 'artist', 'title', 'album')}, 

355 'seconds': round(row['duration'], 1), 

356 'format': row['codec'], 

357 'kbps': round(row['bitrate'] / 1000), 

358 'bytes': row['bytes'], 

359 'source': row['provider'], 

360 'playlists': row['playlists'], 

361 **{k: v for k, v in more.items() if k != 'file'}, 

362 'music_trash': ( 

363 'off' 

364 if not trash_on 

365 else ( 

366 'refuses: ' + _trash_words(refused[row['file']]) 

367 if row['file'] in refused 

368 else 'can take it' 

369 ) 

370 ), 

371 } 

372 for row, more in zip(rows, extra) 

373 ] 

374 } 

375 

376 

377async def tool_compare_audio(args: dict[str, Any]) -> dict[str, Any]: 

378 files = _files_arg(args, least=2) 

379 if len(files) > 10: 

380 raise ToolError('At most 10 files at a time.') 

381 cache = _doctor()._hash_cache() 

382 

383 def digests() -> dict[str, Optional[str]]: 

384 out = {} 

385 for name in files: 

386 path = _full_path(name) 

387 out[name] = cache.digest(path) if path is not None else None 

388 return out 

389 

390 found = await asyncio.to_thread(digests) 

391 same: dict[str, list[str]] = {} 

392 for name, digest in found.items(): 

393 if digest: 

394 same.setdefault(digest, []).append(name) 

395 return { 

396 'identical_audio_groups': [g for g in same.values() if len(g) > 1], 

397 'unreadable': [n for n, d in found.items() if not d], 

398 'note': ( 

399 'Identical audio means the decoded sound is bit-for-bit the ' 

400 'same (tags and format aside). Different audio can still be ' 

401 'the same recording in another format or bitrate.' 

402 ), 

403 } 

404 

405 

406def _credit(rows: Any) -> str: 

407 return ''.join( 

408 str(r.get('name') or '') + str(r.get('joinphrase') or '') 

409 for r in rows or [] 

410 if isinstance(r, dict) 

411 ) 

412 

413 

414async def tool_lookup_musicbrainz(args: dict[str, Any]) -> dict[str, Any]: 

415 title = str(args.get('title') or '').replace('"', ' ').strip() 

416 artist = str(args.get('artist') or '').replace('"', ' ').strip() 

417 if not title: 

418 raise ToolError('Give at least a "title".') 

419 limit = _int_arg(args, 'limit', 5, 10) or 5 

420 query = f'recording:"{title}"' + ( 

421 f' AND artist:"{artist}"' if artist else '' 

422 ) 

423 try: 

424 data = await asyncio.to_thread( 

425 musicbrainz._get, 'recording', query=query, limit=limit 

426 ) 

427 except musicbrainz.MusicBrainzError as exc: 

428 raise ToolError(f'MusicBrainz: {exc}') from None 

429 out = [] 

430 for rec in data.get('recordings') or []: 

431 releases = [] 

432 for rel in (rec.get('releases') or [])[:5]: 

433 group = rel.get('release-group') or {} 

434 releases.append({ 

435 'title': rel.get('title'), 

436 'status': rel.get('status'), 

437 'type': group.get('primary-type'), 

438 'secondary_types': group.get('secondary-types') or [], 

439 'date': rel.get('date'), 

440 'country': rel.get('country'), 

441 }) 

442 length = rec.get('length') 

443 out.append({ 

444 'title': rec.get('title'), 

445 'artist': _credit(rec.get('artist-credit')), 

446 'disambiguation': rec.get('disambiguation') or '', 

447 'seconds': round(length / 1000, 1) if length else None, 

448 'isrcs': rec.get('isrcs') or [], 

449 'score': rec.get('score'), 

450 'releases': releases, 

451 }) 

452 return {'recordings': out} 

453 

454 

455def _song_group(rows: list[dict[str, Any]], grouped: bool) -> dict[str, Any]: 

456 first = rows[0] 

457 kind = 'assistant' 

458 if grouped: 

459 review = (_last_health()['result'].get('duplicates') or {}).get( 

460 'groups' 

461 ) or [] 

462 names = {r['file'] for r in rows} 

463 kind = next( 

464 ( 

465 g.get('kind') 

466 for g in review 

467 if names <= {f['file'] for f in g.get('files') or []} 

468 ), 

469 'likely', 

470 ) 

471 return { 

472 'kind': kind, 

473 'artist': first['artist'], 

474 'title': first['title'], 

475 'files': rows, 

476 } 

477 

478 

479async def tool_suggest_keep_song(args: dict[str, Any]) -> dict[str, Any]: 

480 _check_fresh('duplicates') 

481 keep = norm(args.get('keep')) 

482 if not keep: 

483 raise ToolError('Give "keep": the one copy to keep.') 

484 remove = [f for f in _files_arg(args, 'remove') if f != keep] 

485 if not remove: 

486 raise ToolError('"remove" must list the other copies.') 

487 reason = _reason_arg(args) 

488 ctx = api.library_context() 

489 try: 

490 await asyncio.to_thread(plan_merge, keep, remove, ctx) 

491 except MergeError as exc: 

492 text = _MERGE_CODES.get(exc.code, f'Downtify refused: {exc.code}') 

493 raise ToolError( 

494 f'{text}{": " + exc.file if exc.file else ""}.' 

495 ) from None 

496 refused = await asyncio.to_thread(trash_check, remove) 

497 if refused: 

498 name, reason = next(iter(refused.items())) 

499 hint = ( 

500 ' Ways out: keep that copy instead (if it is the one to keep), ' 

501 'leave this song as it is, have the user fill in its tags ' 

502 '(Library > Upgrade library can add ISRCs to older files), or ' 

503 'have the user turn the music trash off (copies are then ' 

504 'deleted for good).' 

505 if reason == 'identity_uncertain' 

506 else '' 

507 ) 

508 raise ToolError( 

509 f'The music trash would refuse {name!r}: {_trash_words(reason)}. ' 

510 'Applying would stop before changing anything.' + hint 

511 ) 

512 rows = await asyncio.to_thread(_rows_for, [keep, *remove]) 

513 grouped = _grouped([keep, *remove]) 

514 trash = api.state.library_trash is not None 

515 entry = _add({ 

516 'kind': 'songs', 

517 'decision': 'keep', 

518 'paths': [keep, *remove], 

519 'keep': keep, 

520 'remove': remove, 

521 'grouped': grouped, 

522 'permanent': not trash, 

523 'reason': reason, 

524 'group': _song_group(rows, grouped), 

525 }) 

526 return { 

527 'suggestion': entry['id'], 

528 'keep': keep, 

529 'remove': remove, 

530 'found_by_doctor': grouped, 

531 'removed_copies_go_to': 'the music trash (30 days)' 

532 if trash 

533 else 'nowhere: deleted for good (the music trash is off)', 

534 'note': 'Waiting for the user in Settings > Doctor > AI helper.', 

535 } 

536 

537 

538async def tool_suggest_different_songs(args: dict[str, Any]) -> dict[str, Any]: 

539 _check_fresh('duplicates') 

540 files = _files_arg(args, least=2) 

541 reason = _reason_arg(args) 

542 if not _grouped(files): 

543 raise ToolError( 

544 'The Doctor did not group these files, so there is nothing to ' 

545 'keep apart: just leave them.' 

546 ) 

547 rows = await asyncio.to_thread(_rows_for, files) 

548 entry = _add({ 

549 'kind': 'songs', 

550 'decision': 'apart', 

551 'paths': files, 

552 'grouped': True, 

553 'reason': reason, 

554 'group': _song_group(rows, True), 

555 }) 

556 return {'suggestion': entry['id'], 'decision': 'different songs'} 

557 

558 

559async def tool_list_new_spotify_id_repeats( 

560 args: dict[str, Any], 

561) -> dict[str, Any]: 

562 db = api.state.monitor_db 

563 if db is None: 

564 return {'songs': 0, 'examples': []} 

565 offset = _int_arg(args, 'offset', 0, 100_000) 

566 limit = _int_arg(args, 'limit', 50, 200) or 50 

567 

568 def compute() -> dict[str, Any]: 

569 names = {p.id: p.name for p in db.list_playlists()} 

570 listing = {norm(e.get('file')): e for e in _inputs()['entries']} 

571 return relinked_tracks( 

572 db.list_all_downloaded_tracks(), names, listing, limit=None 

573 ) 

574 

575 found = await asyncio.to_thread(compute) 

576 songs = found.get('examples') or [] 

577 return { 

578 'songs': found.get('songs'), 

579 'extra_files': found.get('extra_files'), 

580 'per_watch': found.get('playlists'), 

581 'offset': offset, 

582 'repeats': songs[offset : offset + limit], 

583 'note': ( 

584 'Each repeat is one song a watch downloaded under several ' 

585 'Spotify ids, in several files. Fix one with suggest_keep_song ' 

586 '(keep the best file, remove the others).' 

587 ), 

588 } 

589 

590 

591def _song_steps(chosen: list[dict[str, Any]], user_id: int): 

592 dr = _doctor() 

593 steps = [] 

594 for s in chosen: 

595 if s['decision'] == 'keep': 

596 payload = dr.DuplicateMerge(keep=s['keep'], remove=s['remove']) 

597 

598 async def start(payload=payload, grouped=s['grouped']): 

599 return dr.start_dedupe(payload, user_id, grouped=grouped) 

600 

601 else: 

602 files = dr.DuplicateFiles(files=s['paths']) 

603 

604 async def start(files=files): 

605 await dr.duplicates_keep(files) 

606 

607 steps.append(([s['id']], start)) 

608 return steps 

609 

610 

611# --------------------------------------------------------------------------- 

612# slskd leftovers 

613# --------------------------------------------------------------------------- 

614 

615 

616async def tool_get_slskd_leftovers(args: dict[str, Any]) -> dict[str, Any]: 

617 dr = _doctor() 

618 health = _last_health()['result'].get('slskd') or {} 

619 copies = dr._state.get('copies') or {} 

620 status = str(args.get('status') or '') 

621 rows = [r for r in copies.values() if not status or r.status == status] 

622 rows.sort(key=lambda r: (-r.bytes, r.file)) 

623 offset = _int_arg(args, 'offset', 0, 1_000_000) 

624 limit = _int_arg(args, 'limit', 50, 500) or 50 

625 summary: dict[str, dict[str, int]] = {} 

626 for r in copies.values(): 

627 bucket = summary.setdefault(r.status, {'files': 0, 'bytes': 0}) 

628 bucket['files'] += 1 

629 bucket['bytes'] += r.bytes 

630 return { 

631 'files_left_in_slskd_folder': health.get('in_place', False), 

632 'leftovers_in_health_check': health.get('leftovers'), 

633 'checked': bool(copies), 

634 'summary': summary, 

635 'downloads_held': bool(dr._state.get('hold')), 

636 'offset': offset, 

637 'files': [r.as_dict() for r in rows[offset : offset + limit]], 

638 'note': ( 

639 'Only "verified" leftovers (the same audio as a library file) ' 

640 'can be deleted. Run run_slskd_check first if not checked.' 

641 ), 

642 } 

643 

644 

645async def tool_run_slskd_check(args: dict[str, Any]) -> dict[str, Any]: 

646 dr = _doctor() 

647 wait = _int_arg(args, 'wait_seconds', 120, 600) 

648 if dr._busy(): 

649 raise ToolError('The Doctor is busy: call get_job and try later.') 

650 try: 

651 job = await dr.slskd_scan() 

652 except HTTPException as exc: 

653 raise _http_error(exc) from None 

654 loop = asyncio.get_running_loop() 

655 deadline = loop.time() + wait 

656 while loop.time() < deadline: 

657 if dr._job.get('id') != job['id'] or dr._job.get('state') != 'running': 

658 break 

659 await asyncio.sleep(1) 

660 view = await doctor_ai.tool_get_job({}) 

661 leftovers = await tool_get_slskd_leftovers({'limit': 20}) 

662 leftovers['doctor_job'] = view['doctor_job'] 

663 return leftovers 

664 

665 

666async def tool_resume_downloads(_args: dict[str, Any]) -> dict[str, Any]: 

667 """The page's "Keep files and resume downloads".""" 

668 

669 result = await _doctor().slskd_release() 

670 return { 

671 'downloads_held': bool(_doctor()._state.get('hold')), 

672 'queue': result.get('queue'), 

673 } 

674 

675 

676async def tool_suggest_slskd_clean(args: dict[str, Any]) -> dict[str, Any]: 

677 _check_fresh('slskd') 

678 dr = _doctor() 

679 copies = dr._state.get('copies') or {} 

680 verified = {n: r for n, r in copies.items() if r.status == STATUS_VERIFIED} 

681 if not verified: 

682 raise ToolError( 

683 'No verified leftovers: run run_slskd_check first (or nothing ' 

684 'is safe to delete).' 

685 ) 

686 everything = args.get('all_verified') is True 

687 if everything: 

688 chosen = list(verified.values()) 

689 else: 

690 files = args.get('files') 

691 if not isinstance(files, list) or not files: 

692 raise ToolError('List "files", or set "all_verified": true.') 

693 missing = [f for f in files if f not in verified] 

694 if missing: 

695 raise ToolError( 

696 f'{missing[0]!r} is not a verified leftover; only those ' 

697 'can be deleted.' 

698 ) 

699 chosen = [verified[f] for f in dict.fromkeys(files)] 

700 reason = _reason_arg(args) 

701 chosen.sort(key=lambda r: (-r.bytes, r.file)) 

702 entry = _add({ 

703 'kind': 'slskd', 

704 'decision': 'clean', 

705 'paths': ['slskd:*'] 

706 if everything 

707 else ['slskd:' + r.file for r in chosen], 

708 'files': [] if everything else [r.file for r in chosen], 

709 'reason': reason, 

710 'preview': [r.as_dict() for r in chosen[:50]], 

711 'count': len(chosen), 

712 'bytes': sum(r.bytes for r in chosen), 

713 }) 

714 return { 

715 'suggestion': entry['id'], 

716 'files': len(chosen), 

717 'bytes': sum(r.bytes for r in chosen), 

718 } 

719 

720 

721def _slskd_steps(chosen: list[dict[str, Any]], _user_id: int): 

722 dr = _doctor() 

723 everything = any(not s['files'] for s in chosen) 

724 files = [] if everything else [f for s in chosen for f in s['files']] 

725 

726 async def start(): 

727 return await dr.slskd_clean(dr.Cleanup(files=files)) 

728 

729 return [([s['id'] for s in chosen], start)] 

730 

731 

732# --------------------------------------------------------------------------- 

733# Navidrome 

734# --------------------------------------------------------------------------- 

735 

736 

737def navidrome_plan(nd: dict[str, Any]) -> dict[str, Any]: 

738 """The page's own plan (DoctorSettings.vue ``navidromePlan``).""" 

739 

740 remove: list[str] = [] 

741 blocked: list[str] = [] 

742 for dup in nd.get('duplicates') or []: 

743 members = dup.get('members') or [] 

744 imports = [m for m in members if m.get('kind') == 'import'] 

745 ours = [m for m in members if m.get('kind') == 'downtify'] 

746 live = [m for m in imports if m.get('m3u_exists')] 

747 remove += [m['id'] for m in imports if not m.get('m3u_exists')] 

748 if live: 

749 best = max(m.get('songs') or 0 for m in live) 

750 for copy in ours: 

751 ( 

752 remove if (copy.get('songs') or 0) <= best else blocked 

753 ).append(copy['id']) 

754 elif len(ours) > 1: 

755 keep = max(ours, key=lambda m: m.get('songs') or 0) 

756 remove += [m['id'] for m in ours if m is not keep] 

757 remove += [o['id'] for o in nd.get('orphans') or []] 

758 pairs = any( 

759 d.get('reason') == 'm3u_and_api' for d in nd.get('duplicates') or [] 

760 ) 

761 return { 

762 'delete': list(dict.fromkeys(remove)), 

763 'kept_because_bigger': blocked, 

764 'enable_m3u_import': pairs and not nd.get('m3u_import'), 

765 } 

766 

767 

768async def tool_get_navidrome_issues(_args: dict[str, Any]) -> dict[str, Any]: 

769 nd = _last_health()['result'].get('navidrome') 

770 if nd is None: 

771 raise ToolError('No health check yet: call run_health_check.') 

772 if not nd.get('enabled'): 

773 return {'enabled': False, 'note': 'Navidrome is not set up.'} 

774 if not nd.get('reachable', True): 

775 return {'enabled': True, 'reachable': False} 

776 return { 

777 'enabled': True, 

778 'admin_login_set': nd.get('admin'), 

779 'm3u_import_on': nd.get('m3u_import'), 

780 'playlists': nd.get('playlists'), 

781 'songs': nd.get('songs'), 

782 'duplicates': nd.get('duplicates') or [], 

783 'orphans': nd.get('orphans') or [], 

784 'incomplete': nd.get('incomplete') or [], 

785 'song_duplicates': nd.get('song_duplicates'), 

786 'deletable_ids': sorted(_doctor()._state.get('flagged') or []), 

787 'page_plan': navidrome_plan(nd), 

788 'note': ( 

789 'kind "import" = Navidrome imported it from an M3U file; ' 

790 '"downtify" = Downtify created it through the API. Only ' 

791 'playlists in deletable_ids can be deleted.' 

792 ), 

793 'out_of_date': 'navidrome' in _doctor()._stale, 

794 } 

795 

796 

797async def tool_suggest_navidrome_cleanup( 

798 args: dict[str, Any], 

799) -> dict[str, Any]: 

800 _check_fresh('navidrome') 

801 nd = _last_health()['result'].get('navidrome') or {} 

802 flagged = _doctor()._state.get('flagged') or set() 

803 ids = args.get('delete') 

804 if not isinstance(ids, list): 

805 raise ToolError('"delete" must list Navidrome playlist ids.') 

806 ids = list(dict.fromkeys(str(i) for i in ids if str(i))) 

807 unknown = [i for i in ids if i not in flagged] 

808 if unknown: 

809 raise ToolError( 

810 f'{unknown[0]!r} was not flagged by the health check; only ' 

811 'flagged playlists can be deleted.' 

812 ) 

813 enable = args.get('enable_m3u_import') is True 

814 if not ids and not enable: 

815 raise ToolError('Nothing to do: list ids, or enable M3U import.') 

816 reason = _reason_arg(args) 

817 by_id: dict[str, dict[str, Any]] = {} 

818 for dup in nd.get('duplicates') or []: 

819 for m in dup.get('members') or []: 

820 by_id[m['id']] = m 

821 for o in nd.get('orphans') or []: 

822 by_id.setdefault(o['id'], o) 

823 entry = _add({ 

824 'kind': 'navidrome', 

825 'decision': 'delete', 

826 'paths': ['nd:' + i for i in ids] + (['nd:import'] if enable else []), 

827 'delete': ids, 

828 'enable_m3u_import': enable, 

829 'reason': reason, 

830 'playlists': [ 

831 { 

832 k: by_id.get(i, {}).get(k) 

833 for k in ('id', 'name', 'songs', 'kind', 'm3u', 'm3u_exists') 

834 } 

835 | {'id': i} 

836 for i in ids 

837 ], 

838 }) 

839 return { 

840 'suggestion': entry['id'], 

841 'delete': len(ids), 

842 'enable_m3u_import': enable, 

843 } 

844 

845 

846def _navidrome_steps(chosen: list[dict[str, Any]], _user_id: int): 

847 dr = _doctor() 

848 payload = dr.NavidromeRepair( 

849 delete=list(dict.fromkeys(i for s in chosen for i in s['delete'])), 

850 enable_m3u_import=any(s['enable_m3u_import'] for s in chosen), 

851 ) 

852 

853 async def start(): 

854 return await dr.navidrome_repair(payload) 

855 

856 return [([s['id'] for s in chosen], start)] 

857 

858 

859# --------------------------------------------------------------------------- 

860# Registration 

861# --------------------------------------------------------------------------- 

862 

863 

864def _schema(props: dict[str, Any], required: list[str] = ()) -> dict: 

865 schema: dict[str, Any] = {'type': 'object', 'properties': props} 

866 if required: 

867 schema['required'] = list(required) 

868 return schema 

869 

870 

871_PAGE = { 

872 'offset': {'type': 'integer', 'minimum': 0, 'default': 0}, 

873 'limit': {'type': 'integer', 'minimum': 1}, 

874} 

875_FILES = {'type': 'array', 'items': {'type': 'string'}} 

876_READ = {'readOnlyHint': True} 

877_SUGGEST = {'readOnlyHint': False, 'destructiveHint': False} 

878 

879TOOLS = [ 

880 { 

881 'name': 'list_duplicate_songs', 

882 'description': ( 

883 'Duplicate songs from the last health check: groups of files ' 

884 'with the same artist, title and length ("exact" = the same ' 

885 'file content, "likely" = same song). Each copy with format, ' 

886 'bitrate, length, source, its own tags and its playlists.' 

887 ), 

888 'inputSchema': _schema({ 

889 **_PAGE, 

890 'kind': {'type': 'string', 'enum': ['exact', 'likely']}, 

891 }), 

892 'annotations': _READ, 

893 'run': tool_list_duplicate_songs, 

894 }, 

895 { 

896 'name': 'search_library', 

897 'description': ( 

898 'Find library files whose artist, title, album or path holds ' 

899 'every word of "query". Use it to find versions the Doctor ' 

900 'does not group: remixes, live, sped up, other lengths.' 

901 ), 

902 'inputSchema': _schema( 

903 {'query': {'type': 'string'}, 'limit': {'type': 'integer'}}, 

904 ['query'], 

905 ), 

906 'annotations': _READ, 

907 'run': tool_search_library, 

908 }, 

909 { 

910 'name': 'song_details', 

911 'description': ( 

912 'Up to 10 library files in detail: tags (album, date, track, ' 

913 'version), ISRC, lyrics (synced / plain / none), length, ' 

914 'format, source and the playlists each is in.' 

915 ), 

916 'inputSchema': _schema({'files': _FILES}, ['files']), 

917 'annotations': _READ, 

918 'run': tool_song_details, 

919 }, 

920 { 

921 'name': 'compare_audio', 

922 'description': ( 

923 'Whether 2-10 library files hold bit-for-bit the same decoded ' 

924 "audio (the Doctor's audio fingerprint). Can take a while." 

925 ), 

926 'inputSchema': _schema({'files': _FILES}, ['files']), 

927 'annotations': _READ, 

928 'run': tool_compare_audio, 

929 }, 

930 { 

931 'name': 'lookup_musicbrainz', 

932 'description': ( 

933 'Search MusicBrainz recordings by title (and artist): each ' 

934 'with its length, ISRCs, disambiguation (remix, live, ...) ' 

935 'and releases (official / bootleg, album / single / ' 

936 'compilation, date). Use it to tell the original from other ' 

937 'versions.' 

938 ), 

939 'inputSchema': _schema( 

940 { 

941 'title': {'type': 'string'}, 

942 'artist': {'type': 'string'}, 

943 'limit': {'type': 'integer', 'minimum': 1, 'maximum': 10}, 

944 }, 

945 ['title'], 

946 ), 

947 'annotations': _READ, 

948 'run': tool_lookup_musicbrainz, 

949 }, 

950 { 

951 'name': 'suggest_keep_song', 

952 'description': ( 

953 'Suggest keeping one copy of a song and removing the others. ' 

954 'On Apply, everything that used the others (playlists, likes, ' 

955 'watches, the Spotify id index) moves to the kept copy first; ' 

956 'then they go to the music trash (or are deleted for good if ' 

957 'it is off). The copies need not be a Doctor group: a remix ' 

958 'or live version you found can be folded into the original. ' 

959 '"reason" is shown to the user.' 

960 ), 

961 'inputSchema': _schema( 

962 { 

963 'keep': {'type': 'string'}, 

964 'remove': _FILES, 

965 'reason': {'type': 'string'}, 

966 }, 

967 ['keep', 'remove', 'reason'], 

968 ), 

969 'annotations': _SUGGEST, 

970 'run': tool_suggest_keep_song, 

971 }, 

972 { 

973 'name': 'suggest_different_songs', 

974 'description': ( 

975 'Suggest that the files of a Doctor duplicate group are ' 

976 'different songs, so the Doctor stops listing them.' 

977 ), 

978 'inputSchema': _schema( 

979 {'files': _FILES, 'reason': {'type': 'string'}}, 

980 ['files', 'reason'], 

981 ), 

982 'annotations': _SUGGEST, 

983 'run': tool_suggest_different_songs, 

984 }, 

985 { 

986 'name': 'list_new_spotify_id_repeats', 

987 'description': ( 

988 'Songs a watch downloaded again because Spotify gave the same ' 

989 'song a new id: the watch, the song, its files and ids.' 

990 ), 

991 'inputSchema': _schema(dict(_PAGE)), 

992 'annotations': _READ, 

993 'run': tool_list_new_spotify_id_repeats, 

994 }, 

995 { 

996 'name': 'get_slskd_leftovers', 

997 'description': ( 

998 "Files left in slskd's folder after import, from the last " 

999 'slskd check: verified (same audio as a library file, safe to ' 

1000 'delete), different, unmatched, recent, unreadable.' 

1001 ), 

1002 'inputSchema': _schema({ 

1003 **_PAGE, 

1004 'status': { 

1005 'type': 'string', 

1006 'enum': [ 

1007 'verified', 

1008 'different', 

1009 'unmatched', 

1010 'unreadable', 

1011 'recent', 

1012 'missing', 

1013 ], 

1014 }, 

1015 }), 

1016 'annotations': _READ, 

1017 'run': tool_get_slskd_leftovers, 

1018 }, 

1019 { 

1020 'name': 'run_slskd_check', 

1021 'description': ( 

1022 "Check slskd's leftovers against the library (deletes " 

1023 'nothing). New downloads wait while it runs and until the ' 

1024 'leftovers are cleaned or resume_downloads is called (at ' 

1025 'most an hour): call it when nothing will be cleaned now.' 

1026 ), 

1027 'inputSchema': _schema({ 

1028 'wait_seconds': {'type': 'integer', 'minimum': 0, 'maximum': 600} 

1029 }), 

1030 'annotations': _READ, 

1031 'run': tool_run_slskd_check, 

1032 }, 

1033 { 

1034 'name': 'resume_downloads', 

1035 'description': ( 

1036 'Let new downloads run again after run_slskd_check, leaving ' 

1037 "the leftovers in slskd's folder (the page's \"Keep files and " 

1038 'resume downloads").' 

1039 ), 

1040 'inputSchema': _schema({}), 

1041 'annotations': {'readOnlyHint': False, 'destructiveHint': False}, 

1042 'run': tool_resume_downloads, 

1043 }, 

1044 { 

1045 'name': 'suggest_slskd_clean', 

1046 'description': ( 

1047 'Suggest deleting verified slskd leftovers (listed "files", ' 

1048 'or "all_verified": true). Only verified ones can be deleted.' 

1049 ), 

1050 'inputSchema': _schema( 

1051 { 

1052 'files': _FILES, 

1053 'all_verified': {'type': 'boolean'}, 

1054 'reason': {'type': 'string'}, 

1055 }, 

1056 ['reason'], 

1057 ), 

1058 'annotations': _SUGGEST, 

1059 'run': tool_suggest_slskd_clean, 

1060 }, 

1061 { 

1062 'name': 'get_navidrome_issues', 

1063 'description': ( 

1064 'What Navidrome shows: duplicate playlists (imported M3U vs ' 

1065 "Downtify's API copy), playlists whose M3U is gone, playlists " 

1066 'missing songs, duplicate songs, which playlists may be ' 

1067 "deleted, and the Doctor page's own plan." 

1068 ), 

1069 'inputSchema': _schema({}), 

1070 'annotations': _READ, 

1071 'run': tool_get_navidrome_issues, 

1072 }, 

1073 { 

1074 'name': 'suggest_navidrome_cleanup', 

1075 'description': ( 

1076 'Suggest deleting flagged Navidrome playlists ("delete": ids) ' 

1077 'and/or turning on "Let Navidrome import the M3U playlists". ' 

1078 'Navidrome rescans afterwards.' 

1079 ), 

1080 'inputSchema': _schema( 

1081 { 

1082 'delete': {'type': 'array', 'items': {'type': 'string'}}, 

1083 'enable_m3u_import': {'type': 'boolean'}, 

1084 'reason': {'type': 'string'}, 

1085 }, 

1086 ['delete', 'reason'], 

1087 ), 

1088 'annotations': _SUGGEST, 

1089 'run': tool_suggest_navidrome_cleanup, 

1090 }, 

1091] 

1092 

1093doctor_ai.register(TOOLS) 

1094doctor_ai.APPLIERS.update({ 

1095 'songs': _song_steps, 

1096 'slskd': _slskd_steps, 

1097 'navidrome': _navidrome_steps, 

1098})