forked from BlackGlory/subtitle-translate-tmt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubtitleTranslate - openai.as
93 lines (68 loc) · 2.27 KB
/
SubtitleTranslate - openai.as
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
bool debug = true;
string apiKey = '';
string baseUrl = 'https://api.siliconflow.cn/v1';
string model = 'Qwen/Qwen1.5-14B-Chat';
string GetTitle() {
return
'{$CP936=OpenAI API 翻译$}'
'{$CP0=OpenAI API Translate$}';
}
string GetUserText() {
return 'BaseURL:';
}
string GetPasswordText() {
return 'API Key:';
}
string ServerLogin(string username, string password) {
if (username.empty() || password.empty()) return 'fail';
baseUrl = username;
apiKey = password;
return '200 ok';
}
void ServerLogout() {
apiKey = '';
}
array<string> GetSrcLangs() {
return {'auto', 'zh', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'it', 'ru', 'pt'};
}
array<string> GetDstLangs() {
return {'zh', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'it', 'ru', 'pt'};
}
JsonValue parseJSON(string content) {
JsonReader reader;
JsonValue data;
reader.parse(content, data);
return data;
}
string Translate(string text, string &in srcLang, string &in dstLang) {
if (debug) {
HostOpenConsole();
}
string systemMessage = "You are a professional, authentic machine translation engine.";
string userMessage = "Translate the following text from " + srcLang + " to " + dstLang + ":\n\n" + text;
string headers = "Content-Type: application/json\nAuthorization: Bearer " + apiKey + "\n";
string body = "{\"model\":\"" + model + "\",\"messages\":[{\"role\":\"system\",\"content\":\"You are a professional, authentic machine translation engine..\"},{\"role\":\"user\",\"content\":\"Translate the following text from " + srcLang + " to " + dstLang + ": " + text + "\"}]}";
string url = baseUrl + '/chat/completions';
uintptr response = HostOpenHTTP(url, 'PotPlayer', headers, body, true);
if (response == 0) {
return '翻译请求失败';
}
string content = HostGetContentHTTP(response);
if (debug) {
HostPrintUTF8(content);
}
JsonValue data = parseJSON(content);
if (data.isObject() && data['choices'].isArray()) {
string translatedText = data['choices'][0]['message']['content'].asString();
if (debug) {
HostPrintUTF8(srcLang + '=>' + dstLang);
HostPrintUTF8(text + '\n=>\n' + translatedText);
}
srcLang = 'UTF8';
dstLang = 'UTF8';
HostCloseHTTP(response);
return translatedText;
}
HostCloseHTTP(response);
return '';
}