Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

video.tsx

484 lines16.0 KB

1import { useEffect, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 AlertTriangle,
5 Download,
6 Loader2,
7 RefreshCw,
8 Video,
9} from 'lucide-react'
10​
11// Supported sizes per OpenAI Sora API docs
12type VideoSize = '1280x720' | '720x1280' | '1792x1024' | '1024x1792'
13// Supported durations: 4, 8, or 12 seconds
14type VideoSeconds = 4 | 8 | 12
15​
16interface VideoJob {
17 jobId: string
18 status: 'pending' | 'processing' | 'completed' | 'failed'
19 progress?: number
20 url?: string
21 error?: string
22 expiresAt?: string
24​
25const SIZES: Array<{ value: VideoSize; label: string }> = [
26 { value: '1280x720', label: '1280x720 (Landscape)' },
27 { value: '720x1280', label: '720x1280 (Portrait)' },
28 { value: '1792x1024', label: '1792x1024 (Wide Landscape)' },
29 { value: '1024x1792', label: '1024x1792 (Tall Portrait)' },
31​
32const DURATIONS: Array<{ value: VideoSeconds; label: string }> = [
33 { value: 4, label: '4 seconds' },
34 { value: 8, label: '8 seconds' },
35 { value: 12, label: '12 seconds' },
37​
38function VideoPage() {
39 const [prompt, setPrompt] = useState(
40 'A golden retriever puppy playing in a field of sunflowers on a sunny day, cinematic lighting',
41 )
42 const [size, setSize] = useState<VideoSize>('1280x720')
43 const [seconds, setSeconds] = useState<VideoSeconds>(8)
44 const [job, setJob] = useState<VideoJob | null>(null)
45 const [isLoading, setIsLoading] = useState(false)
46 const [error, setError] = useState<string | null>(null)
47 const [resumeJobId, setResumeJobId] = useState('')
48 const pollingRef = useRef<NodeJS.Timeout | null>(null)
49​
50 // Clean up polling on unmount
51 useEffect(() => {
52 return () => {
53 if (pollingRef.current) {
54 clearInterval(pollingRef.current)
55 }
56 }
57 }, [])
58​
59 const handleGenerate = async () => {
60 setIsLoading(true)
61 setError(null)
62 setJob(null)
63​
64 // Stop any existing polling
65 if (pollingRef.current) {
66 clearInterval(pollingRef.current)
67 pollingRef.current = null
68 }
69​
70 try {
71 const response = await fetch('/api/video', {
72 method: 'POST',
73 headers: { 'Content-Type': 'application/json' },
74 body: JSON.stringify({
75 action: 'create',
76 prompt,
77 size,
78 seconds,
79 }),
80 })
81​
82 const data = await response.json()
83​
84 if (!response.ok) {
85 throw new Error(data.error || 'Failed to create video job')
86 }
87​
88 // Set initial job state
89 setJob({
90 jobId: data.jobId,
91 status: 'pending',
92 })
93​
94 // Start polling for status
95 startPolling(data.jobId)
96 } catch (err: any) {
97 setError(err.message)
98 setIsLoading(false)
99 }
100 }
101​
102 const handleResumeJob = async () => {
103 if (!resumeJobId.trim()) return
104​
105 setIsLoading(true)
106 setError(null)
107 setJob(null)
108​
109 // Stop any existing polling
110 if (pollingRef.current) {
111 clearInterval(pollingRef.current)
112 pollingRef.current = null
113 }
114​
115 // Set initial job state with the provided ID
116 setJob({
117 jobId: resumeJobId.trim(),
118 status: 'pending',
119 })
120​
121 // Start polling for status
122 startPolling(resumeJobId.trim())
123 }
124​
125 const startPolling = (jobId: string) => {
126 const poll = async () => {
127 try {
128 const response = await fetch('/api/video', {
129 method: 'POST',
130 headers: { 'Content-Type': 'application/json' },
131 body: JSON.stringify({
132 action: 'status',
133 jobId,
134 }),
135 })
136​
137 const data = await response.json()
138​
139 if (!response.ok) {
140 throw new Error(data.error || 'Failed to get status')
141 }
142​
143 setJob((prev) => ({
144 ...prev!,
145 status: data.status,
146 progress: data.progress,
147 error: data.error,
148 }))
149​
150 if (data.status === 'completed') {
151 // Stop polling and get URL
152 if (pollingRef.current) {
153 clearInterval(pollingRef.current)
154 pollingRef.current = null
155 }
156 await fetchVideoUrl(jobId)
157 setIsLoading(false)
158 } else if (data.status === 'failed') {
159 // Stop polling
160 if (pollingRef.current) {
161 clearInterval(pollingRef.current)
162 pollingRef.current = null
163 }
164 setError(data.error || 'Video generation failed')
165 setIsLoading(false)
166 }
167 } catch (err: any) {
168 console.error('Polling error:', err)
169 }
170 }
171​
172 // Poll immediately, then every 5 seconds
173 poll()
174 pollingRef.current = setInterval(poll, 5000)
175 }
176​
177 const fetchVideoUrl = async (jobId: string) => {
178 try {
179 const response = await fetch('/api/video', {
180 method: 'POST',
181 headers: { 'Content-Type': 'application/json' },
182 body: JSON.stringify({
183 action: 'url',
184 jobId,
185 }),
186 })
187​
188 const data = await response.json()
189​
190 if (!response.ok) {
191 throw new Error(data.error || 'Failed to get video URL')
192 }
193​
194 setJob((prev) => ({
195 ...prev!,
196 url: data.url,
197 expiresAt: data.expiresAt,
198 }))
199 } catch (err: any) {
200 setError(err.message)
201 }
202 }
203​
204 const handleDownload = async () => {
205 if (!job?.url) return
206​
207 try {
208 const response = await fetch(job.url)
209 const blob = await response.blob()
210 const url = URL.createObjectURL(blob)
211 const a = document.createElement('a')
212 a.href = url
213 a.download = `generated-video-${job.jobId}.mp4`
214 document.body.appendChild(a)
215 a.click()
216 document.body.removeChild(a)
217 URL.revokeObjectURL(url)
218 } catch (err) {
219 console.error('Failed to download video:', err)
220 }
221 }
222​
223 const getStatusColor = (status: VideoJob['status']) => {
224 switch (status) {
225 case 'pending':
226 return 'text-yellow-400'
227 case 'processing':
228 return 'text-blue-400'
229 case 'completed':
230 return 'text-green-400'
231 case 'failed':
232 return 'text-red-400'
233 default:
234 return 'text-gray-400'
235 }
236 }
237​
238 return (
239 <div className="min-h-[calc(100vh-72px)] bg-gray-900 p-6">
240 <div className="max-w-6xl mx-auto">
241 {/* Header with experimental warning */}
242 <div className="flex items-center gap-3 mb-4">
243 <Video className="w-8 h-8 text-purple-500" />
244 <h1 className="text-2xl font-bold text-white">Video Generation</h1>
245 <span className="px-2 py-1 text-xs font-medium text-yellow-400 bg-yellow-400/10 rounded-full border border-yellow-400/30">
246 Experimental
247 </span>
248 </div>
249​
250 {/* Warning banner */}
251 <div className="mb-6 p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-start gap-3">
252 <AlertTriangle className="w-5 h-5 text-yellow-400 shrink-0 mt-0.5" />
253 <div className="text-sm text-yellow-200">
254 <p className="font-medium">Experimental Feature</p>
255 <p className="mt-1 text-yellow-200/80">
256 Video generation using OpenAI Sora-2 is experimental and may
257 require special API access. The API is subject to change without
258 notice.
259 </p>
260 </div>
261 </div>
262​
263 {/* Resume Job Section */}
264 <div className="mb-6 p-4 bg-gray-800 border border-purple-500/20 rounded-lg">
265 <h3 className="text-sm font-medium text-gray-300 mb-3">
266 Resume Existing Job
267 </h3>
268 <div className="flex gap-3">
269 <input
270 type="text"
271 value={resumeJobId}
272 onChange={(e) => setResumeJobId(e.target.value)}
273 disabled={isLoading}
274 placeholder="Enter job ID (e.g., video_abc123...)"
275 className="flex-1 rounded-lg border border-purple-500/20 bg-gray-900 px-3 py-2 text-sm text-white font-mono focus:outline-none focus:ring-2 focus:ring-purple-500/50"
276 />
277 <button
278 onClick={handleResumeJob}
279 disabled={isLoading || !resumeJobId.trim()}
280 className="px-4 py-2 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors flex items-center gap-2"
281 >
282 {isLoading && job?.jobId === resumeJobId.trim() ? (
283 <>
284 <Loader2 className="w-4 h-4 animate-spin" />
285 Resuming...
286 </>
287 ) : (
288 <>
289 <RefreshCw className="w-4 h-4" />
290 Resume
291 </>
292 )}
293 </button>
294 </div>
295 </div>
296​
297 <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
298 {/* Input Panel */}
299 <div className="space-y-4">
300 <div className="grid grid-cols-2 gap-4">
301 <div>
302 <label className="block text-sm font-medium text-gray-300 mb-2">
303 Size
304 </label>
305 <select
306 value={size}
307 onChange={(e) => setSize(e.target.value as VideoSize)}
308 disabled={isLoading}
309 className="w-full rounded-lg border border-purple-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-purple-500/50"
310 >
311 {SIZES.map((s) => (
312 <option key={s.value} value={s.value}>
313 {s.label}
314 </option>
315 ))}
316 </select>
317 </div>
318 <div>
319 <label className="block text-sm font-medium text-gray-300 mb-2">
320 Duration
321 </label>
322 <select
323 value={seconds}
324 onChange={(e) =>
325 setSeconds(Number(e.target.value) as VideoSeconds)
326 }
327 disabled={isLoading}
328 className="w-full rounded-lg border border-purple-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-purple-500/50"
329 >
330 {DURATIONS.map((d) => (
331 <option key={d.value} value={d.value}>
332 {d.label}
333 </option>
334 ))}
335 </select>
336 </div>
337 </div>
338​
339 <div>
340 <label className="block text-sm font-medium text-gray-300 mb-2">
341 Prompt
342 </label>
343 <textarea
344 value={prompt}
345 onChange={(e) => setPrompt(e.target.value)}
346 disabled={isLoading}
347 rows={6}
348 className="w-full rounded-lg border border-purple-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-purple-500/50 resize-none"
349 placeholder="Describe the video you want to generate..."
350 />
351 </div>
352​
353 <button
354 onClick={handleGenerate}
355 disabled={isLoading || !prompt.trim()}
356 className="w-full px-4 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
357 >
358 {isLoading ? (
359 <>
360 <Loader2 className="w-5 h-5 animate-spin" />
361 {job?.status === 'pending'
362 ? 'Queued...'
363 : job?.status === 'processing'
364 ? `Processing${job.progress ? ` (${job.progress}%)` : '...'}`
365 : 'Starting...'}
366 </>
367 ) : (
368 'Generate Video'
369 )}
370 </button>
371​
372 {/* Job Status */}
373 {job && (
374 <div className="p-4 bg-gray-800 rounded-lg border border-purple-500/20">
375 <h3 className="text-sm font-medium text-gray-300 mb-2">
376 Job Status
377 </h3>
378 <div className="space-y-2 text-sm">
379 <p className="text-gray-400">
380 Job ID:{' '}
381 <span className="text-gray-200 font-mono">{job.jobId}</span>
382 </p>
383 <p className="text-gray-400">
384 Status:{' '}
385 <span
386 className={`font-medium ${getStatusColor(job.status)}`}
387 >
388 {job.status.charAt(0).toUpperCase() + job.status.slice(1)}
389 </span>
390 </p>
391 {job.progress !== undefined &&
392 job.status === 'processing' && (
393 <div>
394 <p className="text-gray-400 mb-1">
395 Progress: {job.progress}%
396 </p>
397 <div className="w-full bg-gray-700 rounded-full h-2">
398 <div
399 className="bg-purple-500 h-2 rounded-full transition-all duration-300"
400 style={{ width: `${job.progress}%` }}
401 />
402 </div>
403 </div>
404 )}
405 </div>
406 </div>
407 )}
408 </div>
409​
410 {/* Output Panel */}
411 <div className="lg:col-span-2 bg-gray-800 rounded-lg p-6 border border-purple-500/20">
412 <h2 className="text-lg font-semibold text-white mb-4">
413 Generated Video
414 </h2>
415​
416 {error && (
417 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 mb-4">
418 {error}
419 </div>
420 )}
421​
422 {job?.url ? (
423 <div className="space-y-4">
424 <div className="relative group">
425 <video
426 src={job.url}
427 controls
428 className="w-full rounded-lg border border-gray-700"
429 >
430 Your browser does not support the video tag.
431 </video>
432 <button
433 onClick={handleDownload}
434 className="absolute top-2 right-2 p-2 bg-gray-900/80 hover:bg-gray-900 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity"
435 title="Download video"
436 >
437 <Download className="w-4 h-4 text-white" />
438 </button>
439 </div>
440 <div className="pt-4 border-t border-gray-700 text-sm text-gray-400">
441 <p>
442 Model: <span className="text-purple-400">sora-2</span>
443 </p>
444 <p>
445 Size: <span className="text-purple-400">{size}</span>
446 </p>
447 <p>
448 Duration:{' '}
449 <span className="text-purple-400">{seconds}s</span>
450 </p>
451 {job.expiresAt && (
452 <p>
453 URL expires:{' '}
454 <span className="text-purple-400">
455 {new Date(job.expiresAt).toLocaleString()}
456 </span>
457 </p>
458 )}
459 </div>
460 </div>
461 ) : job?.status === 'processing' || job?.status === 'pending' ? (
462 <div className="flex flex-col items-center justify-center h-64 text-gray-500">
463 <RefreshCw className="w-16 h-16 mb-4 opacity-50 animate-spin" />
464 <p>Video is being generated...</p>
465 <p className="text-sm mt-2">This may take several minutes.</p>
466 </div>
467 ) : !error && !isLoading ? (
468 <div className="flex flex-col items-center justify-center h-64 text-gray-500">
469 <Video className="w-16 h-16 mb-4 opacity-50" />
470 <p>
471 Enter a prompt and click "Generate Video" to create a video.
472 </p>
473 </div>
474 ) : null}
475 </div>
476 </div>
477 </div>
478 </div>
479 )
481​
482export const Route = createFileRoute('/video')({
483 component: VideoPage,
484})