-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslator.java
More file actions
59 lines (52 loc) · 1.89 KB
/
Translator.java
File metadata and controls
59 lines (52 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package cn.sribd.si.threads;
import cn.sribd.si.Utils;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import static cn.sribd.si.Utils.outputBuffer;
public class Translator implements Runnable {
@Override
public void run() {
String englishText, chineseText;
for (; ; ) {
try {
synchronized (Utils.sentenceBuffer) {
while (Utils.sentenceBuffer.isEmpty()) {
Utils.sentenceBuffer.wait();
}
englishText = Utils.sentenceBuffer.removeFirst();
}
chineseText = translate(englishText);
chineseText = cleanWords(chineseText);
outputBuffer.append(chineseText);
synchronized (Utils.speakBuffer) {
Utils.speakBuffer.add(chineseText);
Utils.speakBuffer.notify();
}
if (Utils.isStopped) {
break;
}
} catch (InterruptedException e) {
break;
}
}
}
private String translate(String englishText) {
try {
HttpResponse<String> response = Unirest.post("http://10.20.253.1:5000/translate/")
.header("Content-Type", "application/json")
.body("{\"data\": \"" + englishText + "\"}")
.asString();
return response.getBody();
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
private String cleanWords(String chineseText) {
if(chineseText == null) return null;
chineseText = chineseText.replace('.','。');
chineseText = chineseText.replaceAll("妈的","**");
return chineseText;
}
}