|
| 1 | +import re |
| 2 | +from argparse import Namespace |
| 3 | +from difflib import SequenceMatcher |
| 4 | + |
| 5 | +import ftfy |
| 6 | +import pandas as pd |
| 7 | +from asreview import ASReviewData |
| 8 | +from pandas.api.types import is_object_dtype |
| 9 | +from pandas.api.types import is_string_dtype |
| 10 | +from rich.console import Console |
| 11 | +from rich.text import Text |
| 12 | +from tqdm import tqdm |
| 13 | + |
| 14 | + |
| 15 | +def _print_similar_list( |
| 16 | + similar_list: list[tuple[int, int]], |
| 17 | + data: pd.Series, |
| 18 | + pid: str, |
| 19 | + pids: pd.Series = None |
| 20 | + ) -> None: |
| 21 | + |
| 22 | + print_seq_matcher = SequenceMatcher() |
| 23 | + console = Console() |
| 24 | + |
| 25 | + if pids is not None: |
| 26 | + print(f'Found similar titles or same {pid} at lines:') |
| 27 | + else: |
| 28 | + print('Found similar titles at lines:') |
| 29 | + |
| 30 | + for i, j in similar_list: |
| 31 | + print_seq_matcher.set_seq1(data.iloc[i]) |
| 32 | + print_seq_matcher.set_seq2(data.iloc[j]) |
| 33 | + text = Text() |
| 34 | + |
| 35 | + if pids is not None: |
| 36 | + text.append(f'\nLines {i+1} and {j+1} ', style='bold') |
| 37 | + if pids.iloc[i] == pids.iloc[j]: |
| 38 | + text.append(f'(same {pid} "{pids.iloc[i]}"):\n', style='dim') |
| 39 | + else: |
| 40 | + text.append(f'({pid} "{pids.iloc[i]}" and "{pids.iloc[j]}"):\n', |
| 41 | + style='dim') |
| 42 | + |
| 43 | + else: |
| 44 | + text.append(f'\nLines {i+1} and {j+1}:\n', style='bold') |
| 45 | + |
| 46 | + for tag, i1, i2, j1, j2 in print_seq_matcher.get_opcodes(): |
| 47 | + if tag == 'replace': |
| 48 | + # add rich strikethrough |
| 49 | + text.append(f'{data.iloc[i][i1:i2]}', style='red strike') |
| 50 | + text.append(f'{data.iloc[j][j1:j2]}', style='green') |
| 51 | + if tag == 'delete': |
| 52 | + text.append(f'{data.iloc[i][i1:i2]}', style='red strike') |
| 53 | + if tag == 'insert': |
| 54 | + text.append(f'{data.iloc[j][j1:j2]}', style='green') |
| 55 | + if tag == 'equal': |
| 56 | + text.append(f'{data.iloc[i][i1:i2]}', style='dim') |
| 57 | + |
| 58 | + console.print(text) |
| 59 | + |
| 60 | + print('') |
| 61 | + |
| 62 | + |
| 63 | +def _drop_duplicates_by_similarity( |
| 64 | + asdata: ASReviewData, |
| 65 | + pid: str, |
| 66 | + similarity: float = 0.98, |
| 67 | + skip_abstract: bool = False, |
| 68 | + discard_stopwords: bool = False, |
| 69 | + stopwords_language: str = 'english', |
| 70 | + strict_similarity: bool = False, |
| 71 | + verbose: bool = False, |
| 72 | + ) -> None: |
| 73 | + |
| 74 | + if skip_abstract: |
| 75 | + data = asdata.df['title'] |
| 76 | + else: |
| 77 | + data = pd.Series(asdata.texts) |
| 78 | + |
| 79 | + symbols_regex = re.compile(r'[^ \w\d\-_]') |
| 80 | + spaces_regex = re.compile(r'\s+') |
| 81 | + |
| 82 | + # clean the data |
| 83 | + s = ( |
| 84 | + data |
| 85 | + .apply(ftfy.fix_text) |
| 86 | + .str.replace(symbols_regex, '', regex=True) |
| 87 | + .str.replace(spaces_regex, ' ', regex=True) |
| 88 | + .str.lower() |
| 89 | + .str.strip() |
| 90 | + .replace('', None) |
| 91 | + ) |
| 92 | + |
| 93 | + if discard_stopwords: |
| 94 | + try: |
| 95 | + from nltk.corpus import stopwords |
| 96 | + stopwords_set = set(stopwords.words(stopwords_language)) |
| 97 | + except LookupError: |
| 98 | + import nltk |
| 99 | + nltk.download('stopwords') |
| 100 | + stopwords_set = set(stopwords.words(stopwords_language)) |
| 101 | + |
| 102 | + stopwords_regex = re.compile(rf'\b{"\\b|\\b".join(stopwords_set)}\b') |
| 103 | + s = s.str.replace(stopwords_regex, '', regex=True) |
| 104 | + |
| 105 | + seq_matcher = SequenceMatcher() |
| 106 | + duplicated = [False] * len(s) |
| 107 | + |
| 108 | + if verbose: |
| 109 | + similar_list = [] |
| 110 | + else: |
| 111 | + similar_list = None |
| 112 | + |
| 113 | + if pid in asdata.df.columns: |
| 114 | + if is_string_dtype(asdata.df[pid]) or is_object_dtype(asdata.df[pid]): |
| 115 | + pids = asdata.df[pid].str.strip().replace("", None) |
| 116 | + if pid == "doi": |
| 117 | + pids = pids.str.lower().str.replace( |
| 118 | + r"^https?://(www\.)?doi\.org/", "", regex=True |
| 119 | + ) |
| 120 | + |
| 121 | + else: |
| 122 | + pids = asdata.df[pid] |
| 123 | + |
| 124 | + for i, text in tqdm(s.items(), total=len(s), desc='Deduplicating'): |
| 125 | + seq_matcher.set_seq2(text) |
| 126 | + |
| 127 | + # loop through the rest of the data if it has the same pid or similar length |
| 128 | + for j, t in s.iloc[i+1:][(asdata.df[pid] == asdata.df.iloc[i][pid]) | |
| 129 | + (abs(s.str.len() - len(text)) < 5)].items(): |
| 130 | + seq_matcher.set_seq1(t) |
| 131 | + |
| 132 | + # if the texts have the same pid or are similar enough, |
| 133 | + # mark the second one as duplicate |
| 134 | + if pids.iloc[i] == pids.iloc[j] or \ |
| 135 | + (seq_matcher.real_quick_ratio() > similarity and \ |
| 136 | + seq_matcher.quick_ratio() > similarity and \ |
| 137 | + (not strict_similarity or seq_matcher.ratio() > similarity)): |
| 138 | + |
| 139 | + if verbose and not duplicated[j]: |
| 140 | + similar_list.append((i, j)) |
| 141 | + |
| 142 | + duplicated[j] = True |
| 143 | + |
| 144 | + if verbose: |
| 145 | + _print_similar_list(similar_list, data, pid, pids) |
| 146 | + |
| 147 | + else: |
| 148 | + print(f'Not using {pid} for deduplication because there is no such data.') |
| 149 | + |
| 150 | + for i, text in tqdm(s.items(), total=len(s), desc='Deduplicating'): |
| 151 | + seq_matcher.set_seq2(text) |
| 152 | + |
| 153 | + # loop through the rest of the data if it has similar length |
| 154 | + for j, t in s.iloc[i+1:][abs(s.str.len() - len(text)) < 5].items(): |
| 155 | + seq_matcher.set_seq1(t) |
| 156 | + |
| 157 | + # if the texts are similar enough, mark the second one as duplicate |
| 158 | + if seq_matcher.real_quick_ratio() > similarity and \ |
| 159 | + seq_matcher.quick_ratio() > similarity and \ |
| 160 | + (not strict_similarity or seq_matcher.ratio() > similarity): |
| 161 | + |
| 162 | + if verbose and not duplicated[j]: |
| 163 | + similar_list.append((i, j)) |
| 164 | + |
| 165 | + duplicated[j] = True |
| 166 | + |
| 167 | + if verbose: |
| 168 | + _print_similar_list(similar_list, data, pid) |
| 169 | + |
| 170 | + asdata.df = asdata.df[~pd.Series(duplicated)].reset_index(drop=True) |
| 171 | + |
| 172 | + |
| 173 | +def deduplicate_data(asdata: ASReviewData, args: Namespace) -> None: |
| 174 | + initial_length = len(asdata.df) |
| 175 | + |
| 176 | + if not args.similar: |
| 177 | + if args.pid not in asdata.df.columns: |
| 178 | + print( |
| 179 | + f'Not using {args.pid} for deduplication ' |
| 180 | + 'because there is no such data.' |
| 181 | + ) |
| 182 | + |
| 183 | + # retrieve deduplicated ASReview data object |
| 184 | + asdata.drop_duplicates(pid=args.pid, inplace=True) |
| 185 | + |
| 186 | + else: |
| 187 | + _drop_duplicates_by_similarity( |
| 188 | + asdata, |
| 189 | + args.pid, |
| 190 | + args.threshold, |
| 191 | + args.title_only, |
| 192 | + args.stopwords, |
| 193 | + args.stopwords_language, |
| 194 | + args.strict, |
| 195 | + args.verbose, |
| 196 | + ) |
| 197 | + |
| 198 | + # count duplicates |
| 199 | + n_dup = initial_length - len(asdata.df) |
| 200 | + |
| 201 | + if args.output_path: |
| 202 | + asdata.to_file(args.output_path) |
| 203 | + print( |
| 204 | + f'Removed {n_dup} duplicates from dataset with' |
| 205 | + f' {initial_length} records.' |
| 206 | + ) |
| 207 | + else: |
| 208 | + print( |
| 209 | + f'Found {n_dup} duplicates in dataset with' |
| 210 | + f' {initial_length} records.' |
| 211 | + ) |
0 commit comments