-
Notifications
You must be signed in to change notification settings - Fork 4.8k
293 lines (263 loc) · 11.4 KB
/
Copy pathgithub-content-translator.yml
File metadata and controls
293 lines (263 loc) · 11.4 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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
name: GitHub Content Translator
run-name: "Translate: ${{ github.event.issue.title || github.event.pull_request.title || github.event.comment.body || github.event.review.body || 'GitHub content' }}"
concurrency:
group: translator-${{ github.event.comment.id || github.event.issue.number || github.event.review.id }}
cancel-in-progress: true
on:
issues:
types: [opened]
issue_comment:
types: [created, edited]
pull_request_review:
types: [submitted, edited]
pull_request_review_comment:
types: [created, edited]
jobs:
translate:
if: |
(github.event_name == 'issues')
|| (github.event_name == 'issue_comment' && github.event.sender.type != 'Bot')
|| (
(github.event_name == 'pull_request_review' || github.event_name == 'pull_request_review_comment')
&& github.event.sender.type != 'Bot'
&& github.event.pull_request.head.repo.fork == false
)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
issues: write
pull-requests: write
steps:
- name: Translate and update event content
uses: actions/github-script@v8
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
ANTHROPIC_BASE_URL: ${{ vars.ANTHROPIC_BASE_URL }}
ANTHROPIC_MODEL: ${{ vars.ANTHROPIC_MODEL }}
with:
github-token: ${{ github.token }}
script: |
const ORIGINAL_SUMMARY = '<summary>Original Content</summary>'
const stripCodeFence = (value) =>
value
.trim()
.replace(/^```(?:json)?\s*/i, '')
.replace(/\s*```$/i, '')
.trim()
const parseTranslatorResult = (text, responseMetadata) => {
const strippedText = stripCodeFence(text)
try {
return JSON.parse(strippedText)
} catch (error) {
core.startGroup('Translator response metadata')
core.info(JSON.stringify(responseMetadata, null, 2))
core.endGroup()
core.startGroup('Translator raw model response')
core.info(text)
core.endGroup()
if (strippedText !== text) {
core.startGroup('Translator response after code-fence stripping')
core.info(strippedText)
core.endGroup()
}
throw new Error(`Translator API returned invalid JSON: ${error.message}`)
}
}
const getTranslatedMarker = (kind) => {
switch (kind) {
case 'issue':
return 'This issue was translated automatically.'
case 'issue_comment':
return 'This comment was translated automatically.'
case 'pull_request_review':
return 'This review was translated automatically.'
case 'pull_request_review_comment':
return 'This review comment was translated automatically.'
default:
return 'This content was translated automatically.'
}
}
const buildBody = (kind, translatedBody, originalBody) =>
[
`> ${getTranslatedMarker(kind)}`,
'',
translatedBody.trim(),
'',
'---',
'<details>',
ORIGINAL_SUMMARY,
'',
originalBody.trim(),
'</details>'
].join('\n')
const getTarget = () => {
const payload = context.payload
switch (context.eventName) {
case 'issues':
return {
kind: 'issue',
issueNumber: payload.issue.number,
title: payload.issue.title || '',
body: payload.issue.body || ''
}
case 'issue_comment':
return {
kind: 'issue_comment',
issueNumber: payload.issue.number,
commentId: payload.comment.id,
title: '',
body: payload.comment.body || ''
}
case 'pull_request_review':
return {
kind: 'pull_request_review',
pullNumber: payload.pull_request.number,
reviewId: payload.review.id,
title: '',
body: payload.review.body || ''
}
case 'pull_request_review_comment':
return {
kind: 'pull_request_review_comment',
pullNumber: payload.pull_request.number,
commentId: payload.comment.id,
title: '',
body: payload.comment.body || ''
}
default:
throw new Error(`Unsupported event: ${context.eventName}`)
}
}
const isWorkflowTranslationEdit = (target) => {
const previousBody = context.payload.changes?.body?.from
const translatedMarker = `> ${getTranslatedMarker(target.kind)}`
return (
context.payload.action === 'edited' &&
typeof previousBody === 'string' &&
!previousBody.includes(translatedMarker) &&
target.body.startsWith(translatedMarker) &&
target.body.includes(ORIGINAL_SUMMARY)
)
}
const updateTarget = async (target, translatedTitle, translatedBody, originalBody) => {
const body = buildBody(target.kind, translatedBody, originalBody)
const { owner, repo } = context.repo
switch (target.kind) {
case 'issue':
await github.rest.issues.update({
owner,
repo,
issue_number: target.issueNumber,
title: translatedTitle || target.title,
body
})
return
case 'issue_comment':
await github.rest.issues.updateComment({
owner,
repo,
comment_id: target.commentId,
body
})
return
case 'pull_request_review':
await github.request('PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}', {
owner,
repo,
pull_number: target.pullNumber,
review_id: target.reviewId,
body
})
return
case 'pull_request_review_comment':
await github.rest.pulls.updateReviewComment({
owner,
repo,
comment_id: target.commentId,
body
})
return
}
}
const callTranslator = async (target) => {
const apiKey = process.env.ANTHROPIC_API_KEY
if (!apiKey) {
throw new Error('Missing ANTHROPIC_API_KEY')
}
const baseUrl = (process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com').replace(/\/$/, '')
const model = process.env.ANTHROPIC_MODEL
if (!model) {
throw new Error('Missing ANTHROPIC_MODEL')
}
const response = await fetch(`${baseUrl}/v1/messages`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model,
max_tokens: 4096,
temperature: 0,
system: `You translate GitHub issue, issue comment, pull request review, and pull request review comment content into English.
Return only compact JSON with this exact shape:
{
"should_update": boolean,
"translated_title": string | null,
"translated_body": string | null,
"original_body": string | null
}
Rules:
- If the content is already fully English, return should_update=false.
- If the content already follows the automatic translation format and its Original Content matches the current source, return should_update=false.
- If the content is translated but the original and translated content do not match, return should_update=true and fix it.
- Translate non-English or partially non-English content to natural English.
- For issues, translate the title when it is non-English. For all other event kinds, translated_title must be null.
- Preserve Markdown structure, code blocks, task lists, links, and mentions.
- If the content quotes an earlier automatic translation, keep only the English quoted content and remove translation markers and Original Content sections from the quote.
- If the content quotes non-translated content, keep that quote unchanged.
- If the content is an email reply, remove quoted email history from both translated_body and original_body.
- original_body must be the source text that corresponds to translated_body, after any required email quote cleanup.`,
messages: [
{
role: 'user',
content: JSON.stringify({
event: context.eventName,
target
})
}
]
})
})
if (!response.ok) {
throw new Error(`Translator API failed with ${response.status}: ${await response.text()}`)
}
const data = await response.json()
const text = data.content?.find((part) => part.type === 'text')?.text
if (!text) {
throw new Error('Translator API returned no text content')
}
return parseTranslatorResult(text, {
id: data.id,
model: data.model,
stop_reason: data.stop_reason,
stop_sequence: data.stop_sequence,
usage: data.usage
})
}
const target = getTarget()
if (isWorkflowTranslationEdit(target)) {
core.info('Skipping the edit event emitted by this workflow translation.')
return
}
const result = await callTranslator(target)
if (!result.should_update) {
core.info('Translator reported that no translation update is needed.')
return
}
if (typeof result.translated_body !== 'string' || typeof result.original_body !== 'string') {
throw new Error('Translator requested an update without translated_body and original_body')
}
await updateTarget(target, result.translated_title, result.translated_body, result.original_body)
core.info(`Updated ${target.kind} with English translation.`)