File size: 2,268 Bytes
19e25f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// api/replicate.js
import fs from 'fs';
import path from 'path';
import axios from 'axios';
import Replicate from 'replicate';

export default async function handler(req, res) {
  try {
    // Your existing logic for interacting with Replicate API
    console.log('Received request data:', req.body);

    const replicate = new Replicate({
      auth: process.env.NEXT_PUBLIC_REPLICATE_API_TOKEN,
    });

    const inputData = req.body;
    console.log('Sending to Replicate:', inputData);

    const prediction = await replicate.predictions.create({
      version: "269a616c8b0c2bbc12fc15fd51bb202b11e94ff0f7786c026aa905305c4ed9fb",
      input: inputData,
    });

    console.log('Prediction created:', prediction);

    let isPredictionDone = false;
    let currentPrediction;
    while (!isPredictionDone) {
      console.log('Waiting for prediction to complete...');
      await new Promise(resolve => setTimeout(resolve, 2000));

      currentPrediction = await replicate.predictions.get(prediction.id);
      if (currentPrediction && currentPrediction.status === 'succeeded') {
        isPredictionDone = true;
        console.log('Prediction completed.');
        break;
      }
    }

    console.log('Final Prediction Result:', currentPrediction);
    const videoUrl = currentPrediction.output;

    // Download the video
    const response = await axios.get(videoUrl, { responseType: 'stream' });
    
    // Create output directory if it doesn't exist
    const outputPath = path.resolve(process.cwd(), 'output');
    if (!fs.existsSync(outputPath)) {
      fs.mkdirSync(outputPath);
    }

    // Save the video in the 'output' folder
    const videoPath = path.join(outputPath, `${currentPrediction.id}.mp4`);
    const writer = fs.createWriteStream(videoPath);
    response.data.pipe(writer);

    writer.on('finish', () => {
      console.log('Video saved successfully.');
      res.status(200).json({ prediction: currentPrediction, videoPath });
    });

    writer.on('error', (error) => {
      console.error('Error saving video:', error);
      res.status(500).json({ error: 'Failed to save video' });
    });

  } catch (error) {
    console.log('An error occurred:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
}