checker.py
28 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
"""Lyric candidate ranking and duplicate decision rules."""
from __future__ import annotations
import hashlib
import re
import unicodedata
from dataclasses import dataclass
from enum import Enum
from lyric_dedup.normalization import NormalizedLyrics
from lyric_dedup.normalization import fingerprint_text
from lyric_dedup.normalization import lyric_tokens
from lyric_dedup.normalization import normalize_lyrics
class DuplicateDecision(str, Enum):
DUPLICATE = "duplicate"
REVIEW = "review"
NEW = "new"
@dataclass(frozen=True)
class LyricRecord:
record_id: str
lyrics: str
title: str | None = None
artist: str | None = None
lyricist: str | None = None
composer: str | None = None
@dataclass(frozen=True)
class CandidateMatch:
record_id: str
decision: DuplicateDecision
confidence: float
jaccard: float
line_coverage: float
primary_jaccard: float
primary_line_coverage: float
translation_jaccard: float
translation_line_coverage: float
matched_unique_lines: tuple[str, ...]
reason: str
@dataclass(frozen=True)
class DuplicateCheckResult:
decision: DuplicateDecision
confidence: float
candidates: tuple[CandidateMatch, ...]
normalized_full_text: str
reason: str
@dataclass(frozen=True)
class _IndexedRecord:
record: LyricRecord
normalized: NormalizedLyrics
exact_hash: str
tokens: set[str]
primary_tokens: set[str]
translation_tokens: set[str]
fallback_lines: tuple[str, ...]
fallback_tokens: set[str]
class DuplicateChecker:
"""Rank PostgreSQL-recalled candidates and produce the final decision."""
def __init__(
self,
*,
duplicate_jaccard_threshold: float = 0.78,
duplicate_line_coverage_threshold: float = 0.72,
duplicate_high_coverage_jaccard_threshold: float = 0.78,
duplicate_high_coverage_line_coverage_threshold: float = 0.90,
review_jaccard_threshold: float = 0.45,
review_line_coverage_threshold: float = 0.35,
review_query_coverage_threshold: float = 0.40,
fragment_query_coverage_threshold: float = 0.80,
fragment_max_line_ratio: float = 0.75,
fragment_min_matched_lines: int = 3,
chorus_short_line_count_threshold: int = 6,
chorus_material_overlap_threshold: float = 0.20,
chorus_material_query_coverage_threshold: float = 0.40,
confidence_jaccard_weight: float = 0.58,
confidence_line_coverage_weight: float = 0.42,
metadata_duplicate_jaccard_threshold: float = 0.88,
metadata_duplicate_line_coverage_threshold: float = 0.65,
metadata_duplicate_min_primary_lines: int = 8,
auto_duplicate_min_primary_lines: int = 4,
exact_duplicate_min_primary_chars: int = 40,
) -> None:
self.duplicate_jaccard_threshold = duplicate_jaccard_threshold
self.duplicate_line_coverage_threshold = duplicate_line_coverage_threshold
self.duplicate_high_coverage_jaccard_threshold = duplicate_high_coverage_jaccard_threshold
self.duplicate_high_coverage_line_coverage_threshold = duplicate_high_coverage_line_coverage_threshold
self.review_jaccard_threshold = review_jaccard_threshold
self.review_line_coverage_threshold = review_line_coverage_threshold
self.review_query_coverage_threshold = review_query_coverage_threshold
self.fragment_query_coverage_threshold = fragment_query_coverage_threshold
self.fragment_max_line_ratio = fragment_max_line_ratio
self.fragment_min_matched_lines = fragment_min_matched_lines
self.chorus_short_line_count_threshold = chorus_short_line_count_threshold
self.chorus_material_overlap_threshold = chorus_material_overlap_threshold
self.chorus_material_query_coverage_threshold = chorus_material_query_coverage_threshold
self.confidence_jaccard_weight = confidence_jaccard_weight
self.confidence_line_coverage_weight = confidence_line_coverage_weight
self.metadata_duplicate_jaccard_threshold = metadata_duplicate_jaccard_threshold
self.metadata_duplicate_line_coverage_threshold = metadata_duplicate_line_coverage_threshold
self.metadata_duplicate_min_primary_lines = metadata_duplicate_min_primary_lines
self.auto_duplicate_min_primary_lines = auto_duplicate_min_primary_lines
self.exact_duplicate_min_primary_chars = exact_duplicate_min_primary_chars
def check_record_against_candidates(
self,
record: LyricRecord,
candidates: list[LyricRecord],
*,
max_candidates: int = 10,
) -> DuplicateCheckResult:
"""Rank explicitly supplied candidates without doing in-memory recall.
PostgreSQL-backed callers should use this method after database recall so
there is only one retrieval path: PG returns candidates, Python ranks and
decides.
"""
query = self._index(record)
ranked = sorted(
(
self._rank_exact_candidate(query, indexed)
if indexed.exact_hash == query.exact_hash
else self._rank_candidate(query, indexed)
for indexed in (self._index(candidate) for candidate in candidates)
),
key=lambda item: (item.decision == DuplicateDecision.DUPLICATE, item.confidence, item.jaccard),
reverse=True,
)[:max_candidates]
duplicate = next((candidate for candidate in ranked if candidate.decision == DuplicateDecision.DUPLICATE), None)
if duplicate is not None:
return DuplicateCheckResult(
decision=DuplicateDecision.DUPLICATE,
confidence=duplicate.confidence,
candidates=tuple(ranked),
normalized_full_text=query.normalized.normalized_full_text,
reason=duplicate.reason,
)
review = next((candidate for candidate in ranked if candidate.decision == DuplicateDecision.REVIEW), None)
if review is not None:
return DuplicateCheckResult(
decision=DuplicateDecision.REVIEW,
confidence=review.confidence,
candidates=tuple(ranked),
normalized_full_text=query.normalized.normalized_full_text,
reason=review.reason,
)
return DuplicateCheckResult(
decision=DuplicateDecision.NEW,
confidence=1.0 - (ranked[0].confidence if ranked else 0.0),
candidates=tuple(ranked),
normalized_full_text=query.normalized.normalized_full_text,
reason=(
ranked[0].reason
if ranked and ranked[0].reason.startswith("无有效歌词")
else "精确匹配、近重复召回和字面重合信号都较低"
),
)
def _index(self, record: LyricRecord) -> _IndexedRecord:
normalized = normalize_lyrics(record.lyrics)
return self._index_normalized(record, normalized)
def _index_normalized(self, record: LyricRecord, normalized: NormalizedLyrics) -> _IndexedRecord:
tokens = lyric_tokens(normalized)
primary_tokens = lyric_tokens(normalized, lines=normalized.primary_lines)
translation_tokens = lyric_tokens(normalized, lines=normalized.translation_lines)
fallback_lines = tuple(_fallback_no_lyrics_lines(record.lyrics))
fallback_tokens = set(fallback_lines)
exact_hash = hashlib.sha256(_exact_fingerprint(normalized, fallback_lines).encode("utf-8")).hexdigest()
return _IndexedRecord(
record=record,
normalized=normalized,
exact_hash=exact_hash,
tokens=tokens,
primary_tokens=primary_tokens,
translation_tokens=translation_tokens,
fallback_lines=fallback_lines,
fallback_tokens=fallback_tokens,
)
def _rank_exact_candidate(self, query: _IndexedRecord, candidate: _IndexedRecord) -> CandidateMatch:
low_confidence_split = (
query.normalized.split_confidence == "low" or candidate.normalized.split_confidence == "low"
)
translation_jaccard = _jaccard(query.translation_tokens, candidate.translation_tokens)
translation_coverage, _ = _line_coverage_lines(
query.normalized.translation_lines,
candidate.normalized.translation_lines,
)
no_effective_lyrics = not query.normalized.primary_lines and not candidate.normalized.primary_lines
if no_effective_lyrics:
decision = DuplicateDecision.NEW
confidence = 0.0
reason = "无有效歌词,不使用空内容或元数据兜底指纹自动判重"
elif low_confidence_split:
decision = DuplicateDecision.REVIEW
confidence = 0.95
reason = "原文哈希一致,但疑似整段翻译结构拆分置信度较低,需要人工复核"
elif not _has_enough_primary_text_chars(
query.normalized,
candidate.normalized,
min_chars=self.exact_duplicate_min_primary_chars,
):
decision = DuplicateDecision.REVIEW
confidence = 0.95
reason = "规范化后的原文哈希一致,但有效歌词过短,需要人工复核"
elif _is_generic_primary_lyrics(query.normalized) or _is_generic_primary_lyrics(candidate.normalized):
decision = DuplicateDecision.REVIEW
confidence = 0.95
reason = "规范化后的原文哈希一致,但有效歌词过短或为通用提示,需要人工复核"
elif query.normalized.translation_lines or candidate.normalized.translation_lines:
decision = DuplicateDecision.DUPLICATE
confidence = 1.0
reason = "规范化后的原文歌词哈希完全一致,翻译行未参与自动判重"
else:
decision = DuplicateDecision.DUPLICATE
confidence = 1.0
reason = "规范化后的原文歌词哈希完全一致"
return CandidateMatch(
record_id=candidate.record.record_id,
decision=decision,
confidence=confidence,
jaccard=1.0,
line_coverage=1.0,
primary_jaccard=1.0,
primary_line_coverage=1.0,
translation_jaccard=round(translation_jaccard, 4),
translation_line_coverage=round(translation_coverage, 4),
matched_unique_lines=query.normalized.primary_lines,
reason=reason,
)
def _rank_candidate(self, query: _IndexedRecord, candidate: _IndexedRecord) -> CandidateMatch:
if not query.normalized.primary_lines or not candidate.normalized.primary_lines:
return _rank_no_effective_lyrics_candidate(query, candidate)
jaccard = _jaccard(query.tokens, candidate.tokens)
coverage, matched_lines = _line_coverage(query.normalized, candidate.normalized)
primary_jaccard = _jaccard(query.primary_tokens, candidate.primary_tokens)
primary_coverage, primary_matched_lines = _line_coverage_lines(
query.normalized.primary_lines,
candidate.normalized.primary_lines,
)
query_primary_coverage = _matched_query_line_ratio(query.normalized.primary_lines, primary_matched_lines)
translation_jaccard = _jaccard(query.translation_tokens, candidate.translation_tokens)
translation_coverage, translation_matched_lines = _line_coverage_lines(
query.normalized.translation_lines,
candidate.normalized.translation_lines,
)
chorus_only = _is_chorus_only_match(query.normalized, candidate.normalized, primary_matched_lines)
translation_only = (
bool(translation_matched_lines)
and primary_jaccard < self.review_jaccard_threshold
and primary_coverage < self.review_line_coverage_threshold
and (translation_jaccard >= self.review_jaccard_threshold or translation_coverage >= self.review_line_coverage_threshold)
)
low_confidence_split = (
query.normalized.split_confidence == "low" or candidate.normalized.split_confidence == "low"
)
query_coverage = _matched_query_line_ratio(query.normalized.unique_lines, matched_lines)
is_plain_fragment = _is_plain_fragment(
query.normalized.primary_lines,
candidate.normalized.primary_lines,
primary_matched_lines,
min_query_coverage=self.fragment_query_coverage_threshold,
max_line_ratio=self.fragment_max_line_ratio,
min_matched_lines=self.fragment_min_matched_lines,
)
has_review_level_overlap = (
primary_jaccard >= self.review_jaccard_threshold
or jaccard >= self.review_jaccard_threshold
or (
primary_coverage >= self.review_line_coverage_threshold
and query_primary_coverage >= self.review_query_coverage_threshold
)
or (
coverage >= self.review_line_coverage_threshold
and query_coverage >= self.review_query_coverage_threshold
)
)
has_material_chorus_overlap = chorus_only and (
query.normalized.content_line_count <= self.chorus_short_line_count_threshold
or (
primary_jaccard >= self.chorus_material_overlap_threshold
and query_primary_coverage >= self.chorus_material_query_coverage_threshold
)
or (
jaccard >= self.chorus_material_overlap_threshold
and query_coverage >= self.chorus_material_query_coverage_threshold
)
or (
primary_coverage >= self.chorus_material_overlap_threshold
and query_primary_coverage >= self.chorus_material_query_coverage_threshold
)
or (
coverage >= self.chorus_material_overlap_threshold
and query_coverage >= self.chorus_material_query_coverage_threshold
)
)
has_low_confidence_split_overlap = low_confidence_split and has_review_level_overlap
has_cover_signal = _has_cover_signal(query.record) or _has_cover_signal(candidate.record)
has_metadata_supported_duplicate = self._has_metadata_supported_duplicate(
query,
candidate,
primary_jaccard=primary_jaccard,
primary_coverage=primary_coverage,
)
has_enough_auto_duplicate_lyrics = _has_enough_primary_lyrics(
query.normalized,
candidate.normalized,
min_lines=self.auto_duplicate_min_primary_lines,
)
has_generic_primary_lyrics = (
_is_generic_primary_lyrics(query.normalized)
or _is_generic_primary_lyrics(candidate.normalized)
)
confidence = round(
(self.confidence_jaccard_weight * primary_jaccard)
+ (self.confidence_line_coverage_weight * primary_coverage),
4,
)
if is_plain_fragment:
decision = DuplicateDecision.REVIEW
reason = "歌词片段只覆盖候选完整歌词的一部分,需要人工复核"
elif (
(
primary_jaccard >= self.duplicate_jaccard_threshold
or (
primary_jaccard >= self.duplicate_high_coverage_jaccard_threshold
and primary_coverage >= self.duplicate_high_coverage_line_coverage_threshold
)
)
and primary_coverage >= self.duplicate_line_coverage_threshold
and not chorus_only
and not translation_only
and not low_confidence_split
and not has_cover_signal
and has_enough_auto_duplicate_lyrics
and not has_generic_primary_lyrics
):
decision = DuplicateDecision.DUPLICATE
if query.normalized.translation_lines or candidate.normalized.translation_lines:
reason = "原文歌词高度一致,翻译行未参与自动判重"
else:
reason = "原文 n-gram 字面相似度高,且行级覆盖范围广"
elif has_metadata_supported_duplicate:
decision = DuplicateDecision.REVIEW
reason = "同词曲/同标题且原文歌词主体高度一致,需要人工复核"
elif has_material_chorus_overlap:
decision = DuplicateDecision.REVIEW
reason = "重合内容主要集中在重复副歌行,需要人工复核"
elif (
translation_only
or has_low_confidence_split_overlap
or has_review_level_overlap
or (has_cover_signal and (primary_jaccard >= self.review_jaccard_threshold or primary_coverage >= self.review_line_coverage_threshold))
):
decision = DuplicateDecision.REVIEW
reason = "候选相似度达到复核阈值,需要人工确认"
if translation_only:
reason = "仅翻译行相似,原文字面重合不足,不自动判重"
elif has_low_confidence_split_overlap:
reason = "疑似整段翻译结构但拆分置信度较低,需要人工复核"
elif has_cover_signal:
reason = "疑似翻唱/版本歌词相似,需要人工复核"
else:
decision = DuplicateDecision.NEW
reason = "候选重合度低于复核阈值"
return CandidateMatch(
record_id=candidate.record.record_id,
decision=decision,
confidence=confidence,
jaccard=round(jaccard, 4),
line_coverage=round(coverage, 4),
primary_jaccard=round(primary_jaccard, 4),
primary_line_coverage=round(primary_coverage, 4),
translation_jaccard=round(translation_jaccard, 4),
translation_line_coverage=round(translation_coverage, 4),
matched_unique_lines=tuple(matched_lines),
reason=reason,
)
def _has_metadata_supported_duplicate(
self,
query: _IndexedRecord,
candidate: _IndexedRecord,
*,
primary_jaccard: float,
primary_coverage: float,
) -> bool:
if primary_jaccard < self.metadata_duplicate_jaccard_threshold:
return False
if primary_coverage < self.metadata_duplicate_line_coverage_threshold:
return False
if not _has_enough_primary_lyrics(
query.normalized,
candidate.normalized,
min_lines=self.metadata_duplicate_min_primary_lines,
):
return False
if query.normalized.translation_lines or candidate.normalized.translation_lines:
return False
return _same_title(query.record, candidate.record) or _same_writers(query.record, candidate.record)
def _rank_no_effective_lyrics_candidate(query: _IndexedRecord, candidate: _IndexedRecord) -> CandidateMatch:
fallback_jaccard = _jaccard(query.fallback_tokens, candidate.fallback_tokens)
fallback_coverage, matched_lines = _line_coverage_lines(query.fallback_lines, candidate.fallback_lines)
if fallback_jaccard >= 0.35 and fallback_coverage >= 0.35 and len(matched_lines) >= 2:
return CandidateMatch(
record_id=candidate.record.record_id,
decision=DuplicateDecision.REVIEW,
confidence=round((0.58 * fallback_jaccard) + (0.42 * fallback_coverage), 4),
jaccard=round(fallback_jaccard, 4),
line_coverage=round(fallback_coverage, 4),
primary_jaccard=0.0,
primary_line_coverage=0.0,
translation_jaccard=0.0,
translation_line_coverage=0.0,
matched_unique_lines=tuple(matched_lines),
reason="无有效歌词,文件内容兜底特征高度相似,需要人工复核",
)
if fallback_jaccard >= 0.2 or fallback_coverage >= 0.2:
return CandidateMatch(
record_id=candidate.record.record_id,
decision=DuplicateDecision.REVIEW,
confidence=round((0.58 * fallback_jaccard) + (0.42 * fallback_coverage), 4),
jaccard=round(fallback_jaccard, 4),
line_coverage=round(fallback_coverage, 4),
primary_jaccard=0.0,
primary_line_coverage=0.0,
translation_jaccard=0.0,
translation_line_coverage=0.0,
matched_unique_lines=tuple(matched_lines),
reason="无有效歌词,文件内容兜底特征部分相似,需要人工复核",
)
return CandidateMatch(
record_id=candidate.record.record_id,
decision=DuplicateDecision.NEW,
confidence=0.0,
jaccard=round(fallback_jaccard, 4),
line_coverage=round(fallback_coverage, 4),
primary_jaccard=0.0,
primary_line_coverage=0.0,
translation_jaccard=0.0,
translation_line_coverage=0.0,
matched_unique_lines=(),
reason="无有效歌词,且文件内容兜底特征未命中",
)
def _jaccard(left: set[str], right: set[str]) -> float:
if not left and not right:
return 1.0
if not left or not right:
return 0.0
return len(left & right) / len(left | right)
def _normalize_meta(text: str | None) -> str:
if not text:
return ""
punctuation = " \t\n\r,。!?;:、\"“”‘’·…—~!¥()【】《》〈〉「」『』﹏,.:;!?()[]{}<>|/\\_-"
text = unicodedata.normalize("NFKC", str(text)).strip().lower()
return "".join(char for char in text if char not in punctuation)
def _same_title(left: LyricRecord, right: LyricRecord) -> bool:
left_title = _normalize_meta(left.title)
return bool(left_title) and left_title == _normalize_meta(right.title)
def _same_writers(left: LyricRecord, right: LyricRecord) -> bool:
left_lyricist = _normalize_meta(left.lyricist)
left_composer = _normalize_meta(left.composer)
return bool(left_lyricist or left_composer) and (
left_lyricist == _normalize_meta(right.lyricist)
and left_composer == _normalize_meta(right.composer)
)
def _has_cover_signal(record: LyricRecord) -> bool:
haystack = " ".join(
part for part in (record.title, record.artist, record.lyrics[:500]) if part
)
normalized = unicodedata.normalize("NFKC", haystack).lower()
if any(marker in normalized for marker in ("翻唱", "原唱", "片段", "串烧", "dj版")):
return True
return bool(re.search(r"\b(?:cover|covered by|remix|live|mashup|medley|dj)\b", normalized))
def _has_enough_primary_lyrics(
left: NormalizedLyrics,
right: NormalizedLyrics,
*,
min_lines: int,
) -> bool:
lyric_lines = set(left.primary_lines) | set(right.primary_lines)
meaningful = [
line for line in lyric_lines
if not _is_metadata_like_line(line) and len(line) >= 4
]
return len(meaningful) >= min_lines
def _has_enough_primary_text_chars(
left: NormalizedLyrics,
right: NormalizedLyrics,
*,
min_chars: int,
) -> bool:
left_chars = _normalized_primary_text_length(left)
right_chars = _normalized_primary_text_length(right)
return min(left_chars, right_chars) >= min_chars
def _normalized_primary_text_length(normalized: NormalizedLyrics) -> int:
return len(_normalize_meta("".join(normalized.primary_lines)))
def _is_metadata_like_line(line: str) -> bool:
normalized = _normalize_meta(line)
metadata_prefixes = (
"词",
"曲",
"作词",
"作曲",
"编曲",
"原唱",
"和声",
"制作",
"监制",
"录音",
"混音",
"母带",
"统筹",
"企划",
"营销",
"项目总监",
"出品",
"发行",
"op",
"sp",
"lyrics",
"composer",
"writer",
"producer",
"arranger",
)
return normalized.startswith(metadata_prefixes)
def _is_generic_primary_lyrics(normalized: NormalizedLyrics) -> bool:
"""Reject short non-song prompts from automatic duplicate decisions."""
primary_lines = normalized.primary_lines
if not primary_lines:
return True
meaningful = [
line for line in primary_lines
if not _is_metadata_like_line(line) and len(_normalize_meta(line)) > 3
]
if len(meaningful) > 2:
return False
compact = _normalize_meta(" ".join(primary_lines))
if len(compact) <= 3:
return True
generic_markers = (
"dj音乐",
"请欣赏",
"纯音乐",
"无歌词",
"伴奏",
"instrumental",
)
return any(marker in compact for marker in generic_markers)
def _exact_fingerprint(normalized: NormalizedLyrics, fallback_lines: tuple[str, ...]) -> str:
primary_text = fingerprint_text(normalized)
if primary_text:
return f"lyrics|{primary_text}"
return "no_effective_lyrics_content|" + "\n".join(fallback_lines)
def _fallback_no_lyrics_lines(text: str) -> list[str]:
import re
import unicodedata
lines: list[str] = []
for raw_line in unicodedata.normalize("NFKC", text).splitlines():
line = raw_line.strip().lower()
line = re.sub(r"\[(?:\d{1,2}:)?\d{1,2}:\d{2}(?:[.:]\d{1,3})?\]", "", line)
line = re.sub(r"[【\[].{0,80}?[】\]]", "", line)
if "歌词来自" in line or "qq音乐" in line or "网易云" in line or "酷狗" in line:
continue
if "未经" in line or "不得翻唱" in line or "不得翻录" in line or "著作权" in line:
continue
punctuation = ",。!?;:、“”‘’·…—~!¥()【】《》〈〉「」『』﹏,.;:!?()[]{}<>|/\\_-"
line = "".join(" " if char in punctuation else char for char in line)
line = re.sub(r"\s+", " ", line).strip()
if line:
lines.append(line)
return list(dict.fromkeys(lines))
def _line_coverage(left: NormalizedLyrics, right: NormalizedLyrics) -> tuple[float, list[str]]:
return _line_coverage_lines(left.unique_lines, right.unique_lines)
def _line_coverage_lines(left: tuple[str, ...], right: tuple[str, ...]) -> tuple[float, list[str]]:
left_lines = set(left)
right_lines = set(right)
if not left_lines and not right_lines:
return 1.0, []
if not left_lines or not right_lines:
return 0.0, []
matched = sorted(left_lines & right_lines)
return len(matched) / max(len(left_lines), len(right_lines)), matched
def _matched_query_line_ratio(query_lines: tuple[str, ...], matched_lines: list[str]) -> float:
query_unique_lines = set(query_lines)
if not query_unique_lines:
return 0.0
return len(set(matched_lines)) / len(query_unique_lines)
def _is_plain_fragment(
query_lines: tuple[str, ...],
candidate_lines: tuple[str, ...],
matched_lines: list[str],
*,
min_query_coverage: float,
max_line_ratio: float,
min_matched_lines: int,
) -> bool:
query_unique_lines = set(query_lines)
candidate_unique_lines = set(candidate_lines)
matched_unique_lines = set(matched_lines)
if not query_unique_lines or not candidate_unique_lines:
return False
if len(matched_unique_lines) < min_matched_lines:
return False
line_ratio = len(query_unique_lines) / len(candidate_unique_lines)
query_coverage = len(matched_unique_lines) / len(query_unique_lines)
return line_ratio <= max_line_ratio and query_coverage >= min_query_coverage
def _is_chorus_only_match(left: NormalizedLyrics, right: NormalizedLyrics, matched_lines: list[str]) -> bool:
if not matched_lines:
return False
matched = set(matched_lines)
repeated_matches = [
line
for line in matched
if left.line_counts.get(line, 0) >= 2 or right.line_counts.get(line, 0) >= 2
]
if len(matched) <= 2 and repeated_matches:
return True
if repeated_matches and len(repeated_matches) / len(matched) >= 0.8:
matched_ratio_left = sum(left.line_counts.get(line, 0) for line in matched) / max(left.content_line_count, 1)
matched_ratio_right = sum(right.line_counts.get(line, 0) for line in matched) / max(right.content_line_count, 1)
return min(matched_ratio_left, matched_ratio_right) < 0.7
return False