diff --git a/docs/docs/contributors/developers-guide/migration-guide.md b/docs/docs/contributors/developers-guide/migration-guide.md index 87c7bc7dc..535e03353 100644 --- a/docs/docs/contributors/developers-guide/migration-guide.md +++ b/docs/docs/contributors/developers-guide/migration-guide.md @@ -4,6 +4,44 @@ This guide is a reference for developers maintaining custom integrations with Me While this guide aims to simplify the migration process for developers, it's not necessarily a comprehensive list of breaking changes. Starting with v2, a comprehensive list of breaking changes are highlighted in the release notes. +## Deprecations + +These still work, but are no longer the supported way of doing things, and may be removed in a future major version. + +### `/recipes/create/image` → `/recipes/create/ai` (:octicons-tag-24: v3.23.0) + +AI recipe creation is now a single endpoint that takes content and images together, rather than one endpoint per input type. + +`/recipes/create/image` continues to work and is unchanged from a caller's perspective, but it is hidden from the OpenAPI schema, so it no longer appears in the API docs or in generated clients. It is now a thin wrapper around `/recipes/create/ai`. One behavioral difference: it now publishes a recipe-created notification, like every other creation endpoint, where before it published the event without a message. + +`/recipes/create/ai` takes `multipart/form-data`, so it can accept images alongside everything else: + +| Field | Notes | +| --- | --- | +| `content` | Raw HTML, a schema.org Recipe JSON string, or plain text | +| `url` | Fetched if no `content` is given, and saved as the recipe's source either way | +| `images` | Zero or more image files. The first becomes the recipe's image | +| `translateLanguage` | Optional language to translate the recipe into | +| `createNewOrganizers` | Whether to create tags, categories, and tools that don't already exist | + +At least one of `content`, `url`, or `images` is required. There is also a `/recipes/create/ai/stream` variant that reports progress over SSE, which is what the Mealie frontend uses. + +Note that `/recipes/create/html-or-json` is **not** deprecated. It remains the way to import raw data without involving AI. + +### Custom prompt files (:octicons-tag-24: v3.23.0) + +This only affects you if you've set `OPENAI_CUSTOM_PROMPT_DIR` and overridden the recipe prompts. + +AI recipe creation is now a workflow of separate steps, each with its own prompt, so the two prompts that used to drive it have been replaced: + +| Removed | Replaced by | +| --- | --- | +| `recipes/scrape-recipe.txt` | `recipes/compile-source.txt` and `recipes/build-recipe.txt` | +| `recipes/parse-recipe-image.txt` | `recipes/compile-source.txt` and `recipes/build-recipe.txt` | +| — | `recipes/resolve-organizers.txt` (new) | + +`compile-source.txt` transcribes whatever the user supplied, and `build-recipe.txt` turns that transcription into recipe data. Overrides of the removed files are ignored. `recipes/parse-recipe-video.txt` and `recipes/parse-recipe-ingredients.txt` are unchanged. + ## V1 → V2 The biggest change between V1 and V2 is the introduction of Households. For more information on how households work in relation to groups/users, check out the [Groups and Households](../../documentation/getting-started/features.md#groups-and-households) section in the Features guide. diff --git a/docs/docs/documentation/getting-started/installation/ai-providers.md b/docs/docs/documentation/getting-started/installation/ai-providers.md index 59c6e6e0d..8642d6a5f 100644 --- a/docs/docs/documentation/getting-started/installation/ai-providers.md +++ b/docs/docs/documentation/getting-started/installation/ai-providers.md @@ -24,6 +24,31 @@ While Mealie has prompts for each AI task, you can override these with your own ## AI Features - The OpenAI Ingredient Parser can be used as an alternative to the NLP and Brute Force parsers. Simply choose the OpenAI parser while parsing ingredients (:octicons-tag-24: v1.7.0) -- When importing a recipe via URL, if the default recipe scraper is unable to read the recipe data from a webpage, the webpage contents will be parsed by OpenAI (:octicons-tag-24: v1.9.0) -- You can import an image of a written recipe, which is sent to OpenAI and imported into Mealie. The recipe can be hand-written or typed, as long as the text is in the picture. You can also optionally have OpenAI translate the recipe into your own language (:octicons-tag-24: v1.12.0) -- You can import a recipe via a video URL (e.g., a YouTube link). The video is transcribed AI, and the transcription is parsed into a recipe (:octicons-tag-24: v3.13.0) +- When importing a recipe via URL, if the default recipe scraper is unable to read the recipe data from a webpage, the webpage contents will be parsed by AI (:octicons-tag-24: v1.9.0) +- The **Import with AI** page creates a recipe out of just about anything: pasted text, HTML, or JSON, photos of a recipe, a link, or any combination of them (:octicons-tag-24: v3.23.0) + +## Import with AI + +The **Import with AI** page, found under *Create ➞ Import with AI*, creates a recipe from any combination of: + +- **A URL.** Mealie fetches the page and reads the recipe from it. Give it a link to a video (e.g. YouTube or Instagram) and the video is transcribed instead, provided you've configured an audio provider. The URL is always saved as the recipe's source. +- **Content.** Paste a recipe as plain text, or paste raw HTML or a [schema.org Recipe](https://schema.org/Recipe) JSON object. This is useful when a site blocks Mealie from reading it directly. If you provide content, it's used instead of reading the URL. +- **Images.** Upload one or more photos of a recipe, hand-written or typed. Multiple photos are treated as pages of a single recipe, and the first one becomes the recipe's image. This requires an image provider. + +When you supply your own text alongside photos or a video, your text wins wherever the two disagree, so you can correct a detail or name the recipe yourself. + +You can also optionally have the recipe translated into your own language. + +### Organizers + +Mealie asks AI which tags, categories, and tools the recipe refers to, and always matches what comes back against the organizers you already have, so an import doesn't create a near-duplicate of a tag you're already using. + +Organizers that don't match anything you have are discarded, unless you check **Create new organizers**, in which case they're created for you. + +Mealie only assigns an organizer that the recipe itself refers to. It won't guess a cuisine from the ingredients or a course from the kind of dish, so a bare list of ingredients and steps usually imports with no organizers at all. + +### Which provider is used + +Reading the source material is the only step that needs to understand images or audio, so that's the only step that uses your image or audio provider. Turning what it read into a recipe, and working out its organizers, always use your default provider. + +This means an import with photos attached is read by your image provider even if you also pasted text alongside them. diff --git a/docs/docs/documentation/getting-started/installation/security.md b/docs/docs/documentation/getting-started/installation/security.md index 29f6b19da..e26313542 100644 --- a/docs/docs/documentation/getting-started/installation/security.md +++ b/docs/docs/documentation/getting-started/installation/security.md @@ -19,6 +19,7 @@ Use your best judgement when deciding what to do. By default, the API is **not** rate limited. This leaves Mealie open to a potential **Denial of Service Attack**. While it's possible to perform a **Denial of Service Attack** on any endpoint, there are a few key endpoints that are more vulnerable than others. - `/api/recipes/create/url` +- `/api/recipes/create/ai` - `/api/recipes/{id}/image` These endpoints are used to scrape data based off a user provided URL. It is possible for a malicious user to issue multiple requests to download an arbitrarily large external file (e.g a Debian ISO) and sufficiently saturate a CPU assigned to the container. While we do implement some protections against this by chunking the response, and using a timeout strategy, it's still possible to overload the CPU if an attacker issues multiple requests concurrently. @@ -34,6 +35,7 @@ If you'd like to mitigate this risk, we suggest that you rate limit the API in g ## Server Side Request Forgery - `/api/recipes/create/url` +- `/api/recipes/create/ai` - `/api/recipes/{id}/image` Given the nature of these APIs it's possible to perform a **Server Side Request Forgery** attack. This is where a malicious user can issue a request to an internal network resource, and potentially exfiltrate data. We _do_ perform some checks to mitigate access to resources within your network but at the end of the day, users of Mealie are allowed to trigger HTTP requests on **your server**. diff --git a/frontend/app/components/Domain/Recipe/RecipeImportImages.vue b/frontend/app/components/Domain/Recipe/RecipeImportImages.vue new file mode 100644 index 000000000..1d8e5f979 --- /dev/null +++ b/frontend/app/components/Domain/Recipe/RecipeImportImages.vue @@ -0,0 +1,111 @@ + + + diff --git a/frontend/app/components/Layout/DefaultLayout.vue b/frontend/app/components/Layout/DefaultLayout.vue index f090955be..2efad1b7b 100644 --- a/frontend/app/components/Layout/DefaultLayout.vue +++ b/frontend/app/components/Layout/DefaultLayout.vue @@ -133,7 +133,7 @@ const cookbooks = computed(() => { return []; }); -const showImageImport = computed(() => group.value?.aiProviderSettings?.imageProviderEnabled); +const showAIImport = computed(() => group.value?.aiProviderSettings?.aiEnabled); const sidebar = ref(false); onMounted(() => { @@ -205,12 +205,12 @@ const createLinks = computed(() => [ }, { insertDivider: false, - icon: $globals.icons.fileImage, - title: i18n.t("recipe.create-from-images"), - subtitle: i18n.t("recipe.create-recipe-from-images"), - to: `/g/${groupSlug.value}/r/create/image`, + icon: $globals.icons.autoFix, + title: i18n.t("recipe.import-with-ai"), + subtitle: i18n.t("recipe.import-with-ai-subtitle"), + to: `/g/${groupSlug.value}/r/create/ai`, restricted: true, - hide: !showImageImport.value, + hide: !showAIImport.value, }, { insertDivider: true, diff --git a/frontend/app/composables/use-new-recipe-options.ts b/frontend/app/composables/use-new-recipe-options.ts index 6f01c2b5b..e9c8b0ce6 100644 --- a/frontend/app/composables/use-new-recipe-options.ts +++ b/frontend/app/composables/use-new-recipe-options.ts @@ -5,6 +5,8 @@ export interface UseNewRecipeOptionsProps { enableImportCategories?: boolean; enableStayInEditMode?: boolean; enableParseRecipe?: boolean; + enableTranslateRecipe?: boolean; + enableCreateNewOrganizers?: boolean; } export function useNewRecipeOptions(props: UseNewRecipeOptionsProps = {}) { @@ -13,6 +15,8 @@ export function useNewRecipeOptions(props: UseNewRecipeOptionsProps = {}) { enableImportCategories = true, enableStayInEditMode = true, enableParseRecipe = true, + enableTranslateRecipe = false, + enableCreateNewOrganizers = false, } = props; const router = useRouter(); @@ -62,6 +66,28 @@ export function useNewRecipeOptions(props: UseNewRecipeOptionsProps = {}) { }, }); + const translateRecipe = computed({ + get() { + if (!enableTranslateRecipe) return false; + return recipeCreatePreferences.value.translateRecipe; + }, + set(v: boolean) { + if (!enableTranslateRecipe) return; + recipeCreatePreferences.value.translateRecipe = v; + }, + }); + + const createNewOrganizers = computed({ + get() { + if (!enableCreateNewOrganizers) return false; + return recipeCreatePreferences.value.createNewOrganizers; + }, + set(v: boolean) { + if (!enableCreateNewOrganizers) return; + recipeCreatePreferences.value.createNewOrganizers = v; + }, + }); + function navigateToRecipe(recipeSlug: string, groupSlug: string, createPagePath: string) { const editParam = enableStayInEditMode ? stayInEditMode.value : false; const parseParam = enableParseRecipe ? parseRecipe.value : false; @@ -87,6 +113,8 @@ export function useNewRecipeOptions(props: UseNewRecipeOptionsProps = {}) { importCategories, stayInEditMode, parseRecipe, + translateRecipe, + createNewOrganizers, // Helper functions navigateToRecipe, @@ -96,5 +124,7 @@ export function useNewRecipeOptions(props: UseNewRecipeOptionsProps = {}) { enableImportCategories, enableStayInEditMode, enableParseRecipe, + enableTranslateRecipe, + enableCreateNewOrganizers, }; } diff --git a/frontend/app/composables/use-users/preferences.ts b/frontend/app/composables/use-users/preferences.ts index 96869277f..401cf7e50 100644 --- a/frontend/app/composables/use-users/preferences.ts +++ b/frontend/app/composables/use-users/preferences.ts @@ -67,6 +67,8 @@ export interface UserRecipeCreatePreferences { importCategories: boolean; stayInEditMode: boolean; parseRecipe: boolean; + translateRecipe: boolean; + createNewOrganizers: boolean; } export interface UserActivityPreferences { @@ -224,6 +226,8 @@ export function useRecipeCreatePreferences(): Ref { importCategories: false, stayInEditMode: false, parseRecipe: true, + translateRecipe: false, + createNewOrganizers: false, }, { mergeDefaults: true }, ); diff --git a/frontend/app/lang/messages/en-US.json b/frontend/app/lang/messages/en-US.json index 1a07fccde..311293a56 100644 --- a/frontend/app/lang/messages/en-US.json +++ b/frontend/app/lang/messages/en-US.json @@ -290,6 +290,7 @@ "ai-provider-settings": "AI Provider Settings", "ai-provider": "AI Provider", "ai-providers": "AI Providers", + "ai-providers-description": "Add an AI provider to enable features like enhanced ingredient parsing and creating recipes from photos or videos. This step is optional, and can be set up later in your group settings.", "ai-provider-settings-description": "Configure AI providers to enable AI-powered features, such as enhanced ingredient parsing, creating recipes from videos, and more!", "providers": "Providers", "create-provider": "Create Provider", @@ -661,17 +662,26 @@ "select-one-of-the-various-ways-to-create-a-recipe": "Select one of the various ways to create a recipe", "looking-for-migrations": "Looking For Migrations?", "import-with-url": "Import with URL", + "import-with-ai": "Import with AI", + "import-with-ai-description": "Create a recipe from just about anything using AI. Paste a recipe as text, HTML, or JSON, upload photos of a recipe, give it a link, or use any combination of the three.", + "import-with-ai-subtitle": "Import from text, photos, or URL", + "import-with-ai-video-description": "You can import from videos too, like those on Instagram or YouTube. Paste the video's URL and Mealie will transcribe it into a recipe.", + "import-with-ai-without-ai-question": "Want to create a recipe without using AI?", + "import-with-ai-use-url-import": "Use the URL importer", + "import-with-ai-url-hint": "Optional. Saved as the recipe's source. Videos are always transcribed; other pages are read only if you don't paste content below.", + "import-with-ai-content": "Recipe text, HTML, JSON, or notes", + "import-with-ai-content-hint": "Optional. Paste a recipe, or the contents of a page Mealie can't reach. Alongside photos or a video, this is used as notes instead, so you can say what to name the recipe or correct a detail.", + "import-with-ai-provider-required": "To import recipes with AI, configure a default provider in your group's AI settings.", + "import-with-ai-image-provider-required": "To create recipes from photos, configure an image provider in your group's AI settings.", + "import-with-ai-error-details": "AI was unable to create a recipe from what you provided. Check that it contains a recipe, and try again.", + "create-new-organizers": "Create new organizers", + "create-new-organizers-hint": "Tags, categories, and tools found on the recipe are always matched against the ones you already have. Turn this on to also create the ones you don't.", "create-recipe": "Create Recipe", "create-recipe-description": "Create a new recipe from scratch.", "create-recipes": "Create Recipes", "import-with-zip": "Import with .zip", - "create-recipe-from-images": "Create Recipe from Images", - "create-recipe-from-an-image-description": "Create a recipe by uploading images of the recipe text. Mealie will attempt to extract the text from the images using AI and create a new recipe from it.", "crop-and-rotate-the-image": "Crop and rotate the image so that only the text is visible, and it's in the correct orientation.", - "create-from-images": "Create from Images", "should-translate-description": "Translate the recipe into my language", - "please-wait-image-procesing": "Please wait, the image is processing. This may take some time.", - "please-wait-images-processing": "Please wait, the images are processing. This may take some time.", "bulk-url-import": "Bulk URL Import", "debug-scraper": "Debug Scraper", "create-a-recipe-by-providing-the-name-all-recipes-must-have-unique-names": "Create a recipe by providing the name. All recipes must have unique names.", @@ -681,6 +691,8 @@ "scrape-recipe-description-transcription": "You can also provide the url to a video and Mealie will attempt to transcribe it into a recipe.", "scrape-recipe-have-a-lot-of-recipes": "Have a lot of recipes you want to scrape at once?", "scrape-recipe-suggest-bulk-importer": "Try out the bulk importer", + "scrape-recipe-have-ai-read-the-page": "Want AI to read the page instead?", + "import-from-html-or-json-have-ai-read-it": "Want AI to read your data instead?", "scrape-recipe-have-raw-html-or-json-data": "Have raw HTML or JSON data?", "scrape-recipe-you-can-import-from-raw-data-directly": "You can import from raw data directly", "scrape-recipe-website-being-blocked": "Website being blocked?", diff --git a/frontend/app/lib/api/types/admin.ts b/frontend/app/lib/api/types/admin.ts index 7a086e07f..6644e479f 100644 --- a/frontend/app/lib/api/types/admin.ts +++ b/frontend/app/lib/api/types/admin.ts @@ -17,6 +17,7 @@ export interface AdminAboutInfo { oidcRedirect: boolean; oidcProviderName: string; tokenTime: number; + allowedIframeHosts?: string[]; versionLatest: string; apiPort: number; apiDocs: boolean; diff --git a/frontend/app/lib/api/types/openai.ts b/frontend/app/lib/api/types/openai.ts index a18ae9b3c..65405386a 100644 --- a/frontend/app/lib/api/types/openai.ts +++ b/frontend/app/lib/api/types/openai.ts @@ -5,6 +5,12 @@ /* Do not modify it by hand - just update the pydantic models and then re-run the script */ +export interface OpenAICompiledSource { + contains_recipe: boolean; + content: string; + language?: string | null; + image_url?: string | null; +} export interface OpenAIIngredient { quantity?: number | null; unit?: string | null; @@ -14,6 +20,11 @@ export interface OpenAIIngredient { export interface OpenAIIngredients { ingredients?: OpenAIIngredient[]; } +export interface OpenAIOrganizers { + tags?: string[]; + categories?: string[]; + tools?: string[]; +} export interface OpenAIRecipe { name: string; description?: string | null; @@ -24,6 +35,7 @@ export interface OpenAIRecipe { ingredients?: OpenAIRecipeIngredient[]; instructions?: OpenAIRecipeInstruction[]; notes?: OpenAIRecipeNotes[]; + nutrition?: OpenAIRecipeNutrition | null; } export interface OpenAIRecipeIngredient { title?: string | null; @@ -37,6 +49,19 @@ export interface OpenAIRecipeNotes { title?: string | null; text: string; } +export interface OpenAIRecipeNutrition { + calories?: string | null; + carbohydrate_content?: string | null; + cholesterol_content?: string | null; + fat_content?: string | null; + fiber_content?: string | null; + protein_content?: string | null; + saturated_fat_content?: string | null; + sodium_content?: string | null; + sugar_content?: string | null; + trans_fat_content?: string | null; + unsaturated_fat_content?: string | null; +} export interface OpenAIText { text: string; } diff --git a/frontend/app/lib/api/types/recipe.ts b/frontend/app/lib/api/types/recipe.ts index d869c8914..b483ef1b6 100644 --- a/frontend/app/lib/api/types/recipe.ts +++ b/frontend/app/lib/api/types/recipe.ts @@ -511,6 +511,12 @@ export interface ScrapeRecipe { includeCategories?: boolean; url: string; } +export interface ScrapeRecipeAI { + content?: string | null; + url?: string | null; + translateLanguage?: string | null; + createNewOrganizers?: boolean; +} export interface ScrapeRecipeBase { includeTags?: boolean; includeCategories?: boolean; diff --git a/frontend/app/lib/api/user/recipes/recipe.ts b/frontend/app/lib/api/user/recipes/recipe.ts index 9844a73ad..80aa66136 100644 --- a/frontend/app/lib/api/user/recipes/recipe.ts +++ b/frontend/app/lib/api/user/recipes/recipe.ts @@ -41,7 +41,7 @@ const routes = { recipesCreateUrl: `${prefix}/recipes/create/url/stream`, recipesCreateUrlBulk: `${prefix}/recipes/create/url/bulk`, recipesCreateFromZip: `${prefix}/recipes/create/zip`, - recipesCreateFromImage: `${prefix}/recipes/create/image`, + recipesCreateWithAI: `${prefix}/recipes/create/ai/stream`, recipesCreateFromHtmlOrJson: `${prefix}/recipes/create/html-or-json/stream`, recipesCategory: `${prefix}/recipes/category`, recipesParseIngredient: `${prefix}/parser/ingredient`, @@ -150,16 +150,18 @@ export class RecipeAPI extends BaseCRUDAPI { return await this.requests.post(routes.recipesTestScrapeUrl, { url, useOpenAI }); } - private streamRecipeCreate(streamRoute: string, payload: object, onProgress?: (message: string) => void): Promise> { + private streamRecipeCreate(streamRoute: string, payload: object | FormData, onProgress?: (message: string) => void): Promise> { return new Promise((resolve) => { const { token } = useMealieAuth(); + const isFormData = payload instanceof FormData; const sse = new SSE(streamRoute, { headers: { - "Content-Type": "application/json", + // the browser has to set the multipart Content-Type itself, so it includes the boundary + ...(isFormData ? {} : { "Content-Type": "application/json" }), ...(token.value ? { Authorization: `Bearer ${token.value}` } : {}), }, - payload: JSON.stringify(payload), + payload: isFormData ? payload : JSON.stringify(payload), withCredentials: true, autoReconnect: false, }); @@ -233,19 +235,37 @@ export class RecipeAPI extends BaseCRUDAPI { return await this.requests.post(routes.recipesCreateUrlBulk, payload); } - async createOneFromImages(fileObjects: (Blob | File)[], translateLanguage: string | null = null) { + async createOneWithAI( + payload: { + content?: string | null; + url?: string | null; + images?: (Blob | File)[]; + translateLanguage?: string | null; + createNewOrganizers?: boolean; + }, + onProgress?: (message: string) => void, + ): Promise> { const formData = new FormData(); - fileObjects.forEach((file) => { - formData.append("images", file); - }); - - let apiRoute = routes.recipesCreateFromImage; - if (translateLanguage) { - apiRoute = `${apiRoute}?translateLanguage=${translateLanguage}`; + if (payload.content) { + formData.append("content", payload.content); + } + if (payload.url) { + formData.append("url", payload.url); + } + if (payload.translateLanguage) { + formData.append("translateLanguage", payload.translateLanguage); + } + if (payload.createNewOrganizers) { + formData.append("createNewOrganizers", "true"); } - return await this.requests.post(apiRoute, formData); + (payload.images || []).forEach((image, index) => { + // blobs from the cropper have no filename of their own, and the backend needs one + formData.append("images", image, image instanceof File ? image.name : `image-${index}.webp`); + }); + + return this.streamRecipeCreate(routes.recipesCreateWithAI, formData, onProgress); } async parseIngredients(parser: Parser, ingredients: Array) { diff --git a/frontend/app/lib/icons/icons.ts b/frontend/app/lib/icons/icons.ts index 39f57d556..2489acf12 100644 --- a/frontend/app/lib/icons/icons.ts +++ b/frontend/app/lib/icons/icons.ts @@ -12,6 +12,7 @@ import { mdiArrowRightBold, mdiArrowRightBoldOutline, mdiArrowUp, + mdiAutoFix, mdiBackupRestore, mdiBeakerOutline, mdiBellAlert, @@ -184,6 +185,7 @@ export const icons = { arrowRightBold: mdiArrowRightBold, arrowUp: mdiArrowUp, arrowUpDown: mdiDrag, + autoFix: mdiAutoFix, backupRestore: mdiBackupRestore, bellAlert: mdiBellAlert, bellPlus: mdiBellPlus, @@ -282,6 +284,7 @@ export const icons = { sortClockDescending: mdiSortClockDescending, star: mdiStar, testTube: mdiTestTube, + textBox: mdiTextBoxOutline, textBoxCheckOutline: mdiTextBoxCheckOutline, timelineText: mdiTimelineText, tools: mdiTools, diff --git a/frontend/app/pages/g/[groupSlug]/r/create.vue b/frontend/app/pages/g/[groupSlug]/r/create.vue index ab9e8b83c..def84a8f6 100644 --- a/frontend/app/pages/g/[groupSlug]/r/create.vue +++ b/frontend/app/pages/g/[groupSlug]/r/create.vue @@ -77,10 +77,10 @@ const subpages = computed(() => [ value: "html", }, { - icon: $globals.icons.fileImage, - text: i18n.t("recipe.create-from-images"), - value: "image", - hide: !group.value?.aiProviderSettings?.imageProviderEnabled, + icon: $globals.icons.autoFix, + text: i18n.t("recipe.import-with-ai"), + value: "ai", + hide: !group.value?.aiProviderSettings?.aiEnabled, }, { icon: $globals.icons.edit, diff --git a/frontend/app/pages/g/[groupSlug]/r/create/ai.vue b/frontend/app/pages/g/[groupSlug]/r/create/ai.vue new file mode 100644 index 000000000..a4deaf594 --- /dev/null +++ b/frontend/app/pages/g/[groupSlug]/r/create/ai.vue @@ -0,0 +1,299 @@ + + + + + diff --git a/frontend/app/pages/g/[groupSlug]/r/create/html.vue b/frontend/app/pages/g/[groupSlug]/r/create/html.vue index ca0f692d3..02bbe64aa 100644 --- a/frontend/app/pages/g/[groupSlug]/r/create/html.vue +++ b/frontend/app/pages/g/[groupSlug]/r/create/html.vue @@ -19,6 +19,10 @@ class="text-primary" >https://schema.org/Recipe

