File size: 9,892 Bytes
2153792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import string
from typing import List, Optional, Union, Dict, Any, Callable

import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk import download as nltk_download
from nltk.stem import WordNetLemmatizer
import spacy
from gensim.models import KeyedVectors
from transformers import AutoTokenizer, AutoModel
import torch
import emoji
print('PREPROCESSING IMPORTED')

try:
    nltk_download('punkt', quiet=True)
    nltk_download('stopwords', quiet=True)
    nltk_download('wordnet', quiet=True)
except Exception as e:
    print(f"Warning: NLTK data download failed: {e}")

_SPACY_MODEL = None
_NLTK_LEMMATIZER = None
_BERT_TOKENIZER = None
_BERT_MODEL = None


def _load_spacy_model(lang: str = "en_core_web_sm"):
    global _SPACY_MODEL
    if _SPACY_MODEL is None:
        try:
            _SPACY_MODEL = spacy.load(lang)
        except OSError:
            raise ValueError(
                f"spaCy model '{lang}' not found. Please install it via: python -m spacy download {lang}"
            )
    return _SPACY_MODEL


def _load_nltk_lemmatizer():
    global _NLTK_LEMMATIZER
    if _NLTK_LEMMATIZER is None:
        _NLTK_LEMMATIZER = WordNetLemmatizer()
    return _NLTK_LEMMATIZER


def _load_bert_model(model_name: str = "bert-base-uncased"):
    global _BERT_TOKENIZER, _BERT_MODEL
    if _BERT_TOKENIZER is None or _BERT_MODEL is None:
        _BERT_TOKENIZER = AutoTokenizer.from_pretrained(model_name)
        _BERT_MODEL = AutoModel.from_pretrained(model_name)
    return _BERT_TOKENIZER, _BERT_MODEL


def clean_text(text: str) -> str:
    text = re.sub(r"<[^>]+>", "", text)
    text = re.sub(r"https?://\S+|www\.\S+", "", text)
    text = "".join(ch for ch in text if ch in string.printable)
    text = re.sub(r"\s+", " ", text).strip()
    return text


def replace_emojis(text: str) -> str:
    return emoji.demojize(text, delimiters=(" ", " "))


def preprocess_text(

        text: str,

        lang: str = "en",

        remove_stopwords: bool = True,

        use_spacy: bool = True,

        lemmatize: bool = True,

        emoji_to_text: bool = True,

        lowercase: bool = True,

        spacy_model: Optional[str] = None,

        replace_entities: bool = False  # ← новая опция: по умолчанию НЕ заменяем числа/URL

) -> List[str]:
    import re
    import string

    if emoji_to_text:
        text = replace_emojis(text)

    text = re.sub(r"<[^>]+>", "", text)

    text = re.sub(r"[^\w\s]", " ", text)  # заменяем НЕ-слова и НЕ-пробелы на пробел
    text = re.sub(r"\s+", " ", text).strip()

    if replace_entities:
        text = re.sub(r"\b\d+\b", "<NUM>", text)
        text = re.sub(r"https?://\S+|www\.\S+", "<URL>", text)
        text = re.sub(r"\S+@\S+", "<EMAIL>", text)

    if lowercase:
        text = text.lower()

    if use_spacy:
        spacy_lang = spacy_model or ("en_core_web_sm" if lang == "en" else f"{lang}_core_news_sm")
        nlp = _load_spacy_model(spacy_lang)
        doc = nlp(text)
        if lemmatize:
            tokens = [token.lemma_ for token in doc if not token.is_space and not token.is_punct]
        else:
            tokens = [token.text for token in doc if not token.is_space and not token.is_punct]

        if remove_stopwords:
            tokens = [token for token in tokens if not nlp.vocab[token].is_stop]

    else:
        tokens = word_tokenize(text)
        if lemmatize:
            lemmatizer = _load_nltk_lemmatizer()
            tokens = [lemmatizer.lemmatize(token) for token in tokens]

        if remove_stopwords:
            stop_words = set(stopwords.words(lang)) if lang in stopwords.fileids() else set()
            tokens = [token for token in tokens if token not in stop_words]

    tokens = [token for token in tokens if token not in string.punctuation and len(token) > 0]

    return tokens


class TextVectorizer:
    def __init__(self):
        self.bow_vectorizer = None
        self.tfidf_vectorizer = None

    def bow(self, texts: List[str], **kwargs) -> np.ndarray:
        self.bow_vectorizer = CountVectorizer(**kwargs)
        return self.bow_vectorizer.fit_transform(texts).toarray()

    def tfidf(self, texts: List[str], max_features: int = 5000, **kwargs) -> np.ndarray:
        kwargs['max_features'] = max_features
        self.tfidf_vectorizer = TfidfVectorizer(lowercase=False, **kwargs)
        return self.tfidf_vectorizer.fit_transform(texts).toarray()

    def ngrams(self, texts: List[str], ngram_range: tuple = (1, 2), **kwargs) -> np.ndarray:
        kwargs.setdefault("ngram_range", ngram_range)
        return self.tfidf(texts, **kwargs)


