Views
No views yet
1import torch
2from transformers import AutoModelForTokenClassification, AutoTokenizer
3model_name = 'cointegrated/rubert-tiny2-sentence-compression'
4model = AutoModelForTokenClassification.from_pretrained(model_name)
5tokenizer = AutoTokenizer.from_pretrained(model_name)
6
7
8def compress(text, threshold=0.5, keep_ratio=None):
9 """ Compress a sentence by removing the least important words.
10 Parameters:
11 threshold: cutoff for predicted probabilities of word removal
12 keep_ratio: proportion of words to preserve
13 By default, threshold of 0.5 is used.
14 """
15 with torch.inference_mode():
16 tok = tokenizer(text, return_tensors='pt').to(model.device)
17 proba = torch.softmax(model(**tok).logits, -1).cpu().numpy()[0, :, 1]
18 if keep_ratio is not None:
19 threshold = sorted(proba)[int(len(proba) * keep_ratio)]
20 kept_toks = []
21 keep = False
22 prev_word_id = None
23 for word_id, score, token in zip(tok.word_ids(), proba, tok.input_ids[0]):
24 if word_id is None:
25 keep = True
26 elif word_id != prev_word_id:
27 keep = score < threshold
28 if keep:
29 kept_toks.append(token)
30 prev_word_id = word_id
31 return tokenizer.decode(kept_toks, skip_special_tokens=True)
32
33
34text = 'Кроме того, можно взять идею, рожденную из сердца, и выразить ее в рамках одной '\
35 'из этих структур, без потери искренности идеи и смысла песни.'
36
37print(compress(text))
38print(compress(text, threshold=0.3))
39print(compress(text, threshold=0.1))
40# можно взять идею, рожденную из сердца, и выразить ее в рамках одной из этих структур.
41# можно взять идею, рожденную из сердца выразить ее в рамках одной из этих структур.
42# можно взять идею рожденную выразить структур.
43
44print(compress(text, keep_ratio=0.5))
45# можно взять идею, рожденную из сердца выразить ее в рамках структур.