35591-vm/generate.php
Flatlogic Bot bfa71e661d 2
2025-11-09 09:57:02 +00:00

208 lines
10 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/includes/translations.php';
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/ai/LocalAIApi.php';
// Set language from session or default to English
$lang = $_SESSION['lang'] ?? 'en';
// --- Helper Functions (omitted for brevity, same as before) ---
function translate_to_english($text, $source_lang) { if ($source_lang === 'en') return $text; $prompt = "Translate the following text from '{$source_lang}' to English. Only return the translated text, with no extra commentary:\n\n{$text}"; $response = LocalAIApi::createResponse(['input' => [['role' => 'system', 'content' => 'You are a translation assistant.'],['role' => 'user', 'content' => $prompt]]]); if (!empty($response['success'])) { $decoded = LocalAIApi::decodeJsonFromResponse($response); return $decoded['choices'][0]['message']['content'] ?? $text; } return $text; }
function translate_from_english($text, $target_lang) { if ($target_lang === 'en') return $text; $prompt = "Translate the following text from English to '{$target_lang}'. Only return the translated text, with no extra commentary:\n\n{$text}"; $response = LocalAIApi::createResponse(['input' => [['role' => 'system', 'content' => 'You are a translation assistant.'],['role' => 'user', 'content' => $prompt]]]); if (!empty($response['success'])) { $decoded = LocalAIApi::decodeJsonFromResponse($response); return $decoded['choices'][0]['message']['content'] ?? $text; } return $text; }
// --- Main Logic ---
$result_html = '';
$error_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// --- 0. Subscription & Limit Check ---
if (isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
$pdo = db();
// Fetch user subscription details
$stmt = $pdo->prepare("SELECT subscription_plan, subscription_expires_at FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();
$is_active = $user && $user['subscription_expires_at'] && new DateTime() < new DateTime($user['subscription_expires_at']);
if (!$is_active) {
$_SESSION['generation_error'] = t('subscription_expired_error');
header('Location: pricing.php');
exit();
}
if ($user['subscription_plan'] === 'basic') {
// Count generations in the last 30 days
$stmt = $pdo->prepare("SELECT COUNT(*) FROM generations WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
$stmt->execute([$user_id]);
$generation_count = $stmt->fetchColumn();
if ($generation_count >= 150) {
$_SESSION['generation_error'] = t('generation_limit_exceeded_error');
header('Location: pricing.php');
exit();
}
}
} else {
// If user is not logged in, redirect to login page
$_SESSION['generation_error'] = t('login_to_generate_error');
header('Location: login.php');
exit();
}
// --- 1. Collect and Sanitize Inputs ---
$state = htmlspecialchars($_POST['state'] ?? '');
$size = htmlspecialchars($_POST['size'] ?? '');
$material = htmlspecialchars($_POST['material'] ?? '');
$brand = htmlspecialchars($_POST['brand'] ?? '');
$length = htmlspecialchars($_POST['length'] ?? '');
$chest_width = htmlspecialchars($_POST['chest_width'] ?? '');
$waist_width = htmlspecialchars($_POST['waist_width'] ?? '');
$hips_width = htmlspecialchars($_POST['hips_width'] ?? '');
$additional_info = htmlspecialchars($_POST['additional_info'] ?? '');
// --- 2. Validation ---
if (empty($state) || empty($size)) {
$_SESSION['generation_error'] = t('error_required_fields');
header('Location: index.php#generator');
exit();
}
// --- 3. Translation Pipeline (Input) ---
$state_en = translate_to_english($state, $lang);
$size_en = translate_to_english($size, $lang);
$material_en = translate_to_english($material, $lang);
$brand_en = translate_to_english($brand, $lang);
$additional_info_en = translate_to_english($additional_info, $lang);
// --- 4. Construct AI Prompt ---
$prompt_parts = [
"Generate a product listing for an online clothing store. The target audience is women aged 22-60.",
"The output must be a JSON object with the following keys: 'title', 'short_description', 'description', 'measurements', 'hashtags'.",
"The tone should be engaging, concise, and SEO-aware, incorporating trending keywords naturally.",
"Do not add any extra commentary or editorializing. Stick to the facts provided."
];
if ($state_en === 'used') {
$prompt_parts[] = "Condition: Used (perfect condition).";
} elseif ($state_en === 'visibly_used') {
$prompt_parts[] = "Condition: Visibly used (may have some signs of use).";
} else {
$prompt_parts[] = "Condition: New.";
}
$prompt_parts[] = "Size: {$size_en}";
if (!empty($material_en)) $prompt_parts[] = "Material: {$material_en}";
if (!empty($brand_en)) $prompt_parts[] = "Brand: {$brand_en}";
$measurements_parts = [];
if (!empty($length)) $measurements_parts[] = "Length: {$length} cm";
if (!empty($chest_width)) $measurements_parts[] = "Chest width: {$chest_width} cm";
if (!empty($waist_width)) $measurements_parts[] = "Waist width: {$waist_width} cm";
if (!empty($hips_width)) $measurements_parts[] = "Hips width: {$hips_width} cm";
if (!empty($measurements_parts)) {
$prompt_parts[] = "Measurements: " . implode(', ', $measurements_parts);
}
if (!empty($additional_info_en)) {
$prompt_parts[] = "Additional Details: {$additional_info_en}";
}
$prompt_parts[] = "Generate the output in English.";
$prompt = implode("\n", $prompt_parts);
// --- 4. Call AI API ---
$ai_response = LocalAIApi::createResponse([
'input' => [
['role' => 'system', 'content' => 'You are an expert copywriter for e-commerce fashion brands.'],
['role' => 'user', 'content' => $prompt],
],
'model' => 'gpt-3.5-turbo', // Using a cost-effective model
]);
if (!empty($ai_response['success'])) {
$decoded_response = LocalAIApi::decodeJsonFromResponse($ai_response);
$generated_text = $decoded_response['choices'][0]['message']['content'] ?? '';
// Find the JSON part of the response
$json_start = strpos($generated_text, '{');
$json_end = strrpos($generated_text, '}');
if ($json_start !== false && $json_end !== false) {
$json_str = substr($generated_text, $json_start, $json_end - $json_start + 1);
$output_data = json_decode($json_str, true);
if ($output_data && json_last_error() === JSON_ERROR_NONE) {
// --- 5. Translation Pipeline (Output) ---
$title = translate_from_english(htmlspecialchars($output_data['title'] ?? ''), $lang);
$short_desc = translate_from_english(htmlspecialchars($output_data['short_description'] ?? ''), $lang);
$description = nl2br(translate_from_english(htmlspecialchars($output_data['description'] ?? ''), $lang));
$measurements = translate_from_english(htmlspecialchars($output_data['measurements'] ?? ''), $lang);
$hashtags = translate_from_english(htmlspecialchars($output_data['hashtags'] ?? ''), $lang);
// --- 6. Save to DB if user is logged in ---
if (isset($_SESSION['user_id'])) {
try {
$pdo = db();
$stmt = $pdo->prepare("INSERT INTO generations (user_id, prompt, description) VALUES (?, ?, ?)");
$stmt->execute([$_SESSION['user_id'], $prompt, $json_str]);
} catch (PDOException $e) {
// Optional: log error to a file
error_log("DB Error: " . $e->getMessage());
}
}
// --- 7. Format Output ---
$result_html = "
<div class='result-container'>
<h3>" . t('generated_result') . "</h3>
<div class='result-item'>
<label>" . t('output_title') . "</label>
<p id='result-title'>{$title}</p>
</div>
<div class='result-item'>
<label>" . t('output_short_description') . "</label>
<p id='result-short-desc'>{$short_desc}</p>
</div>
<div class='result-item'>
<label>" . t('output_description') . "</label>
<p id='result-desc'>{$description}</p>
</div>
<div class='result-item'>
<label>" . t('output_measurements') . "</label>
<p id='result-measurements'>{$measurements}</p>
</div>
<div class='result-item'>
<label>" . t('output_hashtags') . "</label>
<p id='result-hashtags'>{$hashtags}</p>
</div>
<div class='result-actions'>
<button class='btn btn-secondary' id='copy-btn'><i class='ph ph-copy'></i> " . t('copy_to_clipboard') . "</button>
<button class='btn btn-primary' id='approve-btn'><i class='ph ph-check'></i> " . t('approve') . "</button>
</div>
</div>
";
} else {
$error_message = t('error_parsing_ai_response');
}
} else {
$error_message = t('error_parsing_ai_response');
}
} else {
$error_message = t('error_calling_ai_api') . ': ' . htmlspecialchars($ai_response['error'] ?? 'Unknown error');
}
}
// Store result in session to display on the main page
$_SESSION['generation_result'] = $result_html;
$_SESSION['generation_error'] = $error_message;
// Redirect back to the main page
header('Location: index.php#generator');
exit();