vidcraft / src /pages /api /animatediff.js
tsi-org's picture
Upload 89 files
19e25f3
// 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' });
}
}