1-800-BAD-CODE
commited on
Commit
•
e62dcf1
1
Parent(s):
5f7487e
Upload run_example.py
Browse files- run_example.py +173 -0
run_example.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sentencepiece import SentencePieceProcessor
|
2 |
+
import onnxruntime as ort
|
3 |
+
import numpy as np
|
4 |
+
from typing import List
|
5 |
+
|
6 |
+
|
7 |
+
# Load the classification and sentencepiece models
|
8 |
+
model_path = "sbd_25lang.onnx"
|
9 |
+
tokenizer_path = "32k_mixed_case_25lang.model"
|
10 |
+
|
11 |
+
tokenizer: SentencePieceProcessor = SentencePieceProcessor(tokenizer_path)
|
12 |
+
ort_session: ort.InferenceSession = ort.InferenceSession(model_path)
|
13 |
+
|
14 |
+
|
15 |
+
# Function to make a simple batch for inference
|
16 |
+
def simple_make_batch(texts: List[str], tokenizer: SentencePieceProcessor):
|
17 |
+
"""Note that a real data loader will account for the model's max input length"""
|
18 |
+
# Encode each input; add EOS and BOS tags
|
19 |
+
bos = tokenizer.bos_id()
|
20 |
+
eos = tokenizer.eos_id()
|
21 |
+
ids_list = [[bos] + tokenizer.EncodeAsIds(x) + [eos] for x in texts]
|
22 |
+
# Pack input IDs into a padded batch
|
23 |
+
batch_size = len(texts)
|
24 |
+
lengths = np.array([len(x) for x in ids_list])
|
25 |
+
max_len = max(lengths)
|
26 |
+
input_ids = np.full(shape=[batch_size, max_len], fill_value=tokenizer.pad_id(), dtype=np.int64)
|
27 |
+
for i, ids in enumerate(ids_list):
|
28 |
+
input_ids[i, : len(ids)] = ids
|
29 |
+
return input_ids, lengths
|
30 |
+
|
31 |
+
|
32 |
+
# Applies model predictions to break up a batch of texts
|
33 |
+
def apply_preds(input_ids: np.array, probs: np.array, lengths: np.array, threshold: float) -> List[List[str]]:
|
34 |
+
out_strings: List[List[str]] = []
|
35 |
+
for i, length in enumerate(lengths):
|
36 |
+
next_strings: List[str] = []
|
37 |
+
# Ignore EOS/BOS
|
38 |
+
next_ids = input_ids[i, 1 : length + 1].tolist()
|
39 |
+
next_probs = probs[i, 1 : length + 1]
|
40 |
+
# Find all positions that exceed the threshold as a sentence boundary
|
41 |
+
break_points: List[int] = np.squeeze(np.argwhere(next_probs > threshold)).tolist()
|
42 |
+
# Add the final token to the break points, to not have leftover tokens after the loop
|
43 |
+
if (not break_points) or (break_points[-1] != len(next_ids) - 1):
|
44 |
+
break_points.append(len(next_ids) - 1)
|
45 |
+
# Break tokens at boundaries, convert back to text
|
46 |
+
for break_num, break_point in enumerate(break_points):
|
47 |
+
start = 0 if break_num == 0 else (break_points[break_num - 1] + 1)
|
48 |
+
sub_ids = next_ids[start : break_point + 1]
|
49 |
+
sub_text = tokenizer.DecodeIds(sub_ids)
|
50 |
+
next_strings.append(sub_text)
|
51 |
+
out_strings.append(next_strings)
|
52 |
+
return out_strings
|
53 |
+
|
54 |
+
|
55 |
+
# Pretty-prints the input texts and the segmented output texts
|
56 |
+
def pretty_print_input_outputs(input_texts: List[str], output_texts: List[List[str]]) -> None:
|
57 |
+
for i, (input_text, next_output_texts) in enumerate(zip(input_texts, output_texts)):
|
58 |
+
print(f"Input {i}: {input_text}")
|
59 |
+
print("Outputs:")
|
60 |
+
for output in next_output_texts:
|
61 |
+
print(f"\t{output}")
|
62 |
+
|
63 |
+
|
64 |
+
# Define a function to run inference and print outputs
|
65 |
+
def run_example(input_texts: List[str], tokenizer: tokenizer):
|
66 |
+
# Make a simple batch
|
67 |
+
input_ids, lengths = simple_make_batch(input_texts, tokenizer)
|
68 |
+
# Run inference and pretty-print the outputs
|
69 |
+
outputs = ort_session.run(None, {"input_ids": input_ids})
|
70 |
+
probs = outputs[0]
|
71 |
+
segmented_texts = apply_preds(input_ids=input_ids, probs=probs, lengths=lengths, threshold=0.5)
|
72 |
+
pretty_print_input_outputs(input_texts, segmented_texts)
|
73 |
+
|
74 |
+
|
75 |
+
# Random texts from the test partition
|
76 |
+
input_texts = [
|
77 |
+
# ar
|
78 |
+
"إنه يبدو غالياً قليلاً بالنسبة لمبنى يحتاج إلى بعض الإصلاحات، هذا كل ما فى الأمر. هذا جيد. ماما وادك بالمنزل.",
|
79 |
+
# bn
|
80 |
+
"তবে ট্রেলারে তার দেখা মিলল না। পরে ব্যাগটি তল্লাশি করে ইয়াবা, চারটি স্বর্ণের বার ও নগদ সাড়ে চার লাখ টাকা পাওয়া যায়। এতে মাছটির দাম বেড়ে গেছে।",
|
81 |
+
# de
|
82 |
+
"Auf alle Fälle sind 90 Minuten voller Einsatz und Konzentration gefordert. Amos Vogel legte seinen Fokus auf die "
|
83 |
+
"Kontextualisierung der einzelnen Filme durch gezielte Programmarbeit. Georgi verspricht Es wird Feierlichkeiten "
|
84 |
+
"geben.",
|
85 |
+
# en
|
86 |
+
"Irwin wrote on Instagram. However, money does talk and the Roosters reported $130000 offer might not be up to "
|
87 |
+
"scratch. There are doctors, but since they joined the civil disobedience protest movement, they can't come to the "
|
88 |
+
"hospital.",
|
89 |
+
# es
|
90 |
+
"Y sí, efectivamente, nos estamos refiriendo a la NASA, la ESA, etc. También tenía un servicio de bar y venta de "
|
91 |
+
"refrescos y bebidas alcohólicas, así como otros productos. En cuanto a la Libre Determinación, su importe se "
|
92 |
+
"distribuirá de forma anual.",
|
93 |
+
# et
|
94 |
+
"Hiljuti suure tagasituleku teinud Mike Tyson naaseb taas poksiringi. Riigikogu liikme Kert Kingo hinnangul on "
|
95 |
+
"valitsus riigikokku toonud seaduseelnõu, millega tahetakse riigis kehtestada totalitaarset kontrolli. Kehakaalu "
|
96 |
+
"tõusu tingib liigne energia tarbimine, mida organism ei jõua päeva jooksul ära kulutada.",
|
97 |
+
# fi
|
98 |
+
"Yksi ongelma ratkaistu. Kuinka kauan olette olleet Meksikossa? Kävin jokin aika sitten tapaamassa komisario "
|
99 |
+
"Fournieria tärkeässä asiassa.",
|
100 |
+
# fr
|
101 |
+
"Avec cette série, on sent quelque chose. En rafale, il pourra dépasser les 65 kmh. Le mercure restera homogène à "
|
102 |
+
"16 °C. Désormais à 10 contre 10 avec un but de retard, Arsenal est complètement relancé dans cette demi finale "
|
103 |
+
"aller.",
|
104 |
+
# hi
|
105 |
+
"प्रभु चरणणों में यही विनती है कि हमारे विचाररों को सदैव पवित्र बनाए रखने की कृपा बनी रहे। भारत में यह सेरेमनी डिज्नी स्टार के चैनललों पर देखी जा सकती है। इस "
|
106 |
+
"कार्रवाई से होटललों और ललांज में अफरा तफरी मच गई है।",
|
107 |
+
# id
|
108 |
+
"Masyarakat juga harus menjalankan protokol kesehatan dengan disiplin dan juga segera divaksinasi bagi yang belum. "
|
109 |
+
"Pelaku ingin nikah, tetapi tidak direstui bapaknya. Untuk selanjutnya, setiap produksi Seven Bucks, baik TV, film "
|
110 |
+
"atau apa pun, kami tidak akan lagi menggunakan senjata sungguhan.",
|
111 |
+
# is
|
112 |
+
"Síðustu vikurnar voru móður okkar hreint kvalræði. Helena Ólafsdóttir og Guðlaug Jónsdóttir knattspyrnukempur "
|
113 |
+
"gengu í heilagt hjónaband um helgina. Þess vegna er alltaf verið að tala um að vera ekki við hraunjaðarinn.",
|
114 |
+
# it
|
115 |
+
"Credevo di potermi fidare di lei. Andare con loro, portarli fuori dal porto? I romani, prima di andarsene, "
|
116 |
+
"sommersero la città. I tuoi antenati custodirono il segreto.",
|
117 |
+
# ja
|
118 |
+
"毛先をそろえる程度で?持たないよ。レベッカ上品な物言いで頼む。またイェーガーに乗ったらあなたは死にます。",
|
119 |
+
# lt
|
120 |
+
"Mokytojau, nusiimk skrybėlę. Kur aš tokia eisiu? Mes galime važiuoti kitą vakarą. Tik arbatos, ačiū.",
|
121 |
+
# lv
|
122 |
+
"Viņa ir gatava izveidot uzbrucēja fotorobotu. Jā. Dažas no labākajām snaudām mūžā esmu izbaudījis Karaliskajā "
|
123 |
+
"Šekspīra teātrī. Kas viņu iedrošinās vēl vairāk.",
|
124 |
+
# ko
|
125 |
+
"하지만 원전 추진에 관한 내부 문건이 분명히 더 있을 겁니다. 한국은 어떤가. 반면 글로벌 제약사들은 이미 콜드체인에 관해 큰 관심을 갖고 있었다.",
|
126 |
+
# no
|
127 |
+
"Ash Ketchum drømmer om eventyr. Ingen i Starfleet kunne gjøre dette. Vil du bli påkjørt? Det går så bra her.",
|
128 |
+
# nl
|
129 |
+
"Ik heb een paar dagen nodig om de mannen weer te verzamelen. Heeft ze een interessant accent? We moeten deze kant "
|
130 |
+
"op. Ik kon er niks aan doen.",
|
131 |
+
# pl
|
132 |
+
"Potraktowaliśmy ją bardzo poważnie. Prace Larsa Vilksa są obecnie wystawiane na wystawie Sztuka polityczna w "
|
133 |
+
"Centrum Sztuki Współczesnej Zamek Ujazdowski w Warszawie. Czy do uznania choroby zawodowej trzeba wykazać, że "
|
134 |
+
"nigdzie poza pracą nie było się narażonym na szkodliwe czynniki?",
|
135 |
+
# pt
|
136 |
+
"John Kennedy, titular em sua ausência, está suspenso com três cartões amarelos. Esses três pilares para a "
|
137 |
+
"imigração, citados pela pesquisa do ESCOE, começaram a cambalear com a pandemia. As poucas oportunidades que teve "
|
138 |
+
"no profissional do Defensor o fizeram reavaliar o futuro.",
|
139 |
+
# ru
|
140 |
+
"Они не знали, что я просто угараю, следует из композиции Элджея. Нас слишком мало, чтобы потерять сотни жизней из "
|
141 |
+
"за злоупотребления алкоголем, когда мы выйдем из пандемии коронавируса. Катар начал предлагать туры для "
|
142 |
+
"болельщиков на ЧМ 2022.",
|
143 |
+
# tr
|
144 |
+
"Yani konjonktürel şartlarla pozisyon alan NATO üyeleri kurumsal işbirliğine zarar veren bir dönemi geçirdi NATO. "
|
145 |
+
"Daha sonra insanları sosyal medyadan bilgilendirdik. Devam eden şampiyonada ülkemizi temsil eden diğer sporculara "
|
146 |
+
"başarılar diliyorum dedi.",
|
147 |
+
# sv
|
148 |
+
"Öppna dina fläskiga, sympatiska armar? Vi spelar. 50 dollar per poäng. Jag menari gär, förraveckan.",
|
149 |
+
# uk
|
150 |
+
"Треба бути тепер готовими до наступного. Багато дітей опинилися ізольованими вдома, а час, який вони проводять у "
|
151 |
+
"мережі, збільшився у рази. Це мала б супроводжувати дискусія у ЗМІ та суспільстві, аби було зрозуміло, чому саме "
|
152 |
+
"це пропаганда, були наведені докази.",
|
153 |
+
# zh
|
154 |
+
"不断刷新的数字背后是满满民生情。但另两名非盟官员说,莫德纳要到明年才能交付疫苗,导致谈判破裂。温室气体等大气���底观测是一项专业性很强的工作,容不得一点马虎。",
|
155 |
+
]
|
156 |
+
|
157 |
+
# Run example with every language.
|
158 |
+
print("Example from each language:")
|
159 |
+
run_example(input_texts, tokenizer)
|
160 |
+
|
161 |
+
# Run ean example with a lot of English acronyms, to see model behavior with non-breaking fullstops. Some random texts
|
162 |
+
# from opensubtitles.
|
163 |
+
input_texts = [
|
164 |
+
"R.J. MacReady, helicopter pilot, U.S. Outpost Number 31. How will I get to L.A.? He's a U.S. Marshal. Let him go. "
|
165 |
+
"Let him go. Let me see your license and I.D. Card."
|
166 |
+
]
|
167 |
+
print("Example with lots of acronyms:")
|
168 |
+
run_example(input_texts, tokenizer)
|
169 |
+
|
170 |
+
# Run with the acronyms in lower-case, to deny the model the true-case information when making decisions
|
171 |
+
print("Example with lower-cased inputs:")
|
172 |
+
input_texts = [x.lower() for x in input_texts]
|
173 |
+
run_example(input_texts, tokenizer)
|