|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import Optional, Any, List |
| 5 | + |
| 6 | +import hnswlib |
| 7 | +import numpy as np |
| 8 | +import pandas as pd |
| 9 | +from sentence_transformers.util import cos_sim |
| 10 | + |
| 11 | +from plagiarism.doc import SourceDocumentCollection, SuspiciousDocumentCollection |
| 12 | +from plagiarism.vectorizer import StyleEmbedding |
| 13 | + |
| 14 | +logger = logging.getLogger() |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class ExtrinsicOutput: |
| 19 | + nn: Any |
| 20 | + score: Any |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class IntrinsicOutput: |
| 25 | + file_names: List |
| 26 | + sentences: List |
| 27 | + |
| 28 | + |
| 29 | +class Plagiarism: |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + source_doc: Optional[SourceDocumentCollection] = None, |
| 33 | + suspicious_doc: Optional[SuspiciousDocumentCollection] = None, |
| 34 | + approach=None, |
| 35 | + ): |
| 36 | + |
| 37 | + self.source_doc = source_doc |
| 38 | + self.suspicious_doc = suspicious_doc |
| 39 | + self.approach = approach |
| 40 | + |
| 41 | + self.index = None |
| 42 | + |
| 43 | + def query(self, **kwargs): |
| 44 | + raise NotImplementedError |
| 45 | + |
| 46 | + def save(self, **kwargs): |
| 47 | + raise NotImplementedError |
| 48 | + |
| 49 | + |
| 50 | +class Extrinsic(Plagiarism): |
| 51 | + def __init__( |
| 52 | + self, |
| 53 | + source_doc: Optional[SourceDocumentCollection] = None, |
| 54 | + suspicious_doc: Optional[SuspiciousDocumentCollection] = None, |
| 55 | + vector_model=None, |
| 56 | + ): |
| 57 | + super().__init__(source_doc, suspicious_doc, vector_model) |
| 58 | + self._header = [ |
| 59 | + "suspicious_filename", |
| 60 | + "plagarised_filename", |
| 61 | + "suspicious", |
| 62 | + "plagarised", |
| 63 | + "score", |
| 64 | + ] |
| 65 | + |
| 66 | + def index_embedding(self, embeddings, pth, ef_construction=400, m=64, ef=50): |
| 67 | + n, dim = embeddings.shape |
| 68 | + self.index = hnswlib.Index(space="cosine", dim=dim) |
| 69 | + self.index.init_index(max_elements=n, ef_construction=ef_construction, M=m) |
| 70 | + self.index.add_items(embeddings, list(range(n))) |
| 71 | + logger.info(f"SAVING GENERATED INDEX AT {pth}") |
| 72 | + self.index.save_index(pth) |
| 73 | + |
| 74 | + self.index.set_ef(ef) |
| 75 | + |
| 76 | + def _load_saved_index(self, pth, dim, ef): |
| 77 | + self.index = hnswlib.Index(space="cosine", dim=dim) |
| 78 | + self.index.load_index(pth) |
| 79 | + self.index.set_ef(ef) |
| 80 | + |
| 81 | + def nn_index( |
| 82 | + self, index_pth, dim: int = None, ef_construction=400, m=64, ef=50, **kwargs |
| 83 | + ): |
| 84 | + if os.path.exists(index_pth): |
| 85 | + logger.info(f"LOADING INDEX FROM {index_pth}") |
| 86 | + self._load_saved_index(index_pth, dim, ef) |
| 87 | + else: |
| 88 | + logger.info("GENERATING INDEX") |
| 89 | + embeddings = self.approach.run(self.source_doc.get_normalised_sentences()) |
| 90 | + self.index_embedding( |
| 91 | + embeddings, index_pth, ef_construction=ef_construction, m=m, ef=ef |
| 92 | + ) |
| 93 | + return self |
| 94 | + |
| 95 | + def query(self, nn=5): |
| 96 | + logger.info("VECTORIZATION IN PROGRESS") |
| 97 | + embeddings = self.approach.run(self.suspicious_doc.get_normalised_sentences()) |
| 98 | + |
| 99 | + logger.info("QUERYING DATA") |
| 100 | + nn, distances = self.index.knn_query(embeddings, nn) |
| 101 | + |
| 102 | + return ExtrinsicOutput(nn, 1 - distances) |
| 103 | + |
| 104 | + def save(self, pth, extrinsic_output: ExtrinsicOutput, distance_threshold=0.20): |
| 105 | + logger.info(f"SAVING IN PROGRESS AT {pth}") |
| 106 | + |
| 107 | + filtered_output_idx = np.where(extrinsic_output.score >= distance_threshold) |
| 108 | + |
| 109 | + suspicious_sentences_idx = filtered_output_idx[0] |
| 110 | + source_sentences_idx = extrinsic_output.nn[filtered_output_idx] |
| 111 | + |
| 112 | + suspicious_sentences_filtered = self.suspicious_doc.get_sentences()[ |
| 113 | + suspicious_sentences_idx |
| 114 | + ] |
| 115 | + source_sentences_filtered = self.source_doc.get_sentences()[ |
| 116 | + source_sentences_idx |
| 117 | + ] |
| 118 | + |
| 119 | + suspicious_file_filtered = self.suspicious_doc.get_file_names()[ |
| 120 | + suspicious_sentences_idx |
| 121 | + ] |
| 122 | + source_file_filtered = self.source_doc.get_file_names()[source_sentences_idx] |
| 123 | + |
| 124 | + pd.DataFrame( |
| 125 | + np.column_stack( |
| 126 | + [ |
| 127 | + suspicious_file_filtered, |
| 128 | + source_file_filtered, |
| 129 | + suspicious_sentences_filtered, |
| 130 | + source_sentences_filtered, |
| 131 | + np.round(extrinsic_output.score[filtered_output_idx], 2), |
| 132 | + ] |
| 133 | + ), |
| 134 | + columns=self._header, |
| 135 | + ).to_csv(pth) |
| 136 | + |
| 137 | + |
| 138 | +class Intrinsic(Plagiarism): |
| 139 | + def __init__( |
| 140 | + self, |
| 141 | + suspicious_doc: Optional[SuspiciousDocumentCollection] = None, |
| 142 | + vector_model=None, |
| 143 | + min_threshold: float = 0.60, |
| 144 | + ignore_sentence_with_len: int = 500, |
| 145 | + ): |
| 146 | + super().__init__(None, suspicious_doc, vector_model) |
| 147 | + self._header = [ |
| 148 | + "suspicious_filename", |
| 149 | + "plagarised", |
| 150 | + ] |
| 151 | + self._min_threshold = min_threshold |
| 152 | + self._ignore_sentence_with_len = ignore_sentence_with_len |
| 153 | + |
| 154 | + def query(self, **kwargs): |
| 155 | + plagiarised_sent = [] |
| 156 | + file_names = [] |
| 157 | + logger.info("QUERYING DATA") |
| 158 | + for file_name, sentences in self.suspicious_doc.sentence_per_file_gen(): |
| 159 | + if len(sentences) < self._ignore_sentence_with_len: |
| 160 | + |
| 161 | + embeddings = self.approach.run(sentences) |
| 162 | + mean_embeddings = embeddings.mean(axis=0).reshape(1, -1) |
| 163 | + cosine_scores = cos_sim(mean_embeddings, embeddings).numpy().flatten() |
| 164 | + |
| 165 | + plagiarised = list( |
| 166 | + sentences[np.where(cosine_scores <= self._min_threshold)] |
| 167 | + ) |
| 168 | + |
| 169 | + if len(plagiarised) > 0: |
| 170 | + file_names.extend([file_name] * len(plagiarised)) |
| 171 | + plagiarised_sent.extend(plagiarised) |
| 172 | + else: |
| 173 | + file_names.extend([file_name]) |
| 174 | + plagiarised_sent.extend(["NONE"]) |
| 175 | + |
| 176 | + return IntrinsicOutput(file_names, plagiarised_sent) |
| 177 | + |
| 178 | + def save(self, pth, intrinsic_output: IntrinsicOutput, **kwargs): |
| 179 | + pd.DataFrame( |
| 180 | + np.column_stack( |
| 181 | + [ |
| 182 | + intrinsic_output.file_names, |
| 183 | + intrinsic_output.sentences, |
| 184 | + ] |
| 185 | + ), |
| 186 | + columns=self._header, |
| 187 | + ).to_csv(pth) |
| 188 | + |
| 189 | + |
| 190 | +def extrinsic_plg( |
| 191 | + source_doc_pth, |
| 192 | + suspicious_doc_pth, |
| 193 | + source_doc_dir: list, |
| 194 | + suspicious_doc_dir: list, |
| 195 | + index_pth: str, |
| 196 | + save_pth: str, |
| 197 | + vector_model, |
| 198 | + distance_threshold: float = 0.90, |
| 199 | +): |
| 200 | + source_doc = SourceDocumentCollection( |
| 201 | + pth=source_doc_pth, |
| 202 | + dir_iter=source_doc_dir, |
| 203 | + ).extract_sentences() |
| 204 | + |
| 205 | + suspicious_doc = SuspiciousDocumentCollection( |
| 206 | + pth=suspicious_doc_pth, dir_iter=suspicious_doc_dir |
| 207 | + ).extract_sentences() |
| 208 | + |
| 209 | + ex = Extrinsic(source_doc, suspicious_doc, vector_model=vector_model) |
| 210 | + ex.nn_index(index_pth) |
| 211 | + ex_op = ex.query() |
| 212 | + ex.save( |
| 213 | + save_pth, |
| 214 | + ex_op, |
| 215 | + distance_threshold=distance_threshold, |
| 216 | + ) |
| 217 | + |
| 218 | + |
| 219 | +def intrinsic_plg(suspicious_pth: str, suspicious_dir: list, features: list): |
| 220 | + suspicious_doc = SuspiciousDocumentCollection( |
| 221 | + pth=suspicious_pth, |
| 222 | + dir_iter=suspicious_dir, |
| 223 | + ).extract_sentences() |
| 224 | + |
| 225 | + ii = Intrinsic(suspicious_doc=suspicious_doc, vector_model=StyleEmbedding(features)) |
| 226 | + op = ii.query() |
| 227 | + ii.save("intrinsic_output.csv", op) |
0 commit comments