+

+ {{ $t("recipe.import-from-html-or-json-have-ai-read-it") }} + {{ $t("recipe.import-with-ai") }}. +

route.params.groupSlug as string || auth.user.value?.groupSlug || ""); const domUrlForm = ref(null); +const { group } = useGroupSelf(); +const aiImporterTarget = computed(() => `/g/${groupSlug.value}/r/create/ai`); +const aiEnabled = computed(() => !!group.value?.aiProviderSettings?.aiEnabled); + const api = useUserApi(); const tags = useTagStore(); diff --git a/frontend/app/pages/g/[groupSlug]/r/create/image.vue b/frontend/app/pages/g/[groupSlug]/r/create/image.vue index 39f4ade6a..94d628363 100644 --- a/frontend/app/pages/g/[groupSlug]/r/create/image.vue +++ b/frontend/app/pages/g/[groupSlug]/r/create/image.vue @@ -1,188 +1,16 @@ diff --git a/frontend/app/pages/g/[groupSlug]/r/create/index.vue b/frontend/app/pages/g/[groupSlug]/r/create/index.vue index 734495353..0f261cfea 100644 --- a/frontend/app/pages/g/[groupSlug]/r/create/index.vue +++ b/frontend/app/pages/g/[groupSlug]/r/create/index.vue @@ -3,9 +3,13 @@ diff --git a/frontend/app/pages/g/[groupSlug]/r/create/url.vue b/frontend/app/pages/g/[groupSlug]/r/create/url.vue index 81e8d8a0b..840718269 100644 --- a/frontend/app/pages/g/[groupSlug]/r/create/url.vue +++ b/frontend/app/pages/g/[groupSlug]/r/create/url.vue @@ -24,6 +24,10 @@ {{ $t('recipe.scrape-recipe-have-raw-html-or-json-data') }} {{ $t('recipe.scrape-recipe-you-can-import-from-raw-data-directly') }}.

+

+ {{ $t('recipe.scrape-recipe-have-ai-read-the-page') }} + {{ $t('recipe.import-with-ai') }}. +

{{ $t("recipe.scrape-recipe-try-importing-raw-html-instead") }}

+

+ {{ $t("recipe.scrape-recipe-have-ai-read-the-page") }} + {{ $t("recipe.import-with-ai") }}. +


