File size: 2,090 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
import * as formidable from 'formidable';
import Replicate from 'replicate';

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async function handler(req, res) {
  const form = new formidable.IncomingForm();
  
  form.parse(req, async (err, fields, files) => {
    if (err) {
      console.error('Error parsing form data:', err);
      return res.status(400).json({ error: 'Error parsing form data' });
    }

    try {
      const inputData = {
        prompt: fields.prompt?.toString(),
        negative_prompt: fields.negative_prompt?.toString(),
        scheduler: fields.scheduler?.toString(),
        seed: parseInt(fields.seed?.toString() || "0"),
        refine: fields.refine?.toString(),
        refine_steps: parseInt(fields.refine_steps?.toString() || "0")
      };
  
      const replicate = new Replicate({
        auth: process.env.NEXT_PUBLIC_REPLICATE_API_TOKEN,
      });
  
      const prediction = await replicate.predictions.create({
        version: "67ed00e8999fecd32035074fa0f2e9a31ee03b57a8415e6a5e2f93a242ddd8d2",
        input: inputData,
      });

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

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

        // Fetch the current state of the prediction
        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);
      return res.status(200).json({ prediction: currentPrediction, videoUrl: currentPrediction.videoUrl });
    } catch (error) {
      console.error('An error occurred:', error);
      return res.status(500).json({ error: 'Internal Server Error' });
    }
  });
}