![]() Server : Apache/2 System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64 User : gositeme ( 1004) PHP Version : 8.2.29 Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname Directory : /home/gositeme/domains/soundstudiopro.com/private_html/utils/ |
<?php
// Generate New Lyrics Script
// Creates new lyrics for tracks using API.box instead of trying to fetch from old task IDs
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('max_execution_time', 0);
ini_set('memory_limit', '512M');
require_once 'config/database.php';
// Configuration
$BATCH_SIZE = 5; // Process tracks in smaller batches
$DELAY_BETWEEN_REQUESTS = 3; // Seconds between API calls
$MAX_RETRIES = 3;
// Logging
$logFile = 'generate_lyrics_log.txt';
function logMessage($message) {
global $logFile;
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[$timestamp] $message\n";
file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
echo $logEntry;
}
// Function to generate lyrics using API.box
function generateLyricsFromAPI($trackId, $title, $prompt) {
global $DELAY_BETWEEN_REQUESTS, $MAX_RETRIES;
$apiUrl = 'https://api.api.box/api/v1/lyrics';
$requestData = [
'prompt' => "Generate lyrics for a song titled '$title'. Style: " . substr($prompt, 0, 200),
'model' => 'v3',
'duration' => 30,
'callBackUrl' => 'https://soundstudiopro.com/callback.php'
];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer 63edba40620216c5aa2c04240ac41dbd',
'User-Agent: SoundStudioPro/1.0'
];
for ($attempt = 1; $attempt <= $MAX_RETRIES; $attempt++) {
try {
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $headers),
'content' => json_encode($requestData),
'timeout' => 60
]
]);
$response = file_get_contents($apiUrl, false, $context);
if ($response === false) {
throw new Exception("Failed to make API request");
}
$responseData = json_decode($response, true);
if (isset($responseData['code']) && $responseData['code'] === 200) {
if (isset($responseData['data']['taskId'])) {
return $responseData['data']['taskId'];
}
}
logMessage("Attempt $attempt failed for track $trackId: Invalid response");
if ($attempt < $MAX_RETRIES) {
sleep($DELAY_BETWEEN_REQUESTS);
}
} catch (Exception $e) {
logMessage("Attempt $attempt failed for track $trackId: " . $e->getMessage());
if ($attempt < $MAX_RETRIES) {
sleep($DELAY_BETWEEN_REQUESTS);
}
}
}
return null;
}
// Function to check task status and get lyrics
function checkTaskStatus($taskId) {
$apiUrl = "https://api.api.box/api/v1/result/$taskId";
$headers = [
'Authorization: Bearer 63edba40620216c5aa2c04240ac41dbd',
'User-Agent: SoundStudioPro/1.0'
];
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => implode("\r\n", $headers),
'timeout' => 30
]
]);
$response = file_get_contents($apiUrl, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
// Extract lyrics from API.box response format
if (isset($data['data']['lyrics'])) {
return $data['data']['lyrics'];
} elseif (isset($data['data']['text'])) {
return $data['data']['text'];
} elseif (isset($data['lyrics'])) {
return $data['lyrics'];
} elseif (isset($data['text'])) {
return $data['text'];
}
return null;
}
// Function to update track with lyrics
function updateTrackLyrics($trackId, $lyrics) {
$pdo = getDBConnection();
if (!$pdo) {
logMessage("Database connection failed");
return false;
}
try {
$stmt = $pdo->prepare("
UPDATE music_tracks
SET lyrics = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
");
$result = $stmt->execute([$lyrics, $trackId]);
if ($result) {
logMessage("Successfully updated lyrics for track $trackId");
return true;
} else {
logMessage("Failed to update lyrics for track $trackId");
return false;
}
} catch (Exception $e) {
logMessage("Database error updating track $trackId: " . $e->getMessage());
return false;
}
}
// Main execution
logMessage("=== GENERATING NEW LYRICS ===");
$pdo = getDBConnection();
if (!$pdo) {
logMessage("ERROR: Cannot connect to database");
exit(1);
}
// Get tracks without lyrics
try {
$stmt = $pdo->prepare("
SELECT id, title, prompt, status
FROM music_tracks
WHERE (lyrics IS NULL OR lyrics = '')
AND status = 'complete'
ORDER BY created_at DESC
LIMIT ?
");
$stmt->execute([$BATCH_SIZE]);
$tracksWithoutLyrics = $stmt->fetchAll();
$totalTracks = count($tracksWithoutLyrics);
logMessage("Found $totalTracks tracks without lyrics");
if ($totalTracks === 0) {
logMessage("No tracks found without lyrics!");
exit(0);
}
$successCount = 0;
$errorCount = 0;
foreach ($tracksWithoutLyrics as $track) {
logMessage("Processing track {$track['id']}: {$track['title']}");
// Generate new lyrics
$taskId = generateLyricsFromAPI($track['id'], $track['title'], $track['prompt']);
if ($taskId) {
logMessage("✅ Generated task ID: $taskId for track {$track['id']}");
// Wait a bit for processing
sleep(5);
// Check status and get lyrics
$lyrics = checkTaskStatus($taskId);
if ($lyrics) {
// Clean up lyrics
$lyrics = str_replace(['[Verse]', '[Chorus]', '[Bridge]', '[Outro]', '[Intro]'], '', $lyrics);
$lyrics = preg_replace('/\[.*?\]/', '', $lyrics);
$lyrics = trim($lyrics);
// Update track
if (updateTrackLyrics($track['id'], $lyrics)) {
$successCount++;
logMessage("✅ Added lyrics to track {$track['id']}");
} else {
$errorCount++;
logMessage("❌ Failed to update track {$track['id']}");
}
} else {
$errorCount++;
logMessage("❌ No lyrics found for task $taskId");
}
} else {
$errorCount++;
logMessage("❌ Failed to generate lyrics for track {$track['id']}");
}
// Delay between requests
sleep($DELAY_BETWEEN_REQUESTS);
}
// Summary
logMessage("=== COMPLETE ===");
logMessage("Total: $totalTracks, Success: $successCount, Errors: $errorCount");
} catch (Exception $e) {
logMessage("ERROR: " . $e->getMessage());
exit(1);
}
logMessage("=== SCRIPT COMPLETED ===");
?>