-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbulkGenerateAltTexts.ts
More file actions
194 lines (168 loc) · 5.31 KB
/
bulkGenerateAltTexts.ts
File metadata and controls
194 lines (168 loc) · 5.31 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
import type { BasePayload, CollectionSlug, PayloadHandler, PayloadRequest } from 'payload'
import pMap from 'p-map'
import { z, ZodError } from 'zod'
import type { AltTextPluginConfig } from '../types/AltTextPluginConfig.js'
import { localesFromConfig } from '../utilities/localesFromConfig.js'
import { matchesMimeType } from '../utilities/mimeTypes.js'
/**
* Generates and updates alt text for multiple images in all locales.
*/
export const bulkGenerateAltTextsEndpoint =
(access: AltTextPluginConfig['access']): PayloadHandler =>
async (req: PayloadRequest) => {
try {
if (!(await access({ req }))) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
const data = 'json' in req && typeof req.json === 'function' ? await req.json() : null
const schema = z.object({
collection: z.string(),
ids: z.array(z.union([z.string(), z.number()])),
})
const { collection, ids } = schema.parse(data)
let updatedDocs = 0
const erroredDocs: (number | string)[] = []
// Get plugin config from payload config
const pluginConfig = req.payload.config.custom?.altTextPluginConfig as
| AltTextPluginConfig
| undefined
if (!pluginConfig) {
return Response.json({ error: 'Plugin config not found' }, { status: 500 })
}
if (!pluginConfig.resolver) {
return Response.json({ error: 'No alt text resolver configured' }, { status: 500 })
}
const concurrency = pluginConfig.maxBulkGenerateConcurrency
// determine target locales based on config
const locales = localesFromConfig(req.payload.config)
const targetLocales = locales ?? [pluginConfig.locale!]
if (!targetLocales) {
return Response.json(
{
error:
'Could not determine target locales for alt text generation. Please check your plugin configuration.',
},
{ status: 500 },
)
}
await pMap(
ids,
async (id) => {
try {
await generateAndUpdateAltText({
id,
collection,
locales: targetLocales,
payload: req.payload,
pluginConfig,
req,
})
updatedDocs++
console.log(
`${updatedDocs}/${ids.length} updated (${Math.round((updatedDocs / ids.length) * 100)}%)`,
)
} catch (error) {
console.error(`Error generating alt text for ${id}:`, error)
erroredDocs.push(id)
}
},
{ concurrency },
)
if (erroredDocs.length > 0) {
console.error(`Failed for: ${erroredDocs.join(', ')}`)
}
return Response.json({
erroredDocs,
totalDocs: ids.length,
updatedDocs,
})
} catch (error) {
if (error instanceof ZodError) {
return Response.json(
{
details: error.issues.map((e) => ({
message: e.message,
path: e.path.join('.'),
})),
error: 'Validation failed',
},
{ status: 400 },
)
}
console.error('Error in bulk generation:', error)
return Response.json(
{
error: `Error generating alt text: ${error instanceof Error ? error.message : 'Unknown error'}`,
},
{ status: 500 },
)
}
}
async function generateAndUpdateAltText({
id,
collection,
locales,
payload,
pluginConfig,
req,
}: {
collection: CollectionSlug
id: number | string
locales: string[]
payload: BasePayload
pluginConfig: AltTextPluginConfig
req: PayloadRequest
}) {
const imageDoc = await payload.findByID({
id,
collection,
depth: 0,
})
if (!imageDoc) {
throw new Error('Image not found')
}
const mimeType =
'mimeType' in imageDoc && typeof imageDoc.mimeType === 'string' ? imageDoc.mimeType : undefined
const collectionConfig = pluginConfig.collections.find((entry) => entry.slug === collection)
if (mimeType && collectionConfig && !matchesMimeType(mimeType, collectionConfig.mimeTypes)) {
throw new Error(
`Alt text is not tracked for files of type "${mimeType}" in the "${collection}" collection. Tracked types: ${collectionConfig.mimeTypes.join(', ')}.`,
)
}
if (
mimeType &&
pluginConfig.resolver.supportedMimeTypes &&
!pluginConfig.resolver.supportedMimeTypes.includes(mimeType)
) {
throw new Error(
`Alt text generation is not supported for files of type "${mimeType}". Supported types: ${pluginConfig.resolver.supportedMimeTypes.join(', ')}.`,
)
}
const imageThumbnailUrl = pluginConfig.getImageThumbnail(imageDoc)
const result = await pluginConfig.resolver.resolveBulk({
filename:
'filename' in imageDoc && typeof imageDoc.filename === 'string'
? imageDoc.filename
: undefined,
imageThumbnailUrl,
locales,
req,
})
if (!result.success) {
throw new Error(result.error || 'Failed to generate alt text')
}
for (const locale of locales) {
const localeResult = result.results[locale]
if (localeResult) {
await payload.update({
id,
collection,
data: {
alt: localeResult.altText,
keywords: localeResult.keywords,
},
locale,
})
}
}
}