miwytt commited on
Commit
b5bb8a8
1 Parent(s): c6208dd
Files changed (1) hide show
  1. app.py +1 -165
app.py CHANGED
@@ -1,170 +1,6 @@
1
  from nmtscore import NMTScorer
2
  import gradio as gr
3
-
4
- from dataclasses import dataclass
5
- from typing import List, Union, Optional
6
- import numpy as np
7
-
8
- from scipy.special import softmax
9
- from scipy.stats import permutation_test
10
-
11
-
12
- @dataclass
13
- class TranslationDirectionResult:
14
- sentence1: Union[str, List[str]]
15
- sentence2: Union[str, List[str]]
16
- lang1: str
17
- lang2: str
18
- raw_prob_1_to_2: float
19
- raw_prob_2_to_1: float
20
- pvalue: Optional[float] = None
21
-
22
- @property
23
- def num_sentences(self):
24
- return len(self.sentence1) if isinstance(self.sentence1, list) else 1
25
-
26
- @property
27
- def prob_1_to_2(self):
28
- return softmax([self.raw_prob_1_to_2, self.raw_prob_2_to_1])[0]
29
-
30
- @property
31
- def prob_2_to_1(self):
32
- return softmax([self.raw_prob_1_to_2, self.raw_prob_2_to_1])[1]
33
-
34
- @property
35
- def predicted_direction(self) -> str:
36
- if self.raw_prob_1_to_2 >= self.raw_prob_2_to_1:
37
- return self.lang1 + '→' + self.lang2
38
- else:
39
- return self.lang2 + '→' + self.lang1
40
-
41
- def __str__(self):
42
- s = f"""\
43
- Predicted direction: {self.predicted_direction}
44
- {self.num_sentences} sentence pair{"s" if self.num_sentences > 1 else ""}
45
- {self.lang1}→{self.lang2}: {self.prob_1_to_2:.3f}
46
- {self.lang2}→{self.lang1}: {self.prob_2_to_1:.3f}"""
47
- if self.pvalue is not None:
48
- s += f"\np-value: {self.pvalue}\n"
49
- return s
50
-
51
-
52
- class TranslationDirectionDetector:
53
-
54
- def __init__(self, scorer: NMTScorer = None, use_normalization: bool = False):
55
- self.scorer = scorer or NMTScorer()
56
- self.use_normalization = use_normalization
57
-
58
- def detect(self,
59
- sentence1: Union[str, List[str]],
60
- sentence2: Union[str, List[str]],
61
- lang1: str,
62
- lang2: str,
63
- return_pvalue: bool = False,
64
- pvalue_n_resamples: int = 9999,
65
- score_kwargs: dict = None
66
- ) -> TranslationDirectionResult:
67
- if isinstance(sentence1, list) and isinstance(sentence2, list):
68
- if len(sentence1) != len(sentence2):
69
- raise ValueError("Lists sentence1 and sentence2 must have same length")
70
- if len(sentence1) == 0:
71
- raise ValueError("Lists sentence1 and sentence2 must not be empty")
72
- if len(sentence1) == 1 and return_pvalue:
73
- raise ValueError("return_pvalue=True requires the documents to have multiple sentences")
74
- if lang1 == lang2:
75
- raise ValueError("lang1 and lang2 must be different")
76
-
77
- prob_1_to_2 = self.scorer.score_direct(
78
- sentence2, sentence1,
79
- lang2, lang1,
80
- normalize=self.use_normalization,
81
- both_directions=False,
82
- score_kwargs=score_kwargs
83
- )
84
- prob_2_to_1 = self.scorer.score_direct(
85
- sentence1, sentence2,
86
- lang1, lang2,
87
- normalize=self.use_normalization,
88
- both_directions=False,
89
- score_kwargs=score_kwargs
90
- )
91
- pvalue = None
92
-
93
- if isinstance(sentence1, list): # document-level
94
- # Compute the average probability per target token, across the complete document
95
- # 1. Convert probabilities back to log probabilities
96
- log_prob_1_to_2 = np.log2(np.array(prob_1_to_2))
97
- log_prob_2_to_1 = np.log2(np.array(prob_2_to_1))
98
- # 2. Reverse the sentence-level length normalization
99
- sentence1_lengths = np.array([self._get_sentence_length(s) for s in sentence1])
100
- sentence2_lengths = np.array([self._get_sentence_length(s) for s in sentence2])
101
- log_prob_1_to_2 = sentence2_lengths * log_prob_1_to_2
102
- log_prob_2_to_1 = sentence1_lengths * log_prob_2_to_1
103
- # 4. Sum up the log probabilities across the document
104
- total_log_prob_1_to_2 = log_prob_1_to_2.sum()
105
- total_log_prob_2_to_1 = log_prob_2_to_1.sum()
106
- # 3. Document-level length normalization
107
- avg_log_prob_1_to_2 = total_log_prob_1_to_2 / sum(sentence2_lengths)
108
- avg_log_prob_2_to_1 = total_log_prob_2_to_1 / sum(sentence1_lengths)
109
- # 4. Convert back to probabilities
110
- prob_1_to_2 = 2 ** avg_log_prob_1_to_2
111
- prob_2_to_1 = 2 ** avg_log_prob_2_to_1
112
-
113
- if return_pvalue:
114
- x = np.vstack([log_prob_1_to_2, sentence2_lengths]).T
115
- y = np.vstack([log_prob_2_to_1, sentence1_lengths]).T
116
- result = permutation_test(
117
- data=(x, y),
118
- statistic=self._statistic_token_mean,
119
- permutation_type="samples",
120
- n_resamples=pvalue_n_resamples,
121
- )
122
- pvalue = result.pvalue
123
- else:
124
- if return_pvalue:
125
- raise ValueError("return_pvalue=True requires sentence1 and sentence2 to be lists of sentences")
126
-
127
- return TranslationDirectionResult(
128
- sentence1=sentence1,
129
- sentence2=sentence2,
130
- lang1=lang1,
131
- lang2=lang2,
132
- raw_prob_1_to_2=prob_1_to_2,
133
- raw_prob_2_to_1=prob_2_to_1,
134
- pvalue=pvalue,
135
- )
136
-
137
- def _get_sentence_length(self, sentence: str) -> int:
138
- tokens = self.scorer.model.tokenizer.tokenize(sentence)
139
- return len(tokens)
140
-
141
- @staticmethod
142
- def _statistic_token_mean(x: np.ndarray, y: np.ndarray, axis: int = -1) -> float:
143
- """
144
- Statistic for scipy.stats.permutation_test
145
-
146
- :param x: Matrix of shape (2 x num_sentences). The first row contains the unnormalized log probability
147
- for lang1→lang2, the second row contains the sentence lengths in lang2.
148
- :param y: Same as x, but for lang2→lang1
149
- :return: Difference between lang1→lang2 and lang2→lang1
150
- """
151
- if axis != -1:
152
- raise NotImplementedError("Only axis=-1 is supported")
153
- # Add batch dim
154
- if x.ndim == 2:
155
- x = x[np.newaxis, ...]
156
- y = y[np.newaxis, ...]
157
- # Sum up the log probabilities across the document
158
- total_log_prob_1_to_2 = x[:, 0].sum(axis=axis)
159
- total_log_prob_2_to_1 = y[:, 0].sum(axis=axis)
160
- # Document-level length normalization
161
- avg_log_prob_1_to_2 = total_log_prob_1_to_2 / x[:, 1].sum(axis=axis)
162
- avg_log_prob_2_to_1 = total_log_prob_2_to_1 / y[:, 1].sum(axis=axis)
163
- # Convert to probabilities
164
- prob_1_to_2 = 2 ** avg_log_prob_1_to_2
165
- prob_2_to_1 = 2 ** avg_log_prob_2_to_1
166
- # Compute difference
167
- return prob_1_to_2 - prob_2_to_1
168
 
169
 
170
  detector = TranslationDirectionDetector(NMTScorer("m2m100_418M"))
 
1
  from nmtscore import NMTScorer
2
  import gradio as gr
3
+ from translation_direction_detection import TranslationDirectionDetector
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
 
6
  detector = TranslationDirectionDetector(NMTScorer("m2m100_418M"))