| |
| import fs from 'fs'; |
| import path from 'path'; |
| import axios from 'axios'; |
| import Replicate from 'replicate'; |
|
|
| export default async function handler(req, res) { |
| try { |
| |
| 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: "7757c5775e962c618053e7df4343052a21075676d6234e8ede5fa67c9e43bce0", |
| 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; |
|
|
| |
| const response = await axios.get(videoUrl, { responseType: 'stream' }); |
| |
| |
| const outputPath = path.resolve(process.cwd(), 'output'); |
| if (!fs.existsSync(outputPath)) { |
| fs.mkdirSync(outputPath); |
| } |
|
|
| |
| 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' }); |
| } |
| } |
|
|