Views
No views yet
1from transformers import AutoModel, AutoTokenizer, AutoModelForMaskedLM
2
3sentence = 'וזה לשון הרמב״ן בפירושו על התורה, שהדבר ידוע ומפורסם לכל בעלי העיון שאין המקרא יוצא מידי פשוטו אף על פי שהדרש אמת.'
4
5# First, load in the segmentation model, to preprocess the text
6seg_tokenizer = AutoTokenizer.from_pretrained('dicta-il/BEREL-seg')
7seg_model = AutoModel.from_pretrained('dicta-il/BEREL-seg', trust_remote_code=True).eval()
8
9segmented_output = seg_model.predict([sentence], seg_tokenizer)[0] # sentence sent as a batch, pick the first one
10
11# we mark the segmented tokens with a special separator, to distinguish them from regular work tokens.
12segmented_sentence = ' '.join('ףףף '.join(segmented_word) for segmented_word in segmented_output[1:-1]) # ignore cls/sep
13print(segmented_sentence.replace('ףףף', '___'))
14# ו___ זה לשון ה___ רמב ״ ן ב___ פירושו על ה___ תורה , שהד___ בר ידוע ו___ מפורסם ל___ כל בעלי ה___ עיון ש___ אין ה___ מקר
15א יוצא מידי פשוטו אף על פי שהד___ רש אמת .
16
17# we can mask out any word we want - in this case, the easiest is to just do a string replace. We could've masked in the original sentence, or anywhere in the pipeline.
18segmented_sentence = segmented_sentence.replace("עיון", "[MASK]")
19
20# Load in the new model
21tokenizer = AutoTokenizer.from_pretrained('dicta-il/pre-BEREL')
22model = AutoModelForMaskedLM.from_pretrained('dicta-il/pre-BEREL').eval()
23
24output = model(tokenizer.encode(segmented_sentence, return_tensors='pt'))
25# the [MASK] is the 24th token (including [CLS])
26import torch
27top_5 = torch.topk(output.logits[0, 23, :], 5)[1]
28print('\n'.join(tokenizer.convert_ids_to_tokens(top_5))) # should print קבלה / פשט / דת / חכמה / גמראtbdtbd