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
5bcc8b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a03d8c
 
 
 
 
 
5bcc8b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a9c884
 
 
 
 
 
 
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
419
420
421
422
423
424
425
426
427
428
429
430
431
import { useState, useRef, useEffect } from "react";
import { useVLMContext } from "../context/useVLMContext";
import { extractJsonFromMarkdown, drawBoundingBoxesOnCanvas } from "./BoxAnnotator";

const MODES = ["Webcam", "URL", "File"] as const;
type Mode = typeof MODES[number];

const EXAMPLE_VIDEO_URL =
  "https://dm0qx8t0i9gc9.cloudfront.net/watermarks/video/47Fj2US_gijjhliil/large-group-of-people-walking-at-city_rpem-bqvu__f51e7e41cf28b832502c9709c8eb2fd8__P360.mp4";
const EXAMPLE_PROMPT = "Find as many objects in the video and box them.";

function isImageFile(file: File) {
  return file.type.startsWith("image/");
}
function isVideoFile(file: File) {
  return file.type.startsWith("video/");
}

export default function MultiSourceCaptioningView() {
  const [mode, setMode] = useState<Mode>("File");
  const [videoUrl, setVideoUrl] = useState<string>(EXAMPLE_VIDEO_URL);
  const [inputUrl, setInputUrl] = useState<string>(EXAMPLE_VIDEO_URL);
  const [prompt, setPrompt] = useState<string>(EXAMPLE_PROMPT);
  const [processing, setProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [webcamActive, setWebcamActive] = useState(false);
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [uploadedUrl, setUploadedUrl] = useState<string>("");
  const [videoProcessing, setVideoProcessing] = useState(false);
  const [imageProcessed, setImageProcessed] = useState(false);

  const videoRef = useRef<HTMLVideoElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const imageRef = useRef<HTMLImageElement | null>(null);
  const webcamStreamRef = useRef<MediaStream | null>(null);
  const { isLoaded, runInference } = useVLMContext();

  // Webcam setup and teardown (unchanged)
  useEffect(() => {
    if (mode !== "Webcam") {
      if (webcamStreamRef.current) {
        webcamStreamRef.current.getTracks().forEach((track: MediaStreamTrack) => track.stop());
        webcamStreamRef.current = null;
      }
      setWebcamActive(false);
      return;
    }
    const setupWebcam = async () => {
      try {
        setError(null);
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        webcamStreamRef.current = stream;
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          setWebcamActive(true);
        }
      } catch (e) {
        setError("Could not access webcam: " + (e instanceof Error ? e.message : String(e)));
        setWebcamActive(false);
      }
    };
    setupWebcam();
    return () => {
      if (webcamStreamRef.current) {
        webcamStreamRef.current.getTracks().forEach((track: MediaStreamTrack) => track.stop());
        webcamStreamRef.current = null;
      }
      setWebcamActive(false);
    };
  }, [mode]);

  // Process webcam frames (unchanged)
  useEffect(() => {
    if (mode !== "Webcam" || !isLoaded || !webcamActive) return;
    let interval: ReturnType<typeof setInterval> | null = null;
    const processFrame = async () => {
      if (!videoRef.current || !canvasRef.current) return;
      const video = videoRef.current;
      const canvas = canvasRef.current;
      if (video.videoWidth === 0) return;
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext("2d");
      if (!ctx) return;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      try {
        setProcessing(true);
        setError(null);
        const fakeVideo = {
          videoWidth: canvas.width,
          videoHeight: canvas.height,
          getContext: () => ctx,
        } as unknown as HTMLVideoElement;
        const result = await runInference(fakeVideo, prompt);
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const boxes = extractJsonFromMarkdown(result) || [];
        drawBoundingBoxesOnCanvas(ctx, boxes);
      } catch (e) {
        setError(e instanceof Error ? e.message : String(e));
      } finally {
        setProcessing(false);
      }
    };
    interval = setInterval(() => {
      processFrame();
    }, 1000);
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [mode, isLoaded, prompt, runInference, webcamActive]);

  // Process video frames for URL mode (unchanged)
  useEffect(() => {
    if (mode !== "URL" || !isLoaded) return;
    let interval: ReturnType<typeof setInterval> | null = null;
    const processFrame = async () => {
      if (!videoRef.current || !canvasRef.current) return;
      const video = videoRef.current;
      const canvas = canvasRef.current;
      if (video.paused || video.ended || video.videoWidth === 0) return;
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext("2d");
      if (!ctx) return;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      try {
        setProcessing(true);
        setError(null);
        const fakeVideo = {
          videoWidth: canvas.width,
          videoHeight: canvas.height,
          getContext: () => ctx,
        } as unknown as HTMLVideoElement;
        const result = await runInference(fakeVideo, prompt);
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const boxes = extractJsonFromMarkdown(result) || [];
        drawBoundingBoxesOnCanvas(ctx, boxes);
      } catch (e) {
        setError(e instanceof Error ? e.message : String(e));
      } finally {
        setProcessing(false);
      }
    };
    interval = setInterval(() => {
      processFrame();
    }, 1000);
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [mode, isLoaded, prompt, runInference]);

  // File mode: process uploaded image (only on button click)
  const handleProcessImage = async () => {
    if (!isLoaded || !uploadedFile || !isImageFile(uploadedFile) || !imageRef.current || !canvasRef.current) return;
    const img = imageRef.current;
    const canvas = canvasRef.current;
    canvas.width = img.naturalWidth;
    canvas.height = img.naturalHeight;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    try {
      setProcessing(true);
      setError(null);
      const fakeVideo = {
        videoWidth: canvas.width,
        videoHeight: canvas.height,
        getContext: () => ctx,
      } as unknown as HTMLVideoElement;
      const result = await runInference(fakeVideo, prompt);
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      const boxes = extractJsonFromMarkdown(result) || [];
      drawBoundingBoxesOnCanvas(ctx, boxes);
      setImageProcessed(true);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setProcessing(false);
    }
  };

  // File mode: process uploaded video frames (start/stop)
  useEffect(() => {
    if (mode !== "File" || !isLoaded || !uploadedFile || !isVideoFile(uploadedFile) || !videoProcessing) return;
    let interval: ReturnType<typeof setInterval> | null = null;
    const processFrame = async () => {
      if (!videoRef.current || !canvasRef.current) return;
      const video = videoRef.current;
      const canvas = canvasRef.current;
      if (video.paused || video.ended || video.videoWidth === 0) return;
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext("2d");
      if (!ctx) return;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      try {
        setProcessing(true);
        setError(null);
        const fakeVideo = {
          videoWidth: canvas.width,
          videoHeight: canvas.height,
          getContext: () => ctx,
        } as unknown as HTMLVideoElement;
        const result = await runInference(fakeVideo, prompt);
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const boxes = extractJsonFromMarkdown(result) || [];
        drawBoundingBoxesOnCanvas(ctx, boxes);
      } catch (e) {
        setError(e instanceof Error ? e.message : String(e));
      } finally {
        setProcessing(false);
      }
    };
    interval = setInterval(() => {
      processFrame();
    }, 1000);
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [mode, isLoaded, prompt, runInference, uploadedFile, videoProcessing]);

  // Handle file upload
  const handleFileChange = (e: any) => {
    const file = e.target.files?.[0] || null;
    setUploadedFile(file);
    setUploadedUrl(file ? URL.createObjectURL(file) : "");
    setError(null);
    setImageProcessed(false);
    setVideoProcessing(false);
  };

  // Handle start/stop for video processing
  const handleToggleVideoProcessing = () => {
    setVideoProcessing((prev) => !prev);
  };

  return (
    <div className="absolute inset-0 text-white">

      <div className="flex flex-col items-center justify-center h-full w-full">

        {/* Mode Selector */}

        <div className="mb-6">

          <div className="flex space-x-4">

            {MODES.map((m) => (

              <button

                key={m}

                className={`px-6 py-2 rounded-lg font-semibold transition-all duration-200 ${

                  mode === m ? "bg-blue-600 text-white" : "bg-gray-700 text-gray-300 hover:bg-blue-500"

                }`}

                onClick={() => setMode(m)}

              >

                {m}

              </button>

            ))}

          </div>

        </div>



        {/* Mode Content */}

        <div className="w-full max-w-2xl flex-1 flex flex-col items-center justify-center">

          {mode === "Webcam" && (

            <div className="w-full text-center flex flex-col items-center">

              <div className="mb-4 w-full max-w-xl">

                <label className="block text-left mb-2 font-medium">Detection Prompt:</label>

                <textarea

                  className="w-full p-2 rounded-lg text-black"

                  rows={3}

                  value={prompt}

                  onChange={(e) => setPrompt(e.target.value)}

                />

              </div>

              <div className="relative w-full max-w-xl">

                <video

                  ref={videoRef}

                  autoPlay

                  muted

                  playsInline

                  className="w-full rounded-lg shadow-lg mb-2"

                  style={{ background: "#222" }}

                />

                <canvas

                  ref={canvasRef}

                  className="absolute top-0 left-0 w-full h-full pointer-events-none"

                  style={{ zIndex: 10, pointerEvents: "none" }}

                />

              </div>

              {processing && <div className="text-blue-400 mt-2">Processing frame...</div>}

              {error && <div className="text-red-400 mt-2">Error: {error}</div>}

            </div>

          )}

          {mode === "URL" && (

            <div className="w-full text-center flex flex-col items-center">

              <p className="mb-4">Enter a video stream URL (e.g., HTTP MP4, MJPEG, HLS, etc.):</p>

              <div className="flex w-full max-w-xl mb-4">

                <input

                  type="text"

                  className="flex-1 px-4 py-2 rounded-l-lg text-black"

                  value={inputUrl}

                  onChange={(e) => setInputUrl(e.target.value)}

                  placeholder="Paste video URL here"

                />

                <button

                  className="px-4 py-2 rounded-r-lg bg-blue-600 text-white font-semibold"

                  onClick={() => setVideoUrl(inputUrl)}

                >

                  Load

                </button>

              </div>

              <div className="mb-4 w-full max-w-xl">

                <label className="block text-left mb-2 font-medium">Detection Prompt:</label>

                <textarea

                  className="w-full p-2 rounded-lg text-black"

                  rows={3}

                  value={prompt}

                  onChange={(e) => setPrompt(e.target.value)}

                />

              </div>

              <div className="relative w-full max-w-xl">

                <video

                  ref={videoRef}

                  src={videoUrl}

                  controls

                  autoPlay

                  loop

                  className="w-full rounded-lg shadow-lg mb-2"

                  style={{ background: "#222" }}

                />

                <canvas

                  ref={canvasRef}

                  className="absolute top-0 left-0 w-full h-full pointer-events-none"

                  style={{ zIndex: 10, pointerEvents: "none" }}

                />

              </div>

              {processing && <div className="text-blue-400 mt-2">Processing frame...</div>}

              {error && <div className="text-red-400 mt-2">Error: {error}</div>}

            </div>

          )}

          {mode === "File" && (

            <div className="w-full text-center flex flex-col items-center">

              <div className="mb-4 w-full max-w-xl">

                <label className="block text-left mb-2 font-medium">Detection Prompt:</label>

                <textarea

                  className="w-full p-2 rounded-lg text-black"

                  rows={3}

                  value={prompt}

                  onChange={(e) => setPrompt(e.target.value)}

                />

              </div>

              <div className="mb-4 w-full max-w-xl">

                <input

                  type="file"

                  accept="image/*,video/*"

                  onChange={handleFileChange}

                  className="block w-full text-sm text-gray-300 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-600 file:text-white hover:file:bg-blue-700"

                />

              </div>

              {/* Show uploaded image */}

              {uploadedFile && isImageFile(uploadedFile) && (

                <div className="relative w-full max-w-xl">

                  <img

                    ref={imageRef}

                    src={uploadedUrl}

                    alt="Uploaded"

                    className="w-full rounded-lg shadow-lg mb-2"

                    style={{ background: "#222" }}

                  />

                  <canvas

                    ref={canvasRef}

                    className="absolute top-0 left-0 w-full h-full pointer-events-none"

                    style={{ zIndex: 10, pointerEvents: "none" }}

                  />

                  <button

                    className="mt-4 px-6 py-2 rounded-lg bg-blue-600 text-white font-semibold"

                    onClick={handleProcessImage}

                    disabled={processing}

                  >

                    {processing ? "Processing..." : imageProcessed ? "Reprocess Image" : "Process Image"}

                  </button>

                </div>

              )}

              {/* Show uploaded video */}

              {uploadedFile && isVideoFile(uploadedFile) && (

                <div className="relative w-full max-w-xl">

                  <video

                    ref={videoRef}

                    src={uploadedUrl}

                    controls

                    autoPlay

                    loop

                    className="w-full rounded-lg shadow-lg mb-2"

                    style={{ background: "#222" }}

                  />

                  <canvas

                    ref={canvasRef}

                    className="absolute top-0 left-0 w-full h-full pointer-events-none"

                    style={{ zIndex: 10, pointerEvents: "none" }}

                  />

                  <button

                    className="mt-4 px-6 py-2 rounded-lg bg-blue-600 text-white font-semibold"

                    onClick={handleToggleVideoProcessing}

                  >

                    {videoProcessing ? "Stop Processing" : "Start Processing"}

                  </button>

                </div>

              )}

              {/* Show example video if no file uploaded */}

              {!uploadedFile && (

                <div className="relative w-full max-w-xl">

                  <video

                    ref={videoRef}

                    src={EXAMPLE_VIDEO_URL}

                    controls

                    autoPlay

                    loop

                    className="w-full rounded-lg shadow-lg mb-2"

                    style={{ background: "#222" }}

                  />

                  <canvas

                    ref={canvasRef}

                    className="absolute top-0 left-0 w-full h-full pointer-events-none"

                    style={{ zIndex: 10, pointerEvents: "none" }}

                  />

                </div>

              )}

              {processing && <div className="text-blue-400 mt-2">Processing frame...</div>}

              {error && <div className="text-red-400 mt-2">Error: {error}</div>}

            </div>

          )}

        </div>

      </div>

    </div>
  );
}