35604-vm/api/scan_recipe.php
2026-01-26 19:57:12 +00:00

70 lines
2.5 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../ai/LocalAIApi.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['success' => false, 'error' => 'Method not allowed']);
exit;
}
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
echo json_encode(['success' => false, 'error' => 'No image uploaded or upload error']);
exit;
}
$imagePath = $_FILES['image']['tmp_name'];
$imageData = base64_encode(file_get_contents($imagePath));
$imageType = $_FILES['image']['type'];
$prompt = "Analyze this image. If it's a photo of a dish, identify what it is and generate a possible recipe for it. If it's a photo of a written recipe, extract the information.
Extract or generate the following information in JSON format:
- name: The name of the dish/recipe
- category: One of 'Drinks', 'Breakfast', 'Dinner', 'Appetizers'
- ingredients: An array of objects, each with:
- name: Name of the ingredient
- quantity: Numeric quantity (float)
- unit: Unit of measurement (e.g., 'g', 'kg', 'ml', 'l', 'piece', 'pack')
- guests: The default number of guests/servings the recipe is for (integer)
Important:
1. The quantities should be for 1 person if possible, or for the number of guests specified. If you're generating a recipe for a dish, default to 1 or 2 guests.
2. Return ONLY the JSON object.
3. If you can't determine something, provide a best guess or null.";
try {
$response = LocalAIApi::createResponse([
'input' => [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => $prompt
],
[
'type' => 'image_url',
'image_url' => [
'url' => "data:$imageType;base64,$imageData"
]
]
]
]
]
]);
if (!$response['success']) {
throw new Exception($response['error'] ?? 'AI request failed');
}
$recipeData = LocalAIApi::decodeJsonFromResponse($response);
if (!$recipeData) {
throw new Exception('Failed to parse AI response as JSON. Raw response: ' . LocalAIApi::extractText($response));
}
echo json_encode(['success' => true, 'data' => $recipeData]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}