36643-vm/api/generate_script.php
2025-12-04 07:22:31 +00:00

50 lines
1.9 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../ai/LocalAIApi.php';
// Basic input validation
$requestBody = file_get_contents('php://input');
$data = json_decode($requestBody, true);
$genre = isset($data['genre']) ? trim($data['genre']) : '';
$topic = isset($data['topic']) ? trim($data['topic']) : '';
if (empty($genre) || empty($topic)) {
http_response_code(400);
echo json_encode(['error' => 'Genre and topic are required.']);
exit;
}
// Prepare the prompt for the AI
$prompt = "You are a creative assistant for social media influencers. Generate a short video script (around 150-200 words) for the genre: '{$genre}'. The script should be about: '{$topic}'. The script should be engaging, concise, and suitable for platforms like TikTok, Instagram Reels, or YouTube Shorts. Include suggestions for visuals or on-screen text where appropriate. Format the output as plain text.";
try {
$resp = LocalAIApi::createResponse(
[
'input' => [
['role' => 'system', 'content' => 'You are a helpful scriptwriting assistant for social media creators.'],
['role' => 'user', 'content' => $prompt],
],
],
[
'poll_interval' => 5,
'poll_timeout' => 300
]
);
if (!empty($resp['success'])) {
$text = LocalAIApi::extractText($resp);
if ($text === '') {
throw new Exception('AI returned an empty response.');
}
echo json_encode(['script' => nl2br(htmlspecialchars($text))]);
} else {
throw new Exception($resp['error'] ?? 'Unknown AI API error.');
}
} catch (Exception $e) {
error_log('AI script generation error: ' . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => 'Sorry, we couldn\'t generate a script at this time. Please try again later.']);
}