1from transformers import AutoTokenizer, AutoModelForTokenClassification
2from transformers import pipeline
3
4tokenizer = AutoTokenizer.from_pretrained("yeshpanovrustem/xlm-roberta-large-kaznerd")
5model = AutoModelForTokenClassification.from_pretrained("yeshpanovrustem/xlm-roberta-large-kaznerd")
6
7# aggregation_strategy = "none"
8nlp = pipeline("ner", model = model, tokenizer = tokenizer, aggregation_strategy = "none")
9example = "Қазақстан Республикасы — Шығыс Еуропа мен Орталық Азияда орналасқан мемлекет."
10
11ner_results = nlp(example)
12for result in ner_results:
13 print(result)
14
15# output:
16# {'entity': 'B-GPE', 'score': 0.9995646, 'index': 1, 'word': '▁Қазақстан', 'start': 0, 'end': 9}
17# {'entity': 'I-GPE', 'score': 0.9994935, 'index': 2, 'word': '▁Республикасы', 'start': 10, 'end': 22}
18# {'entity': 'B-LOCATION', 'score': 0.99906737, 'index': 4, 'word': '▁Шығыс', 'start': 25, 'end': 30}
19# {'entity': 'I-LOCATION', 'score': 0.999153, 'index': 5, 'word': '▁Еуропа', 'start': 31, 'end': 37}
20# {'entity': 'B-LOCATION', 'score': 0.9991597, 'index': 7, 'word': '▁Орталық', 'start': 42, 'end': 49}
21# {'entity': 'I-LOCATION', 'score': 0.9991725, 'index': 8, 'word': '▁Азия', 'start': 50, 'end': 54}
22# {'entity': 'I-LOCATION', 'score': 0.9992299, 'index': 9, 'word': 'да', 'start': 54, 'end': 56}
23
24token = ""
25label_list = []
26token_list = []
27
28for result in ner_results:
29 if result["word"].startswith("▁"):
30 if token:
31 token_list.append(token.replace("▁", ""))
32 token = result["word"]
33 label_list.append(result["entity"])
34 else:
35 token += result["word"]
36
37token_list.append(token.replace("▁", ""))
38
39for token, label in zip(token_list, label_list):
40 print(f"{token}\t{label}")
41
42# output:
43# Қазақстан B-GPE
44# Республикасы I-GPE
45# Шығыс B-LOCATION
46# Еуропа I-LOCATION
47# Орталық B-LOCATION
48# Азияда I-LOCATION
49
50# aggregation_strategy = "simple"
51nlp = pipeline("ner", model = model, tokenizer = tokenizer, aggregation_strategy = "simple")
52example = "Қазақстан Республикасы — Шығыс Еуропа мен Орталық Азияда орналасқан мемлекет."
53
54ner_results = nlp(example)
55for result in ner_results:
56 print(result)
57
58# output:
59# {'entity_group': 'GPE', 'score': 0.999529, 'word': 'Қазақстан Республикасы', 'start': 0, 'end': 22}
60# {'entity_group': 'LOCATION', 'score': 0.9991102, 'word': 'Шығыс Еуропа', 'start': 25, 'end': 37}
61# {'entity_group': 'LOCATION', 'score': 0.9991874, 'word': 'Орталық Азияда', 'start': 42, 'end': 56}
62