-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathuse-generation.ts
More file actions
418 lines (374 loc) · 12.3 KB
/
Copy pathuse-generation.ts
File metadata and controls
418 lines (374 loc) · 12.3 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import { useState, useCallback, useRef } from 'react'
import type { GenerationSettings } from '../components/SettingsPanel'
import { ApiClient } from '../lib/api-client'
import { useAppSettings } from '../contexts/AppSettingsContext'
interface GenerationState {
isGenerating: boolean
progress: number
statusMessage: string
videoPath: string | null
imagePath: string | null
imagePaths: string[]
error: string | null
}
type GenerateVideoRequest = Parameters<typeof ApiClient.generateVideo>[0]
type GenerateImageRequest = Parameters<typeof ApiClient.generateImage>[0]
interface UseGenerationReturn extends GenerationState {
generate: (prompt: string, imagePath: string | null, settings: GenerationSettings, audioPath?: string | null) => Promise<{ success: boolean; videoPath: string | null }>
generateImage: (prompt: string, settings: GenerationSettings) => Promise<{ success: boolean }>
cancel: () => void
reset: () => void
}
const IMAGE_SHORT_SIDE_BY_RESOLUTION: Record<string, number> = {
'1080p': 1080,
'1440p': 1440,
'2048p': 2048,
}
const IMAGE_ASPECT_RATIO_VALUE: Record<string, number> = {
'1:1': 1,
'16:9': 16 / 9,
'9:16': 9 / 16,
'4:3': 4 / 3,
'3:4': 3 / 4,
'21:9': 21 / 9,
}
function getImageDimensions(settings: GenerationSettings): { width: number; height: number } {
const shortSide = IMAGE_SHORT_SIDE_BY_RESOLUTION[settings.imageResolution]
if (!shortSide) {
throw new Error(`Unsupported image resolution mapping: ${settings.imageResolution}`)
}
const ratio = IMAGE_ASPECT_RATIO_VALUE[settings.imageAspectRatio]
if (!ratio) {
throw new Error(`Unsupported image aspect ratio mapping: ${settings.imageAspectRatio}`)
}
if (ratio >= 1) {
return { width: Math.round(shortSide * ratio), height: shortSide }
}
return { width: shortSide, height: Math.round(shortSide / ratio) }
}
// Map phase to user-friendly message
function getPhaseMessage(phase: string): string {
switch (phase) {
case 'validating_request':
return 'Validating request...'
case 'uploading_image':
return 'Uploading image...'
case 'uploading_audio':
return 'Uploading audio...'
case 'loading_model':
return 'Loading model...'
case 'encoding_text':
return 'Encoding prompt...'
case 'inference':
return 'Generating...'
case 'downloading_output':
return 'Downloading output...'
case 'decoding':
return 'Decoding video...'
case 'complete':
return 'Complete!'
default:
return 'Generating...'
}
}
export function useGeneration(): UseGenerationReturn {
const { settings: appSettings, forceApiGenerations, refreshSettings } = useAppSettings()
const [state, setState] = useState<GenerationState>({
isGenerating: false,
progress: 0,
statusMessage: '',
videoPath: null,
imagePath: null,
imagePaths: [],
error: null,
})
const abortControllerRef = useRef<AbortController | null>(null)
const generate = useCallback(async (
prompt: string,
imagePath: string | null,
settings: GenerationSettings,
audioPath?: string | null,
): Promise<{ success: boolean; videoPath: string | null }> => {
const statusMsg = settings.model === 'pro'
? 'Loading Pro model & generating...'
: 'Generating video...'
setState({
isGenerating: true,
progress: 0,
statusMessage: statusMsg,
videoPath: null,
imagePath: null,
imagePaths: [],
error: null,
})
abortControllerRef.current = new AbortController()
let progressInterval: ReturnType<typeof setInterval> | null = null
let shouldApplyPollingUpdates = true
let succeeded = false
let resultVideoPath: string | null = null
try {
// Prepare JSON body
const body: Record<string, unknown> = {
prompt,
model: settings.model,
duration: settings.duration,
resolution: settings.videoResolution,
fps: settings.fps,
audio: settings.audio,
cameraMotion: settings.cameraMotion,
negativePrompt: (settings as { negativePrompt?: string }).negativePrompt ?? '',
aspectRatio: settings.aspectRatio || '16:9',
}
if (imagePath) {
body.imagePath = imagePath
}
if (audioPath) {
body.audioPath = audioPath
}
// Poll for real progress from backend with time-based interpolation
let lastPhase = ''
let inferenceStartTime = 0
// Estimated inference time in seconds based on model
const estimatedInferenceTime = settings.model === 'pro' ? 120 : 45
const pollProgress = async () => {
if (!shouldApplyPollingUpdates) return
try {
const data = await ApiClient.getGenerationProgress()
if (!shouldApplyPollingUpdates) return
let displayProgress = data.progress
let statusMessage = getPhaseMessage(data.phase)
// Time-based interpolation during inference phase
if (data.phase === 'inference') {
if (lastPhase !== 'inference') {
inferenceStartTime = Date.now()
}
const elapsed = (Date.now() - inferenceStartTime) / 1000
// Interpolate from 15% to 95% based on estimated time
const inferenceProgress = Math.min(elapsed / estimatedInferenceTime, 0.95)
displayProgress = 15 + Math.floor(inferenceProgress * 80)
}
// Keep API/local completion as a terminal response state, not polling state.
// Polling complete means backend state is finalized, but request can still be in-flight.
if (data.phase === 'complete' || data.status === 'complete') {
displayProgress = 95
statusMessage = 'Finalizing...'
}
lastPhase = data.phase
setState(prev => ({
...prev,
progress: displayProgress,
statusMessage,
}))
} catch {
// Ignore polling errors
}
}
progressInterval = setInterval(pollProgress, 500)
// Start generation (HTTP POST - synchronous, returns when done)
const payload = await ApiClient.generateVideo(body as unknown as GenerateVideoRequest, {
signal: abortControllerRef.current.signal,
})
shouldApplyPollingUpdates = false
if (payload.status === 'complete') {
resultVideoPath = payload.video_path
setState({
isGenerating: false,
progress: 100,
statusMessage: 'Complete!',
videoPath: payload.video_path,
imagePath: null,
imagePaths: [],
error: null,
})
succeeded = true
} else if (payload.status === 'cancelled') {
setState(prev => ({
...prev,
isGenerating: false,
statusMessage: 'Cancelled',
}))
} else {
throw new Error('Unexpected response from /api/generate')
}
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
setState(prev => ({
...prev,
isGenerating: false,
statusMessage: 'Cancelled',
}))
} else {
setState(prev => ({
...prev,
isGenerating: false,
error: error instanceof Error ? error.message : 'Unknown error',
}))
}
} finally {
shouldApplyPollingUpdates = false
if (progressInterval) {
clearInterval(progressInterval)
}
}
return { success: succeeded, videoPath: resultVideoPath }
}, [])
const cancel = useCallback(async () => {
// Abort the fetch request
abortControllerRef.current?.abort()
// Also tell the backend to cancel
try {
await ApiClient.cancelGeneration()
} catch {
// Ignore errors from cancel request
}
setState(prev => ({
...prev,
isGenerating: false,
statusMessage: 'Cancelled',
}))
}, [])
const generateImage = useCallback(async (
prompt: string,
settings: GenerationSettings
): Promise<{ success: boolean }> => {
if (forceApiGenerations) {
try {
const payload = await ApiClient.getSettings()
if (!payload.hasFalApiKey) {
void refreshSettings()
window.dispatchEvent(new CustomEvent('open-api-gateway', {
detail: {
requiredKeys: ['fal'],
title: 'Connect FAL AI',
description: 'FAL AI is required for generating images with Z Image Turbo when API generations are enabled.',
blocking: false,
},
}))
return { success: false }
}
} catch {
if (!appSettings.hasFalApiKey) {
window.dispatchEvent(new CustomEvent('open-api-gateway', {
detail: {
requiredKeys: ['fal'],
title: 'Connect FAL AI',
description: 'FAL AI is required for generating images with Z Image Turbo when API generations are enabled.',
blocking: false,
},
}))
return { success: false }
}
}
}
const numImages = settings.variations || 1
setState({
isGenerating: true,
progress: 0,
statusMessage: numImages > 1 ? `Generating ${numImages} images...` : 'Generating image...',
videoPath: null,
imagePath: null,
imagePaths: [],
error: null,
})
abortControllerRef.current = new AbortController()
let succeeded = false
try {
// Skip prompt enhancement for T2I - use original prompt directly
const finalPrompt = prompt
const dims = getImageDimensions(settings)
const numSteps = settings.imageSteps || 4
// Poll for progress
const pollProgress = async () => {
try {
const data = await ApiClient.getGenerationProgress()
const currentImage = data.currentStep || 0
const totalImages = data.totalSteps || numImages
setState(prev => ({
...prev,
progress: data.progress,
statusMessage: data.phase === 'loading_model'
? 'Loading Z-Image Turbo model...'
: data.phase === 'inference'
? numImages > 1
? `Generating image ${currentImage + 1}/${totalImages}...`
: 'Generating image...'
: data.phase === 'complete'
? 'Complete!'
: 'Generating...',
}))
} catch {
// Ignore polling errors
}
}
const progressInterval = setInterval(pollProgress, 500)
const imageRequest: GenerateImageRequest = {
prompt: finalPrompt,
width: dims.width,
height: dims.height,
numSteps,
numImages,
}
const payload = await ApiClient.generateImage(imageRequest, {
signal: abortControllerRef.current.signal,
})
clearInterval(progressInterval)
if (payload.status === 'complete') {
const rawPaths = payload.image_paths
if (rawPaths.length === 0) {
throw new Error('Image generation completed without output images')
}
setState({
isGenerating: false,
progress: 100,
statusMessage: 'Complete!',
videoPath: null,
imagePath: rawPaths[0],
imagePaths: rawPaths,
error: null,
})
succeeded = true
} else if (payload.status === 'cancelled') {
setState(prev => ({
...prev,
isGenerating: false,
statusMessage: 'Cancelled',
}))
} else {
throw new Error('Unexpected response from /api/generate-image')
}
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
setState(prev => ({
...prev,
isGenerating: false,
statusMessage: 'Cancelled',
}))
} else {
setState(prev => ({
...prev,
isGenerating: false,
error: error instanceof Error ? error.message : 'Unknown error',
}))
}
}
return { success: succeeded }
}, [appSettings.hasFalApiKey, forceApiGenerations, refreshSettings])
const reset = useCallback(() => {
setState({
isGenerating: false,
progress: 0,
statusMessage: '',
videoPath: null,
imagePath: null,
imagePaths: [],
error: null,
})
}, [])
return {
...state,
generate,
generateImage,
cancel,
reset,
}
}