File size: 12,689 Bytes
11a28db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838da49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11a28db
 
 
 
 
 
 
a3caaa3
 
 
838da49
 
 
 
 
 
 
11a28db
 
 
838da49
11a28db
 
 
 
 
 
838da49
 
 
11a28db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Metadata comparison between bib entries and fetched metadata.
"""
from datetime import datetime
from dataclasses import dataclass
from typing import Optional, List, Union, Any, Tuple

from .parser import BibEntry
from .utils import TextNormalizer

CURRENT_YEAR = datetime.now().year

# Year source priority: lower number = more trustworthy
YEAR_SOURCE_PRIORITY = {
    "crossref":          0,   # DOI-verified, most accurate
    "dblp":              1,   # Conference proceedings
    "openalex":          2,
    "semantic_scholar":   3,
    "arxiv_journal_ref": 4,   # arXiv's journal_ref field
    "scholar":           5,
    "arxiv":             99,  # arXiv submission date β€” last resort
}


def resolve_year(candidates: list, bib_year: str = "") -> Tuple[Optional[str], Optional[str]]:
    """
    Pick the best year across all candidate results using source priority.
    Conference/journal year always beats arXiv submission year.
    Never returns a future year.
    
    Args:
        candidates: list of ComparisonResult objects
        bib_year: the current bib entry year (fallback)
    Returns:
        (best_year, best_source) or (None, None)
    """
    pool = []
    for cand in candidates:
        if not cand or not cand.fetched_data:
            continue
        source = cand.source
        fetched_year = str(getattr(cand.fetched_data, 'year', '') or '').strip()
        
        if not fetched_year or not fetched_year.isdigit():
            continue
        
        # Check for conference_year from arXiv journal_ref
        conf_year = str(getattr(cand.fetched_data, 'conference_year', '') or '').strip()
        if source == "arxiv" and conf_year and conf_year.isdigit():
            pool.append((YEAR_SOURCE_PRIORITY.get("arxiv_journal_ref", 4), conf_year, "arxiv_journal_ref"))
        
        priority = YEAR_SOURCE_PRIORITY.get(source, 50)
        pool.append((priority, fetched_year, source))
    
    if not pool:
        return None, None
    
    pool.sort()
    
    # Pick best year that isn't in the future
    for _, year, source in pool:
        if int(year) <= CURRENT_YEAR:
            return year, source
    
    # All years are future β€” return None
    return None, None


@dataclass
class ComparisonResult:
    """Result of comparing bib entry with fetched metadata."""
    entry_key: str
    
    # Title comparison
    title_match: bool
    title_similarity: float
    bib_title: str
    fetched_title: str
    
    # Author comparison
    author_match: bool
    author_similarity: float
    bib_authors: list[str]
    fetched_authors: list[str]
    
    # Year comparison
    year_match: bool
    bib_year: str
    fetched_year: str
    
    # Overall assessment
    is_match: bool
    confidence: float
    issues: list[str]
    source: str
    
    # Raw metadata for auto-fixing
    fetched_data: Any = None
    
    # Author initial conflict flag
    author_initial_conflict: bool = False
    
    @property
    def has_issues(self) -> bool:
        return len(self.issues) > 0

@dataclass
class EntryReport:
    """Complete report for a single bib entry."""
    entry: BibEntry
    comparison: Optional[ComparisonResult]
    evaluations: list = None
    
    def __post_init__(self):
        if self.evaluations is None:
            self.evaluations = []



class MetadataComparator:
    """Compares bibliography entries with fetched metadata."""
    
    # Thresholds for matching
    TITLE_THRESHOLD = 0.8
    AUTHOR_THRESHOLD = 0.6
    
    def __init__(self):
        self.normalizer = TextNormalizer
    
    def compare(self, bib_entry: BibEntry, fetched_data: Any, source_name: str) -> ComparisonResult:
        """
        Generic comparison method for any data source.
        fetched_data must have 'title', 'year', and 'authors' attributes.
        """
        issues = []
        
        # --- Title Comparison ---
        bib_title_norm = self.normalizer.normalize_for_comparison(bib_entry.title)
        fetched_title_norm = self.normalizer.normalize_for_comparison(fetched_data.title)
        
        title_similarity = self.normalizer.similarity_ratio(bib_title_norm, fetched_title_norm)
        if len(bib_title_norm) < 100:
            lev_sim = self.normalizer.levenshtein_similarity(bib_title_norm, fetched_title_norm)
            title_similarity = max(title_similarity, lev_sim)
            
        title_match = title_similarity >= self.TITLE_THRESHOLD
        if not title_match:
            issues.append(f"Title mismatch (similarity: {title_similarity:.2%})")
            
        # --- Author Comparison ---
        bib_authors = self.normalizer.normalize_author_list(bib_entry.author)
        
        # Check for DBLP disambiguation IDs in bib entry author names
        raw_author_list = self.normalizer.parse_author_list(bib_entry.author)
        for raw_auth in raw_author_list:
            if self.normalizer.has_dblp_disambiguation_id(raw_auth.strip()):
                issues.append(f"DBLP disambiguation ID in author: '{raw_auth.strip()}'")
        
        # Handle different author formats (list vs string)
        fetched_authors_raw = getattr(fetched_data, 'authors', [])
        if isinstance(fetched_authors_raw, str):
            # Scholar style: "Author1, Author2"
            fetched_authors_raw = [a.strip() for a in fetched_authors_raw.split(',')]
            
        fetched_authors = [
            self.normalizer.normalize_author_name(str(a)) 
            for a in fetched_authors_raw
        ]
        
        author_similarity = self._compare_author_lists(bib_authors, fetched_authors)
        author_match = author_similarity >= self.AUTHOR_THRESHOLD

        allows_truncated_authors = any(
            token in str(raw_author).lower()
            for raw_author in raw_author_list
            for token in ("others", "et al")
        )
        if (
            author_match
            and bib_authors
            and fetched_authors
            and len(bib_authors) != len(fetched_authors)
            and not allows_truncated_authors
        ):
            author_match = False
            issues.append(f"Author count mismatch: bib={len(bib_authors)}, fetched={len(fetched_authors)}")
        
        if not author_match:
            issues.append(f"Author mismatch (similarity: {author_similarity:.2%})")
            
        # --- Year Comparison ---
        bib_year = str(bib_entry.year).strip()
        fetched_year = str(getattr(fetched_data, 'year', '')).strip()
        conference_year = str(getattr(fetched_data, 'conference_year', '') or '').strip()
        if source_name.startswith("arxiv") and conference_year and conference_year.isdigit():
            fetched_year = conference_year
        year_match = bool(bib_year and fetched_year and bib_year == fetched_year)

        if not bib_year:
            issues.append("Missing year in BibTeX entry")
        elif not fetched_year:
            issues.append(f"Missing year from {source_name} metadata")
        elif not year_match:
            issues.append(f"Year mismatch: bib={bib_year}, {source_name}={fetched_year}")
            
        # --- Overall Assessment ---
        is_match = title_match and author_match and year_match
        # Simple weighted confidence score
        confidence = (
            title_similarity * 0.5 + 
            author_similarity * 0.3 + 
            (1.0 if year_match else 0.5) * 0.2
        )
        if not year_match:
            # A title/author match with the wrong year is not safe enough to auto-fix.
            confidence = min(confidence, 0.8)
        
        # --- Author Initial Conflict Detection ---
        author_initial_conflict = self._check_author_initial_conflict(
            bib_authors, fetched_authors,
            self.normalizer.parse_author_list(bib_entry.author),
            fetched_authors_raw
        )
        if author_initial_conflict:
            issues.append("Author initial conflict detected (e.g., first-name initials differ)")
            # Cap confidence β€” don't auto-adopt these authors
            confidence = min(confidence, 0.7)
        
        return ComparisonResult(
            entry_key=bib_entry.key,
            title_match=title_match,
            title_similarity=title_similarity,
            bib_title=bib_entry.title,
            fetched_title=fetched_data.title,
            author_match=author_match,
            author_similarity=author_similarity,
            bib_authors=bib_authors,
            fetched_authors=fetched_authors,
            year_match=year_match,
            bib_year=bib_year,
            fetched_year=fetched_year,
            is_match=is_match,
            confidence=confidence,
            issues=issues,
            source=source_name,
            fetched_data=fetched_data,
            author_initial_conflict=author_initial_conflict
        )

    def create_unable_result(self, bib_entry: BibEntry, reason: str = "Unable to fetch metadata") -> ComparisonResult:
        """Create result when metadata couldn't be fetched."""
        return ComparisonResult(
            entry_key=bib_entry.key,
            title_match=False, title_similarity=0.0,
            bib_title=bib_entry.title, fetched_title="",
            author_match=False, author_similarity=0.0,
            bib_authors=self.normalizer.normalize_author_list(bib_entry.author), fetched_authors=[],
            year_match=False, bib_year=bib_entry.year, fetched_year="",
            is_match=False, confidence=0.0,
            issues=[reason], source="unable",
            fetched_data=None
        )
    
    def _compare_author_lists(self, list1: list[str], list2: list[str]) -> float:
        """Compare two author lists."""
        if not list1 and not list2: return 1.0
        if not list1 or not list2: return 0.0
        
        total_similarity = 0.0
        for author1 in list1:
            best_match = 0.0
            for author2 in list2:
                if self._names_match(author1, author2):
                    best_match = 1.0
                    break
                sim = self.normalizer.similarity_ratio(author1, author2)
                best_match = max(best_match, sim)
            total_similarity += best_match
        
        return total_similarity / len(list1)
    
    def _names_match(self, name1: str, name2: str) -> bool:
        """Check if two names match (handles abbreviated names)."""
        def split_name(n):
            parts = n.lower().replace('.', '').split()
            return parts

        words1 = split_name(name1)
        words2 = split_name(name2)
        if not words1 or not words2: return False
        
        # Last name must match (assuming last word is last name)
        if words1[-1] != words2[-1]:
             return False
             
        # First name check:
        if len(words1) > 1 and len(words2) > 1:
            f1 = words1[0]
            f2 = words2[0]
            
            # If one is just an initial
            if len(f1) == 1 or len(f2) == 1:
                if f1[0] != f2[0]: return False
            else:
                # Both full names - must match
                if f1 != f2: return False
                
        return True

    def _check_author_initial_conflict(
        self,
        bib_authors_norm: list[str],
        fetched_authors_norm: list[str],
        bib_authors_raw: list[str],
        fetched_authors_raw: list,
    ) -> bool:
        """
        Detect when first-name initials clearly conflict between
        bib entry and fetched data.
        
        e.g., "Y. Zhou" (bib) vs "Henry Zhou" (fetched) β†’ True (Y β‰  H)
        This prevents blindly overwriting authors with wrong names.
        """
        # Compare by position β€” aligned authors
        min_len = min(len(bib_authors_norm), len(fetched_authors_norm))
        if min_len == 0:
            return False

        for i in range(min_len):
            bib_parts = bib_authors_norm[i].split()
            fetched_parts = fetched_authors_norm[i].split()
            
            if len(bib_parts) < 2 or len(fetched_parts) < 2:
                continue
            
            # Last name must match to consider this a potential conflict
            if bib_parts[-1] != fetched_parts[-1]:
                continue
            
            bib_first = bib_parts[0]
            fetched_first = fetched_parts[0]
            
            # Both have first name info (not empty)
            if not bib_first or not fetched_first:
                continue
            
            # If initials differ, it's a conflict
            if bib_first[0] != fetched_first[0]:
                return True
        
        return False