![]() 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/public_html/admin/ |
<?php
session_start();
// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'Unauthorized']);
exit;
}
require_once '../config/database.php';
header('Content-Type: application/json');
$pdo = getDBConnection();
$action = $_GET['action'] ?? '';
// Function to download and store audio files locally
function downloadAndStoreAudio($audioUrl, $taskId, $type = 'main', $variationIndex = null) {
if (empty($audioUrl) || !filter_var($audioUrl, FILTER_VALIDATE_URL)) {
return null;
}
// Create audio storage directory
$audioDir = '../audio_files/';
if (!is_dir($audioDir)) {
mkdir($audioDir, 0755, true);
}
// Generate filename
$extension = pathinfo(parse_url($audioUrl, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'mp3';
if ($type === 'variation' && $variationIndex !== null) {
$filename = "{$taskId}_variation_{$variationIndex}.{$extension}";
} else {
$filename = "{$taskId}.{$extension}";
}
$localPath = $audioDir . $filename;
$webPath = '/audio_files/' . $filename;
// Skip if file already exists
if (file_exists($localPath)) {
return $webPath;
}
// Download the file
$context = stream_context_create([
'http' => [
'timeout' => 300,
'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
]
]);
$audioContent = file_get_contents($audioUrl, false, $context);
if ($audioContent === false) {
return null;
}
// Save the file
if (file_put_contents($localPath, $audioContent, LOCK_EX)) {
chmod($localPath, 0644);
// Log the download
$downloadLog = [
'timestamp' => date('Y-m-d H:i:s'),
'action' => 'audio_downloaded_async',
'task_id' => $taskId,
'original_url' => $audioUrl,
'local_path' => $localPath,
'web_path' => $webPath,
'file_size' => strlen($audioContent),
'type' => $type,
'variation_index' => $variationIndex
];
$downloadLogFile = '../logs/audio_downloads.log';
file_put_contents($downloadLogFile, json_encode($downloadLog) . "\n", FILE_APPEND | LOCK_EX);
return $webPath;
}
return null;
}
// Function to extract comprehensive metadata
function extractComprehensiveMetadata($data) {
return [
'raw_callback' => $data,
'genre' => $data['genre'] ?? $data['tags'][0] ?? 'Electronic',
'style' => $data['style'] ?? '',
'tags' => $data['tags'] ?? [],
'bpm' => $data['bpm'] ?? $data['tempo'] ?? 120,
'key' => $data['key'] ?? 'C major',
'time_signature' => $data['time_signature'] ?? '4/4',
'mood' => $data['mood'] ?? 'neutral',
'energy' => $data['energy'] ?? 'medium',
'instruments' => $data['instruments'] ?? ['synthesizer'],
'audio_quality' => [
'bitrate' => $data['bitrate'] ?? $data['audio_bitrate'] ?? null,
'sample_rate' => $data['sample_rate'] ?? $data['audio_sample_rate'] ?? null,
'format' => $data['format'] ?? $data['audio_format'] ?? 'mp3',
'channels' => $data['channels'] ?? $data['audio_channels'] ?? 2,
'file_size' => $data['file_size'] ?? null,
'duration' => $data['duration'] ?? null,
'audio_quality_score' => $data['audio_quality_score'] ?? null
],
'generation_parameters' => [
'model_version' => $data['model_version'] ?? $data['model'] ?? 'v3',
'model_name' => $data['model_name'] ?? null,
'temperature' => $data['temperature'] ?? null,
'top_p' => $data['top_p'] ?? null,
'max_tokens' => $data['max_tokens'] ?? null,
'seed' => $data['seed'] ?? null,
'parameters' => $data['parameters'] ?? $data['generation_params'] ?? []
],
'processing_info' => [
'processing_time' => $data['processing_time'] ?? $data['generation_time'] ?? null,
'queue_time' => $data['queue_time'] ?? null,
'total_time' => $data['total_time'] ?? null,
'start_time' => $data['start_time'] ?? null,
'end_time' => $data['end_time'] ?? null,
'server_id' => $data['server_id'] ?? null,
'worker_id' => $data['worker_id'] ?? null
],
'cost_info' => [
'api_cost' => $data['api_cost'] ?? $data['cost'] ?? null,
'credits_used' => $data['credits_used'] ?? null,
'currency' => $data['currency'] ?? 'USD',
'pricing_tier' => $data['pricing_tier'] ?? null,
'cost_per_second' => $data['cost_per_second'] ?? null
],
'waveform_data' => [
'waveform' => $data['waveform'] ?? $data['waveform_data'] ?? null,
'waveform_url' => $data['waveform_url'] ?? null,
'waveform_points' => $data['waveform_points'] ?? null,
'waveform_resolution' => $data['waveform_resolution'] ?? null
],
'spectrum_analysis' => [
'spectrum' => $data['spectrum'] ?? $data['spectrum_data'] ?? null,
'spectrum_url' => $data['spectrum_url'] ?? null,
'frequency_data' => $data['frequency_data'] ?? null,
'spectral_centroid' => $data['spectral_centroid'] ?? null,
'spectral_rolloff' => $data['spectral_rolloff'] ?? null,
'spectral_bandwidth' => $data['spectral_bandwidth'] ?? null
],
'audio_segments' => [
'segments' => $data['segments'] ?? $data['audio_segments'] ?? [],
'verse_timestamps' => $data['verse_timestamps'] ?? null,
'chorus_timestamps' => $data['chorus_timestamps'] ?? null,
'bridge_timestamps' => $data['bridge_timestamps'] ?? null,
'intro_timestamps' => $data['intro_timestamps'] ?? null,
'outro_timestamps' => $data['outro_timestamps'] ?? null,
'section_labels' => $data['section_labels'] ?? null
],
'error_details' => [
'error_code' => $data['error_code'] ?? $data['code'] ?? null,
'error_message' => $data['error_message'] ?? $data['msg'] ?? null,
'error_type' => $data['error_type'] ?? null,
'error_category' => $data['error_category'] ?? null,
'error_suggestions' => $data['error_suggestions'] ?? null,
'retry_available' => $data['retry_available'] ?? null,
'error_timestamp' => $data['error_timestamp'] ?? null
],
'audio_analysis' => [
'loudness' => $data['loudness'] ?? null,
'dynamic_range' => $data['dynamic_range'] ?? null,
'peak_amplitude' => $data['peak_amplitude'] ?? null,
'rms_amplitude' => $data['rms_amplitude'] ?? null,
'zero_crossing_rate' => $data['zero_crossing_rate'] ?? null,
'harmonic_content' => $data['harmonic_content'] ?? null,
'percussive_content' => $data['percussive_content'] ?? null
],
'system_info' => [
'created_with' => 'AI Music Generation',
'version' => '3.0',
'async_sync_processed' => date('Y-m-d H:i:s'),
'api_version' => $data['api_version'] ?? null,
'api_endpoint' => $data['api_endpoint'] ?? null
]
];
}
switch ($action) {
case 'get_tracks':
try {
$stmt = $pdo->query("
SELECT COUNT(*) as total
FROM music_tracks
WHERE status = 'complete'
AND metadata IS NOT NULL
AND metadata != ''
");
$result = $stmt->fetch();
echo json_encode([
'success' => true,
'total_tracks' => (int)$result['total']
]);
} catch (Exception $e) {
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}
break;
case 'get_stats':
try {
$stats = [];
$stmt = $pdo->query("SELECT COUNT(*) as total FROM music_tracks WHERE status = 'complete'");
$stats['total_tracks'] = (int)$stmt->fetch()['total'];
$stmt = $pdo->query("SELECT COUNT(*) as total FROM music_tracks WHERE status = 'complete' AND metadata IS NOT NULL AND metadata != ''");
$stats['tracks_with_metadata'] = (int)$stmt->fetch()['total'];
$stmt = $pdo->query("SELECT COUNT(*) as total FROM music_tracks WHERE status = 'complete' AND audio_url LIKE '/audio_files/%'");
$stats['tracks_with_local_files'] = (int)$stmt->fetch()['total'];
$stmt = $pdo->query("SELECT COUNT(*) as total FROM music_tracks WHERE status = 'complete' AND audio_quality IS NOT NULL");
$stats['tracks_with_enhanced_metadata'] = (int)$stmt->fetch()['total'];
echo json_encode([
'success' => true,
...$stats
]);
} catch (Exception $e) {
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}
break;
case 'process_batch':
try {
$offset = (int)($_GET['offset'] ?? 0);
$limit = (int)($_GET['limit'] ?? 5);
// Get batch of tracks
$stmt = $pdo->prepare("
SELECT id, title, metadata, task_id, audio_url, video_url, status
FROM music_tracks
WHERE status = 'complete'
AND metadata IS NOT NULL
AND metadata != ''
ORDER BY id
LIMIT ? OFFSET ?
");
$stmt->execute([$limit, $offset]);
$tracks = $stmt->fetchAll();
$processed = 0;
$updated = 0;
$filesDownloaded = 0;
$errors = 0;
$logEntries = [];
$currentTrack = '';
foreach ($tracks as $track) {
$processed++;
$currentTrack = $track['title'] ?: 'Track ' . $track['id'];
try {
$metadata = json_decode($track['metadata'], true);
if (!$metadata) {
$errors++;
$logEntries[] = ['message' => "Track {$track['id']}: Invalid metadata", 'type' => 'error'];
continue;
}
// Extract comprehensive metadata
$enhanced_metadata = extractComprehensiveMetadata($metadata);
// Download audio files locally
$localAudioUrl = null;
$localVideoUrl = null;
if ($track['audio_url'] && strpos($track['audio_url'], 'http') === 0) {
$localAudioUrl = downloadAndStoreAudio($track['audio_url'], $track['task_id'], 'main');
if ($localAudioUrl) {
$filesDownloaded++;
$logEntries[] = ['message' => "Downloaded audio for track {$track['id']}", 'type' => 'success'];
}
}
if ($track['video_url'] && strpos($track['video_url'], 'http') === 0) {
$localVideoUrl = downloadAndStoreAudio($track['video_url'], $track['task_id'], 'video');
if ($localVideoUrl) {
$filesDownloaded++;
$logEntries[] = ['message' => "Downloaded video for track {$track['id']}", 'type' => 'success'];
}
}
// Update individual metadata fields
$updates = [];
$params = [];
$updates[] = 'metadata = ?';
$params[] = json_encode($enhanced_metadata);
// Update individual fields
if (isset($enhanced_metadata['audio_quality'])) {
$updates[] = 'audio_quality = ?';
$params[] = json_encode($enhanced_metadata['audio_quality']);
}
if (isset($enhanced_metadata['generation_parameters'])) {
$updates[] = 'generation_parameters = ?';
$params[] = json_encode($enhanced_metadata['generation_parameters']);
}
if (isset($enhanced_metadata['processing_info'])) {
$updates[] = 'processing_info = ?';
$params[] = json_encode($enhanced_metadata['processing_info']);
}
if (isset($enhanced_metadata['cost_info'])) {
$updates[] = 'cost_info = ?';
$params[] = json_encode($enhanced_metadata['cost_info']);
}
if (isset($enhanced_metadata['waveform_data'])) {
$updates[] = 'waveform_data = ?';
$params[] = json_encode($enhanced_metadata['waveform_data']);
}
if (isset($enhanced_metadata['spectrum_analysis'])) {
$updates[] = 'spectrum_analysis = ?';
$params[] = json_encode($enhanced_metadata['spectrum_analysis']);
}
if (isset($enhanced_metadata['audio_segments'])) {
$updates[] = 'audio_segments = ?';
$params[] = json_encode($enhanced_metadata['audio_segments']);
}
if (isset($enhanced_metadata['error_details'])) {
$updates[] = 'error_details = ?';
$params[] = json_encode($enhanced_metadata['error_details']);
}
if (isset($enhanced_metadata['audio_analysis'])) {
$updates[] = 'audio_analysis = ?';
$params[] = json_encode($enhanced_metadata['audio_analysis']);
}
if (isset($enhanced_metadata['system_info'])) {
$updates[] = 'system_info = ?';
$params[] = json_encode($enhanced_metadata['system_info']);
}
// Update audio URLs if local files were downloaded
if ($localAudioUrl) {
$updates[] = 'audio_url = ?';
$params[] = $localAudioUrl;
}
if ($localVideoUrl) {
$updates[] = 'video_url = ?';
$params[] = $localVideoUrl;
}
$params[] = $track['id'];
$sql = "UPDATE music_tracks SET " . implode(', ', $updates) . ", updated_at = NOW() WHERE id = ?";
$update_stmt = $pdo->prepare($sql);
$update_stmt->execute($params);
$updated++;
$logEntries[] = ['message' => "Updated track {$track['id']}: {$currentTrack}", 'type' => 'success'];
} catch (Exception $e) {
$errors++;
$logEntries[] = ['message' => "Error processing track {$track['id']}: " . $e->getMessage(), 'type' => 'error'];
}
}
echo json_encode([
'success' => true,
'processed' => $processed,
'updated' => $updated,
'files_downloaded' => $filesDownloaded,
'errors' => $errors,
'current_track' => $currentTrack,
'log_entries' => $logEntries
]);
} catch (Exception $e) {
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}
break;
default:
echo json_encode([
'success' => false,
'error' => 'Invalid action'
]);
break;
}
?>