class EmbeddingVectorizer:
    def __init__(self):
        self.word2vec_model = None
        self.fasttext_model = None
        self.glove_vectors = None

    def load_word2vec(self, path: str):
        self.word2vec_model = KeyedVectors.load_word2vec_format(path, binary=True)

    def load_fasttext(self, path: str):
        self.fasttext_model = KeyedVectors.load(path)

    def load_glove(self, glove_file: str, vocab_size: int = 400000, dim: int = 300):
        self.glove_vectors = {}
        with open(glove_file, "r", encoding="utf-8") as f:
            for i, line in enumerate(f):
                if i >= vocab_size:
                    break
                values = line.split()
                word = values[0]
                vector = np.array(values[1:], dtype="float32")
                self.glove_vectors[word] = vector

    def _get_word_vector(self, word: str, method: str = "word2vec") -> Optional[np.ndarray]:
        if method == "word2vec" and self.word2vec_model and word in self.word2vec_model:
            return self.word2vec_model[word]
        elif method == "fasttext" and self.fasttext_model and word in self.fasttext_model:
            return self.fasttext_model[word]
        elif method == "glove" and self.glove_vectors and word in self.glove_vectors:
            return self.glove_vectors[word]
        return None

    def _aggregate_vectors(

            self, vectors: List[np.ndarray], strategy: str = "mean"

    ) -> np.ndarray:
        if not vectors:
            return np.zeros(300)  # default dim
        if strategy == "mean":
            return np.mean(vectors, axis=0)
        elif strategy == "max":
            return np.max(vectors, axis=0)
        else:
            raise ValueError("Strategy must be 'mean' or 'max'")

    def get_embeddings(

            self,

            tokenized_texts: List[List[str]],

            method: str = "word2vec",

            aggregation: str = "mean",

    ) -> np.ndarray:
        embeddings = []
        for tokens in tokenized_texts:
            vectors = [
                self._get_word_vector(token, method=method) for token in tokens
            ]
            vectors = [v for v in vectors if v is not None]
            doc_vec = self._aggregate_vectors(vectors, strategy=aggregation)
            embeddings.append(doc_vec)
        return np.array(embeddings)


def get_contextual_embeddings(

        texts: List[str],

        model_name: str = "bert-base-uncased",

        aggregation: str = "mean",

        device: str = "cpu",

) -> np.ndarray:
    tokenizer, model = _load_bert_model(model_name)
    model.to(device)
    model.eval()

    embeddings = []
    with torch.no_grad():
        for text in texts:
            inputs = tokenizer(
                text,
                return_tensors="pt",
                truncation=True,
                padding=True,
                max_length=512,
            )
            inputs = {k: v.to(device) for k, v in inputs.items()}
            outputs = model(**inputs)
            token_embeddings = outputs.last_hidden_state[0].cpu().numpy()

            # Exclude [CLS] and [SEP] if needed (simple heuristic: skip first and last)
            if len(token_embeddings) > 2:
                token_embeddings = token_embeddings[1:-1]

            if aggregation == "mean":
                doc_emb = np.mean(token_embeddings, axis=0)
            elif aggregation == "max":
                doc_emb = np.max(token_embeddings, axis=0)
            else:
                raise ValueError("aggregation must be 'mean' or 'max'")
            embeddings.append(doc_emb)

    return np.array(embeddings)


def extract_meta_features(texts: Union[List[str], pd.Series]) -> pd.DataFrame:
    if isinstance(texts, pd.Series):
        texts = texts.tolist()

    features = []
    for text in texts:
        original_len = len(text)
        words = text.split()
        word_lengths = [len(w) for w in words] if words else [0]
        avg_word_len = np.mean(word_lengths)
        num_unique_words = len(set(words)) if words else 0
        num_punct = sum(1 for c in text if c in string.punctuation)
        num_upper = sum(1 for c in text if c.isupper())
        num_digits = sum(1 for c in text if c.isdigit())

        try:
            flesch = np.nan
        except Exception:
            flesch = np.nan

        features.append({
            "text_length": original_len,
            "avg_word_length": avg_word_len,
            "num_unique_words": num_unique_words,
            "punctuation_ratio": num_punct / original_len if original_len > 0 else 0,
            "uppercase_ratio": num_upper / original_len if original_len > 0 else 0,
            "digit_ratio": num_digits / original_len if original_len > 0 else 0,
            "flesch_reading_ease": flesch,
        })

    return pd.DataFrame(features)