{{ $t("new-recipe.error-details") }} @@ -178,6 +186,8 @@ const { const bulkImporterTarget = computed(() => `/g/${groupSlug.value}/r/create/bulk`); const htmlOrJsonImporterTarget = computed(() => `/g/${groupSlug.value}/r/create/html`); +const aiImporterTarget = computed(() => `/g/${groupSlug.value}/r/create/ai`); +const aiEnabled = computed(() => !!group.value?.aiProviderSettings?.aiEnabled); function handleResponse(response: AxiosResponse | null, refreshTags = false) { if (response?.status !== 201) { diff --git a/mealie/lang/messages/en-US.json b/mealie/lang/messages/en-US.json index 29e1ee8f7..be6ed7252 100644 --- a/mealie/lang/messages/en-US.json +++ b/mealie/lang/messages/en-US.json @@ -20,14 +20,25 @@ }, "and-amount": "and {amount}", "or-ingredient": "or {ingredient}", + "import-errors": { + "ai-not-enabled": "AI services are not enabled", + "image-provider-not-enabled": "AI image services are not enabled", + "no-recipe-found": "No recipe was found in the provided source", + "no-source": "No content, images, or URL were provided", + "provider-returned-nothing": "The AI provider did not return a recipe", + "unreadable-source": "Unable to read any content from the provided source" + }, "create-progress": { - "creating-recipe-with-ai": "Creating recipe with AI...", + "creating-recipe": "Creating recipe...", "creating-recipe-from-transcript-with-ai": "Creating recipe from transcript with AI...", "creating-recipe-from-webpage-data": "Creating recipe from webpage data...", "downloading-image": "Downloading image...", "downloading-video": "Downloading video...", "extracting-recipe-data": "Extracting recipe data...", "fetching-webpage": "Fetching webpage...", + "organizing-recipe": "Organizing recipe...", + "reading-images-with-ai": "Reading images with AI...", + "reading-source-with-ai": "Reading source with AI...", "transcribing-audio-with-ai": "Transcribing audio with AI..." } }, @@ -47,6 +58,7 @@ "permission_denied": "You do not have permission to perform this action", "recursive-recipe-link": "A recipe cannot reference itself, either directly or indirectly", "no-entry-found": "The requested resource was not found", + "rate-limit-error": "The AI provider is rate limiting requests. Please wait a moment and try again", "integrity-error": "Database integrity error", "username-conflict-error": "This username is already taken", "email-conflict-error": "This email is already in use" diff --git a/mealie/routes/recipe/recipe_crud_routes.py b/mealie/routes/recipe/recipe_crud_routes.py index 2178aca27..433a0c42c 100644 --- a/mealie/routes/recipe/recipe_crud_routes.py +++ b/mealie/routes/recipe/recipe_crud_routes.py @@ -1,7 +1,8 @@ import asyncio from collections import defaultdict -from collections.abc import AsyncIterable +from collections.abc import AsyncIterable, Awaitable, Callable from shutil import copyfileobj +from typing import Annotated from uuid import UUID import orjson @@ -41,7 +42,7 @@ from mealie.schema.recipe.recipe import ( RecipeSummary, ) from mealie.schema.recipe.recipe_asset import RecipeAsset -from mealie.schema.recipe.recipe_scraper import ScrapeRecipeTest +from mealie.schema.recipe.recipe_scraper import ScrapeRecipeAI, ScrapeRecipeTest from mealie.schema.recipe.recipe_suggestion import RecipeSuggestionQuery, RecipeSuggestionResponse from mealie.schema.recipe.request_helpers import ( RecipeDuplicate, @@ -64,6 +65,8 @@ from mealie.services.event_bus_service.event_types import ( EventRecipeData, EventTypes, ) +from mealie.services.recipe.ai_recipe_service import AIProviderNotEnabledError, AIRecipeService +from mealie.services.recipe.import_workflow.exceptions import NoRecipeDataError from mealie.services.recipe.recipe_data_service import ( InvalidDomainError, NotAnImageError, @@ -129,10 +132,22 @@ class RecipeController(BaseRecipeController): @router.post("/test-scrape-url") async def test_parse_recipe_url(self, data: ScrapeRecipeTest): - # Debugger should produce the same result as the scraper sees before cleaning - ScraperClass = RecipeScraperOpenAI if data.use_openai else RecipeScraperPackage try: - if scraped_data := await ScraperClass(data.url, self.translator, self.repos).scrape_url(): + if data.use_openai: + # the AI scraper builds a recipe directly, so there's no scraped schema to show + scraper = RecipeScraperOpenAI(data.url, self.translator, self.repos) + try: + result = await scraper.parse() + except NoRecipeDataError: + result = None + + if result and result[0]: + return result[0].model_dump(by_alias=True) + + return "AI was unable to extract a recipe from this URL" + + # Debugger should produce the same result as the scraper sees before cleaning + if scraped_data := await RecipeScraperPackage(data.url, self.translator, self.repos).scrape_url(): return scraped_data.schema.data except ForceTimeoutException as e: raise HTTPException( @@ -193,8 +208,7 @@ class RecipeController(BaseRecipeController): async for event in self._create_recipe_from_web(req): yield event - @staticmethod - def _error_message(ex: Exception) -> str: + def _error_message(self, ex: Exception) -> str: """ Extract a meaningful message from an exception raised during recipe creation. @@ -202,6 +216,12 @@ class RecipeController(BaseRecipeController): (e.g. BAD_RECIPE_DATA), which is far more useful to the client than the class name. """ + if isinstance(ex, exceptions.RateLimitError): + return self.t("exceptions.rate-limit-error") + + if isinstance(ex, NoRecipeDataError | AIProviderNotEnabledError): + return str(ex) + if isinstance(ex, HTTPException): detail = ex.detail if isinstance(detail, dict) and (details := detail.get("details")): @@ -211,9 +231,13 @@ class RecipeController(BaseRecipeController): return ex.__class__.__name__ - async def _create_recipe_from_web(self, req: ScrapeRecipe | ScrapeRecipeData) -> AsyncIterable[ServerSentEvent]: + async def _stream_recipe_creation( + self, create: Callable[[Callable[[str], Awaitable[None]]], Awaitable[str]] + ) -> AsyncIterable[ServerSentEvent]: """ - Create a recipe from the web, returning progress via SSE. + Run a recipe creation coroutine, returning progress via SSE. + + `create` is passed a progress callback, and returns the new recipe's slug. Events will continue to be yielded until: - The recipe is created, emitting: - event=SSEDataEventStatus.DONE @@ -223,13 +247,6 @@ class RecipeController(BaseRecipeController): - data=SSEDataEventMessage(...) """ - if isinstance(req, ScrapeRecipeData): - html = req.data - url = req.url or "" - else: - html = None - url = req.url - queue: asyncio.Queue[ServerSentEvent | None] = asyncio.Queue() async def on_progress(message: str) -> None: @@ -242,8 +259,7 @@ class RecipeController(BaseRecipeController): async def run() -> None: try: - recipe, extras = await create_from_html(url, self.repos, self.translator, html, on_progress=on_progress) - slug = self._finish_recipe_from_web(req, recipe, extras) + slug = await create(on_progress) await queue.put( ServerSentEvent( data=SSEDataEventDone(slug=slug), @@ -265,6 +281,30 @@ class RecipeController(BaseRecipeController): while (event := await queue.get()) is not None: yield event + def _create_recipe_from_web(self, req: ScrapeRecipe | ScrapeRecipeData) -> AsyncIterable[ServerSentEvent]: + """Create a recipe from the web, returning progress via SSE""" + + if isinstance(req, ScrapeRecipeData): + html = req.data + url = req.url or "" + else: + html = None + url = req.url + + async def create(on_progress: Callable[[str], Awaitable[None]]) -> str: + recipe, extras = await create_from_html( + url, + self.repos, + self.translator, + html, + on_progress=on_progress, + include_tags=req.include_tags, + include_categories=req.include_categories, + ) + return self._finish_recipe_from_web(req, recipe, extras) + + return self._stream_recipe_creation(create) + def _finish_recipe_from_web(self, req: ScrapeRecipe | ScrapeRecipeData, recipe: Recipe, extras: object) -> str: if req.include_tags: ctx = ScraperContext(self.repos) @@ -275,22 +315,99 @@ class RecipeController(BaseRecipeController): recipe.recipe_category = extras.use_categories(ctx) # type: ignore new_recipe = self.service.create_one(recipe) - - if new_recipe: - self.publish_event( - event_type=EventTypes.recipe_created, - document_data=EventRecipeData(operation=EventOperation.create, recipe_slug=new_recipe.slug), - group_id=new_recipe.group_id, - household_id=new_recipe.household_id, - message=self.t( - "notifications.generic-created-with-url", - name=new_recipe.name, - url=urls.recipe_url(self.group.slug, new_recipe.slug, self.settings.BASE_URL), - ), - ) - + self._publish_recipe_created(new_recipe) return new_recipe.slug + def _publish_recipe_created(self, new_recipe: Recipe) -> None: + if not new_recipe: + return + + self.publish_event( + event_type=EventTypes.recipe_created, + document_data=EventRecipeData(operation=EventOperation.create, recipe_slug=new_recipe.slug), + group_id=new_recipe.group_id, + household_id=new_recipe.household_id, + message=self.t( + "notifications.generic-created-with-url", + name=new_recipe.name, + url=urls.recipe_url(self.group.slug, new_recipe.slug, self.settings.BASE_URL), + ), + ) + + # ======================================================================= + # AI Operations + + @router.post("/create/ai", status_code=201, response_model=str) + async def create_recipe_with_ai( + self, + content: Annotated[str | None, Form()] = None, + url: Annotated[str | None, Form()] = None, + translate_language: Annotated[str | None, Form(alias="translateLanguage")] = None, + create_new_organizers: Annotated[bool, Form(alias="createNewOrganizers")] = False, + images: list[UploadFile] = File(default_factory=list), + ) -> str: + """ + Create a recipe from any combination of content (HTML, JSON, or text), images, and a URL, + using AI. Optionally specify a language for it to translate the recipe to. + """ + + req = ScrapeRecipeAI( + content=content, + url=url, + translate_language=translate_language, + create_new_organizers=create_new_organizers, + ) + async for event in self._create_recipe_with_ai(req, images): + if isinstance(event.data, SSEDataEventDone): + return event.data.slug + if isinstance(event.data, SSEDataEventMessage) and event.event == SSEDataEventStatus.ERROR: + raise HTTPException(status_code=400, detail=ErrorResponse.respond(message=event.data.message)) + + # This should never be reachable, since we should always hit DONE or hit an exception/ERROR + raise HTTPException(status_code=500, detail=ErrorResponse.respond(message="Unknown Error")) + + @router.post("/create/ai/stream", response_class=EventSourceResponse) + async def create_recipe_with_ai_stream( + self, + content: Annotated[str | None, Form()] = None, + url: Annotated[str | None, Form()] = None, + translate_language: Annotated[str | None, Form(alias="translateLanguage")] = None, + create_new_organizers: Annotated[bool, Form(alias="createNewOrganizers")] = False, + images: list[UploadFile] = File(default_factory=list), + ) -> AsyncIterable[ServerSentEvent]: + """ + Create a recipe from any combination of content (HTML, JSON, or text), images, and a URL, + using AI, streaming progress via SSE + """ + + req = ScrapeRecipeAI( + content=content, + url=url, + translate_language=translate_language, + create_new_organizers=create_new_organizers, + ) + async for event in self._create_recipe_with_ai(req, images): + yield event + + def _create_recipe_with_ai(self, req: ScrapeRecipeAI, images: list[UploadFile]) -> AsyncIterable[ServerSentEvent]: + """Create a recipe using AI, returning progress via SSE""" + + ai_service = AIRecipeService(self.repos, self.user, self.household, translator=self.translator) + + async def create(on_progress: Callable[[str], Awaitable[None]]) -> str: + recipe = await ai_service.create_from_ai( + content=req.content, + images=images, + url=req.url, + translate_language=req.translate_language, + create_new_organizers=req.create_new_organizers, + on_progress=on_progress, + ) + self._publish_recipe_created(recipe) + return recipe.slug + + return self._stream_recipe_creation(create) + @router.post("/create/url/bulk", status_code=202) def parse_recipe_url_bulk(self, bulk: CreateRecipeByUrlBulk, bg_tasks: BackgroundTasks): """Takes in a URL and attempts to scrape data and load it into the database""" @@ -324,33 +441,26 @@ class RecipeController(BaseRecipeController): return recipe.slug - @router.post("/create/image", status_code=201) + @router.post("/create/image", status_code=201, deprecated=True, include_in_schema=False) async def create_recipe_from_image( self, images: list[UploadFile] = File(...), translate_language: str | None = Query(None, alias="translateLanguage"), ): """ - Create a recipe from an image using OpenAI. - Optionally specify a language for it to translate the recipe to. + Deprecated in favor of `/create/ai`, which accepts images alongside other content. + Kept so existing integrations keep working. """ - ai_settings = self.group.ai_provider_settings - if not (ai_settings and ai_settings.image_provider_enabled): - raise HTTPException( - status_code=400, - detail=ErrorResponse.respond("OpenAI image services are not enabled"), - ) + req = ScrapeRecipeAI(translate_language=translate_language) + async for event in self._create_recipe_with_ai(req, images): + if isinstance(event.data, SSEDataEventDone): + return event.data.slug + if isinstance(event.data, SSEDataEventMessage) and event.event == SSEDataEventStatus.ERROR: + raise HTTPException(status_code=400, detail=ErrorResponse.respond(message=event.data.message)) - recipe = await self.service.create_from_images(images, translate_language) - self.publish_event( - event_type=EventTypes.recipe_created, - document_data=EventRecipeData(operation=EventOperation.create, recipe_slug=recipe.slug), - group_id=recipe.group_id, - household_id=recipe.household_id, - ) - - return recipe.slug + # This should never be reachable, since we should always hit DONE or hit an exception/ERROR + raise HTTPException(status_code=500, detail=ErrorResponse.respond(message="Unknown Error")) # ================================================================================================================== # CRUD Operations diff --git a/mealie/schema/openai/__init__.py b/mealie/schema/openai/__init__.py index 0f67fb866..d57285b5c 100644 --- a/mealie/schema/openai/__init__.py +++ b/mealie/schema/openai/__init__.py @@ -1,14 +1,25 @@ # This file is auto-generated by gen_schema_exports.py +from .compiled_source import OpenAICompiledSource from .general import OpenAIText -from .recipe import OpenAIRecipe, OpenAIRecipeIngredient, OpenAIRecipeInstruction, OpenAIRecipeNotes +from .organizers import OpenAIOrganizers +from .recipe import ( + OpenAIRecipe, + OpenAIRecipeIngredient, + OpenAIRecipeInstruction, + OpenAIRecipeNotes, + OpenAIRecipeNutrition, +) from .recipe_ingredient import OpenAIIngredient, OpenAIIngredients __all__ = [ + "OpenAIOrganizers", + "OpenAICompiledSource", "OpenAIIngredient", "OpenAIIngredients", "OpenAIRecipe", "OpenAIRecipeIngredient", "OpenAIRecipeInstruction", "OpenAIRecipeNotes", + "OpenAIRecipeNutrition", "OpenAIText", ] diff --git a/mealie/schema/openai/compiled_source.py b/mealie/schema/openai/compiled_source.py new file mode 100644 index 000000000..67c3ca256 --- /dev/null +++ b/mealie/schema/openai/compiled_source.py @@ -0,0 +1,38 @@ +from pydantic import Field + +from ._base import OpenAIBase + + +class OpenAICompiledSource(OpenAIBase): + """ + A faithful transcription of whatever source material the user supplied, produced by + the first step of the recipe import workflow. + + Every field must be derivable without an AI provider, since sources that already contain + structured data are compiled mechanically. + """ + + contains_recipe: bool = Field( + ..., + description="Whether the source contains a recipe at all. Set to false if there is nothing to transcribe.", + ) + + content: str = Field( + ..., + description=( + "The complete source content, transcribed as markdown. Include everything: the title, yield, " + "times, every ingredient (with any section headings), every instruction step in order, notes, " + "tips, storage advice, equipment, nutrition information, and attribution. Transcribe, do not " + "summarize, and do not translate." + ), + ) + + language: str | None = Field( + None, + description="The language the source content is written in, e.g., 'English' or 'French'.", + ) + + image_url: str | None = Field( + None, + description="URL of the recipe's image, but only if one appears in the source. Never guess a URL.", + ) diff --git a/mealie/schema/openai/organizers.py b/mealie/schema/openai/organizers.py new file mode 100644 index 000000000..e07f4e7e3 --- /dev/null +++ b/mealie/schema/openai/organizers.py @@ -0,0 +1,20 @@ +from pydantic import Field + +from ._base import OpenAIBase + + +class OpenAIOrganizers(OpenAIBase): + tags: list[str] = Field( + default_factory=list, + description="Tags describing the recipe, e.g., 'Vegetarian', 'Quick', 'Weeknight'.", + ) + + categories: list[str] = Field( + default_factory=list, + description="Categories the recipe belongs to, e.g., 'Dinner', 'Dessert', 'Breakfast'.", + ) + + tools: list[str] = Field( + default_factory=list, + description="Equipment needed to make the recipe, e.g., 'Dutch Oven', 'Stand Mixer'.", + ) diff --git a/mealie/schema/openai/recipe.py b/mealie/schema/openai/recipe.py index 387c072bf..87069a6fd 100644 --- a/mealie/schema/openai/recipe.py +++ b/mealie/schema/openai/recipe.py @@ -42,6 +42,20 @@ class OpenAIRecipeNotes(OpenAIBase): ) +class OpenAIRecipeNutrition(OpenAIBase): + calories: str | None = Field(None, description="Calories per serving, as a number without units.") + carbohydrate_content: str | None = Field(None, description="Carbohydrates per serving, in grams.") + cholesterol_content: str | None = Field(None, description="Cholesterol per serving, in milligrams.") + fat_content: str | None = Field(None, description="Total fat per serving, in grams.") + fiber_content: str | None = Field(None, description="Fiber per serving, in grams.") + protein_content: str | None = Field(None, description="Protein per serving, in grams.") + saturated_fat_content: str | None = Field(None, description="Saturated fat per serving, in grams.") + sodium_content: str | None = Field(None, description="Sodium per serving, in milligrams.") + sugar_content: str | None = Field(None, description="Sugar per serving, in grams.") + trans_fat_content: str | None = Field(None, description="Trans fat per serving, in grams.") + unsaturated_fat_content: str | None = Field(None, description="Unsaturated fat per serving, in grams.") + + class OpenAIRecipe(OpenAIBase): name: str = Field( ..., @@ -87,3 +101,8 @@ class OpenAIRecipe(OpenAIBase): default_factory=list, description="List of notes, tips, or variations.", ) + + nutrition: OpenAIRecipeNutrition | None = Field( + None, + description="Nutrition information, only if the source provides it. Do not calculate or estimate it.", + ) diff --git a/mealie/schema/recipe/__init__.py b/mealie/schema/recipe/__init__.py index 48785e4a4..5dfb7fb42 100644 --- a/mealie/schema/recipe/__init__.py +++ b/mealie/schema/recipe/__init__.py @@ -72,7 +72,7 @@ from .recipe_ingredient import ( ) from .recipe_notes import RecipeNote from .recipe_nutrition import Nutrition -from .recipe_scraper import ScrapeRecipe, ScrapeRecipeBase, ScrapeRecipeData, ScrapeRecipeTest +from .recipe_scraper import ScrapeRecipe, ScrapeRecipeAI, ScrapeRecipeBase, ScrapeRecipeData, ScrapeRecipeTest from .recipe_settings import RecipeSettings from .recipe_share_token import RecipeShareToken, RecipeShareTokenCreate, RecipeShareTokenSave, RecipeShareTokenSummary from .recipe_step import IngredientReferences, RecipeStep @@ -179,6 +179,7 @@ __all__ = [ "RecipeTool", "RecipeToolPagination", "ScrapeRecipe", + "ScrapeRecipeAI", "ScrapeRecipeBase", "ScrapeRecipeData", "ScrapeRecipeTest", diff --git a/mealie/schema/recipe/recipe_scraper.py b/mealie/schema/recipe/recipe_scraper.py index 0500afca6..69015994c 100644 --- a/mealie/schema/recipe/recipe_scraper.py +++ b/mealie/schema/recipe/recipe_scraper.py @@ -32,3 +32,30 @@ class ScrapeRecipeData(ScrapeRecipeBase): url: str | None = None """Optional URL of the recipe source""" + + +class ScrapeRecipeAI(MealieModel): + """Source material for an AI recipe import. At least one field, or one image, is required.""" + + content: str | None = None + """HTML, a JSON string of a https://schema.org/Recipe object, or plain text""" + + url: str | None = None + """Optional URL of the recipe source. Fetched if no content is provided""" + + translate_language: str | None = None + """Optional language to translate the recipe into""" + + create_new_organizers: bool = False + """Whether to create tags, categories, and tools that don't already exist in the group""" + + model_config = ConfigDict( + json_schema_extra={ + "example": { + "content": "...", + "url": "https://myfavoriterecipes.com/recipes", + "translateLanguage": "English", + "createNewOrganizers": False, + }, + } + ) diff --git a/mealie/services/matching.py b/mealie/services/matching.py new file mode 100644 index 000000000..20c40dbf5 --- /dev/null +++ b/mealie/services/matching.py @@ -0,0 +1,19 @@ +from pydantic import BaseModel +from rapidfuzz import fuzz, process + + +def find_match[T: BaseModel](match_value: str, *, store_map: dict[str, T], fuzzy_match_threshold: int = 0) -> T | None: + """Looks up a value in a store, falling back to the closest fuzzy match above the threshold.""" + + # check for literal matches + if match_value in store_map: + return store_map[match_value] + + # fuzzy match against the store + fuzz_result = process.extractOne( + match_value, store_map.keys(), scorer=fuzz.ratio, score_cutoff=fuzzy_match_threshold + ) + if fuzz_result is None: + return None + + return store_map[fuzz_result[0]] diff --git a/mealie/services/openai/content.py b/mealie/services/openai/content.py new file mode 100644 index 000000000..8ab51cae2 --- /dev/null +++ b/mealie/services/openai/content.py @@ -0,0 +1,85 @@ +import bs4 + +MAX_SOURCE_CONTENT_LENGTH = 100_000 +""" +Upper bound on how much source text is sent to an AI provider. + +Webpages and pasted content are unbounded, and every character costs tokens, so we cut off +anything beyond a length that comfortably fits even a very long recipe. +""" + +TRUNCATION_NOTICE = "\n\n[content truncated]" + + +def truncate_source_content(content: str, max_length: int = MAX_SOURCE_CONTENT_LENGTH) -> str: + """Caps source content, marking it so the model knows the text is incomplete.""" + + if len(content) <= max_length: + return content + + return content[:max_length] + TRUNCATION_NOTICE + + +def extract_json_ld_data_from_html(soup: bs4.BeautifulSoup) -> str: + data_parts: list[str] = [] + for script in soup.find_all("script", type="application/ld+json"): + try: + script_data = script.string + if script_data: + data_parts.append(str(script_data)) + except AttributeError: + pass + + return "\n\n".join(data_parts) + + +def find_image(soup: bs4.BeautifulSoup) -> str | None: + # find the open graph image tag + og_image = soup.find("meta", property="og:image") + if og_image and og_image.get("content"): + return og_image["content"] + + # find the largest image on the page + largest_img = None + max_size = 0 + for img in soup.find_all("img"): + width = img.get("width", 0) + height = img.get("height", 0) + if not width or not height: + continue + + try: + size = int(width) * int(height) + except (ValueError, TypeError): + size = 1 + if size > max_size: + max_size = size + largest_img = img + + if largest_img: + return largest_img.get("src") + + return None + + +def extract_page_content(html: str) -> tuple[str, str | None]: + """ + Strips an HTML document down to its text content, with any ld+json data appended, + along with the page's primary image, if one can be found. + + Raises if the document contains neither text nor ld+json data. + """ + + soup = bs4.BeautifulSoup(html, "lxml") + + text = soup.get_text(separator="\n", strip=True) + text += extract_json_ld_data_from_html(soup) + if not text: + raise ValueError("No text or ld+json data found in HTML") + + try: + image = find_image(soup) + except Exception: + image = None + + return text, image diff --git a/mealie/services/openai/prompts/recipes/build-recipe.txt b/mealie/services/openai/prompts/recipes/build-recipe.txt new file mode 100644 index 000000000..21b5d9da5 --- /dev/null +++ b/mealie/services/openai/prompts/recipes/build-recipe.txt @@ -0,0 +1,17 @@ +You convert a transcribed recipe source document into structured recipe data. + +The user message contains the transcribed source. Everything you return must come from it. Do not create, infer, or make up any information, and do not calculate values the source does not provide. Leave a field empty rather than guessing at it. + +When converting: +- If the source has a section of text supplied by the user, that section is authoritative. Where it disagrees with the rest of the source, follow it: if it names the recipe, use their name; if it corrects or adds a detail, use theirs. +- Keep ingredients and instructions in their original order. +- Preserve section headings by setting the title on the first ingredient or instruction of each section, and leaving it blank on the rest. +- Keep each ingredient as a single line of text, exactly as written, e.g. "2 cups of onions, chopped". +- When the source already presents its instructions as discrete steps, keep those steps as they are. Do not split or merge them. +- When the source narrates cooking continuously, as a video transcript does, group the actions into steps a cook would recognize. Actions done back to back on the same thing belong together: "Drain the pasta, set it aside, and turn off the heat" is one step, not three. +- Start a new step where the cook's attention shifts: a wait or a cooking time begins, a different component or pan is started, the temperature changes, or something goes into or comes out of the oven. +- Do not overcorrect. A recipe should not come out as one or two long steps, and no step should be too long to follow without re-reading it. +- Strip numeric prefixes like "1." or "Step 1", but keep word prefixes like "First". +- Put tips, variations, storage advice, and similar asides into notes rather than instructions. +- Only fill in nutrition if the source states it. +- If the source gives only one time, use total_time and leave prep_time and perform_time empty. diff --git a/mealie/services/openai/prompts/recipes/compile-source.txt b/mealie/services/openai/prompts/recipes/compile-source.txt new file mode 100644 index 000000000..45fbf8d47 --- /dev/null +++ b/mealie/services/openai/prompts/recipes/compile-source.txt @@ -0,0 +1,30 @@ +You transcribe recipe source material into a single plain-text document. You are not writing a recipe, you are making a faithful record of what the source says, so that a later step can turn it into structured data. + +The user message contains the source material. It may be text extracted from a webpage, a schema.org JSON object, plain text, a video transcript, one or more images, or some combination. Assume everything you receive describes exactly one recipe. + +Capture at least the following, when the source contains them: +- The recipe title +- The description, introduction, or headnote +- Yield or servings +- Prep time, cook time, and total time +- Every ingredient, in order, including any section headings such as "For the sauce" +- Every instruction step, in order, including any section headings +- Notes, tips, variations, and substitutions +- Storage, make-ahead, and reheating advice +- Equipment or tools mentioned +- Nutrition information +- Attribution, such as the author, publication, or source URL +- The URL of the recipe's image, if one appears in the source + +Rules: +- Text the user supplies alongside images or a video is authoritative. Where it disagrees with what you read in the images, follow the user's text: if they name the recipe, use their name; if they correct or add a detail, use theirs. Apply it to the document you produce rather than noting it separately. +- Transcribe, do not summarize. If you are unsure whether something belongs, include it. +- The list above is a minimum, not a limit. Transcribe anything else the source says about the recipe, even when it doesn't fit one of the categories above. Serving suggestions, drink pairings, difficulty, cost, allergen information, dietary labels, ingredient substitutions, temperature or measurement conversions, and cultural or historical notes all belong in the document. +- Leave out anything on the page that isn't about the recipe, such as navigation, advertisements, cookie and subscription notices, reader comments, and links to other recipes. +- Do not create, infer, or make up any information that is not in the source. +- Do not translate. Preserve the original wording and language. +- Preserve the original ordering of ingredients and steps. +- Use markdown headings to separate sections so the content stays easy to read. +- If the source is one or more images, they may be photographs of a page, printed text, or handwriting. They may be rotated or poorly cropped. Work out which part of the image is the recipe and transcribe that. Multiple images are pages of the same recipe, in the order given. +- Mark any text you cannot read as [illegible] rather than guessing at it. +- If the source contains no recipe at all, set contains_recipe to false and leave the content empty. diff --git a/mealie/services/openai/prompts/recipes/parse-recipe-image.txt b/mealie/services/openai/prompts/recipes/parse-recipe-image.txt deleted file mode 100644 index 3cb08ae2e..000000000 --- a/mealie/services/openai/prompts/recipes/parse-recipe-image.txt +++ /dev/null @@ -1,5 +0,0 @@ -You are a bot that reads an image, or a set of images, and parses it into recipe JSON. You will receive an image from the user and you need to extract the recipe data. It is imperative that you do not create any data or otherwise make up any information. - -The user message that you receive will be one or more images. Assume all images provided belong to a single recipe, not multiple recipes. The recipe may consist of printed text or handwritten text. It may be rotated or not properly cropped. It is your job to figure out which part of the image is the important content and extract it. - -If the user requests a translation, translate all text (name, ingredients, instructions, etc.) to the requested language. Otherwise, preserve the text as-is. diff --git a/mealie/services/openai/prompts/recipes/resolve-organizers.txt b/mealie/services/openai/prompts/recipes/resolve-organizers.txt new file mode 100644 index 000000000..f33cf4d1c --- /dev/null +++ b/mealie/services/openai/prompts/recipes/resolve-organizers.txt @@ -0,0 +1,13 @@ +You assign tags, categories, and tools to a recipe, so it can be organized alongside the rest of a user's collection. + +The user message contains the recipe. You may also be given the tags, categories, and tools that already exist in the user's collection. + +Tags describe what the recipe is like: dietary information, occasion, season, cuisine, effort. Categories are the broader groups a recipe belongs to, such as the course or meal. Tools are the equipment needed to make it. + +Rules: +- Only assign an organizer the recipe itself refers to. The recipe has to say it. +- Do not infer. Do not derive a cuisine from the ingredients, a course or meal from the kind of dish, an occasion or season from the style, or a diet from what the recipe happens to leave out. +- Only assign a tool when the recipe says that tool is used to make it. +- Returning empty lists is the correct answer for most recipes. A plain list of ingredients and steps, with nothing else said about it, has no organizers at all. +- When the recipe does refer to something that matches a name already in the user's collection, return that name exactly as it is written there, matching its spelling and capitalization. +- Do not invent names to fill out the lists, and do not repeat a name across tags, categories, and tools. diff --git a/mealie/services/openai/prompts/recipes/scrape-recipe.txt b/mealie/services/openai/prompts/recipes/scrape-recipe.txt deleted file mode 100644 index df6f2df3b..000000000 --- a/mealie/services/openai/prompts/recipes/scrape-recipe.txt +++ /dev/null @@ -1,5 +0,0 @@ -Extract recipe data from webpage contents (HTML, text, etc.) and return it in schema.org Recipe format. Reference: https://schema.org/Recipe - -Do not create or make up any information. If insufficient data is found, return an empty object. - -You will receive the webpage contents, including (but not necessarily limited to) text extracted from the HTML. diff --git a/mealie/services/openai/transcription.py b/mealie/services/openai/transcription.py new file mode 100644 index 000000000..7c838ae81 --- /dev/null +++ b/mealie/services/openai/transcription.py @@ -0,0 +1,159 @@ +import functools +import re +from collections.abc import Awaitable, Callable +from pathlib import Path +from typing import TypedDict + +import yt_dlp +from yt_dlp.extractor.generic import GenericIE + +from mealie.core import exceptions +from mealie.core.root_logger import get_logger + +from .openai import OpenAIService + +SUBTITLE_LANGS = ["en", "fr", "es", "de", "it"] + +logger = get_logger() + + +class TranscribedAudio(TypedDict): + audio: Path + subtitle: Path | None + title: str + description: str + thumbnail_url: str | None + transcription: str + + +@functools.cache +def get_yt_dlp_extractors() -> list: + """Build and cache the yt-dlp extractor list once per process lifetime.""" + return [ie for ie in yt_dlp.extractor.gen_extractors() if ie.working() and not isinstance(ie, GenericIE)] + + +def is_video_url(url: str) -> bool: + """Whether yt-dlp recognizes the URL as something it can download.""" + + if not url: + return False + + return any(ie.suitable(url) for ie in get_yt_dlp_extractors()) + + +def parse_subtitle_content(subtitle_content: str) -> str: + # TODO: is there a better way to parse subtitles that's more efficient? + + lines = [] + for line in subtitle_content.split("\n"): + if line.strip() and not line.startswith("WEBVTT") and "-->" not in line and not line.isdigit(): + lines.append(line.strip()) + + raw_content = " ".join(lines) + content = re.sub(r"<[^>]+>", "", raw_content) + return content + + +def download_video(url: str, temp_path: Path) -> TranscribedAudio: + """Downloads audio and subtitles from a video URL.""" + + output_template = temp_path / "mealie" # No extension here + + ydl_opts = { + "format": "bestaudio/best", + "outtmpl": str(output_template) + ".%(ext)s", + "quiet": True, + "writesubtitles": True, + "writeautomaticsub": True, + "subtitleslangs": SUBTITLE_LANGS, + "skip_download": False, + "ignoreerrors": True, + "postprocessors": [ + { + "key": "FFmpegExtractAudio", + "preferredcodec": "mp3", + "preferredquality": "32", + } + ], + "postprocessor_args": ["-ac", "1"], + } + + try: + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(url, download=True) + + if info is None: + raise exceptions.VideoDownloadError( + "Failed to extract video information. The video may be unavailable or the URL is invalid." + ) + + sub_path = None + for lang in SUBTITLE_LANGS: + potential_path = output_template.with_suffix(f".{lang}.vtt") + if potential_path.exists(): + sub_path = potential_path + break + + return { + "audio": output_template.with_suffix(".mp3"), + "subtitle": sub_path, + "title": info.get("title", ""), + "description": info.get("description", ""), + "thumbnail_url": info.get("thumbnail") or None, + "transcription": "", + } + except exceptions.VideoDownloadError: + raise + except Exception as e: + raise exceptions.VideoDownloadError(f"Failed to download video: {e}") from e + + +def read_subtitles(video_data: TranscribedAudio) -> str: + """Reads the downloaded subtitle file, if there is one. Returns an empty string on failure.""" + + subtitle_path = video_data["subtitle"] + if not subtitle_path: + return "" + + try: + with open(subtitle_path, encoding="utf-8") as f: + subtitle_content = f.read() + + logger.info("Using subtitles from video instead of transcription") + return parse_subtitle_content(subtitle_content) + except Exception: + logger.exception("Failed to read subtitles, falling back to transcription") + return "" + + +async def resolve_transcription( + video_data: TranscribedAudio, + openai_service: OpenAIService, + before_transcribe: Callable[[], Awaitable[None]] | None = None, +) -> str: + """ + Resolves a video's transcript, preferring one that's already known, then its subtitles, + and falling back to transcribing the audio with AI. `before_transcribe` is awaited only + if that fallback is needed. + """ + + if video_data["transcription"]: + return video_data["transcription"] + + if subtitles := read_subtitles(video_data): + return subtitles + + if before_transcribe: + await before_transcribe() + + try: + transcript = await openai_service.transcribe_audio(video_data["audio"]) + except exceptions.RateLimitError: + raise + except Exception as e: + raise exceptions.OpenAIServiceError(f"Failed to transcribe audio: {e}") from e + + if not transcript: + raise exceptions.OpenAIServiceError("No transcription returned from OpenAI") + + return transcript diff --git a/mealie/services/parser_services/_base.py b/mealie/services/parser_services/_base.py index d04eaf1ac..3da1cbf9c 100644 --- a/mealie/services/parser_services/_base.py +++ b/mealie/services/parser_services/_base.py @@ -1,7 +1,6 @@ from abc import ABC, abstractmethod from pydantic import UUID4, BaseModel -from rapidfuzz import fuzz, process from sqlalchemy.orm import Session from mealie.db.models.recipe.ingredient import IngredientFoodModel, IngredientUnitModel @@ -16,6 +15,7 @@ from mealie.schema.recipe.recipe_ingredient import ( ParsedIngredient, ) from mealie.schema.response.pagination import PaginationQuery +from mealie.services.matching import find_match class DataMatcher: @@ -100,18 +100,7 @@ class DataMatcher: def find_match[T: BaseModel]( cls, match_value: str, *, store_map: dict[str, T], fuzzy_match_threshold: int = 0 ) -> T | None: - # check for literal matches - if match_value in store_map: - return store_map[match_value] - - # fuzzy match against food store - fuzz_result = process.extractOne( - match_value, store_map.keys(), scorer=fuzz.ratio, score_cutoff=fuzzy_match_threshold - ) - if fuzz_result is None: - return None - - return store_map[fuzz_result[0]] + return find_match(match_value, store_map=store_map, fuzzy_match_threshold=fuzzy_match_threshold) def find_food_match(self, food: IngredientFood | CreateIngredientFood | str) -> IngredientFood | None: if isinstance(food, IngredientFood): diff --git a/mealie/services/recipe/ai_recipe_service.py b/mealie/services/recipe/ai_recipe_service.py new file mode 100644 index 000000000..dd606b725 --- /dev/null +++ b/mealie/services/recipe/ai_recipe_service.py @@ -0,0 +1,127 @@ +import shutil +from collections.abc import Awaitable, Callable +from pathlib import Path + +from fastapi import UploadFile + +from mealie.core.dependencies.dependencies import get_temporary_path +from mealie.schema.recipe.recipe import Recipe +from mealie.services.openai import OpenAIService +from mealie.services.scraper.scraper import finalize_scraped_recipe + +from .import_workflow import ( + RecipeImportWorkflow, + WorkflowContext, + WorkflowInput, + WorkflowOptions, +) +from .import_workflow.exceptions import NoRecipeDataError +from .recipe_data_service import RecipeDataService +from .recipe_service import RecipeService + + +class AIProviderNotEnabledError(Exception): + """Raised when the group hasn't configured the AI provider a request needs.""" + + pass + + +class AIRecipeService(RecipeService): + """Creates recipes from arbitrary source material by running the recipe import workflow.""" + + async def create_from_ai( + self, + *, + content: str | None = None, + images: list[UploadFile] | None = None, + url: str | None = None, + translate_language: str | None = None, + create_new_organizers: bool = False, + on_progress: Callable[[str], Awaitable[None]] | None = None, + ) -> Recipe: + """ + Creates a recipe from any combination of content, images, and a URL. + + The first image, if any, becomes the recipe's cover image. + """ + + with get_temporary_path() as temp_path: + local_images = self._store_images(images or [], temp_path) + + recipe_data = await self.build_recipe( + content=content, + images=local_images, + url=url, + translate_language=translate_language, + create_new_organizers=create_new_organizers, + on_progress=on_progress, + ) + + recipe = self.create_one(recipe_data) + if local_images: + with open(local_images[0], "rb") as f: + RecipeDataService(recipe.id).write_image(f.read(), "webp") + + return recipe + + async def build_recipe( + self, + *, + content: str | None = None, + images: list[Path] | None = None, + url: str | None = None, + translate_language: str | None = None, + create_new_organizers: bool = False, + on_progress: Callable[[str], Awaitable[None]] | None = None, + ) -> Recipe: + """ + Compiles the given source material into a recipe. + + The recipe is not persisted; that's up to the caller. + """ + + workflow_input = WorkflowInput(content=content, images=images or [], url=url) + if workflow_input.is_empty: + raise NoRecipeDataError(self.t("recipe.import-errors.no-source")) + + ai_service = OpenAIService(self.repos) + self._validate_providers(ai_service, has_images=bool(workflow_input.images)) + + ctx = WorkflowContext( + input=workflow_input, + options=WorkflowOptions( + translate_language=translate_language, + create_new_organizers=create_new_organizers, + ), + repos=self.repos, + user=self.user, + household=self.household, + translator=self.translator, + ai=ai_service, + on_progress=on_progress, + ) + + result = await RecipeImportWorkflow().run(ctx) + return await finalize_scraped_recipe(result.recipe, self.translator, on_progress=on_progress) + + @staticmethod + def _store_images(images: list[UploadFile], temp_path: Path) -> list[Path]: + local_images: list[Path] = [] + for image in images: + if not image.filename: + continue + + image_path = temp_path.joinpath(Path(image.filename).name) + with image_path.open("wb") as buffer: + shutil.copyfileobj(image.file, buffer) + local_images.append(image_path) + + return local_images + + def _validate_providers(self, ai_service: OpenAIService, *, has_images: bool) -> None: + settings = ai_service.provider_settings + if not (settings and settings.ai_enabled): + raise AIProviderNotEnabledError(self.t("recipe.import-errors.ai-not-enabled")) + + if has_images and not settings.image_provider_enabled: + raise AIProviderNotEnabledError(self.t("recipe.import-errors.image-provider-not-enabled")) diff --git a/mealie/services/recipe/import_workflow/__init__.py b/mealie/services/recipe/import_workflow/__init__.py new file mode 100644 index 000000000..14ea8f2f8 --- /dev/null +++ b/mealie/services/recipe/import_workflow/__init__.py @@ -0,0 +1,20 @@ +from .base import WorkflowStep +from .context import ( + StepOutcome, + WorkflowContext, + WorkflowInput, + WorkflowOptions, + WorkflowResult, +) +from .workflow import DEFAULT_WORKFLOW_STEPS, RecipeImportWorkflow + +__all__ = [ + "DEFAULT_WORKFLOW_STEPS", + "RecipeImportWorkflow", + "StepOutcome", + "WorkflowContext", + "WorkflowInput", + "WorkflowOptions", + "WorkflowResult", + "WorkflowStep", +] diff --git a/mealie/services/recipe/import_workflow/base.py b/mealie/services/recipe/import_workflow/base.py new file mode 100644 index 000000000..4a17cfdfb --- /dev/null +++ b/mealie/services/recipe/import_workflow/base.py @@ -0,0 +1,33 @@ +from abc import ABC, abstractmethod + +from .context import WorkflowContext + + +class WorkflowStep(ABC): + """ + A single unit of work in the recipe import workflow. + + Steps run in order and communicate by reading and writing the context. To add a step, + implement this class and add it to `DEFAULT_WORKFLOW_STEPS`. + + A step that needs to know what the *source* said must read `ctx.compiled_source`, which is + the only faithful record of it. The draft recipe is a lossy derivative: anything the recipe + schema has no field for, such as keywords, is gone by the time it exists, and reading the + draft instead silently returns nothing rather than failing. Only steps that refine data + already extracted into the recipe should read `ctx.draft_recipe`. + """ + + name: str + """Identifier used in logs and step outcomes""" + + progress_key: str | None = None + """Translation key reported to the client before the step runs""" + + required: bool = True + """If a required step fails the workflow aborts, otherwise the failure is logged and skipped""" + + def should_run(self, ctx: WorkflowContext) -> bool: + return True + + @abstractmethod + async def run(self, ctx: WorkflowContext) -> None: ... diff --git a/mealie/services/recipe/import_workflow/compilers/__init__.py b/mealie/services/recipe/import_workflow/compilers/__init__.py new file mode 100644 index 000000000..d625f7121 --- /dev/null +++ b/mealie/services/recipe/import_workflow/compilers/__init__.py @@ -0,0 +1,23 @@ +from .base import COMPILE_SOURCE_PROMPT, SourceCompiler +from .image import ImageCompiler +from .structured_data import StructuredDataCompiler +from .transcription import TranscriptionCompiler +from .web_page import WebPageCompiler + +DEFAULT_SOURCE_COMPILERS: list[type[SourceCompiler]] = [ + ImageCompiler, + TranscriptionCompiler, + StructuredDataCompiler, + WebPageCompiler, +] +"""Order matters: the first compiler that can handle the input is used""" + +__all__ = [ + "COMPILE_SOURCE_PROMPT", + "DEFAULT_SOURCE_COMPILERS", + "ImageCompiler", + "SourceCompiler", + "StructuredDataCompiler", + "TranscriptionCompiler", + "WebPageCompiler", +] diff --git a/mealie/services/recipe/import_workflow/compilers/base.py b/mealie/services/recipe/import_workflow/compilers/base.py new file mode 100644 index 000000000..53105abac --- /dev/null +++ b/mealie/services/recipe/import_workflow/compilers/base.py @@ -0,0 +1,41 @@ +from abc import ABC, abstractmethod + +from mealie.core.root_logger import get_logger +from mealie.schema.openai.compiled_source import OpenAICompiledSource + +from ..context import WorkflowContext + +COMPILE_SOURCE_PROMPT = "recipes.compile-source" + + +class SourceCompiler(ABC): + """ + Turns one kind of source material into a Compiled Source Document. + + Compilers are tried in order and the first one that can handle the input wins, so a new + input modality is a new compiler rather than another branch. Note that not every compiler + calls an AI provider: sources that already contain structured data are compiled directly. + """ + + progress_key: str | None = None + """Translation key reported to the client before compiling. Left unset if compiling is instant.""" + + requires_content: bool = True + """ + Whether the compiler needs the source content. Compilers that work from the input alone are + offered the input first, so that e.g. a video URL is downloaded rather than fetched as a webpage. + """ + + def __init__(self, ctx: WorkflowContext) -> None: + self.ctx = ctx + self.logger = get_logger() + + @property + def content(self) -> str | None: + return self.ctx.source_content + + @abstractmethod + def can_compile(self) -> bool: ... + + @abstractmethod + async def compile(self) -> OpenAICompiledSource | None: ... diff --git a/mealie/services/recipe/import_workflow/compilers/image.py b/mealie/services/recipe/import_workflow/compilers/image.py new file mode 100644 index 000000000..e84ab2c5a --- /dev/null +++ b/mealie/services/recipe/import_workflow/compilers/image.py @@ -0,0 +1,40 @@ +import os + +from mealie.schema.openai.compiled_source import OpenAICompiledSource +from mealie.services.openai import OpenAILocalImage +from mealie.services.openai.content import truncate_source_content + +from .base import COMPILE_SOURCE_PROMPT, SourceCompiler + + +class ImageCompiler(SourceCompiler): + """Reads uploaded images. Runs on the group's image provider, since it needs vision.""" + + progress_key = "recipe.create-progress.reading-images-with-ai" + requires_content = False + + def can_compile(self) -> bool: + return bool(self.ctx.input.images) + + async def compile(self) -> OpenAICompiledSource | None: + images = self.ctx.input.images + attachments = [OpenAILocalImage(filename=os.path.basename(image), path=image) for image in images] + + message_parts = [ + f"Attached {'are' if len(images) > 1 else 'is'} {len(images)} " + f"{'images' if len(images) > 1 else 'image'} of a single recipe." + ] + if self.content: + message_parts.append( + "The user supplied the following text along with the " + f"{'images' if len(images) > 1 else 'image'}. It is authoritative: where it disagrees " + f"with the {'images' if len(images) > 1 else 'image'}, follow the text." + ) + message_parts.append(truncate_source_content(self.content)) + + return await self.ctx.ai.get_response( + self.ctx.ai.get_prompt(COMPILE_SOURCE_PROMPT), + "\n".join(message_parts), + response_schema=OpenAICompiledSource, + attachments=attachments, + ) diff --git a/mealie/services/recipe/import_workflow/compilers/structured_data.py b/mealie/services/recipe/import_workflow/compilers/structured_data.py new file mode 100644 index 000000000..42ee8cf7c --- /dev/null +++ b/mealie/services/recipe/import_workflow/compilers/structured_data.py @@ -0,0 +1,88 @@ +import json +from typing import Any + +import bs4 + +from mealie.schema.openai.compiled_source import OpenAICompiledSource +from mealie.services.openai.content import extract_json_ld_data_from_html, find_image, truncate_source_content +from mealie.services.scraper import cleaner + +from ..context import WorkflowContext +from .base import SourceCompiler + + +def _looks_like_json(content: str) -> bool: + stripped = content.lstrip() + return stripped.startswith("{") or stripped.startswith("[") + + +def _looks_like_html(content: str) -> bool: + return "<" in content and ">" in content + + +class StructuredDataCompiler(SourceCompiler): + """ + Compiles sources that are already usable as-is: a schema.org JSON object, HTML containing + ld+json data, or plain text. These need no AI provider, which keeps single-call imports + at a single call. + """ + + def __init__(self, ctx: WorkflowContext) -> None: + super().__init__(ctx) + self._soup: bs4.BeautifulSoup | None = None + + @property + def soup(self) -> bs4.BeautifulSoup: + if self._soup is None: + self._soup = bs4.BeautifulSoup(self.content or "", "lxml") + + return self._soup + + def can_compile(self) -> bool: + # images always have to be read by a provider + if self.ctx.input.images or not self.content: + return False + + if _looks_like_json(self.content): + return True + + if _looks_like_html(self.content): + # HTML is only usable directly if the page carries structured data + return bool(extract_json_ld_data_from_html(self.soup)) + + # plain text is already a faithful record of itself + return True + + def _image_from_json(self, content: str) -> str | None: + try: + data: Any = json.loads(content) + except json.JSONDecodeError: + return None + + if isinstance(data, list): + data = next((item for item in data if isinstance(item, dict)), None) + if not isinstance(data, dict): + return None + + return cleaner.clean_image(data.get("image"), default="")[0] or None + + async def compile(self) -> OpenAICompiledSource | None: + content = self.content or "" + image_url: str | None = None + + if _looks_like_json(content): + image_url = self._image_from_json(content) + elif _looks_like_html(content): + image_url = find_image(self.soup) + content = self.soup.get_text(separator="\n", strip=True) + extract_json_ld_data_from_html(self.soup) + + content = content.strip() + if not content: + return None + + return OpenAICompiledSource( + contains_recipe=True, + content=truncate_source_content(content), + language=None, + image_url=image_url, + ) diff --git a/mealie/services/recipe/import_workflow/compilers/transcription.py b/mealie/services/recipe/import_workflow/compilers/transcription.py new file mode 100644 index 000000000..de9bbc732 --- /dev/null +++ b/mealie/services/recipe/import_workflow/compilers/transcription.py @@ -0,0 +1,63 @@ +import asyncio + +from mealie.core.dependencies.dependencies import get_temporary_path +from mealie.schema.openai.compiled_source import OpenAICompiledSource +from mealie.services.openai import transcription +from mealie.services.openai.content import truncate_source_content + +from .base import SourceCompiler + + +class TranscriptionCompiler(SourceCompiler): + """ + Compiles a video into its transcript. The audio provider does the transcribing, but the + transcript itself is already a faithful record of the source, so no further AI call is made. + """ + + progress_key = "recipe.create-progress.downloading-video" + requires_content = False + + def can_compile(self) -> bool: + url = self.ctx.input.url + if not url: + return False + + settings = self.ctx.ai.provider_settings + if not (settings and settings.audio_provider_enabled): + return False + + return transcription.is_video_url(url) + + async def compile(self) -> OpenAICompiledSource | None: + url = self.ctx.input.url or "" + + with get_temporary_path() as temp_path: + video_data = await asyncio.to_thread(transcription.download_video, url, temp_path) + + async def report_transcribing() -> None: + await self.ctx.report_progress("recipe.create-progress.transcribing-audio-with-ai") + + transcript = await transcription.resolve_transcription( + video_data, self.ctx.ai, before_transcribe=report_transcribing + ) + + if not transcript: + self.logger.error("Could not extract a transcript (no data)") + return None + + content_parts = [f"# {video_data['title']}"] if video_data["title"] else [] + if video_data["description"]: + content_parts.append(f"## Video description\n\n{video_data['description']}") + content_parts.append(f"## Video transcript\n\n{transcript}") + + # text pasted alongside the video link is often where the ingredient list actually lives. + # It goes last so that truncation trims it before the transcript. + if self.content: + content_parts.append(f"## Text supplied by the user\n\n{self.content}") + + return OpenAICompiledSource( + contains_recipe=True, + content=truncate_source_content("\n\n".join(content_parts)), + language=None, + image_url=video_data["thumbnail_url"], + ) diff --git a/mealie/services/recipe/import_workflow/compilers/web_page.py b/mealie/services/recipe/import_workflow/compilers/web_page.py new file mode 100644 index 000000000..c66581469 --- /dev/null +++ b/mealie/services/recipe/import_workflow/compilers/web_page.py @@ -0,0 +1,41 @@ +from mealie.schema.openai.compiled_source import OpenAICompiledSource +from mealie.services.openai.content import extract_page_content, truncate_source_content + +from .base import COMPILE_SOURCE_PROMPT, SourceCompiler + + +class WebPageCompiler(SourceCompiler): + """ + Reads webpage content that has no usable structured data, so the recipe has to be picked + out of the surrounding page text. + """ + + progress_key = "recipe.create-progress.reading-source-with-ai" + + def can_compile(self) -> bool: + return bool(self.content) + + async def compile(self) -> OpenAICompiledSource | None: + content = self.content or "" + image_url: str | None = None + + try: + content, image_url = extract_page_content(content) + except ValueError: + return None + + message_parts = ["The following content was extracted from a webpage."] + if image_url: + message_parts.append(f"The page's primary image is: {image_url}") + message_parts.append(truncate_source_content(content)) + + compiled = await self.ctx.ai.get_response( + self.ctx.ai.get_prompt(COMPILE_SOURCE_PROMPT), + "\n".join(message_parts), + response_schema=OpenAICompiledSource, + ) + + if compiled and not compiled.image_url: + compiled.image_url = image_url + + return compiled diff --git a/mealie/services/recipe/import_workflow/context.py b/mealie/services/recipe/import_workflow/context.py new file mode 100644 index 000000000..7bf105de3 --- /dev/null +++ b/mealie/services/recipe/import_workflow/context.py @@ -0,0 +1,95 @@ +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from enum import StrEnum +from pathlib import Path + +from pydantic import BaseModel, Field + +from mealie.lang.providers import Translator +from mealie.repos.repository_factory import AllRepositories +from mealie.schema.household.household import HouseholdInDB +from mealie.schema.openai.compiled_source import OpenAICompiledSource +from mealie.schema.openai.organizers import OpenAIOrganizers +from mealie.schema.recipe.recipe import Recipe +from mealie.schema.user.user import PrivateUser +from mealie.services.openai import OpenAIService + + +class WorkflowInput(BaseModel): + """The source material a recipe is imported from. At least one field must be populated.""" + + content: str | None = None + """Raw HTML, a JSON string of a https://schema.org/Recipe object, or plain text""" + + images: list[Path] = Field(default_factory=list) + """Local paths to uploaded images, in order. The first is used as the recipe's cover image.""" + + url: str | None = None + """Source URL. Fetched if no content is supplied, and recorded as the recipe's original URL.""" + + @property + def is_empty(self) -> bool: + return not (self.content or self.images or self.url) + + +class WorkflowOptions(BaseModel): + """How the source material should be processed.""" + + translate_language: str | None = None + + resolve_organizers: bool = True + """Whether to ask the provider for the recipe's tags, categories, and tools""" + + attach_organizers: bool = True + """ + Whether resolved organizers should be attached to the recipe. Callers that apply organizers + themselves can switch this off and read the names off the context instead. + """ + + create_new_organizers: bool = False + """Whether organizers that don't already exist in the group should be created""" + + +class StepOutcome(StrEnum): + COMPLETED = "completed" + SKIPPED = "skipped" + FAILED = "failed" + + +@dataclass +class WorkflowContext: + """Carries workflow inputs and accumulating state between steps.""" + + input: WorkflowInput + options: WorkflowOptions + + repos: AllRepositories + translator: Translator + ai: OpenAIService + + user: PrivateUser | None = None + household: HouseholdInDB | None = None + """Recipe owner. Optional, since callers that persist the recipe themselves assign it.""" + + on_progress: Callable[[str], Awaitable[None]] | None = None + + source_content: str | None = None + """Input content, or the HTML fetched from the input URL""" + + compiled_source: OpenAICompiledSource | None = None + """Output of the compile step""" + + organizer_names: OpenAIOrganizers | None = None + """Organizer names returned by the organizer step, before they're matched to the database""" + + draft_recipe: Recipe | None = None + """Recipe under construction. Not persisted; the caller is responsible for saving it.""" + + async def report_progress(self, key: str) -> None: + if self.on_progress: + await self.on_progress(self.translator.t(key)) + + +class WorkflowResult(BaseModel): + recipe: Recipe + outcomes: dict[str, StepOutcome] = Field(default_factory=dict) diff --git a/mealie/services/recipe/import_workflow/exceptions.py b/mealie/services/recipe/import_workflow/exceptions.py new file mode 100644 index 000000000..3dcc73c09 --- /dev/null +++ b/mealie/services/recipe/import_workflow/exceptions.py @@ -0,0 +1,4 @@ +class NoRecipeDataError(Exception): + """Raised when the supplied source material doesn't contain a usable recipe.""" + + pass diff --git a/mealie/services/recipe/import_workflow/steps/__init__.py b/mealie/services/recipe/import_workflow/steps/__init__.py new file mode 100644 index 000000000..cd0dc4e06 --- /dev/null +++ b/mealie/services/recipe/import_workflow/steps/__init__.py @@ -0,0 +1,9 @@ +from .build_recipe import BuildRecipeStep +from .compile_source import CompileSourceStep +from .resolve_organizers import ResolveOrganizersStep + +__all__ = [ + "BuildRecipeStep", + "CompileSourceStep", + "ResolveOrganizersStep", +] diff --git a/mealie/services/recipe/import_workflow/steps/build_recipe.py b/mealie/services/recipe/import_workflow/steps/build_recipe.py new file mode 100644 index 000000000..6e40f5a86 --- /dev/null +++ b/mealie/services/recipe/import_workflow/steps/build_recipe.py @@ -0,0 +1,99 @@ +from pydantic.alias_generators import to_camel + +from mealie.schema.openai.recipe import OpenAIRecipe +from mealie.schema.recipe.recipe import Recipe, create_recipe_slug +from mealie.schema.recipe.recipe_ingredient import RecipeIngredient +from mealie.schema.recipe.recipe_notes import RecipeNote +from mealie.schema.recipe.recipe_nutrition import Nutrition +from mealie.schema.recipe.recipe_step import RecipeStep +from mealie.services.scraper import cleaner + +from ..base import WorkflowStep +from ..context import WorkflowContext +from ..exceptions import NoRecipeDataError + +BUILD_RECIPE_PROMPT = "recipes.build-recipe" + + +class BuildRecipeStep(WorkflowStep): + """Turns the Compiled Source Document into a draft recipe.""" + + name = "build-recipe" + progress_key = "recipe.create-progress.creating-recipe" + + def _build_message(self, ctx: WorkflowContext) -> str: + compiled = ctx.compiled_source + if not compiled: + raise NoRecipeDataError(ctx.translator.t("recipe.import-errors.unreadable-source")) + + message_parts = ["Below is the transcribed recipe source.", compiled.content] + + translate_language = ctx.options.translate_language + if translate_language and translate_language.lower() != (compiled.language or "").lower(): + message_parts.insert( + 0, + f"Translate the recipe into {translate_language}. " + "Translate every field, including ingredients and instructions.", + ) + + return "\n\n".join(message_parts) + + def _convert_nutrition(self, openai_recipe: OpenAIRecipe) -> Nutrition | None: + if not openai_recipe.nutrition: + return None + + # clean_nutrition expects schema.org's camelCase keys + raw = {to_camel(key): value for key, value in openai_recipe.nutrition.model_dump().items()} + cleaned = cleaner.clean_nutrition(raw) + return Nutrition(**cleaned) if cleaned else None + + def _convert_recipe(self, ctx: WorkflowContext, openai_recipe: OpenAIRecipe) -> Recipe: + compiled = ctx.compiled_source + + # callers that persist the recipe themselves assign its owner, so only set it when known + owner = ( + {"user_id": ctx.user.id, "group_id": ctx.user.group_id, "household_id": ctx.household.id} + if ctx.user and ctx.household + else {} + ) + + return Recipe( + **owner, + name=openai_recipe.name, + slug=create_recipe_slug(openai_recipe.name), + description=openai_recipe.description, + recipe_yield=openai_recipe.recipe_yield, + total_time=openai_recipe.total_time, + prep_time=openai_recipe.prep_time, + perform_time=openai_recipe.perform_time, + recipe_ingredient=[ + RecipeIngredient(title=ingredient.title, note=ingredient.text) + for ingredient in openai_recipe.ingredients + if ingredient.text + ], + recipe_instructions=[ + RecipeStep(title=instruction.title, text=instruction.text) + for instruction in openai_recipe.instructions + if instruction.text + ], + notes=[RecipeNote(title=note.title or "", text=note.text) for note in openai_recipe.notes if note.text], + nutrition=self._convert_nutrition(openai_recipe), + # uploaded images take precedence, and are attached to the recipe after it's created + image=None if ctx.input.images else compiled and compiled.image_url, + org_url=ctx.input.url, + ) + + async def run(self, ctx: WorkflowContext) -> None: + response = await ctx.ai.get_response( + ctx.ai.get_prompt(BUILD_RECIPE_PROMPT), + self._build_message(ctx), + response_schema=OpenAIRecipe, + ) + + if not response: + raise NoRecipeDataError(ctx.translator.t("recipe.import-errors.provider-returned-nothing")) + + if not (response.ingredients or response.instructions): + raise NoRecipeDataError(ctx.translator.t("recipe.import-errors.no-recipe-found")) + + ctx.draft_recipe = cleaner.clean(self._convert_recipe(ctx, response), ctx.translator) diff --git a/mealie/services/recipe/import_workflow/steps/compile_source.py b/mealie/services/recipe/import_workflow/steps/compile_source.py new file mode 100644 index 000000000..531cd7301 --- /dev/null +++ b/mealie/services/recipe/import_workflow/steps/compile_source.py @@ -0,0 +1,61 @@ +from mealie.services.scraper.fetch import safe_scrape_html + +from ..base import WorkflowStep +from ..compilers import DEFAULT_SOURCE_COMPILERS, SourceCompiler +from ..context import WorkflowContext +from ..exceptions import NoRecipeDataError + + +class CompileSourceStep(WorkflowStep): + """ + Compiles the workflow input into a Compiled Source Document: a faithful transcription of + the source material that later steps read instead of the raw input. + """ + + name = "compile-source" + + def __init__(self, compilers: list[type[SourceCompiler]] | None = None) -> None: + self.compilers = DEFAULT_SOURCE_COMPILERS if compilers is None else compilers + + async def _fetch_source_content(self, ctx: WorkflowContext) -> None: + if ctx.source_content or not ctx.input.url: + return + + await ctx.report_progress("recipe.create-progress.fetching-webpage") + ctx.source_content = await safe_scrape_html(ctx.input.url) or None + + async def _compile(self, ctx: WorkflowContext, compilers: list[type[SourceCompiler]]) -> bool: + for CompilerClass in compilers: + compiler = CompilerClass(ctx) + if not compiler.can_compile(): + continue + + if compiler.progress_key: + await ctx.report_progress(compiler.progress_key) + + compiled = await compiler.compile() + if not compiled: + continue + + if not (compiled.contains_recipe and compiled.content.strip()): + raise NoRecipeDataError(ctx.translator.t("recipe.import-errors.no-recipe-found")) + + ctx.compiled_source = compiled + return True + + return False + + async def run(self, ctx: WorkflowContext) -> None: + ctx.source_content = ctx.input.content + + # compilers that work from the input alone go first, so that a video URL is downloaded + # rather than fetched and read as a webpage + if await self._compile(ctx, [c for c in self.compilers if not c.requires_content]): + return + + await self._fetch_source_content(ctx) + if not ctx.source_content: + raise NoRecipeDataError(ctx.translator.t("recipe.import-errors.unreadable-source")) + + if not await self._compile(ctx, [c for c in self.compilers if c.requires_content]): + raise NoRecipeDataError(ctx.translator.t("recipe.import-errors.unreadable-source")) diff --git a/mealie/services/recipe/import_workflow/steps/resolve_organizers.py b/mealie/services/recipe/import_workflow/steps/resolve_organizers.py new file mode 100644 index 000000000..248cdb586 --- /dev/null +++ b/mealie/services/recipe/import_workflow/steps/resolve_organizers.py @@ -0,0 +1,120 @@ +from mealie.schema.openai.organizers import OpenAIOrganizers +from mealie.services.openai import OpenAIDataInjection +from mealie.services.openai.content import truncate_source_content + +from ...organizer_resolver import OrganizerResolver +from ..base import WorkflowStep +from ..context import WorkflowContext + +RESOLVE_ORGANIZERS_PROMPT = "recipes.resolve-organizers" + +MAX_INJECTED_TAGS = 200 +""" +Tag collections can get large, and every name costs tokens. Injecting a subset only weakens the +model's ability to echo an existing name back; the resolver still matches against all of them. +""" + + +class ResolveOrganizersStep(WorkflowStep): + """ + Assigns tags, categories, and tools to the draft recipe, matching against the group's + existing organizers and optionally creating the ones that don't exist yet. + """ + + name = "resolve-organizers" + progress_key = "recipe.create-progress.organizing-recipe" + required = False + + def _build_injections(self, resolver: OrganizerResolver) -> list[OpenAIDataInjection]: + existing = resolver.existing_names() + injections: list[OpenAIDataInjection] = [] + + if tags := existing["tags"][:MAX_INJECTED_TAGS]: + injections.append( + OpenAIDataInjection( + description=( + "Below are the tags that already exist in the user's collection. Prefer these over " + "suggesting new ones, and return them exactly as they are written here." + ), + value=tags, + ) + ) + + if categories := existing["categories"]: + injections.append( + OpenAIDataInjection( + description=( + "Below are the categories that already exist in the user's collection. Prefer these " + "over suggesting new ones, and return them exactly as they are written here." + ), + value=categories, + ) + ) + + if tools := existing["tools"]: + injections.append( + OpenAIDataInjection( + description=( + "Below are the tools that already exist in the user's collection. Prefer these over " + "suggesting new ones, and return them exactly as they are written here." + ), + value=tools, + ) + ) + + return injections + + @staticmethod + def _build_message(ctx: WorkflowContext) -> str: + if ctx.compiled_source and ctx.compiled_source.content.strip(): + return truncate_source_content(ctx.compiled_source.content) + + recipe = ctx.draft_recipe + if not recipe: + return "" + + message_parts = [f"Name: {recipe.name}"] + if recipe.description: + message_parts.append(f"Description: {recipe.description}") + + if ingredients := [ingredient.note for ingredient in recipe.recipe_ingredient if ingredient.note]: + message_parts.append("Ingredients:\n" + "\n".join(ingredients)) + + if instructions := [step.text for step in recipe.recipe_instructions or [] if step.text]: + message_parts.append("Instructions:\n" + "\n".join(instructions)) + + return truncate_source_content("\n\n".join(message_parts)) + + def should_run(self, ctx: WorkflowContext) -> bool: + return ctx.options.resolve_organizers + + async def run(self, ctx: WorkflowContext) -> None: + recipe = ctx.draft_recipe + if not recipe: + return + + resolver = OrganizerResolver(ctx.repos) + create_missing = ctx.options.create_new_organizers + + existing = resolver.existing_names() + if ctx.options.attach_organizers and not (create_missing or any(existing.values())): + # nothing to match against and nothing may be created, so there's no work to do + return + + response = await ctx.ai.get_response( + ctx.ai.get_prompt(RESOLVE_ORGANIZERS_PROMPT, data_injections=self._build_injections(resolver)), + self._build_message(ctx), + response_schema=OpenAIOrganizers, + ) + + if not response: + return + + ctx.organizer_names = response + if not ctx.options.attach_organizers: + # the caller applies these itself + return + + recipe.tags = resolver.resolve_tags(response.tags, create_missing) + recipe.recipe_category = resolver.resolve_categories(response.categories, create_missing) + recipe.tools = resolver.resolve_tools(response.tools, create_missing) diff --git a/mealie/services/recipe/import_workflow/workflow.py b/mealie/services/recipe/import_workflow/workflow.py new file mode 100644 index 000000000..37eb6fff1 --- /dev/null +++ b/mealie/services/recipe/import_workflow/workflow.py @@ -0,0 +1,56 @@ +from mealie.core.root_logger import get_logger + +from .base import WorkflowStep +from .context import StepOutcome, WorkflowContext, WorkflowResult +from .steps import BuildRecipeStep, CompileSourceStep, ResolveOrganizersStep + +DEFAULT_WORKFLOW_STEPS: list[WorkflowStep] = [ + CompileSourceStep(), + BuildRecipeStep(), + ResolveOrganizersStep(), +] + + +class RecipeImportWorkflow: + """ + Turns arbitrary source material into a recipe by running a series of steps in order. + + Run by the `/recipes/create/ai` route and by `RecipeScraperOpenAI`, the fallback strategy for + `/recipes/create/url`. The other scraper strategies don't use it, so an ordinary URL import of + a well-marked-up site never runs the workflow at all. + + The workflow never persists the recipe; it returns a draft for the caller to save. + """ + + def __init__(self, steps: list[WorkflowStep] | None = None) -> None: + self.steps = DEFAULT_WORKFLOW_STEPS if steps is None else steps + self.logger = get_logger() + + async def run(self, ctx: WorkflowContext) -> WorkflowResult: + outcomes: dict[str, StepOutcome] = {} + + for step in self.steps: + if not step.should_run(ctx): + self.logger.debug(f"Skipping workflow step {step.name}") + outcomes[step.name] = StepOutcome.SKIPPED + continue + + if step.progress_key: + await ctx.report_progress(step.progress_key) + + try: + await step.run(ctx) + outcomes[step.name] = StepOutcome.COMPLETED + except Exception: + if step.required: + raise + + self.logger.exception(f"Optional workflow step {step.name} failed, continuing") + outcomes[step.name] = StepOutcome.FAILED + + self.logger.debug(f"Workflow finished: {', '.join(f'{name}={outcome}' for name, outcome in outcomes.items())}") + + if not ctx.draft_recipe: + raise ValueError("Workflow completed without producing a recipe") + + return WorkflowResult(recipe=ctx.draft_recipe, outcomes=outcomes) diff --git a/mealie/services/recipe/organizer_resolver.py b/mealie/services/recipe/organizer_resolver.py new file mode 100644 index 000000000..f3719b675 --- /dev/null +++ b/mealie/services/recipe/organizer_resolver.py @@ -0,0 +1,127 @@ +from collections.abc import Callable + +from pydantic import BaseModel +from slugify import slugify + +from mealie.repos.repository_factory import AllRepositories +from mealie.schema.recipe.recipe import RecipeCategory, RecipeTag, RecipeTool +from mealie.schema.recipe.recipe_category import CategorySave, TagSave +from mealie.schema.recipe.recipe_tool import RecipeToolSave +from mealie.schema.response.pagination import PaginationQuery +from mealie.services.matching import find_match + +ORGANIZER_FUZZY_MATCH_THRESHOLD = 90 +""" +Deliberately stricter than the ingredient parser's thresholds. Attaching the wrong organizer is +worse than missing one, and near-misses are common among organizer names ("Vegan"/"Vegetarian"). +""" + + +class OrganizerResolver: + """ + Turns organizer names into database entities, matching against the group's existing + organizers before creating anything new. + """ + + def __init__(self, repos: AllRepositories, fuzzy_match_threshold: int = ORGANIZER_FUZZY_MATCH_THRESHOLD) -> None: + self.repos = repos + self.fuzzy_match_threshold = fuzzy_match_threshold + + self._tags: dict[str, RecipeTag] | None = None + self._categories: dict[str, RecipeCategory] | None = None + self._tools: dict[str, RecipeTool] | None = None + + @staticmethod + def _normalize(name: str) -> str: + return slugify(name) + + def _load[T: BaseModel](self, repo, schema: type[T]) -> dict[str, T]: + query = PaginationQuery(page=1, per_page=-1) + items = repo.page_all(query).items + return {self._normalize(item.name): schema.model_validate(item, from_attributes=True) for item in items} + + @property + def tags(self) -> dict[str, RecipeTag]: + if self._tags is None: + self._tags = self._load(self.repos.tags, RecipeTag) + + return self._tags + + @property + def categories(self) -> dict[str, RecipeCategory]: + if self._categories is None: + self._categories = self._load(self.repos.categories, RecipeCategory) + + return self._categories + + @property + def tools(self) -> dict[str, RecipeTool]: + if self._tools is None: + self._tools = self._load(self.repos.tools, RecipeTool) + + return self._tools + + def existing_names(self) -> dict[str, list[str]]: + """The group's existing organizer names, for injecting into a prompt.""" + + return { + "tags": [tag.name for tag in self.tags.values()], + "categories": [category.name for category in self.categories.values()], + "tools": [tool.name for tool in self.tools.values()], + } + + def _resolve[T: BaseModel]( + self, + names: list[str], + store: dict[str, T], + create_missing: bool, + create: Callable[[str], T], + ) -> list[T]: + resolved: list[T] = [] + seen: set[str] = set() + + for name in names: + name = name.strip() + if not name: + continue + + normalized = self._normalize(name) + if not normalized or normalized in seen: + continue + + seen.add(normalized) + + match = find_match(normalized, store_map=store, fuzzy_match_threshold=self.fuzzy_match_threshold) + if match: + resolved.append(match) + continue + + if not create_missing: + continue + + created = create(name) + store[normalized] = created + resolved.append(created) + + return resolved + + def resolve_tags(self, names: list[str], create_missing: bool) -> list[RecipeTag]: + def create(name: str) -> RecipeTag: + saved = self.repos.tags.create(TagSave(name=name, group_id=self.repos.group_id)) + return RecipeTag.model_validate(saved, from_attributes=True) + + return self._resolve(names, self.tags, create_missing, create) + + def resolve_categories(self, names: list[str], create_missing: bool) -> list[RecipeCategory]: + def create(name: str) -> RecipeCategory: + saved = self.repos.categories.create(CategorySave(name=name, group_id=self.repos.group_id)) + return RecipeCategory.model_validate(saved, from_attributes=True) + + return self._resolve(names, self.categories, create_missing, create) + + def resolve_tools(self, names: list[str], create_missing: bool) -> list[RecipeTool]: + def create(name: str) -> RecipeTool: + saved = self.repos.tools.create(RecipeToolSave(name=name, group_id=self.repos.group_id)) + return RecipeTool.model_validate(saved, from_attributes=True) + + return self._resolve(names, self.tools, create_missing, create) diff --git a/mealie/services/recipe/recipe_service.py b/mealie/services/recipe/recipe_service.py index ae66d0b3b..aae740aed 100644 --- a/mealie/services/recipe/recipe_service.py +++ b/mealie/services/recipe/recipe_service.py @@ -1,5 +1,4 @@ import json -import os import shutil from datetime import UTC, datetime from pathlib import Path @@ -13,17 +12,14 @@ import sqlalchemy as sa from fastapi import UploadFile from mealie.core import exceptions -from mealie.core.dependencies.dependencies import get_temporary_path from mealie.lang.providers import Translator from mealie.pkgs import cache from mealie.repos.all_repositories import get_repositories from mealie.repos.repository_factory import AllRepositories from mealie.repos.repository_generic import RepositoryGeneric from mealie.schema.household.household import HouseholdInDB, HouseholdRecipeUpdate -from mealie.schema.openai.recipe import OpenAIRecipe from mealie.schema.recipe.recipe import CreateRecipe, Recipe, create_recipe_slug from mealie.schema.recipe.recipe_ingredient import RecipeIngredient -from mealie.schema.recipe.recipe_notes import RecipeNote from mealie.schema.recipe.recipe_settings import RecipeSettings from mealie.schema.recipe.recipe_step import RecipeStep from mealie.schema.recipe.recipe_timeline_events import RecipeTimelineEventCreate, TimelineEventType @@ -31,9 +27,7 @@ from mealie.schema.recipe.request_helpers import RecipeDuplicate from mealie.schema.user.user import PrivateUser, UserRatingCreate from mealie.services._base_service import BaseService from mealie.services.household_services.household_service import HouseholdService -from mealie.services.openai import OpenAILocalImage, OpenAIService from mealie.services.recipe.recipe_data_service import RecipeDataService -from mealie.services.scraper import cleaner from .template_service import TemplateService @@ -332,29 +326,6 @@ class RecipeService(RecipeServiceBase): return recipe - async def create_from_images(self, images: list[UploadFile], translate_language: str | None = None) -> Recipe: - openai_recipe_service = OpenAIRecipeService(self.repos, self.user, self.household, self.translator) - with get_temporary_path() as temp_path: - local_images: list[Path] = [] - for image in images: - safe_filename = Path(image.filename).name - image_path = temp_path.joinpath(safe_filename) - with image_path.open("wb") as buffer: - shutil.copyfileobj(image.file, buffer) - local_images.append(image_path) - - recipe_data = await openai_recipe_service.build_recipe_from_images( - local_images, translate_language=translate_language - ) - recipe_data = cleaner.clean(recipe_data, self.translator) - - recipe = self.create_one(recipe_data) - data_service = RecipeDataService(recipe.id) - - with open(local_images[0], "rb") as f: - data_service.write_image(f.read(), "webp") - return recipe - def duplicate_one(self, old_slug_or_id: str | UUID, dup_data: RecipeDuplicate) -> Recipe: """Duplicates a recipe and returns the new recipe.""" @@ -593,66 +564,3 @@ class RecipeService(RecipeServiceBase): def render_template(self, recipe: Recipe, temp_dir: Path, template: str) -> Path: t_service = TemplateService(temp_dir) return t_service.render(recipe, template) - - -class OpenAIRecipeService(RecipeServiceBase): - def _convert_recipe(self, openai_recipe: OpenAIRecipe) -> Recipe: - return Recipe( - user_id=self.user.id, - group_id=self.user.group_id, - household_id=self.household.id, - name=openai_recipe.name, - slug=create_recipe_slug(openai_recipe.name), - description=openai_recipe.description, - recipe_yield=openai_recipe.recipe_yield, - total_time=openai_recipe.total_time, - prep_time=openai_recipe.prep_time, - perform_time=openai_recipe.perform_time, - recipe_ingredient=[ - RecipeIngredient(title=ingredient.title, note=ingredient.text) - for ingredient in openai_recipe.ingredients - if ingredient.text - ], - recipe_instructions=[ - RecipeStep(title=instruction.title, text=instruction.text) - for instruction in openai_recipe.instructions - if instruction.text - ], - notes=[RecipeNote(title=note.title or "", text=note.text) for note in openai_recipe.notes if note.text], - ) - - async def build_recipe_from_images(self, images: list[Path], translate_language: str | None) -> Recipe: - openai_service = OpenAIService(self.repos) - if not (openai_service.provider_settings and openai_service.provider_settings.image_provider_enabled): - raise ValueError("OpenAI image services are not available") - - prompt = openai_service.get_prompt("recipes.parse-recipe-image") - - openai_images = [OpenAILocalImage(filename=os.path.basename(image), path=image) for image in images] - message = ( - f"Please extract the recipe from the {'images' if len(openai_images) > 1 else 'image'} provided." - "There should be exactly one recipe." - ) - - if translate_language: - message += f" Please translate the recipe to {translate_language}." - - try: - response = await openai_service.get_response( - prompt, - message, - response_schema=OpenAIRecipe, - attachments=openai_images, - ) - if not response: - raise ValueError("Received empty response from OpenAI") - - except Exception as e: - raise Exception("Failed to call OpenAI services") from e - - try: - recipe = self._convert_recipe(response) - except Exception as e: - raise ValueError("Unable to parse recipe from image") from e - - return recipe diff --git a/mealie/services/scraper/cleaner.py b/mealie/services/scraper/cleaner.py index 5d26eace5..8c087aafd 100644 --- a/mealie/services/scraper/cleaner.py +++ b/mealie/services/scraper/cleaner.py @@ -17,6 +17,9 @@ from mealie.services.parser_services.parser_utils import extract_quantity_from_s logger = get_logger("recipe-scraper") +NO_IMAGE = "no image" +"""Placeholder stored on a recipe that has no image. Not a URL, and must never be fetched.""" + MATCH_DIGITS = re.compile(r"\d+([.,]\d+)?") """ Allow for commas as decimals (common in Europe) """ @@ -47,9 +50,13 @@ def clean(recipe_data: Recipe | dict, translator: Translator, url=None) -> Recip dict: cleaned recipe dictionary """ if not isinstance(recipe_data, dict): - # format the recipe like a scraped dictionary + # format the recipe like a scraped dictionary. Ingredients are flattened to their display + # text, but keep their section titles, which are otherwise lost on the way through recipe_data_dict = recipe_data.model_dump(by_alias=True) - recipe_data_dict["recipeIngredient"] = [ing.display for ing in recipe_data.recipe_ingredient] + recipe_data_dict["recipeIngredient"] = [ + {"title": ing.title, "note": ing.display} if ing.title else {"note": ing.display} + for ing in recipe_data.recipe_ingredient + ] recipe_data = recipe_data_dict @@ -102,7 +109,7 @@ def clean_string(text: str | list | int | float) -> str: return cleaned_text -def clean_image(image: str | list | dict | None = None, default: str = "no image") -> list[str]: +def clean_image(image: str | list | dict | None = None, default: str = NO_IMAGE) -> list[str]: """ image attempts to parse the image field from a recipe and return a string. Currenty @@ -166,6 +173,7 @@ def clean_instructions(steps_object: list | dict | str, default: list | None = N # return [ {"text": _sanitize_instruction_text(instruction["text"])} + | ({"title": instruction["title"]} if instruction.get("title") else {}) for instruction in steps_object if "text" in instruction and instruction["text"].strip() ] diff --git a/mealie/services/scraper/fetch.py b/mealie/services/scraper/fetch.py new file mode 100644 index 000000000..4e04dad9a --- /dev/null +++ b/mealie/services/scraper/fetch.py @@ -0,0 +1,19 @@ +from mealie.pkgs import safehttp + +SCRAPER_TIMEOUT = safehttp.SCRAPER_TIMEOUT +BROWSER_IMPERSONATIONS = safehttp.BROWSER_IMPERSONATIONS +ForceTimeoutException = safehttp.ForceTimeoutException + + +async def safe_scrape_html(url: str) -> str: + """ + Scrapes the html from a url but will cancel the request + if the request takes longer than SCRAPER_TIMEOUT seconds. This is used to mitigate + DDOS attacks from users providing a url with arbitrary large content. + + Cycles through browser TLS impersonations (via httpx-curl-cffi) to bypass + bot-detection systems that fingerprint the TLS handshake (JA3/JA4), + such as Cloudflare. + """ + result = await safehttp.resilient_fetch(url) + return result.text if result else "" diff --git a/mealie/services/scraper/recipe_scraper.py b/mealie/services/scraper/recipe_scraper.py index 332d01c6b..adadeecac 100644 --- a/mealie/services/scraper/recipe_scraper.py +++ b/mealie/services/scraper/recipe_scraper.py @@ -48,11 +48,16 @@ class RecipeScraper: url: str, html: str | None = None, on_progress: Callable[[str], Awaitable[None]] | None = None, + include_tags: bool = False, + include_categories: bool = False, ) -> tuple[Recipe, ScrapedExtras] | tuple[None, None]: """ Scrapes a recipe from the web. Skips the network request if `html` is provided. Optionally reports progress back via `on_progress`. + + `include_tags` and `include_categories` tell strategies whether the caller intends to use + organizers, so that strategies which have to ask a provider for them can skip the request. """ if not html: @@ -64,7 +69,14 @@ class RecipeScraper: return None, None for ScraperClass in self.scrapers: - scraper = ScraperClass(url, self.translator, self.repos, raw_html=html) + scraper = ScraperClass( + url, + self.translator, + self.repos, + raw_html=html, + include_tags=include_tags, + include_categories=include_categories, + ) if not scraper.can_scrape(): self.logger.debug(f"Skipping {scraper.__class__.__name__}") continue diff --git a/mealie/services/scraper/scraped_extras.py b/mealie/services/scraper/scraped_extras.py index 2d3928694..dcab7d387 100644 --- a/mealie/services/scraper/scraped_extras.py +++ b/mealie/services/scraper/scraped_extras.py @@ -5,6 +5,7 @@ from slugify import slugify from mealie.repos.repository_factory import AllRepositories from mealie.schema.recipe import TagOut from mealie.schema.recipe.recipe_category import CategorySave, TagSave +from mealie.schema.recipe.recipe_tool import RecipeToolOut, RecipeToolSave class NoContextException(Exception): @@ -20,6 +21,7 @@ class ScrapedExtras: def __init__(self) -> None: self._tags: list[str] = [] self._categories: list[str] = [] + self._tools: list[str] = [] def set_tags(self, tags: list[str]) -> None: self._tags = tags @@ -27,6 +29,9 @@ class ScrapedExtras: def set_categories(self, categories: list[str]) -> None: self._categories = categories + def set_tools(self, tools: list[str]) -> None: + self._tools = tools + def use_tags(self, ctx: ScraperContext) -> list[TagOut]: if not self._tags: return [] @@ -80,3 +85,30 @@ class ScrapedExtras: categories.append(db_category) return categories + + def use_tools(self, ctx: ScraperContext) -> list[RecipeToolOut]: + if not self._tools: + return [] + + repo = ctx.repos.tools + + tools = [] + seen_tool_slugs: set[str] = set() + for tool in self._tools: + slugify_tool = slugify(tool) + if slugify_tool in seen_tool_slugs: + continue + + seen_tool_slugs.add(slugify_tool) + + # Check if tool exists + if db_tool := repo.get_one(slugify_tool, "slug"): + tools.append(db_tool) + continue + + save_data = RecipeToolSave(name=tool, group_id=ctx.repos.group_id) + db_tool = repo.create(save_data) + + tools.append(db_tool) + + return tools diff --git a/mealie/services/scraper/scraper.py b/mealie/services/scraper/scraper.py index cebce076f..2ebfa0f58 100644 --- a/mealie/services/scraper/scraper.py +++ b/mealie/services/scraper/scraper.py @@ -14,6 +14,7 @@ from mealie.schema.recipe.recipe import create_recipe_slug from mealie.services.recipe.recipe_data_service import RecipeDataService from mealie.services.scraper.scraped_extras import ScrapedExtras +from .cleaner import NO_IMAGE from .recipe_scraper import RecipeScraper @@ -29,6 +30,8 @@ async def create_from_html( translator: Translator, html: str | None = None, on_progress: Callable[[str], Awaitable[None]] | None = None, + include_tags: bool = False, + include_categories: bool = False, ) -> tuple[Recipe, ScrapedExtras | None]: """Main entry point for generating a recipe from a URL. Pass in a URL and a Recipe object will be returned if successful. Optionally pass in the HTML to skip fetching it. @@ -49,37 +52,58 @@ async def create_from_html( raise HTTPException(status.HTTP_400_BAD_REQUEST, {"details": ParserErrors.BAD_RECIPE_DATA.value}) url = extracted_url.group(0) - new_recipe, extras = await scraper.scrape(url, html, on_progress=on_progress) + new_recipe, extras = await scraper.scrape( + url, + html, + on_progress=on_progress, + include_tags=include_tags, + include_categories=include_categories, + ) if not new_recipe: raise HTTPException(status.HTTP_400_BAD_REQUEST, {"details": ParserErrors.BAD_RECIPE_DATA.value}) - new_recipe.id = uuid4() - logger = get_logger() - logger.debug(f"Image {new_recipe.image}") + new_recipe = await finalize_scraped_recipe(new_recipe, translator, on_progress=on_progress) + return new_recipe, extras - recipe_data_service = RecipeDataService(new_recipe.id) + +async def finalize_scraped_recipe( + recipe: Recipe, + translator: Translator, + on_progress: Callable[[str], Awaitable[None]] | None = None, +) -> Recipe: + """Assigns an id to a freshly scraped recipe, downloads its image, and guarantees it has a name and slug. + + The recipe is not persisted; that's up to the caller. + """ + + recipe.id = uuid4() + logger = get_logger() + logger.debug(f"Image {recipe.image}") + + recipe_data_service = RecipeDataService(recipe.id) try: - if new_recipe.image: - if isinstance(new_recipe.image, list): - new_recipe.image = new_recipe.image[0] + if isinstance(recipe.image, list): + recipe.image = recipe.image[0] if recipe.image else None + # NO_IMAGE is a placeholder rather than a URL, so there's nothing to download for it + if recipe.image and recipe.image != NO_IMAGE: if on_progress: await on_progress(translator.t("recipe.create-progress.downloading-image")) - await recipe_data_service.scrape_image(new_recipe.image) # type: ignore + await recipe_data_service.scrape_image(recipe.image) # type: ignore - if new_recipe.name is None: - new_recipe.name = "Untitled" + if recipe.name is None: + recipe.name = "Untitled" - new_recipe.slug = create_recipe_slug(new_recipe.name) - new_recipe.image = cache.new_key(4) + recipe.slug = create_recipe_slug(recipe.name) + recipe.image = cache.new_key(4) except Exception as e: recipe_data_service.logger.exception(f"Error Scraping Image: {e}") - new_recipe.image = "no image" + recipe.image = NO_IMAGE - if new_recipe.name is None or new_recipe.name == "": - new_recipe.name = f"No Recipe Name Found - {uuid4()!s}" - new_recipe.slug = create_recipe_slug(new_recipe.name) + if recipe.name is None or recipe.name == "": + recipe.name = f"No Recipe Name Found - {uuid4()!s}" + recipe.slug = create_recipe_slug(recipe.name) - return new_recipe, extras + return recipe diff --git a/mealie/services/scraper/scraper_strategies.py b/mealie/services/scraper/scraper_strategies.py index 0d6fd7404..5216388f1 100644 --- a/mealie/services/scraper/scraper_strategies.py +++ b/mealie/services/scraper/scraper_strategies.py @@ -1,64 +1,46 @@ import asyncio -import functools -import re from abc import ABC, abstractmethod from collections.abc import Awaitable, Callable -from pathlib import Path -from typing import Any, TypedDict +from typing import Any -import bs4 import extruct -import yt_dlp from fastapi import HTTPException, status from recipe_scrapers import NoSchemaFoundInWildMode, SchemaScraperFactory, scrape_html from slugify import slugify from w3lib.html import get_base_url -from yt_dlp.extractor.generic import GenericIE from mealie.core import exceptions from mealie.core.dependencies.dependencies import get_temporary_path from mealie.core.root_logger import get_logger from mealie.lang.providers import Translator -from mealie.pkgs import safehttp from mealie.repos.repository_factory import AllRepositories -from mealie.schema.openai.general import OpenAIText from mealie.schema.openai.recipe import OpenAIRecipe from mealie.schema.recipe.recipe import Recipe, RecipeStep from mealie.schema.recipe.recipe_ingredient import RecipeIngredient from mealie.schema.recipe.recipe_notes import RecipeNote -from mealie.services.openai import OpenAIService +from mealie.services.openai import OpenAIService, transcription +from mealie.services.recipe.import_workflow import ( + RecipeImportWorkflow, + WorkflowContext, + WorkflowInput, + WorkflowOptions, +) from mealie.services.scraper.scraped_extras import ScrapedExtras from . import cleaner # Re-exported for backwards compatibility with existing importers (e.g. recipe route error handling). -SCRAPER_TIMEOUT = safehttp.SCRAPER_TIMEOUT -BROWSER_IMPERSONATIONS = safehttp.BROWSER_IMPERSONATIONS -ForceTimeoutException = safehttp.ForceTimeoutException +# safe_scrape_html lives in `fetch` so the import workflow can fetch pages without importing this module. +from .fetch import ( # noqa: F401 + BROWSER_IMPERSONATIONS, + SCRAPER_TIMEOUT, + ForceTimeoutException, + safe_scrape_html, +) logger = get_logger() -@functools.cache -def _get_yt_dlp_extractors() -> list: - """Build and cache the yt-dlp extractor list once per process lifetime.""" - return [ie for ie in yt_dlp.extractor.gen_extractors() if ie.working() and not isinstance(ie, GenericIE)] - - -async def safe_scrape_html(url: str) -> str: - """ - Scrapes the html from a url but will cancel the request - if the request takes longer than SCRAPER_TIMEOUT seconds. This is used to mitigate - DDOS attacks from users providing a url with arbitrary large content. - - Cycles through browser TLS impersonations (via httpx-curl-cffi) to bypass - bot-detection systems that fingerprint the TLS handshake (JA3/JA4), - such as Cloudflare. - """ - result = await safehttp.resilient_fetch(url) - return result.text if result else "" - - class ABCScraperStrategy(ABC): """ Abstract class for all recipe parsers. @@ -72,6 +54,8 @@ class ABCScraperStrategy(ABC): translator: Translator, repos: AllRepositories, raw_html: str | None = None, + include_tags: bool = False, + include_categories: bool = False, ) -> None: self.logger = get_logger() self.url = url @@ -79,6 +63,11 @@ class ABCScraperStrategy(ABC): self.translator = translator self.repos = repos + # only used by strategies that have to ask for organizers, rather than reading them + # out of the page's structured data + self.include_tags = include_tags + self.include_categories = include_categories + @abstractmethod def can_scrape(self) -> bool: ... @@ -264,109 +253,49 @@ class RecipeScraperPackage(ABCScraperStrategy): return self.clean_scraper(scraped_data, self.url) -class RecipeScraperOpenAI(RecipeScraperPackage): +class RecipeScraperOpenAI(ABCScraperStrategy): """ - A wrapper around the `RecipeScraperPackage` class that uses OpenAI to extract the recipe from the URL, - rather than trying to scrape it directly. + Extracts a recipe from a URL using AI, by running the recipe import workflow over the + page's contents rather than trying to scrape it directly. """ def can_scrape(self) -> bool: settings = self.repos.group_ai_provider_settings.get_one(self.repos.group_id) - return bool(settings and settings.ai_enabled and super().can_scrape()) - - def extract_json_ld_data_from_html(self, soup: bs4.BeautifulSoup) -> str: - data_parts: list[str] = [] - for script in soup.find_all("script", type="application/ld+json"): - try: - script_data = script.string - if script_data: - data_parts.append(str(script_data)) - except AttributeError: - pass - - return "\n\n".join(data_parts) - - def find_image(self, soup: bs4.BeautifulSoup) -> str | None: - # find the open graph image tag - og_image = soup.find("meta", property="og:image") - if og_image and og_image.get("content"): - return og_image["content"] - - # find the largest image on the page - largest_img = None - max_size = 0 - for img in soup.find_all("img"): - width = img.get("width", 0) - height = img.get("height", 0) - if not width or not height: - continue - - try: - size = int(width) * int(height) - except (ValueError, TypeError): - size = 1 - if size > max_size: - max_size = size - largest_img = img - - if largest_img: - return largest_img.get("src") - - return None - - def format_html_to_text(self, html: str) -> str: - soup = bs4.BeautifulSoup(html, "lxml") - - text = soup.get_text(separator="\n", strip=True) - text += self.extract_json_ld_data_from_html(soup) - if not text: - raise Exception("No text or ld+json data found in HTML") - - try: - image = self.find_image(soup) - except Exception: - image = None - - components = [f"Convert this content to JSON: {text}"] - if image: - components.append(f"Recipe Image: {image}") - return "\n".join(components) + return bool(settings and settings.ai_enabled and (self.url or self.raw_html)) async def get_html(self, url: str) -> str: - service = OpenAIService(self.repos) - html = self.raw_html or await safe_scrape_html(url) - text = self.format_html_to_text(html) - try: - prompt = service.get_prompt("recipes.scrape-recipe") + # required by the base class, but unused: the workflow fetches the page itself + return self.raw_html or await safe_scrape_html(url) - response = await service.get_response(prompt, text, response_schema=OpenAIText) - if not (response and response.text): - raise Exception("OpenAI did not return any data") - - return self.ld_json_to_html(response.text) - except Exception: - self.logger.exception(f"OpenAI was unable to extract a recipe from {url}") - return "" + def build_context(self, on_progress: Callable[[str], Awaitable[None]] | None = None) -> WorkflowContext: + return WorkflowContext( + input=WorkflowInput(content=self.raw_html, url=self.url), + options=WorkflowOptions( + # organizers are only worth asking for if the caller intends to use them, and + # they're reported back through ScrapedExtras so the caller stays in control + resolve_organizers=self.include_tags or self.include_categories, + attach_organizers=False, + ), + repos=self.repos, + translator=self.translator, + ai=OpenAIService(self.repos), + on_progress=on_progress, + ) async def parse(self, on_progress: Callable[[str], Awaitable[None]] | None = None): - if on_progress: - await on_progress(self.translator.t("recipe.create-progress.creating-recipe-with-ai")) + ctx = self.build_context(on_progress) + result = await RecipeImportWorkflow().run(ctx) - return await super().parse() + extras = ScrapedExtras() + if ctx.organizer_names: + # normalized the same way as organizers read out of a page's structured data + extras.set_tags(cleaner.clean_tags(ctx.organizer_names.tags)) + extras.set_categories(cleaner.clean_categories(ctx.organizer_names.categories)) - -class TranscribedAudio(TypedDict): - audio: Path - subtitle: Path | None - title: str - description: str - thumbnail_url: str | None - transcription: str + return result.recipe, extras class RecipeScraperOpenAITranscription(ABCScraperStrategy): - SUBTITLE_LANGS = ["en", "fr", "es", "de", "it"] - def can_scrape(self) -> bool: if not self.url: return False @@ -376,72 +305,7 @@ class RecipeScraperOpenAITranscription(ABCScraperStrategy): return False # Check if we can actually download something to transcribe - return any(ie.suitable(self.url) for ie in _get_yt_dlp_extractors()) - - @staticmethod - def _parse_subtitle_content(subtitle_content: str) -> str: - # TODO: is there a better way to parse subtitles that's more efficient? - - lines = [] - for line in subtitle_content.split("\n"): - if line.strip() and not line.startswith("WEBVTT") and "-->" not in line and not line.isdigit(): - lines.append(line.strip()) - - raw_content = " ".join(lines) - content = re.sub(r"<[^>]+>", "", raw_content) - return content - - def _download_audio(self, temp_path: Path) -> TranscribedAudio: - """Downloads audio and subtitles from the video URL.""" - output_template = temp_path / "mealie" # No extension here - - ydl_opts = { - "format": "bestaudio/best", - "outtmpl": str(output_template) + ".%(ext)s", - "quiet": True, - "writesubtitles": True, - "writeautomaticsub": True, - "subtitleslangs": self.SUBTITLE_LANGS, - "skip_download": False, - "ignoreerrors": True, - "postprocessors": [ - { - "key": "FFmpegExtractAudio", - "preferredcodec": "mp3", - "preferredquality": "32", - } - ], - "postprocessor_args": ["-ac", "1"], - } - - try: - with yt_dlp.YoutubeDL(ydl_opts) as ydl: - info = ydl.extract_info(self.url, download=True) - - if info is None: - raise exceptions.VideoDownloadError( - "Failed to extract video information. The video may be unavailable or the URL is invalid." - ) - - sub_path = None - for lang in self.SUBTITLE_LANGS: - potential_path = output_template.with_suffix(f".{lang}.vtt") - if potential_path.exists(): - sub_path = potential_path - break - - return { - "audio": output_template.with_suffix(".mp3"), - "subtitle": sub_path, - "title": info.get("title", ""), - "description": info.get("description", ""), - "thumbnail_url": info.get("thumbnail") or None, - "transcription": "", - } - except exceptions.VideoDownloadError: - raise - except Exception as e: - raise exceptions.VideoDownloadError(f"Failed to download video: {e}") from e + return transcription.is_video_url(self.url) async def get_html(self, url: str) -> str: return self.raw_html or "" # we don't use HTML with this scraper since we use ytdlp @@ -456,31 +320,15 @@ class RecipeScraperOpenAITranscription(ABCScraperStrategy): if on_progress: await on_progress(self.translator.t("recipe.create-progress.downloading-video")) - video_data = await asyncio.to_thread(self._download_audio, temp_path) + video_data = await asyncio.to_thread(transcription.download_video, self.url, temp_path) - if video_data["subtitle"]: - try: - with open(video_data["subtitle"], encoding="utf-8") as f: - subtitle_content = f.read() - video_data["transcription"] = self._parse_subtitle_content(subtitle_content) - self.logger.info("Using subtitles from video instead of transcription") - except Exception: - self.logger.exception("Failed to read subtitles, falling back to transcription") - video_data["transcription"] = "" - - if not video_data["transcription"]: + async def report_transcribing() -> None: if on_progress: await on_progress(self.translator.t("recipe.create-progress.transcribing-audio-with-ai")) - try: - transcription = await openai_service.transcribe_audio(video_data["audio"]) - except exceptions.RateLimitError: - raise - except Exception as e: - raise exceptions.OpenAIServiceError(f"Failed to transcribe audio: {e}") from e - if not transcription: - raise exceptions.OpenAIServiceError("No transcription returned from OpenAI") - video_data["transcription"] = transcription + video_data["transcription"] = await transcription.resolve_transcription( + video_data, openai_service, before_transcribe=report_transcribing + ) if not video_data["transcription"]: self.logger.error("Could not extract a transcript (no data)") diff --git a/tests/integration_tests/test_validators.py b/tests/integration_tests/test_validators.py index 6858d29fc..6dddf220e 100644 --- a/tests/integration_tests/test_validators.py +++ b/tests/integration_tests/test_validators.py @@ -4,9 +4,16 @@ from uuid import UUID from fastapi.testclient import TestClient from mealie.schema.recipe.recipe import Recipe -from tests.utils import api_routes, random_string +from tests.utils import random_string from tests.utils.fixture_schemas import TestUser +# The validators router is hidden from the OpenAPI schema, so these aren't in the generated +# api_routes helpers. +VALIDATORS_USER_NAME = "/api/validators/user/name" +VALIDATORS_USER_EMAIL = "/api/validators/user/email" +VALIDATORS_GROUP = "/api/validators/group" +VALIDATORS_RECIPE = "/api/validators/recipe" + @dataclass() class SimpleCase: @@ -21,7 +28,7 @@ def test_validators_username(api_client: TestClient, unique_user: TestUser): ] for user in users: - response = api_client.get(api_routes.validators_user_name + "?name=" + user.value) + response = api_client.get(VALIDATORS_USER_NAME + "?name=" + user.value) assert response.status_code == 200 response_data = response.json() assert response_data["valid"] == user.is_valid @@ -34,7 +41,7 @@ def test_validators_email(api_client: TestClient, unique_user: TestUser): ] for user in emails: - response = api_client.get(api_routes.validators_user_email + "?email=" + user.value) + response = api_client.get(VALIDATORS_USER_EMAIL + "?email=" + user.value) assert response.status_code == 200 response_data = response.json() assert response_data["valid"] == user.is_valid @@ -51,7 +58,7 @@ def test_validators_group_name(api_client: TestClient, unique_user: TestUser): ] for user in groups: - response = api_client.get(api_routes.validators_group + "?name=" + user.value) + response = api_client.get(VALIDATORS_GROUP + "?name=" + user.value) assert response.status_code == 200 response_data = response.json() assert response_data["valid"] == user.is_valid @@ -72,7 +79,7 @@ def test_validators_recipe(api_client: TestClient, random_recipe: Recipe): ] for recipe in recipes: - response = api_client.get(api_routes.validators_recipe + f"?group_id={recipe.group}&name={recipe.name}") + response = api_client.get(VALIDATORS_RECIPE + f"?group_id={recipe.group}&name={recipe.name}") assert response.status_code == 200 response_data = response.json() assert response_data["valid"] == recipe.is_valid diff --git a/tests/integration_tests/user_recipe_tests/test_recipe_create_from_ai.py b/tests/integration_tests/user_recipe_tests/test_recipe_create_from_ai.py new file mode 100644 index 000000000..1d6006d5d --- /dev/null +++ b/tests/integration_tests/user_recipe_tests/test_recipe_create_from_ai.py @@ -0,0 +1,709 @@ +import json +from collections.abc import Generator +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient +from slugify import slugify + +import mealie.services.openai.transcription as transcription_module +import mealie.services.recipe.import_workflow.steps.compile_source as compile_source_module +from mealie.core import exceptions +from mealie.schema.group.ai_providers import AIProviderCreate, AIProviderSettingsUpdate +from mealie.schema.openai.compiled_source import OpenAICompiledSource +from mealie.schema.openai.organizers import OpenAIOrganizers +from mealie.schema.openai.recipe import ( + OpenAIRecipe, + OpenAIRecipeIngredient, + OpenAIRecipeInstruction, + OpenAIRecipeNotes, + OpenAIRecipeNutrition, +) +from mealie.schema.recipe.recipe_category import TagSave +from mealie.services.openai import OpenAIService +from mealie.services.recipe.organizer_resolver import OrganizerResolver +from mealie.services.recipe.recipe_data_service import RecipeDataService +from mealie.services.scraper.cleaner import NO_IMAGE +from tests.utils import api_routes +from tests.utils.factories import random_string +from tests.utils.fixture_schemas import TestUser +from tests.utils.helpers import parse_sse_events + +VIDEO_URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" + + +@pytest.fixture(autouse=True) +def ai_providers(unique_user: TestUser) -> Generator[None, None, None]: + """Enable both the default and image providers, restoring the original settings afterwards.""" + + provider = unique_user.repos.group_ai_providers.create( + AIProviderCreate(name=random_string(), model="gpt-4o", api_key="test-key") + ) + unique_user.repos.group_ai_provider_settings.update( + unique_user.repos.group_id, + AIProviderSettingsUpdate( + default_provider_id=provider.id, + audio_provider_id=provider.id, + image_provider_id=provider.id, + ), + ) + + yield + + unique_user.repos.group_ai_provider_settings.update( + unique_user.repos.group_id, + AIProviderSettingsUpdate(default_provider_id=None, audio_provider_id=None, image_provider_id=None), + ) + + +@pytest.fixture(autouse=True) +def no_image_downloads(monkeypatch: pytest.MonkeyPatch): + async def mock_scrape_image(*_, **__) -> str: + return "TEST_IMAGE" + + monkeypatch.setattr(RecipeDataService, "scrape_image", mock_scrape_image) + + +@pytest.fixture() +def recipe_name() -> str: + return random_string() + + +@pytest.fixture() +def openai_recipe(recipe_name: str) -> OpenAIRecipe: + return OpenAIRecipe( + name=recipe_name, + description=random_string(), + recipe_yield="4 servings", + total_time="1 hour", + ingredients=[ + OpenAIRecipeIngredient(title="For the sauce", text=random_string()), + OpenAIRecipeIngredient(text=random_string()), + ], + instructions=[ + OpenAIRecipeInstruction(title="Prep", text=random_string()), + OpenAIRecipeInstruction(text=random_string()), + ], + notes=[OpenAIRecipeNotes(text=random_string())], + nutrition=OpenAIRecipeNutrition(calories="250", protein_content="12 g"), + ) + + +class AIResponses: + """Stands in for the AI provider, recording which response schemas were asked for.""" + + def __init__( + self, + recipe: OpenAIRecipe | None = None, + compiled: OpenAICompiledSource | None = None, + organizers: OpenAIOrganizers | None = None, + ) -> None: + self.recipe = recipe + self.compiled = compiled or OpenAICompiledSource( + contains_recipe=True, content=random_string(), language=None, image_url=None + ) + self.organizers = organizers + self.requested_schemas: list[str] = [] + self.prompts: list[str] = [] + + def install(self, monkeypatch: pytest.MonkeyPatch) -> "AIResponses": + responses = self + + async def mock_get_response(self, prompt, message, *args, response_schema=None, **kwargs): + responses.requested_schemas.append(response_schema.__name__) + responses.prompts.append(prompt) + + if response_schema is OpenAICompiledSource: + return responses.compiled + if response_schema is OpenAIRecipe: + return responses.recipe + if response_schema is OpenAIOrganizers: + return responses.organizers + + return None + + monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) + return self + + +def post_ai(api_client: TestClient, user: TestUser, data: dict | None = None, files: list | None = None): + return api_client.post( + api_routes.recipes_create_ai, + data=data or {}, + files=files, + headers=user.token, + ) + + +def test_create_from_content( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + recipe_name: str, +): + ai = AIResponses(recipe=openai_recipe).install(monkeypatch) + + r = post_ai(api_client, unique_user, {"content": "Grandma's pancakes\n2 cups flour\nMix and fry."}) + assert r.status_code == 201 + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + assert recipe["name"] == recipe_name + + # plain text is compiled without an AI call, so only the build step should hit the provider + assert "OpenAICompiledSource" not in ai.requested_schemas + + +def test_create_from_ld_json_skips_the_compile_call( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + ai = AIResponses(recipe=openai_recipe).install(monkeypatch) + + ld_json = json.dumps( + { + "@context": "https://schema.org", + "@type": "Recipe", + "name": random_string(), + "recipeIngredient": [random_string()], + } + ) + + r = post_ai(api_client, unique_user, {"content": ld_json}) + assert r.status_code == 201 + assert "OpenAICompiledSource" not in ai.requested_schemas + + +def test_create_from_images( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + test_image_jpg: str, +): + ai = AIResponses(recipe=openai_recipe).install(monkeypatch) + + with open(test_image_jpg, "rb") as f: + r = post_ai(api_client, unique_user, files=[("images", ("recipe.jpg", f, "image/jpeg"))]) + + assert r.status_code == 201 + slug = json.loads(r.text) + + # images have to be read by the provider, so both steps make a call + assert ai.requested_schemas[:2] == ["OpenAICompiledSource", "OpenAIRecipe"] + + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + r = api_client.get( + api_routes.media_recipes_recipe_id_images_file_name(recipe["id"], "original.webp"), + headers=unique_user.token, + ) + assert r.status_code == 200 + + +def test_create_from_content_and_images( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + test_image_jpg: str, +): + ai = AIResponses(recipe=openai_recipe).install(monkeypatch) + + with open(test_image_jpg, "rb") as f: + r = post_ai( + api_client, + unique_user, + data={"content": random_string()}, + files=[("images", ("recipe.jpg", f, "image/jpeg"))], + ) + + assert r.status_code == 201 + assert ai.requested_schemas[:2] == ["OpenAICompiledSource", "OpenAIRecipe"] + + +def test_create_from_url( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + recipe_name: str, +): + AIResponses(recipe=openai_recipe).install(monkeypatch) + + url = f"https://example.com/recipe/{random_string()}" + ld_json = json.dumps({"@context": "https://schema.org", "@type": "Recipe", "name": random_string()}) + html = f'Recipe' + + async def mock_safe_scrape_html(_: str) -> str: + return html + + monkeypatch.setattr(compile_source_module, "safe_scrape_html", mock_safe_scrape_html) + + r = post_ai(api_client, unique_user, {"url": url}) + assert r.status_code == 201 + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + assert recipe["name"] == recipe_name + assert recipe["orgURL"] == url + + +def test_create_from_video_url( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + recipe_name: str, +): + ai = AIResponses(recipe=openai_recipe).install(monkeypatch) + + def mock_download_video(url: str, temp_path: Path): + return { + "audio": temp_path / "mealie.mp3", + "subtitle": None, + "title": random_string(), + "description": random_string(), + "thumbnail_url": "https://example.com/thumbnail.jpg", + "transcription": random_string(), + } + + async def fail_if_fetched(_: str) -> str: + raise AssertionError("a video URL should be downloaded, not fetched as a webpage") + + monkeypatch.setattr(transcription_module, "download_video", mock_download_video) + monkeypatch.setattr(compile_source_module, "safe_scrape_html", fail_if_fetched) + + r = post_ai(api_client, unique_user, {"url": VIDEO_URL}) + assert r.status_code == 201 + + # the transcript is already a faithful record, so only the build step hits the provider + assert "OpenAICompiledSource" not in ai.requested_schemas + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + assert recipe["name"] == recipe_name + assert recipe["orgURL"] == VIDEO_URL + + +def test_create_from_video_url_keeps_accompanying_text( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + """Text pasted alongside a video link is often the ingredient list, so it must survive.""" + + transcript = random_string() + pasted_text = random_string() + messages: list[str] = [] + + async def mock_get_response(self, prompt, message, *args, response_schema=None, **kwargs): + messages.append(message) + return openai_recipe if response_schema is OpenAIRecipe else None + + def mock_download_video(url: str, temp_path: Path): + return { + "audio": temp_path / "mealie.mp3", + "subtitle": None, + "title": random_string(), + "description": random_string(), + "thumbnail_url": None, + "transcription": transcript, + } + + monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) + monkeypatch.setattr(transcription_module, "download_video", mock_download_video) + + r = post_ai(api_client, unique_user, {"url": VIDEO_URL, "content": pasted_text}) + assert r.status_code == 201 + + build_message = messages[0] + assert transcript in build_message + assert pasted_text in build_message + + +def test_create_from_url_ignores_the_page_when_content_is_pasted( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + """Pasted content wins over the URL, which is still recorded as the recipe's source.""" + + AIResponses(recipe=openai_recipe).install(monkeypatch) + + async def fail_if_fetched(_: str) -> str: + raise AssertionError("the page should not be fetched when content is provided") + + monkeypatch.setattr(compile_source_module, "safe_scrape_html", fail_if_fetched) + + url = f"https://example.com/recipe/{random_string()}" + r = post_ai(api_client, unique_user, {"url": url, "content": random_string()}) + assert r.status_code == 201 + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + assert recipe["orgURL"] == url + + +def test_create_from_video_url_without_audio_provider_falls_back_to_fetching( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + settings = unique_user.repos.group_ai_provider_settings.get_one(unique_user.repos.group_id) + assert settings + unique_user.repos.group_ai_provider_settings.update( + unique_user.repos.group_id, + AIProviderSettingsUpdate( + default_provider_id=settings.default_provider_id, + audio_provider_id=None, + image_provider_id=settings.image_provider_id, + ), + ) + + AIResponses(recipe=openai_recipe).install(monkeypatch) + + fetched: list[str] = [] + + async def mock_safe_scrape_html(url: str) -> str: + fetched.append(url) + return f"{random_string()}" + + monkeypatch.setattr(compile_source_module, "safe_scrape_html", mock_safe_scrape_html) + + r = post_ai(api_client, unique_user, {"url": VIDEO_URL}) + assert r.status_code == 201 + assert fetched == [VIDEO_URL] + + +def test_organizers_are_skipped_when_there_is_nothing_to_do( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + """With no existing organizers and creation switched off, the step can't do anything.""" + + assert not any(OrganizerResolver(unique_user.repos).existing_names().values()), ( + "this test needs a group that has no organizers yet" + ) + + ai = AIResponses(recipe=openai_recipe, organizers=OpenAIOrganizers(tags=[random_string()])).install(monkeypatch) + + r = post_ai(api_client, unique_user, {"content": random_string()}) + assert r.status_code == 201 + assert "OpenAIOrganizers" not in ai.requested_schemas + + +def test_existing_organizers_are_attached_without_creating_new_ones( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + existing_tag = unique_user.repos.tags.create(TagSave(name=random_string(), group_id=unique_user.repos.group_id)) + + new_name = random_string() + organizers = OpenAIOrganizers(tags=[existing_tag.name, new_name], categories=[new_name], tools=[new_name]) + ai = AIResponses(recipe=openai_recipe, organizers=organizers).install(monkeypatch) + + r = post_ai(api_client, unique_user, {"content": random_string()}) + assert r.status_code == 201 + assert "OpenAIOrganizers" in ai.requested_schemas + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + + # the existing tag is attached, and the unmatched names are dropped rather than created + assert [tag["name"] for tag in recipe["tags"]] == [existing_tag.name] + assert recipe["recipeCategory"] == [] + assert recipe["tools"] == [] + assert not unique_user.repos.tags.get_one(slugify(new_name), "slug") + + +def test_new_organizers_are_created_when_requested( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + tag_name = random_string() + category_name = random_string() + tool_name = random_string() + + organizers = OpenAIOrganizers(tags=[tag_name], categories=[category_name], tools=[tool_name]) + AIResponses(recipe=openai_recipe, organizers=organizers).install(monkeypatch) + + r = post_ai(api_client, unique_user, {"content": random_string(), "createNewOrganizers": "true"}) + assert r.status_code == 201 + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + + assert [tag["name"] for tag in recipe["tags"]] == [tag_name] + assert [category["name"] for category in recipe["recipeCategory"]] == [category_name] + assert [tool["name"] for tool in recipe["tools"]] == [tool_name] + + +def test_organizers_are_resolved_from_the_source_not_the_built_recipe( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + """ + Keywords live in the source, and the recipe schema has no field for them, so the organizer + step has to read the compiled source or they're gone by the time it runs. + """ + + keyword_line = f"tags: {random_string()}, {random_string()}" + content = f"awesome recipe\neggs, chicken, broth\nscramble the eggs\n{keyword_line}" + + messages: list[str] = [] + + async def mock_get_response(self, prompt, message, *args, response_schema=None, **kwargs): + messages.append(message) + if response_schema is OpenAIRecipe: + return openai_recipe + if response_schema is OpenAIOrganizers: + return OpenAIOrganizers() + + return None + + monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) + + r = post_ai(api_client, unique_user, {"content": content, "createNewOrganizers": "true"}) + assert r.status_code == 201 + + # the last call is the organizer step; it must still be able to see the keywords + assert keyword_line in messages[-1] + + +def test_existing_organizers_are_offered_to_the_provider( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + existing_tag = unique_user.repos.tags.create(TagSave(name=random_string(), group_id=unique_user.repos.group_id)) + + ai = AIResponses(recipe=openai_recipe, organizers=OpenAIOrganizers()).install(monkeypatch) + + r = post_ai(api_client, unique_user, {"content": random_string()}) + assert r.status_code == 201 + + organizer_prompt = ai.prompts[ai.requested_schemas.index("OpenAIOrganizers")] + assert existing_tag.name in organizer_prompt + + +def test_organizer_failures_do_not_lose_the_recipe( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + recipe_name: str, +): + """The organizer step is optional, so a failure should be logged and skipped.""" + + async def mock_get_response(self, prompt, message, *args, response_schema=None, **kwargs): + if response_schema is OpenAIOrganizers: + raise Exception("organizer resolution blew up") + + return openai_recipe if response_schema is OpenAIRecipe else None + + monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) + + r = post_ai(api_client, unique_user, {"content": random_string(), "createNewOrganizers": "true"}) + assert r.status_code == 201 + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + assert recipe["name"] == recipe_name + + +def test_create_does_not_download_the_no_image_placeholder( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + """cleaner.clean stores "no image" when a recipe has none; it is not a URL.""" + + AIResponses(recipe=openai_recipe).install(monkeypatch) + + async def fail_if_called(*_, **__) -> str: + raise AssertionError("the no-image placeholder should never be fetched") + + monkeypatch.setattr(RecipeDataService, "scrape_image", fail_if_called) + + r = post_ai(api_client, unique_user, {"content": random_string()}) + assert r.status_code == 201 + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + assert recipe["image"] != NO_IMAGE + + +def test_create_surfaces_rate_limit_errors( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, +): + async def mock_get_response(self, prompt, message, *args, **kwargs): + raise exceptions.RateLimitError("429 too many requests") + + monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) + + r = post_ai(api_client, unique_user, {"content": random_string()}) + assert r.status_code == 400 + assert "rate limiting" in r.text + + +def test_create_preserves_sections_and_nutrition( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + AIResponses(recipe=openai_recipe).install(monkeypatch) + + r = post_ai(api_client, unique_user, {"content": random_string()}) + assert r.status_code == 201 + + slug = json.loads(r.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + + # untitled entries fall back to each schema's own default: None for ingredients, "" for steps + assert [i["title"] for i in recipe["recipeIngredient"]] == ["For the sauce", None] + assert [i["title"] for i in recipe["recipeInstructions"]] == ["Prep", ""] + assert recipe["nutrition"]["calories"] == "250" + assert recipe["nutrition"]["proteinContent"] == "12" + + +def test_create_translates_when_requested( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, +): + messages: list[str] = [] + + async def mock_get_response(self, prompt, message, *args, response_schema=None, **kwargs): + messages.append(message) + return openai_recipe if response_schema is OpenAIRecipe else None + + monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) + + r = post_ai(api_client, unique_user, {"content": random_string(), "translateLanguage": "French"}) + assert r.status_code == 201 + assert any("French" in message for message in messages) + + +def test_create_with_no_source_is_rejected(api_client: TestClient, unique_user: TestUser): + r = post_ai(api_client, unique_user, {}) + assert r.status_code == 400 + + +def test_create_when_source_has_no_recipe( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + test_image_jpg: str, +): + compiled = OpenAICompiledSource(contains_recipe=False, content="", language=None, image_url=None) + AIResponses(compiled=compiled).install(monkeypatch) + + with open(test_image_jpg, "rb") as f: + r = post_ai(api_client, unique_user, files=[("images", ("not-a-recipe.jpg", f, "image/jpeg"))]) + + assert r.status_code == 400 + + +def test_create_when_provider_returns_nothing( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, +): + AIResponses(recipe=None).install(monkeypatch) + + r = post_ai(api_client, unique_user, {"content": random_string()}) + assert r.status_code == 400 + + +def test_create_with_ai_disabled(api_client: TestClient, unique_user: TestUser): + unique_user.repos.group_ai_provider_settings.update( + unique_user.repos.group_id, + AIProviderSettingsUpdate(default_provider_id=None, audio_provider_id=None, image_provider_id=None), + ) + + r = post_ai(api_client, unique_user, {"content": random_string()}) + assert r.status_code == 400 + + +def test_create_with_images_but_no_image_provider( + api_client: TestClient, + unique_user: TestUser, + test_image_jpg: str, +): + settings = unique_user.repos.group_ai_provider_settings.get_one(unique_user.repos.group_id) + assert settings + unique_user.repos.group_ai_provider_settings.update( + unique_user.repos.group_id, + AIProviderSettingsUpdate( + default_provider_id=settings.default_provider_id, + audio_provider_id=None, + image_provider_id=None, + ), + ) + + with open(test_image_jpg, "rb") as f: + r = post_ai(api_client, unique_user, files=[("images", ("recipe.jpg", f, "image/jpeg"))]) + + assert r.status_code == 400 + + +def test_create_stream_emits_progress( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + test_image_jpg: str, +): + AIResponses(recipe=openai_recipe).install(monkeypatch) + + with open(test_image_jpg, "rb") as f: + r = api_client.post( + api_routes.recipes_create_ai_stream, + files=[("images", ("recipe.jpg", f, "image/jpeg"))], + headers=unique_user.token, + ) + + assert r.status_code == 200 + events = parse_sse_events(r.text) + event_types = [e["event"] for e in events] + + assert "done" in event_types + assert "progress" in event_types + + +def test_create_stream_emits_error( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, +): + AIResponses(recipe=None).install(monkeypatch) + + r = api_client.post( + api_routes.recipes_create_ai_stream, + data={"content": random_string()}, + headers=unique_user.token, + ) + + assert r.status_code == 200 + events = parse_sse_events(r.text) + assert [e["event"] for e in events][-1] == "error" diff --git a/tests/integration_tests/user_recipe_tests/test_recipe_create_from_image.py b/tests/integration_tests/user_recipe_tests/test_recipe_create_from_image.py deleted file mode 100644 index 7f86107d4..000000000 --- a/tests/integration_tests/user_recipe_tests/test_recipe_create_from_image.py +++ /dev/null @@ -1,75 +0,0 @@ -import json - -import pytest -from fastapi.testclient import TestClient - -from mealie.schema.group.ai_providers import AIProviderCreate, AIProviderSettingsUpdate -from mealie.schema.openai.recipe import ( - OpenAIRecipe, - OpenAIRecipeIngredient, - OpenAIRecipeInstruction, - OpenAIRecipeNotes, -) -from mealie.services.openai import OpenAIService -from tests.utils import api_routes -from tests.utils.factories import random_int, random_string -from tests.utils.fixture_schemas import TestUser - - -@pytest.fixture(scope="module", autouse=True) -def setup_ai_providers(unique_user: TestUser): - """Create AI providers for the test group so image-based OpenAI routes are enabled.""" - provider = unique_user.repos.group_ai_providers.create( - AIProviderCreate(name="test-provider", model="gpt-4o", api_key="test-key") - ) - unique_user.repos.group_ai_provider_settings.update( - unique_user.repos.group_id, - AIProviderSettingsUpdate( - default_provider_id=provider.id, - audio_provider_id=None, - image_provider_id=provider.id, - ), - ) - - -def test_openai_create_recipe_from_image( - api_client: TestClient, - monkeypatch: pytest.MonkeyPatch, - unique_user: TestUser, - test_image_jpg: str, -): - async def mock_get_response(self, prompt: str, message: str, *args, **kwargs) -> OpenAIRecipe | None: - data = OpenAIRecipe( - name=random_string(), - description=random_string(), - recipe_yield=random_string(), - total_time=random_string(), - prep_time=random_string(), - perform_time=random_string(), - ingredients=[OpenAIRecipeIngredient(text=random_string()) for _ in range(random_int(5, 10))], - instructions=[OpenAIRecipeInstruction(text=random_string()) for _ in range(1, random_int(5, 10))], - notes=[OpenAIRecipeNotes(text=random_string()) for _ in range(random_int(2, 5))], - ) - return data - - monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) - with open(test_image_jpg, "rb") as f: - r = api_client.post( - api_routes.recipes_create_image, - files={"images": ("test_image_jpg.jpg", f, "image/jpeg")}, - data={"extension": "jpg"}, - headers=unique_user.token, - ) - assert r.status_code == 201 - - # since OpenAI is mocked, we don't need to validate the data, we just need to make sure a recipe is created, - # and that it has an image - slug: str = json.loads(r.text) - r = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token) - assert r.status_code == 200 - recipe_id = r.json()["id"] - - r = api_client.get( - api_routes.media_recipes_recipe_id_images_file_name(recipe_id, "original.webp"), headers=unique_user.token - ) - assert r.status_code == 200 diff --git a/tests/integration_tests/user_recipe_tests/test_recipe_create_from_openai.py b/tests/integration_tests/user_recipe_tests/test_recipe_create_from_openai.py index c78a05857..9489eeb26 100644 --- a/tests/integration_tests/user_recipe_tests/test_recipe_create_from_openai.py +++ b/tests/integration_tests/user_recipe_tests/test_recipe_create_from_openai.py @@ -5,7 +5,9 @@ from fastapi.testclient import TestClient import mealie.services.scraper.recipe_scraper as recipe_scraper_module from mealie.schema.group.ai_providers import AIProviderCreate, AIProviderSettingsUpdate -from mealie.schema.openai.general import OpenAIText +from mealie.schema.openai.compiled_source import OpenAICompiledSource +from mealie.schema.openai.organizers import OpenAIOrganizers +from mealie.schema.openai.recipe import OpenAIRecipe, OpenAIRecipeIngredient, OpenAIRecipeInstruction from mealie.services.openai import OpenAIService from mealie.services.recipe.recipe_data_service import RecipeDataService from mealie.services.scraper.scraper_strategies import RecipeScraperOpenAI @@ -21,18 +23,12 @@ def recipe_name() -> str: @pytest.fixture() -def recipe_ld_json(recipe_name: str) -> str: - return json.dumps( - { - "@context": "https://schema.org", - "@type": "Recipe", - "name": recipe_name, - "recipeIngredient": [random_string() for _ in range(3)], - "recipeInstructions": [ - {"@type": "HowToStep", "text": random_string()}, - {"@type": "HowToStep", "text": random_string()}, - ], - } +def openai_recipe(recipe_name: str) -> OpenAIRecipe: + return OpenAIRecipe( + name=recipe_name, + description=random_string(), + ingredients=[OpenAIRecipeIngredient(text=random_string()) for _ in range(3)], + instructions=[OpenAIRecipeInstruction(text=random_string()) for _ in range(2)], ) @@ -66,20 +62,41 @@ def openai_scraper_setup(monkeypatch: pytest.MonkeyPatch, bare_html: str, unique monkeypatch.setattr(RecipeDataService, "scrape_image", lambda *_: "TEST_IMAGE") +def mock_ai( + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe | None, + organizers: OpenAIOrganizers | None = None, +) -> list[str]: + """Installs a stand-in provider, returning the list of schemas it was asked for.""" + + requested_schemas: list[str] = [] + + async def mock_get_response(self, prompt, message, *args, response_schema=None, **kwargs): + requested_schemas.append(response_schema.__name__) + + if response_schema is OpenAICompiledSource: + return OpenAICompiledSource(contains_recipe=True, content=random_string(), language=None, image_url=None) + if response_schema is OpenAIRecipe: + return openai_recipe + if response_schema is OpenAIOrganizers: + return organizers + + return None + + monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) + return requested_schemas + + def test_create_by_url_via_openai( api_client: TestClient, unique_user: TestUser, monkeypatch: pytest.MonkeyPatch, - recipe_ld_json: str, + openai_recipe: OpenAIRecipe, recipe_url: str, recipe_name: str, ): - async def mock_get_response(self, prompt, message, *args, **kwargs) -> OpenAIText | None: - return OpenAIText(text=recipe_ld_json) + mock_ai(monkeypatch, openai_recipe) - monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) - - api_client.delete(api_routes.recipes_slug("openai-test-cake"), headers=unique_user.token) response = api_client.post( api_routes.recipes_create_url, json={"url": recipe_url, "include_tags": False}, @@ -99,16 +116,12 @@ def test_create_by_html_or_json_via_openai( api_client: TestClient, unique_user: TestUser, monkeypatch: pytest.MonkeyPatch, - recipe_ld_json: str, + openai_recipe: OpenAIRecipe, bare_html: str, recipe_name: str, ): - async def mock_get_response(self, prompt, message, *args, **kwargs) -> OpenAIText | None: - return OpenAIText(text=recipe_ld_json) + mock_ai(monkeypatch, openai_recipe) - monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) - - api_client.delete(api_routes.recipes_slug("openai-test-cake"), headers=unique_user.token) response = api_client.post( api_routes.recipes_create_html_or_json, json={"data": bare_html, "include_tags": False}, @@ -122,19 +135,58 @@ def test_create_by_html_or_json_via_openai( assert recipe["name"] == recipe_name +def test_organizers_are_not_requested_unless_they_are_wanted( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + recipe_url: str, +): + requested_schemas = mock_ai(monkeypatch, openai_recipe) + + response = api_client.post( + api_routes.recipes_create_url, + json={"url": recipe_url, "include_tags": False, "include_categories": False}, + headers=unique_user.token, + ) + + assert response.status_code == 201 + assert "OpenAIOrganizers" not in requested_schemas + + +def test_tags_are_imported_when_requested( + api_client: TestClient, + unique_user: TestUser, + monkeypatch: pytest.MonkeyPatch, + openai_recipe: OpenAIRecipe, + recipe_url: str, +): + tag_name = random_string() + requested_schemas = mock_ai(monkeypatch, openai_recipe, OpenAIOrganizers(tags=[tag_name])) + + response = api_client.post( + api_routes.recipes_create_url, + json={"url": recipe_url, "include_tags": True}, + headers=unique_user.token, + ) + + assert response.status_code == 201 + assert "OpenAIOrganizers" in requested_schemas + + slug = json.loads(response.text) + recipe = api_client.get(api_routes.recipes_slug(slug), headers=unique_user.token).json() + assert [tag["name"] for tag in recipe["tags"]] == [tag_name.title()] + + def test_create_stream_via_openai_emits_progress( api_client: TestClient, unique_user: TestUser, monkeypatch: pytest.MonkeyPatch, - recipe_ld_json: str, + openai_recipe: OpenAIRecipe, bare_html: str, ): - async def mock_get_response(self, prompt, message, *args, **kwargs) -> OpenAIText | None: - return OpenAIText(text=recipe_ld_json) + mock_ai(monkeypatch, openai_recipe) - monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) - - api_client.delete(api_routes.recipes_slug("openai-test-cake"), headers=unique_user.token) response = api_client.post( api_routes.recipes_create_html_or_json_stream, json={"data": bare_html, "include_tags": False}, @@ -155,12 +207,9 @@ def test_create_by_url_openai_returns_none( monkeypatch: pytest.MonkeyPatch, recipe_url: str, ): - """When OpenAI returns None the endpoint should return 400.""" + """When the provider returns nothing the endpoint should return 400.""" - async def mock_get_response(self, prompt, message, *args, **kwargs) -> OpenAIText | None: - return None - - monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) + mock_ai(monkeypatch, None) response = api_client.post( api_routes.recipes_create_url, diff --git a/tests/integration_tests/user_recipe_tests/test_recipe_create_from_video.py b/tests/integration_tests/user_recipe_tests/test_recipe_create_from_video.py index eb54f3a25..853d30dbc 100644 --- a/tests/integration_tests/user_recipe_tests/test_recipe_create_from_video.py +++ b/tests/integration_tests/user_recipe_tests/test_recipe_create_from_video.py @@ -4,6 +4,7 @@ from pathlib import Path import pytest from fastapi.testclient import TestClient +import mealie.services.openai.transcription as transcription_module import mealie.services.scraper.recipe_scraper as recipe_scraper_module from mealie.core import exceptions from mealie.schema.group.ai_providers import AIProviderCreate, AIProviderSettingsUpdate @@ -57,7 +58,7 @@ def test_create_recipe_from_video( ): openai_recipe = _make_openai_recipe() - def mock_download_audio(self, temp_path: Path): + def mock_download_video(url: str, temp_path: Path): return { "audio": temp_path / "mealie.mp3", "subtitle": None, @@ -70,7 +71,7 @@ def test_create_recipe_from_video( async def mock_get_response(self, prompt, message, *args, **kwargs) -> OpenAIRecipe | None: return openai_recipe - monkeypatch.setattr(RecipeScraperOpenAITranscription, "_download_audio", mock_download_audio) + monkeypatch.setattr(transcription_module, "download_video", mock_download_video) monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) r = api_client.post(api_routes.recipes_create_url, json={"url": VIDEO_URL}, headers=unique_user.token) @@ -98,7 +99,7 @@ def test_create_recipe_from_video_uses_subtitle_over_transcription( subtitle_file = tmp_path / "mealie.en.vtt" subtitle_file.write_text(f"WEBVTT\n\n1\n00:00:01.000 --> 00:00:03.000\n{subtitle_text}\n") - def mock_download_audio(self, temp_path: Path): + def mock_download_video(url: str, temp_path: Path): return { "audio": temp_path / "mealie.mp3", "subtitle": subtitle_file, @@ -116,7 +117,7 @@ def test_create_recipe_from_video_uses_subtitle_over_transcription( assert subtitle_text in message return openai_recipe - monkeypatch.setattr(RecipeScraperOpenAITranscription, "_download_audio", mock_download_audio) + monkeypatch.setattr(transcription_module, "download_video", mock_download_video) monkeypatch.setattr(OpenAIService, "transcribe_audio", mock_transcribe_audio) monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) @@ -143,10 +144,10 @@ def test_create_recipe_from_video_download_error( monkeypatch: pytest.MonkeyPatch, unique_user: TestUser, ): - def mock_download_audio(self, temp_path: Path): + def mock_download_video(url: str, temp_path: Path): raise exceptions.VideoDownloadError("Mock video download error") - monkeypatch.setattr(RecipeScraperOpenAITranscription, "_download_audio", mock_download_audio) + monkeypatch.setattr(transcription_module, "download_video", mock_download_video) r = api_client.post(api_routes.recipes_create_url, json={"url": VIDEO_URL}, headers=unique_user.token) assert r.status_code == 400 @@ -157,7 +158,7 @@ def test_create_recipe_from_video_transcription_error( monkeypatch: pytest.MonkeyPatch, unique_user: TestUser, ): - def mock_download_audio(self, temp_path: Path): + def mock_download_video(url: str, temp_path: Path): return { "audio": temp_path / "mealie.mp3", "subtitle": None, @@ -170,7 +171,7 @@ def test_create_recipe_from_video_transcription_error( async def mock_transcribe_audio(self, audio_file_path: Path) -> str | None: raise Exception("Mock transcribe audio exception") - monkeypatch.setattr(RecipeScraperOpenAITranscription, "_download_audio", mock_download_audio) + monkeypatch.setattr(transcription_module, "download_video", mock_download_video) monkeypatch.setattr(OpenAIService, "transcribe_audio", mock_transcribe_audio) r = api_client.post(api_routes.recipes_create_url, json={"url": VIDEO_URL}, headers=unique_user.token) @@ -182,7 +183,7 @@ def test_create_recipe_from_video_empty_openai_response( monkeypatch: pytest.MonkeyPatch, unique_user: TestUser, ): - def mock_download_audio(self, temp_path: Path): + def mock_download_video(url: str, temp_path: Path): return { "audio": temp_path / "mealie.mp3", "subtitle": None, @@ -195,7 +196,7 @@ def test_create_recipe_from_video_empty_openai_response( async def mock_get_response(self, prompt, message, *args, **kwargs) -> OpenAIRecipe | None: return None - monkeypatch.setattr(RecipeScraperOpenAITranscription, "_download_audio", mock_download_audio) + monkeypatch.setattr(transcription_module, "download_video", mock_download_video) monkeypatch.setattr(OpenAIService, "get_response", mock_get_response) r = api_client.post(api_routes.recipes_create_url, json={"url": VIDEO_URL}, headers=unique_user.token) diff --git a/tests/unit_tests/services_tests/scraper_tests/test_scraper.py b/tests/unit_tests/services_tests/scraper_tests/test_scraper.py index ca2e27cd3..dff0c27ce 100644 --- a/tests/unit_tests/services_tests/scraper_tests/test_scraper.py +++ b/tests/unit_tests/services_tests/scraper_tests/test_scraper.py @@ -21,7 +21,7 @@ async def test_create_from_html_truncates_long_slug(monkeypatch): # ~1300 characters, mirroring the caption-as-title data from the bug report long_name = "High Protein Low Calorie Recipes Smash Or Pass " * 28 - async def fake_scrape(self, url, html=None, on_progress=None): + async def fake_scrape(self, url, html=None, on_progress=None, **kwargs): return Recipe(name=long_name), ScrapedExtras() monkeypatch.setattr(RecipeScraper, "scrape", fake_scrape) diff --git a/tests/unit_tests/services_tests/test_organizer_resolver.py b/tests/unit_tests/services_tests/test_organizer_resolver.py new file mode 100644 index 000000000..38291716f --- /dev/null +++ b/tests/unit_tests/services_tests/test_organizer_resolver.py @@ -0,0 +1,85 @@ +import pytest +from slugify import slugify + +from mealie.schema.recipe.recipe_category import CategorySave, TagSave +from mealie.schema.recipe.recipe_tool import RecipeToolSave +from mealie.services.recipe.organizer_resolver import OrganizerResolver +from tests.utils.factories import random_string +from tests.utils.fixture_schemas import TestUser + + +@pytest.fixture() +def resolver(unique_user: TestUser) -> OrganizerResolver: + return OrganizerResolver(unique_user.repos) + + +def test_matches_an_existing_tag_exactly(unique_user: TestUser, resolver: OrganizerResolver): + name = random_string() + existing = unique_user.repos.tags.create(TagSave(name=name, group_id=unique_user.repos.group_id)) + + resolved = resolver.resolve_tags([name], create_missing=False) + assert [tag.id for tag in resolved] == [existing.id] + + +def test_matches_an_existing_tag_regardless_of_case_and_spacing(unique_user: TestUser, resolver: OrganizerResolver): + existing = unique_user.repos.tags.create(TagSave(name="Slow Cooker", group_id=unique_user.repos.group_id)) + + resolved = resolver.resolve_tags(["slow cooker"], create_missing=False) + assert [tag.id for tag in resolved] == [existing.id] + + +def test_matches_a_close_variant(unique_user: TestUser, resolver: OrganizerResolver): + existing = unique_user.repos.categories.create(CategorySave(name="Dinners", group_id=unique_user.repos.group_id)) + + resolved = resolver.resolve_categories(["Dinner"], create_missing=False) + assert [category.id for category in resolved] == [existing.id] + + +def test_does_not_match_below_the_threshold(unique_user: TestUser, resolver: OrganizerResolver): + unique_user.repos.tags.create(TagSave(name="Vegetarian", group_id=unique_user.repos.group_id)) + + resolved = resolver.resolve_tags(["Vegan"], create_missing=False) + assert resolved == [] + + +def test_unmatched_names_are_dropped_when_not_creating(unique_user: TestUser, resolver: OrganizerResolver): + resolved = resolver.resolve_tags([random_string(), random_string()], create_missing=False) + assert resolved == [] + + +def test_unmatched_names_are_created_when_requested(unique_user: TestUser, resolver: OrganizerResolver): + name = random_string() + + resolved = resolver.resolve_tags([name], create_missing=True) + assert [tag.name for tag in resolved] == [name] + assert unique_user.repos.tags.get_one(slugify(name), "slug") + + +def test_existing_tools_are_reused_rather_than_recreated(unique_user: TestUser, resolver: OrganizerResolver): + name = random_string() + existing = unique_user.repos.tools.create(RecipeToolSave(name=name, group_id=unique_user.repos.group_id)) + + resolved = resolver.resolve_tools([name], create_missing=True) + assert [tool.id for tool in resolved] == [existing.id] + + +def test_duplicate_and_blank_names_are_collapsed(unique_user: TestUser, resolver: OrganizerResolver): + name = random_string() + + resolved = resolver.resolve_tags([name, name.upper(), " ", ""], create_missing=True) + assert len(resolved) == 1 + + +def test_existing_names_are_reported_for_prompt_injection(unique_user: TestUser, resolver: OrganizerResolver): + tag = random_string() + category = random_string() + tool = random_string() + + unique_user.repos.tags.create(TagSave(name=tag, group_id=unique_user.repos.group_id)) + unique_user.repos.categories.create(CategorySave(name=category, group_id=unique_user.repos.group_id)) + unique_user.repos.tools.create(RecipeToolSave(name=tool, group_id=unique_user.repos.group_id)) + + existing = resolver.existing_names() + assert tag in existing["tags"] + assert category in existing["categories"] + assert tool in existing["tools"] diff --git a/tests/unit_tests/services_tests/test_recipe_import_workflow.py b/tests/unit_tests/services_tests/test_recipe_import_workflow.py new file mode 100644 index 000000000..a45124a18 --- /dev/null +++ b/tests/unit_tests/services_tests/test_recipe_import_workflow.py @@ -0,0 +1,120 @@ +import json +import re +from pathlib import Path + +import pytest + +import mealie +from mealie.lang import get_locale_provider +from mealie.lang.providers import TRANSLATIONS +from mealie.services.openai.content import ( + MAX_SOURCE_CONTENT_LENGTH, + TRUNCATION_NOTICE, + truncate_source_content, +) +from mealie.services.recipe.import_workflow.compilers import DEFAULT_SOURCE_COMPILERS +from mealie.services.recipe.import_workflow.workflow import DEFAULT_WORKFLOW_STEPS + +MEALIE_DIR = Path(mealie.__file__).parent +PROGRESS_KEY_PATTERN = re.compile(r"[\"'](recipe\.create-progress\.[a-zA-Z0-9-]+)[\"']") +IMPORT_ERROR_KEY_PATTERN = re.compile(r"[\"'](recipe\.import-errors\.[a-zA-Z0-9-]+)[\"']") + +translator = get_locale_provider("en-US") + + +def is_translatable(key: str) -> bool: + """The JSON provider falls back to returning the key itself when it can't resolve one.""" + + return translator.t(key) != key + + +def declared_progress_keys() -> list[str]: + """Progress keys declared by the workflow's steps and source compilers.""" + + keys = [step.progress_key for step in DEFAULT_WORKFLOW_STEPS if step.progress_key] + keys += [compiler.progress_key for compiler in DEFAULT_SOURCE_COMPILERS if compiler.progress_key] + return keys + + +def keys_in_source(pattern: re.Pattern) -> list[str]: + """Every matching translation key referenced as a literal anywhere in the backend.""" + + keys: set[str] = set() + for path in MEALIE_DIR.rglob("*.py"): + keys.update(pattern.findall(path.read_text())) + + return sorted(keys) + + +def progress_keys_in_source() -> list[str]: + return keys_in_source(PROGRESS_KEY_PATTERN) + + +def import_error_keys_in_source() -> list[str]: + return keys_in_source(IMPORT_ERROR_KEY_PATTERN) + + +def test_workflow_declares_keys(): + # guards the tests below against silently passing on an empty list + assert declared_progress_keys() + assert progress_keys_in_source() + assert import_error_keys_in_source() + + +@pytest.mark.parametrize("key", declared_progress_keys()) +def test_declared_progress_keys_are_translatable(key: str): + assert is_translatable(key), f"Progress key '{key}' is missing from the backend translations" + + +@pytest.mark.parametrize("key", progress_keys_in_source()) +def test_progress_keys_used_in_source_are_translatable(key: str): + assert is_translatable(key), f"Progress key '{key}' is missing from the backend translations" + + +@pytest.mark.parametrize("key", import_error_keys_in_source()) +def test_import_error_keys_are_translatable(key: str): + """These are surfaced to the user, so an unresolved key shows up as raw text in the UI.""" + + assert is_translatable(key), f"Import error key '{key}' is missing from the backend translations" + + +def test_short_content_is_not_truncated(): + content = "a" * 100 + assert truncate_source_content(content) == content + + +def test_content_at_the_limit_is_not_truncated(): + content = "a" * MAX_SOURCE_CONTENT_LENGTH + assert truncate_source_content(content) == content + + +def test_long_content_is_truncated_and_marked(): + content = "a" * (MAX_SOURCE_CONTENT_LENGTH + 1) + truncated = truncate_source_content(content) + + assert truncated.endswith(TRUNCATION_NOTICE) + assert len(truncated) == MAX_SOURCE_CONTENT_LENGTH + len(TRUNCATION_NOTICE) + + +def test_content_can_be_truncated_to_a_custom_length(): + assert truncate_source_content("abcdef", max_length=3) == "abc" + TRUNCATION_NOTICE + + +def test_no_orphaned_import_error_keys(): + """Import error translations that nothing references anymore should be removed.""" + + messages = json.loads((TRANSLATIONS / "en-US.json").read_text()) + defined = set(messages["recipe"]["import-errors"]) + used = {key.rsplit(".", 1)[-1] for key in import_error_keys_in_source()} + + assert defined - used == set() + + +def test_no_orphaned_progress_keys(): + """Progress translations that nothing references anymore should be removed.""" + + messages = json.loads((TRANSLATIONS / "en-US.json").read_text()) + defined = set(messages["recipe"]["create-progress"]) + used = {key.rsplit(".", 1)[-1] for key in progress_keys_in_source()} + + assert defined - used == set() diff --git a/tests/utils/api_routes/__init__.py b/tests/utils/api_routes/__init__.py index f73105e34..3adaea53e 100644 --- a/tests/utils/api_routes/__init__.py +++ b/tests/utils/api_routes/__init__.py @@ -153,12 +153,14 @@ recipes_bulk_actions_settings = "/api/recipes/bulk-actions/settings" """`/api/recipes/bulk-actions/settings`""" recipes_bulk_actions_tag = "/api/recipes/bulk-actions/tag" """`/api/recipes/bulk-actions/tag`""" +recipes_create_ai = "/api/recipes/create/ai" +"""`/api/recipes/create/ai`""" +recipes_create_ai_stream = "/api/recipes/create/ai/stream" +"""`/api/recipes/create/ai/stream`""" recipes_create_html_or_json = "/api/recipes/create/html-or-json" """`/api/recipes/create/html-or-json`""" recipes_create_html_or_json_stream = "/api/recipes/create/html-or-json/stream" """`/api/recipes/create/html-or-json/stream`""" -recipes_create_image = "/api/recipes/create/image" -"""`/api/recipes/create/image`""" recipes_create_url = "/api/recipes/create/url" """`/api/recipes/create/url`""" recipes_create_url_bulk = "/api/recipes/create/url/bulk" @@ -199,16 +201,6 @@ users_self_ratings = "/api/users/self/ratings" """`/api/users/self/ratings`""" utils_download = "/api/utils/download" """`/api/utils/download`""" -validators_group = "/api/validators/group" -"""`/api/validators/group`""" -validators_household = "/api/validators/household" -"""`/api/validators/household`""" -validators_recipe = "/api/validators/recipe" -"""`/api/validators/recipe`""" -validators_user_email = "/api/validators/user/email" -"""`/api/validators/user/email`""" -validators_user_name = "/api/validators/user/name" -"""`/api/validators/user/name`""" def admin_backups_file_name(file_name):