Spaces:
Sleeping
Sleeping
File size: 2,172 Bytes
36d488d | 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 | const { createClient } = require('pexels');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
/**
* Pexels Service for high-quality stock video automation
*/
class PexelsService {
constructor() {
this.apiKey = process.env.PEXELS_API_KEY;
if (this.apiKey) {
this.client = createClient(this.apiKey);
}
}
/**
* Search for a 9:16 portrait video matching the query
* @param {string} query - Search term
* @returns {string|null} Download link for the best matching video
*/
async searchVideo(query) {
if (!this.client) {
console.warn('⚠️ Pexels API Key missing. Skipping stock video search.');
return null;
}
try {
console.log(` 🔍 Pexels: Searching for "${query}"...`);
const result = await this.client.videos.search({
query,
orientation: 'portrait',
per_page: 5, // Get a few to find the best match
});
if (!result.videos || result.videos.length === 0) {
console.log(` ⚠️ Pexels: No videos found for "${query}"`);
return null;
}
// Find the best quality 1080x1920 file
const video = result.videos[0];
const videoFile = video.video_files.find(
f => f.width === 1080 && f.height === 1920
) || video.video_files[0]; // Fallback to first file
return videoFile.link;
} catch (error) {
console.error(' ❌ Pexels Search Error:', error.message);
return null;
}
}
/**
* Download a video from a URL
* @param {string} url - Download URL
* @param {string} outputPath - Path to save the file
* @returns {string} Saved file path
*/
async downloadVideo(url, outputPath) {
console.log(` 📥 Pexels: Downloading video...`);
const response = await axios({
method: 'get',
url: url,
responseType: 'stream',
});
const writer = fs.createWriteStream(outputPath);
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', () => resolve(outputPath));
writer.on('error', reject);
});
}
}
module.exports = new PexelsService();
|