38671-vm/api/ai_analyze.php
2026-02-21 16:37:23 +00:00

51 lines
2.0 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../ai/LocalAIApi.php';
$input = json_decode(file_get_contents('php://input'), true);
$text = $input['text'] ?? '';
if (empty($text)) {
echo json_encode(['error' => 'No text provided']);
http_response_code(400);
exit;
}
$prompt = "You are a nutrition expert. Analyze the following food description and provide the estimated nutritional information.
The user is from Bulgaria, so understand Bulgarian food names (e.g., 'banitsa', 'shopska salad', 'lyutenitsa', 'kebapche', 'tarator') and language.
If the description is in Bulgarian, translate the 'entry_name' to English but use the Bulgarian context for nutritional estimation.
Return only a JSON object with the following keys:
- 'entry_name': A short, descriptive name of the food (in English).
- 'calories': Estimated total calories (integer).
- 'protein': Estimated protein in grams (integer).
- 'creatine': Estimated creatine in grams (float, usually 0 unless it's a supplement).
If the user mentions a supplement like 'creatine', ensure to include it.
If multiple items are mentioned, provide the total for all of them.
Food description: \"$text\"";
$response = LocalAIApi::createResponse([
'input' => [
['role' => 'system', 'content' => 'You are a nutrition expert that returns only JSON. You understand Bulgarian and international cuisine.'],
['role' => 'user', 'content' => $prompt],
],
]);
if (!empty($response['success'])) {
$decoded = LocalAIApi::decodeJsonFromResponse($response);
if ($decoded) {
echo json_encode($decoded);
} else {
$rawText = LocalAIApi::extractText($response);
if (preg_match('/{.*}/s', $rawText, $matches)) {
echo $matches[0];
} else {
echo json_encode(['error' => 'Failed to parse AI response', 'raw' => $rawText]);
http_response_code(500);
}
}
} else {
echo json_encode(['error' => $response['error'] ?? 'AI request failed']);
http_response_code(500);
}