1 | |
2 | type Deepl = { |
3 | apiKey: string; |
4 | baseUrl: string; |
5 | }; |
6 | type Base64 = string; |
7 | |
8 | * Upload and Translate a Document |
9 | * This call uploads a document and queues it for translation. |
10 | */ |
11 | export async function main( |
12 | auth: Deepl, |
13 | body: { |
14 | source_lang?: |
15 | | "BG" |
16 | | "CS" |
17 | | "DA" |
18 | | "DE" |
19 | | "EL" |
20 | | "EN" |
21 | | "ES" |
22 | | "ET" |
23 | | "FI" |
24 | | "FR" |
25 | | "HU" |
26 | | "ID" |
27 | | "IT" |
28 | | "JA" |
29 | | "KO" |
30 | | "LT" |
31 | | "LV" |
32 | | "NB" |
33 | | "NL" |
34 | | "PL" |
35 | | "PT" |
36 | | "RO" |
37 | | "RU" |
38 | | "SK" |
39 | | "SL" |
40 | | "SV" |
41 | | "TR" |
42 | | "UK" |
43 | | "ZH"; |
44 | target_lang: |
45 | | "BG" |
46 | | "CS" |
47 | | "DA" |
48 | | "DE" |
49 | | "EL" |
50 | | "ES" |
51 | | "ET" |
52 | | "FI" |
53 | | "FR" |
54 | | "HU" |
55 | | "ID" |
56 | | "IT" |
57 | | "JA" |
58 | | "KO" |
59 | | "LT" |
60 | | "LV" |
61 | | "NB" |
62 | | "NL" |
63 | | "PL" |
64 | | "RO" |
65 | | "RU" |
66 | | "SK" |
67 | | "SL" |
68 | | "SV" |
69 | | "TR" |
70 | | "UK" |
71 | | "ZH" |
72 | | "EN-GB" |
73 | | "EN-US" |
74 | | "PT-BR" |
75 | | "PT-PT" |
76 | | "ZH-HANS"; |
77 | file: { |
78 | base64: Base64; |
79 | type: |
80 | | "image/png" |
81 | | "image/jpeg" |
82 | | "image/gif" |
83 | | "application/pdf" |
84 | | "appication/json" |
85 | | "text/csv" |
86 | | "text/plain" |
87 | | "audio/mpeg" |
88 | | "audio/wav" |
89 | | "video/mp4"; |
90 | name: string; |
91 | }; |
92 | filename?: string; |
93 | output_format?: string; |
94 | formality?: "default" | "more" | "less" | "prefer_more" | "prefer_less"; |
95 | glossary_id?: string; |
96 | }, |
97 | ) { |
98 | const url = new URL(`${auth.baseUrl}/v2/document`); |
99 |
|
100 | const formData = new FormData(); |
101 | for (const [k, v] of Object.entries(body)) { |
102 | if (v !== undefined && v !== "") { |
103 | if (["file"].includes(k)) { |
104 | const { base64, type, name } = v as { |
105 | base64: Base64; |
106 | type: string; |
107 | name: string; |
108 | }; |
109 | formData.append( |
110 | k, |
111 | new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], { |
112 | type, |
113 | }), |
114 | name, |
115 | ); |
116 | } else { |
117 | formData.append(k, String(v)); |
118 | } |
119 | } |
120 | } |
121 | const response = await fetch(url, { |
122 | method: "POST", |
123 | headers: { |
124 | Authorization: "DeepL-Auth-Key " + auth.apiKey, |
125 | }, |
126 | body: formData, |
127 | }); |
128 | if (!response.ok) { |
129 | const text = await response.text(); |
130 | throw new Error(`${response.status} ${text}`); |
131 | } |
132 | return await response.json(); |
133 | } |
134 |
|