NightPrince commited on
Commit
1427b10
·
verified ·
1 Parent(s): 1e01b6c

Add catt/xer.py

Browse files
Files changed (1) hide show
  1. catt/xer.py +76 -0
catt/xer.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ @author
3
+ ______ _ _
4
+ | ____| (_) /\ | |
5
+ | |__ __ _ _ __ _ ___ / \ | | __ _ ___ _ __ ___ __ _ _ __ _ _
6
+ | __/ _` | '__| / __| / /\ \ | |/ _` / __| '_ ` _ \ / _` | '__| | | |
7
+ | | | (_| | | | \__ \ / ____ \| | (_| \__ \ | | | | | (_| | | | |_| |
8
+ |_| \__,_|_| |_|___/ /_/ \_\_|\__,_|___/_| |_| |_|\__,_|_| \__, |
9
+ __/ |
10
+ |___/
11
+ Email: farisalasmary@gmail.com
12
+ Date: Mar 15, 2022
13
+ """
14
+
15
+ # pip install git+https://github.com/pzelasko/kaldialign.git
16
+
17
+ from kaldialign import edit_distance
18
+
19
+
20
+ def cer(ref, hyp):
21
+ """
22
+ Computes the Character Error Rate, defined as the edit distance.
23
+
24
+ Arguments:
25
+ ref (string): a space-separated ground truth string
26
+ hyp (string): a space-separated hypothesis
27
+ """
28
+ ref, hyp, = ref.replace(' ', '').strip(), hyp.replace(' ', '').strip()
29
+ info = edit_distance(ref, hyp)
30
+ distance = info['total']
31
+ ref_length = float(len(ref))
32
+
33
+ data = {
34
+ 'insertions': info['ins'],
35
+ 'deletions': info['del'],
36
+ 'substitutions': info['sub'],
37
+ 'distance': distance,
38
+ 'ref_length': ref_length,
39
+ 'Error Rate': (distance / ref_length) * 100
40
+ }
41
+
42
+ return data
43
+
44
+
45
+ def wer(ref, hyp):
46
+ """
47
+ Computes the Word Error Rate, defined as the edit distance between the
48
+ two provided sentences after tokenizing to words.
49
+ Arguments:
50
+ ref (string): a space-separated ground truth string
51
+ hyp (string): a space-separated hypothesis
52
+ """
53
+
54
+ # build mapping of words to integers
55
+ b = set(ref.split() + hyp.split())
56
+ word2char = dict(zip(b, range(len(b))))
57
+
58
+ # map the words to a char array (Levenshtein packages only accepts strings)
59
+ w1 = [chr(word2char[w]) for w in ref.split()]
60
+ w2 = [chr(word2char[w]) for w in hyp.split()]
61
+
62
+ info = edit_distance(''.join(w1), ''.join(w2))
63
+ distance = info['total']
64
+ ref_length = float(len(w1))
65
+
66
+ data = {
67
+ 'insertions': info['ins'],
68
+ 'deletions': info['del'],
69
+ 'substitutions': info['sub'],
70
+ 'distance': distance,
71
+ 'ref_length': ref_length,
72
+ 'Error Rate': (distance / ref_length) * 100
73
+ }
74
+
75
+ return data
76
+