feat: import recipes from PDF, Word, ODT, and text documents (#8536)

This commit is contained in:
Brad Schroth authored and GitHub committed 2026-11-28 16:28:37 +00:00
1 parent ad8d7b823c
commit 2dc253dc12
25 files changed
+1181 -26

No files matched your search

@@ -1,18 +1,36 @@
<template>
<div>
<AppButtonUpload
class="ml-auto"
url="none"
file-name="images"
accept="image/*"
:text="images.length ? $t('recipe.upload-more-images') : $t('recipe.upload-images')"
file-name="files"
:accept="uploadAccept"
:text="$t('recipe.import-with-ai-upload-files')"
:text-btn="false"
:post="false"
:multiple="true"
:disabled="disabled"
@uploaded="uploadImages"
@uploaded="handleFilesUploaded"
/>
<div v-if="images.length" class="mt-3">
<p class="text-caption mt-1">
{{ $t('recipe.import-with-ai-upload-files-hint') }}
</p>
<ul v-if="documents.length" class="mt-2">
<li v-for="(file, index) in documents" :key="index">
{{ file.name }}
<v-btn
icon
size="x-small"
variant="text"
:disabled="disabled"
@click="removeDocument(index)"
>
<v-icon size="small">
{{ $globals.icons.close }}
</v-icon>
</v-btn>
</li>
</ul>
<div v-if="images.length" class="mt-6">
<p class="my-2">
{{ $t("recipe.crop-and-rotate-the-image") }}
</p>
@@ -55,16 +73,76 @@
</template>
<script setup lang="ts">
withDefaults(defineProps<{
import { alert } from "~/composables/use-toast";
// keep in sync with the extensions handled by mealie/services/recipe/document_text_extraction.py
const DOCUMENT_EXTENSIONS = [".pdf", ".docx", ".odt", ".md", ".txt", ".rtf", ".html"];
const IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".avif", ".heic", ".heif", ".tif", ".tiff"];
const props = withDefaults(defineProps<{
disabled?: boolean;
imagesEnabled?: boolean;
}>(), {
disabled: false,
imagesEnabled: true,
});
const images = defineModel<(Blob | File)[]>({ default: () => [] });
const documents = defineModel<File[]>("documents", { default: () => [] });
const i18n = useI18n();
const previewUrls = ref<string[]>([]);
const uploadAccept = computed(() => {
const accept = [...DOCUMENT_EXTENSIONS];
if (props.imagesEnabled) {
accept.push("image/*");
}
return accept.join(",");
});
function isDocumentFile(file: File): boolean {
const name = file.name.toLowerCase();
return DOCUMENT_EXTENSIONS.some(extension => name.endsWith(extension));
}
function isImageFile(file: File): boolean {
const name = file.name.toLowerCase();
return file.type.startsWith("image/") || IMAGE_EXTENSIONS.some(extension => name.endsWith(extension));
}
function handleFilesUploaded(files: File[]) {
const newDocumentFiles: File[] = [];
const newImageFiles: File[] = [];
for (const file of files) {
if (isDocumentFile(file)) {
newDocumentFiles.push(file);
}
else if (isImageFile(file) && props.imagesEnabled) {
newImageFiles.push(file);
}
else if (!isImageFile(file)) {
const key = file.name.toLowerCase().endsWith(".doc")
? "recipe.import-with-ai-unsupported-file"
: "recipe.import-with-ai-unsupported-file-generic";
alert.error(i18n.t(key, { name: file.name }));
}
}
if (newDocumentFiles.length) {
documents.value = [...documents.value, ...newDocumentFiles];
}
if (newImageFiles.length) {
uploadImages(newImageFiles);
}
}
function removeDocument(index: number) {
documents.value.splice(index, 1);
}
function uploadImages(files: File[]) {
images.value = [...images.value, ...files];
previewUrls.value = [...previewUrls.value, ...files.map(file => URL.createObjectURL(file))];
+5 -1
View File
@@ -626,7 +626,7 @@
"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. Give it a link, upload photos of a recipe, paste a recipe as text, HTML, or JSON, or use any combination of the three. Everything you provide is read together as a single recipe.",
"import-with-ai-description": "Create a recipe from just about anything using AI. Give it a link, upload photos of a recipe or a document, paste a recipe as text, HTML, or JSON, or use any combination of these. Everything you provide is read together as a single recipe.",
"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, along with anything else you provide.",
"import-with-ai-without-ai-question": "Want to create a recipe without using AI?",
@@ -637,6 +637,10 @@
"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.",
"import-with-ai-upload-files": "Upload files",
"import-with-ai-upload-files-hint": "Optional. Upload photos or documents of a recipe.",
"import-with-ai-unsupported-file": "{name} isn't a supported format. Try converting it to .docx, or use a different file.",
"import-with-ai-unsupported-file-generic": "{name} isn't a supported format.",
"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",
@@ -250,6 +250,7 @@ export class RecipeAPI extends BaseCRUDAPI<RecipeCreate, RecipeOut, RecipeDraft,
content?: string | null;
url?: string | null;
images?: (Blob | File)[];
documents?: File[];
translateLanguage?: string | null;
createNewOrganizers?: boolean;
},
@@ -263,6 +264,9 @@ export class RecipeAPI extends BaseCRUDAPI<RecipeCreate, RecipeOut, RecipeDraft,
if (payload.url) {
formData.append("url", payload.url);
}
(payload.documents || []).forEach((document) => {
formData.append("documents", document, document.name);
});
if (payload.translateLanguage) {
formData.append("translateLanguage", payload.translateLanguage);
}
@@ -68,11 +68,16 @@
:disabled="state.loading"
/>
<div v-if="imagesEnabled" class="mt-6">
<RecipeImportImages v-model="uploadedImages" :disabled="state.loading" />
<div class="mt-6">
<RecipeImportImages
v-model="uploadedImages"
v-model:documents="documentFiles"
:images-enabled="imagesEnabled"
:disabled="state.loading"
/>
</div>
<v-alert
v-else
v-if="!imagesEnabled"
type="info"
variant="tonal"
class="mt-6"
@@ -201,6 +206,7 @@ const domUrlForm = ref<VForm | null>(null);
const recipeUrl = ref<string | null>(null);
const newRecipeData = ref<string | object | null>(null);
const uploadedImages = ref<(Blob | File)[]>([]);
const documentFiles = ref<File[]>([]);
const createStatus = ref<string | null>(null);
const {
@@ -225,7 +231,7 @@ const contentAsString = computed(() => {
return typeof data === "string" ? data : JSON.stringify(data);
});
const hasSource = computed(() => !!(recipeUrl.value || contentAsString.value || uploadedImages.value.length));
const hasSource = computed(() => !!(recipeUrl.value || contentAsString.value || uploadedImages.value.length || documentFiles.value.length));
function handleIsEditJson() {
if (state.isEditJSON) {
@@ -269,6 +275,7 @@ async function createRecipe() {
content: contentAsString.value,
url: recipeUrl.value,
images: uploadedImages.value,
documents: documentFiles.value,
translateLanguage: translateRecipe.value ? i18n.locale.value : null,
createNewOrganizers: createNewOrganizers.value,
},
+2
View File
@@ -38,6 +38,8 @@
"import-errors": {
"ai-not-enabled": "AI services are not enabled",
"ai-request-failed": "The AI provider was unable to complete the request. Please try again",
"document-too-many-images": "{filename} has too many images to process (more than {max_images}).",
"document-unreadable": "Couldn't read {filename}. It may be empty, damaged or password protected, or contain no text.",
"image-provider-not-enabled": "AI image services are not enabled",
"invalid-mealie-export": "This looks like a recipe exported from Mealie, but it could not be imported",
"no-recipe-found": "No recipe was found in the provided source",
+18 -9
View File
@@ -67,7 +67,7 @@ from mealie.services.event_bus_service.event_types import (
EventTypes,
)
from mealie.services.openai import OpenAINotEnabledException
from mealie.services.recipe.ai_recipe_service import AIProviderNotEnabledError, AIRecipeService
from mealie.services.recipe.ai_recipe_service import AIProviderNotEnabledError, AIRecipeService, DocumentReadError
from mealie.services.recipe.import_workflow.exceptions import NoRecipeDataError
from mealie.services.recipe.mealie_export import InvalidMealieExportError, parse_mealie_export
from mealie.services.recipe.recipe_data_service import (
@@ -279,7 +279,7 @@ class RecipeController(BaseRecipeController):
if isinstance(ex, exceptions.RateLimitError):
return self.t("exceptions.rate-limit-error")
if isinstance(ex, NoRecipeDataError | AIProviderNotEnabledError | InvalidMealieExportError):
if isinstance(ex, NoRecipeDataError | AIProviderNotEnabledError | DocumentReadError | InvalidMealieExportError):
# these are raised with an already-translated message
if message := str(ex):
return message
@@ -445,10 +445,12 @@ class RecipeController(BaseRecipeController):
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),
documents: 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.
Create a recipe from any combination of content (HTML, JSON, or text), images, a URL, and
uploaded documents (PDF, Word, ODT, Markdown, plain text, RTF, or HTML), using AI.
Optionally specify a language for it to translate the recipe to.
"""
req = ScrapeRecipeAI(
@@ -457,7 +459,7 @@ class RecipeController(BaseRecipeController):
translate_language=translate_language,
create_new_organizers=create_new_organizers,
)
async for event in self._create_recipe_with_ai(req, images):
async for event in self._create_recipe_with_ai(req, images, documents):
if isinstance(event.data, SSEDataEventDone):
return event.data.slug
if isinstance(event.data, SSEDataEventMessage) and event.event == SSEDataEventStatus.ERROR:
@@ -474,10 +476,11 @@ class RecipeController(BaseRecipeController):
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),
documents: 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
Create a recipe from any combination of content (HTML, JSON, or text), images, a URL, and
uploaded documents, using AI, streaming progress via SSE
"""
req = ScrapeRecipeAI(
@@ -486,10 +489,15 @@ class RecipeController(BaseRecipeController):
translate_language=translate_language,
create_new_organizers=create_new_organizers,
)
async for event in self._create_recipe_with_ai(req, images):
async for event in self._create_recipe_with_ai(req, images, documents):
yield event
def _create_recipe_with_ai(self, req: ScrapeRecipeAI, images: list[UploadFile]) -> AsyncIterable[ServerSentEvent]:
def _create_recipe_with_ai(
self,
req: ScrapeRecipeAI,
images: list[UploadFile],
documents: list[UploadFile] | None = None,
) -> AsyncIterable[ServerSentEvent]:
"""Create a recipe using AI, returning progress via SSE"""
ai_service = AIRecipeService(self.repos, self.user, self.household, translator=self.translator)
@@ -499,6 +507,7 @@ class RecipeController(BaseRecipeController):
content=req.content,
images=images,
url=req.url,
documents=documents,
translate_language=req.translate_language,
create_new_organizers=req.create_new_organizers,
on_progress=on_progress,
+105 -2
View File
@@ -1,3 +1,4 @@
import asyncio
import shutil
from collections.abc import Awaitable, Callable
from pathlib import Path
@@ -9,6 +10,14 @@ from mealie.schema.recipe.recipe import RecipeDraft, RecipeOut
from mealie.services.openai import OpenAIService
from mealie.services.scraper.scraper import finalize_scraped_recipe
from . import document_text_extraction
from .document_text_extraction import (
DocumentExtractionError,
EmptyPdfTextError,
TooManyPdfImagesError,
extract_images_from_pdf,
extract_text_from_document,
)
from .import_workflow import (
RecipeImportWorkflow,
WorkflowContext,
@@ -26,6 +35,12 @@ class AIProviderNotEnabledError(Exception):
pass
class DocumentReadError(Exception):
"""Raised with an already-translated message, naming the file, when an uploaded document can't be read."""
pass
class AIRecipeService(RecipeService):
"""Creates recipes from arbitrary source material by running the recipe import workflow."""
@@ -35,23 +50,32 @@ class AIRecipeService(RecipeService):
content: str | None = None,
images: list[UploadFile] | None = None,
url: str | None = None,
documents: list[UploadFile] | None = None,
translate_language: str | None = None,
create_new_organizers: bool = False,
on_progress: Callable[[str], Awaitable[None]] | None = None,
) -> RecipeOut:
"""
Creates a recipe from any combination of content, images, and a URL.
Creates a recipe from any combination of content, images, a URL, and uploaded documents.
Text is extracted from each document, and images embedded in a scanned PDF are routed
through the same vision pipeline as uploaded images. Raises DocumentReadError if a
document can't be read.
The first image, if any, becomes the recipe's cover image.
"""
document_content, document_images = await self._extract_document_content(documents or [])
with get_temporary_path() as temp_path:
local_images = self._store_images(images or [], temp_path)
local_images += self._store_document_images(document_images, temp_path)
recipe_data = await self.build_recipe(
content=content,
images=local_images,
url=url,
document_content=document_content,
translate_language=translate_language,
create_new_organizers=create_new_organizers,
on_progress=on_progress,
@@ -72,6 +96,7 @@ class AIRecipeService(RecipeService):
content: str | None = None,
images: list[Path] | None = None,
url: str | None = None,
document_content: str | None = None,
translate_language: str | None = None,
create_new_organizers: bool = False,
on_progress: Callable[[str], Awaitable[None]] | None = None,
@@ -82,7 +107,7 @@ class AIRecipeService(RecipeService):
The recipe is not persisted; that's up to the caller.
"""
workflow_input = WorkflowInput(content=content, images=images or [], url=url)
workflow_input = WorkflowInput(content=content, images=images or [], url=url, document_content=document_content)
if workflow_input.is_empty:
raise NoRecipeDataError(self.t("recipe.import-errors.no-source"))
@@ -106,6 +131,71 @@ class AIRecipeService(RecipeService):
result = await RecipeImportWorkflow().run(ctx)
return await finalize_scraped_recipe(result.recipe, self.translator, on_progress=on_progress)
def _document_read_error(self, filename: str, error: DocumentExtractionError | None = None) -> DocumentReadError:
if isinstance(error, TooManyPdfImagesError):
# read the cap at call time, so the message always matches the limit that was applied
message = self.t(
"recipe.import-errors.document-too-many-images",
filename=filename,
max_images=document_text_extraction.MAX_PDF_IMAGES,
)
else:
message = self.t("recipe.import-errors.document-unreadable", filename=filename)
return DocumentReadError(message)
async def _extract_one_document(self, document: UploadFile) -> tuple[str | None, list[tuple[str, bytes]]]:
"""
Reads one uploaded document and extracts either its text, or, for a scanned PDF with no
text layer, its embedded page images. Parsing runs in a thread so it can't block the event loop.
"""
file_bytes = await document.read()
filename = document.filename or ""
try:
return await asyncio.to_thread(extract_text_from_document, file_bytes, filename), []
except EmptyPdfTextError:
pass
except DocumentExtractionError as e:
raise self._document_read_error(filename, e) from e
try:
document_images = await asyncio.to_thread(extract_images_from_pdf, file_bytes)
except DocumentExtractionError as e:
raise self._document_read_error(filename, e) from e
if not document_images:
raise self._document_read_error(filename)
return None, document_images
async def _extract_document_content(
self, documents: list[UploadFile]
) -> tuple[str | None, list[tuple[str, bytes]]]:
"""
Reads every uploaded document and extracts their text and/or (for a scanned PDF with no
text layer) embedded page images. Returns (None, []) if no documents were given.
A single document's extracted text is returned as-is; with more than one, each is
labelled with its filename so the merged text still shows which file each part came from.
"""
texts: list[tuple[str, str]] = []
document_images: list[tuple[str, bytes]] = []
for document in documents:
text, images = await self._extract_one_document(document)
if text is not None:
texts.append((document.filename or "", text))
document_images.extend(images)
if not texts:
document_content = None
elif len(texts) == 1:
document_content = texts[0][1]
else:
document_content = "\n\n".join(f"## {filename}\n\n{text}" for filename, text in texts)
return document_content, document_images
@staticmethod
def _store_images(images: list[UploadFile], temp_path: Path) -> list[Path]:
local_images: list[Path] = []
@@ -120,6 +210,19 @@ class AIRecipeService(RecipeService):
return local_images
@staticmethod
def _store_document_images(document_images: list[tuple[str, bytes]], temp_path: Path) -> list[Path]:
"""Writes images extracted from an uploaded document (e.g. a scanned PDF's pages) to disk."""
local_images: list[Path] = []
for index, (filename, image_bytes) in enumerate(document_images):
# pypdf's embedded image names are only unique within a page, so index-prefix them
# to avoid collisions between pages when writing into the same temp directory
image_path = temp_path.joinpath(f"{index}-{Path(filename).name}")
image_path.write_bytes(image_bytes)
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):
@@ -0,0 +1,139 @@
"""Extracts plain text from uploaded document files, for recipe import."""
import io
import odf.teletype
import odf.text
from docx import Document
from odf.opendocument import load as load_odf
from pypdf import PdfReader
from striprtf.striprtf import rtf_to_text
from mealie.services.openai.content import extract_page_content
MIN_TEXT_LENGTH = 20
"""Below this many characters (after stripping whitespace), extracted text is treated as unreadable."""
MAX_PDF_IMAGES = 30
"""Cap on embedded images extracted from one PDF, so an oversized scan can't flood the vision API."""
class DocumentExtractionError(ValueError):
"""
Raised when text can't be extracted from an uploaded document.
The message is for logs only. The caller shows the user its own translated message.
"""
class TooManyPdfImagesError(DocumentExtractionError):
"""Raised when a PDF has more than MAX_PDF_IMAGES embedded images."""
class EmptyPdfTextError(DocumentExtractionError):
"""
Raised when a PDF's text layer is empty or too short.
Unlike other DocumentExtractionErrors, this one is specific to PDFs and recoverable: a
scanned PDF has no text layer at all, so the caller may fall back to reading its embedded
page images instead of failing the import outright.
"""
def _extract_pdf(file_bytes: bytes) -> str:
reader = PdfReader(io.BytesIO(file_bytes))
return "\n".join(page.extract_text() or "" for page in reader.pages)
def extract_images_from_pdf(file_bytes: bytes) -> list[tuple[str, bytes]]:
"""
Extracts every image embedded in a PDF, in page order, as (filename, image_bytes) pairs.
Used as a fallback for scanned PDFs, whose pages are photographs with no text layer: the
images are meant to be handed to the same vision pipeline a photo upload would go through,
not read with OCR.
Iterating a malformed PDF's images can fail on the first broken one, so each image is
retrieved independently and skipped on error rather than aborting the whole PDF. Raises
TooManyPdfImagesError if there are more than MAX_PDF_IMAGES embedded images.
"""
reader = PdfReader(io.BytesIO(file_bytes))
images: list[tuple[str, bytes]] = []
for page in reader.pages:
for name in page.images.keys(): # noqa: SIM118
if len(images) >= MAX_PDF_IMAGES:
raise TooManyPdfImagesError(f"PDF has more than {MAX_PDF_IMAGES} embedded images")
try:
image_file_object = page.images[name]
images.append((image_file_object.name, image_file_object.data))
except Exception:
continue
return images
def _extract_docx(file_bytes: bytes) -> str:
document = Document(io.BytesIO(file_bytes))
return "\n".join(paragraph.text for paragraph in document.paragraphs)
def _extract_odt(file_bytes: bytes) -> str:
document = load_odf(io.BytesIO(file_bytes))
paragraphs = document.getElementsByType(odf.text.P)
return "\n".join(odf.teletype.extractText(paragraph) for paragraph in paragraphs)
def _extract_plain_text(file_bytes: bytes) -> str:
return file_bytes.decode("utf-8")
def _extract_rtf(file_bytes: bytes) -> str:
return rtf_to_text(file_bytes.decode("utf-8", errors="replace"))
def _extract_html(file_bytes: bytes) -> str:
text, _ = extract_page_content(file_bytes.decode("utf-8", errors="replace"))
return text
_EXTRACTORS = {
"pdf": _extract_pdf,
"docx": _extract_docx,
"odt": _extract_odt,
"md": _extract_plain_text,
"txt": _extract_plain_text,
"rtf": _extract_rtf,
"html": _extract_html,
}
def extract_text_from_document(file_bytes: bytes, filename: str) -> str:
"""
Extracts plain text from a document file, dispatching by the filename's extension
(case-insensitive). Supported formats: pdf, docx, odt, md, txt, rtf, html.
Raises DocumentExtractionError if the extension is unsupported, the file can't be
parsed, or the extracted text is empty or too short to plausibly be a recipe.
"""
extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
extractor = _EXTRACTORS.get(extension)
if extractor is None:
raise DocumentExtractionError(f"Unsupported file type: .{extension}" if extension else "Unsupported file type")
try:
text = extractor(file_bytes)
except DocumentExtractionError:
raise
except Exception as e:
raise DocumentExtractionError("File could not be parsed") from e
if len(text.strip()) < MIN_TEXT_LENGTH:
if extension == "pdf":
raise EmptyPdfTextError("PDF has no readable text")
raise DocumentExtractionError("File has no readable text")
return text
@@ -38,9 +38,15 @@ class WorkflowInput(BaseModel):
URL; otherwise URL compilers still see only `url`.
"""
document_content: str | None = None
"""
Text extracted from an uploaded document. Compiled in addition to any other source, never
instead of one.
"""
@property
def is_empty(self) -> bool:
return not (self.content or self.images or self.url or self.page_content)
return not (self.content or self.images or self.url or self.page_content or self.document_content)
class WorkflowOptions(BaseModel):
@@ -12,6 +12,7 @@ from ..exceptions import NoRecipeDataError
IMAGES_LABEL = "Uploaded images"
PAGE_LABEL = "Recipe source page"
DOCUMENT_LABEL = "Uploaded document"
CONTENT_LABEL = "Content supplied by the user"
MULTI_SOURCE_PREAMBLE = (
@@ -133,10 +134,14 @@ class CompileSourceStep(WorkflowStep):
)
async def run(self, ctx: WorkflowContext) -> None:
# the user's own content goes last, so it reads as an addendum to what it accompanies
# the user's own content goes last, so it reads as an addendum to what it accompanies.
# An uploaded document is also the user's own material, but `content` is typically short,
# deliberate notes or corrections (e.g. "name this Grandma's Pancakes") that should have
# the final word, so the document is placed just before it rather than after.
sources = [
(IMAGES_LABEL, await self._compile_images(ctx)),
(PAGE_LABEL, await self._compile_page(ctx)),
(DOCUMENT_LABEL, await self._compile_content(ctx, ctx.input.document_content)),
(CONTENT_LABEL, await self._compile_content(ctx, ctx.input.content)),
]
+4
View File
@@ -48,6 +48,10 @@ dependencies = [
"httpx-curl-cffi==0.1.5",
"curl-cffi==0.17.0",
"fpdf2==2.9.0",
"pypdf==6.19.0",
"python-docx==1.2.0",
"odfpy==1.4.1",
"striprtf==0.0.33",
]
[project.scripts]
+25
View File
@@ -57,6 +57,31 @@ images_test_image_1 = CWD / "images/test-image-1.jpg"
images_test_image_2 = CWD / "images/test-image-2.png"
document_recipe_pdf = CWD / "documents/recipe.pdf"
document_recipe_docx = CWD / "documents/recipe.docx"
document_recipe_odt = CWD / "documents/recipe.odt"
document_recipe_md = CWD / "documents/recipe.md"
document_recipe_txt = CWD / "documents/recipe.txt"
document_recipe_rtf = CWD / "documents/recipe.rtf"
document_recipe_html = CWD / "documents/recipe.html"
document_empty_txt = CWD / "documents/empty.txt"
document_scanned_recipe_pdf = CWD / "documents/scanned_recipe.pdf"
"""A PDF with an embedded image of the recipe and no text layer, as a real scanner would produce"""
document_recipe_with_text_and_image_pdf = CWD / "documents/recipe_with_text_and_image.pdf"
"""A PDF with both a real text layer and an embedded image"""
document_blank_pdf = CWD / "documents/blank.pdf"
"""A PDF with neither a text layer nor any embedded images"""
html_mealie_recipe = CWD / "html/mealie-recipe.html"
html_sous_vide_smoked_beef_ribs = CWD / "html/sous-vide-smoked-beef-ribs.html"
+68
View File
@@ -0,0 +1,68 @@
%PDF-1.3
%“Œ‹ž ReportLab Generated PDF document (opensource)
1 0 obj
<<
/F1 2 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/Contents 7 0 R /MediaBox [ 0 0 612 792 ] /Parent 6 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
4 0 obj
<<
/PageMode /UseNone /Pages 6 0 R /Type /Catalog
>>
endobj
5 0 obj
<<
/Author (anonymous) /CreationDate (D:20260921211901-04'00') /Creator (anonymous) /Keywords () /ModDate (D:20260921211901-04'00') /Producer (ReportLab PDF Library - \(opensource\))
/Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
6 0 obj
<<
/Count 1 /Kids [ 3 0 R ] /Type /Pages
>>
endobj
7 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 79
>>
stream
GapQh0E=F,0U\H3T\pNYT^QKk?tc>IP,;W#U1^23ihPEM_Nh$,C&gT2$75r]@%<u'bb`)Y!1u@^[K~>endstream
endobj
xref
0 8
0000000000 65535 f
0000000061 00000 n
0000000092 00000 n
0000000199 00000 n
0000000392 00000 n
0000000460 00000 n
0000000721 00000 n
0000000780 00000 n
trailer
<<
/ID
[<84cd046107a1a1436e522bbdf4292c43><84cd046107a1a1436e522bbdf4292c43>]
% ReportLab generated PDF document -- digest (opensource)
/Info 5 0 R
/Root 4 0 R
/Size 8
>>
startxref
948
%%EOF
+3
View File
@@ -0,0 +1,3 @@
Binary file not shown.
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html><head><title>Grandma's Pancakes</title></head>
<body><h1>Grandma's Pancakes</h1><pre>Grandma's Pancakes
Ingredients:
2 cups flour
2 eggs
1.5 cups milk
Instructions:
Mix all ingredients together and fry on a hot griddle until golden brown.
</pre></body></html>
+11
View File
@@ -0,0 +1,11 @@
# Grandma's Pancakes
Grandma's Pancakes
Ingredients:
2 cups flour
2 eggs
1.5 cups milk
Instructions:
Mix all ingredients together and fry on a hot griddle until golden brown.
Binary file not shown.
+68
View File
@@ -0,0 +1,68 @@
%PDF-1.3
%“Œ‹ž ReportLab Generated PDF document (opensource)
1 0 obj
<<
/F1 2 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/Contents 7 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 6 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
4 0 obj
<<
/PageMode /UseNone /Pages 6 0 R /Type /Catalog
>>
endobj
5 0 obj
<<
/Author (anonymous) /CreationDate (D:20260921203629-04'00') /Creator (anonymous) /Keywords () /ModDate (D:20260921203629-04'00') /Producer (ReportLab PDF Library - \(opensource\))
/Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
6 0 obj
<<
/Count 1 /Kids [ 3 0 R ] /Type /Pages
>>
endobj
7 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 285
>>
stream
Gat%\6#+:k&4Q=R`S\)J_Qf&pROePT.(%?T/tcCRU-p%+8Z'VsCD&QXZo/W7/2VjJoS+OX&%g?&"kEa5-O*U:1gjlq6G-\NB)Ok3U<=NVSjTlphZcZPQ$3gYP%o9hnH!)01&jE-=C"Dqmd^>;apD<m`BBCk>$4QKY/Wb[8qFQ87PrD7@5Q3/YHTosr,[8T@G13DD65mYV^GI=9dQ[`e]E-+E8cGmX$&a0#Q)17,]@eYl%"6%BYkXY+L1ME-<R+77RtQ])"3\9]EeI&foMIRqZOVkMKf~>endstream
endobj
xref
0 8
0000000000 65535 f
0000000061 00000 n
0000000092 00000 n
0000000199 00000 n
0000000402 00000 n
0000000470 00000 n
0000000731 00000 n
0000000790 00000 n
trailer
<<
/ID
[<8910de7a1289cefa601d0ce28c0fb08a><8910de7a1289cefa601d0ce28c0fb08a>]
% ReportLab generated PDF document -- digest (opensource)
/Info 5 0 R
/Root 4 0 R
/Size 8
>>
startxref
1165
%%EOF
+1
View File
@@ -0,0 +1 @@
{\rtf1\ansi\deff0 {\fonttbl{\f0 Arial;}}\f0\pard Grandma's Pancakes\par Grandma's Pancakes\par \par Ingredients:\par 2 cups flour\par 2 eggs\par 1.5 cups milk\par \par Instructions:\par Mix all ingredients together and fry on a hot griddle until golden brown.\par }
+9
View File
@@ -0,0 +1,9 @@
Grandma's Pancakes
Ingredients:
2 cups flour
2 eggs
1.5 cups milk
Instructions:
Mix all ingredients together and fry on a hot griddle until golden brown.
@@ -0,0 +1,79 @@
%PDF-1.3
%“Œ‹ž ReportLab Generated PDF document (opensource)
1 0 obj
<<
/F1 2 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /FlateDecode ] /Height 200 /Length 181 /Subtype /Image
/Type /XObject /Width 200
>>
stream
Gb"0<0bFBc$j34%rJR\W.Yn0d\l)O.<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<E3%!<HWd#-;N:~>endstream
endobj
4 0 obj
<<
/Contents 8 0 R /MediaBox [ 0 0 612 792 ] /Parent 7 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject <<
/FormXob.7208c37a1c397f35cd57bdc02ebaa6d7 3 0 R
>>
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
5 0 obj
<<
/PageMode /UseNone /Pages 7 0 R /Type /Catalog
>>
endobj
6 0 obj
<<
/Author (anonymous) /CreationDate (D:20260921211901-04'00') /Creator (anonymous) /Keywords () /ModDate (D:20260921211901-04'00') /Producer (ReportLab PDF Library - \(opensource\))
/Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
7 0 obj
<<
/Count 1 /Kids [ 4 0 R ] /Type /Pages
>>
endobj
8 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 245
>>
stream
Garo<b79+X&4Q?lMS&Jb^cm;.egPDmdA./ZV1:k5<="H\]i?n/+dpGG1-,)@Af.HWp9)C:$\_a+^c5:"('Yr3"tN.?S:+5UI8VJOn[d,7h!.apS\>qH([V@j"?$-&TtQ,sFOq;iflbO^*%,+'3$*i<j1*-3&G<373nM8kf[JU?%_jpEk4-@G#cI;(^Nr9kkj'I(QFb'W>Sd+('-j;b7a,Em,*PMPb73Q%VKJD%/03CWO=)Fc:pL~>endstream
endobj
xref
0 9
0000000000 65535 f
0000000061 00000 n
0000000092 00000 n
0000000199 00000 n
0000000570 00000 n
0000000826 00000 n
0000000894 00000 n
0000001155 00000 n
0000001214 00000 n
trailer
<<
/ID
[<7c3b789399775e7087862ddaf2893f1a><7c3b789399775e7087862ddaf2893f1a>]
% ReportLab generated PDF document -- digest (opensource)
/Info 6 0 R
/Root 5 0 R
/Size 9
>>
startxref
1549
%%EOF
+79
View File
@@ -0,0 +1,79 @@
%PDF-1.3
%“Ś‹ž ReportLab Generated PDF document (opensource)
1 0 obj
<<
/F1 2 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /FlateDecode ] /Height 200 /Length 182 /Subtype /Image
/Type /XObject /Width 200
>>
stream
Gb"0<!=]#/$j*(sAhpHmT&:&cXI6)gWiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiE)!WiH($A1O_Y~>endstream
endobj
4 0 obj
<<
/Contents 8 0 R /MediaBox [ 0 0 612 792 ] /Parent 7 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject <<
/FormXob.bff6a6a048c7324bb267931c0ea1c2eb 3 0 R
>>
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
5 0 obj
<<
/PageMode /UseNone /Pages 7 0 R /Type /Catalog
>>
endobj
6 0 obj
<<
/Author (anonymous) /CreationDate (D:20260921211901-04'00') /Creator (anonymous) /Keywords () /ModDate (D:20260921211901-04'00') /Producer (ReportLab PDF Library - \(opensource\))
/Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
7 0 obj
<<
/Count 1 /Kids [ 4 0 R ] /Type /Pages
>>
endobj
8 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 130
>>
stream
Gaoe40b/^V&-VlW`P+V+!)Zsq<]29=[N(FT&H.*PR,,tEZNC+M5LTd0!UV?JK9.7ZE<mML5W;j.hl>G]ecW<qH*3oUUH/58,J,,lei6[iqpA$q1J0F#@P5#$kQQ0B)E7~>endstream
endobj
xref
0 9
0000000000 65535 f
0000000061 00000 n
0000000092 00000 n
0000000199 00000 n
0000000571 00000 n
0000000827 00000 n
0000000895 00000 n
0000001156 00000 n
0000001215 00000 n
trailer
<<
/ID
[<0c42452bde76efbe2e977a11642e8810><0c42452bde76efbe2e977a11642e8810>]
% ReportLab generated PDF document -- digest (opensource)
/Info 6 0 R
/Root 5 0 R
/Size 9
>>
startxref
1435
%%EOF
@@ -1,5 +1,7 @@
import asyncio
import json
from collections.abc import Generator
from contextlib import ExitStack, contextmanager
from pathlib import Path
import httpx
@@ -8,6 +10,8 @@ from fastapi.testclient import TestClient
from slugify import slugify
import mealie.services.openai.transcription as transcription_module
import mealie.services.recipe.ai_recipe_service as ai_recipe_service_module
import mealie.services.recipe.document_text_extraction as document_text_extraction_module
import mealie.services.recipe.import_workflow.steps.compile_source as compile_source_module
from mealie.core import exceptions
from mealie.lang import get_locale_provider
@@ -27,6 +31,7 @@ from mealie.services.openai import OpenAINotEnabledException, 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 import data as test_data
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
@@ -534,6 +539,392 @@ def test_new_organizers_are_created_when_requested(
assert [tool["name"] for tool in recipe["tools"]] == [tool_name]
# =================================================================
# Document Upload
@contextmanager
def document_file(path, filename: str, content_type: str):
with open(path, "rb") as f:
yield [("documents", (filename, f, content_type))]
@contextmanager
def document_files(*specs: tuple[Path, str, str]):
"""Like `document_file`, but opens several files and uploads them together."""
with ExitStack() as stack:
files = [
("documents", (filename, stack.enter_context(open(path, "rb")), content_type))
for path, filename, content_type in specs
]
yield files
@pytest.mark.parametrize(
"path,filename,content_type",
[
(test_data.document_recipe_pdf, "recipe.pdf", "application/pdf"),
(
test_data.document_recipe_docx,
"recipe.docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
),
(test_data.document_recipe_odt, "recipe.odt", "application/vnd.oasis.opendocument.text"),
(test_data.document_recipe_md, "recipe.md", "text/markdown"),
(test_data.document_recipe_txt, "recipe.txt", "text/plain"),
(test_data.document_recipe_rtf, "recipe.rtf", "application/rtf"),
(test_data.document_recipe_html, "recipe.html", "text/html"),
],
)
def test_create_from_document(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
recipe_name: str,
path,
filename: str,
content_type: str,
):
ai = AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_file(path, filename, content_type) as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 201
# extracted document text is already a faithful record, so it's compiled without an AI call
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
def test_create_from_document_combines_with_pasted_content(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
"""A document and pasted content are separate sources, and both must reach the build step."""
pasted_content = 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
monkeypatch.setattr(OpenAIService, "get_response", mock_get_response)
with document_file(test_data.document_recipe_txt, "recipe.txt", "text/plain") as files:
r = post_ai(api_client, unique_user, data={"content": pasted_content}, files=files)
assert r.status_code == 201
build_message = messages[0]
assert "Grandma's Pancakes" in build_message
assert pasted_content in build_message
def test_create_from_document_combines_with_url(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
"""A document and a URL are separate sources, and both must reach the build step."""
page_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
async def mock_resilient_fetch(url: str):
ld_json = json.dumps({"@context": "https://schema.org", "@type": "Recipe", "name": page_text})
return html_fetch_result(
f'<html><head><script type="application/ld+json">{ld_json}</script></head><body>Recipe</body></html>',
url,
)
monkeypatch.setattr(OpenAIService, "get_response", mock_get_response)
monkeypatch.setattr(compile_source_module, "resilient_fetch", mock_resilient_fetch)
url = f"https://example.com/recipe/{random_string()}"
with document_file(test_data.document_recipe_txt, "recipe.txt", "text/plain") as files:
r = post_ai(api_client, unique_user, data={"url": url}, files=files)
assert r.status_code == 201
build_message = messages[0]
assert page_text in build_message
assert "Grandma's Pancakes" in build_message
def test_document_parsing_runs_in_a_worker_thread(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
"""Parsing a document is blocking work, so it must not run on the event loop."""
AIResponses(recipe=openai_recipe).install(monkeypatch)
threaded_calls: list[str] = []
real_to_thread = asyncio.to_thread
async def spy_to_thread(func, /, *args, **kwargs):
threaded_calls.append(func.__name__)
return await real_to_thread(func, *args, **kwargs)
monkeypatch.setattr(ai_recipe_service_module.asyncio, "to_thread", spy_to_thread)
with document_file(test_data.document_recipe_txt, "recipe.txt", "text/plain") as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 201
assert "extract_text_from_document" in threaded_calls
def test_create_from_document_empty_text_returns_400(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_file(test_data.document_empty_txt, "empty.txt", "text/plain") as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 400
assert r.json()["detail"]["message"] == (
"Couldn't read empty.txt. It may be empty, damaged or password protected, or contain no text."
)
def test_create_from_document_unsupported_extension_returns_400(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_file(test_data.document_recipe_txt, "recipe.doc", "application/msword") as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 400
assert r.json()["detail"]["message"] == (
"Couldn't read recipe.doc. It may be empty, damaged or password protected, or contain no text."
)
def test_create_from_document_unreadable_file_returns_400(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
AIResponses(recipe=openai_recipe).install(monkeypatch)
# plain text with a .pdf extension can't be parsed as a PDF
with document_file(test_data.document_recipe_txt, "broken.pdf", "application/pdf") as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 400
assert r.json()["detail"]["message"] == (
"Couldn't read broken.pdf. It may be empty, damaged or password protected, or contain no text."
)
def test_create_stream_from_unsupported_document_emits_translated_error(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_file(test_data.document_recipe_txt, "recipe.doc", "application/msword") as files:
r = api_client.post(api_routes.recipes_create_ai_stream, files=files, headers=unique_user.token)
assert r.status_code == 200
error = parse_sse_events(r.text)[-1]
assert error["event"] == "error"
assert error["data"]["message"] == (
"Couldn't read recipe.doc. It may be empty, damaged or password protected, or contain no text."
)
# =================================================================
# Multiple Document Upload
def test_create_from_multiple_documents_combines_with_headers(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
"""More than one document is joined with a per-file header, unlike the single-document case."""
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)
with document_files(
(test_data.document_recipe_txt, "recipe1.txt", "text/plain"),
(test_data.document_recipe_md, "recipe2.md", "text/markdown"),
) as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 201
build_message = messages[0]
assert "## recipe1.txt" in build_message
assert "## recipe2.md" in build_message
def test_create_from_multiple_documents_second_failure_names_that_file(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_files(
(test_data.document_recipe_txt, "recipe1.txt", "text/plain"),
(test_data.document_recipe_txt, "recipe2.doc", "application/msword"),
) as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 400
assert "recipe2.doc" in r.json()["detail"]["message"]
def test_create_from_two_scanned_pdfs_merges_images_into_one_list(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
"""Images extracted from multiple scanned PDFs all reach the vision path as one image list."""
ai = AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_files(
(test_data.document_scanned_recipe_pdf, "scan1.pdf", "application/pdf"),
(test_data.document_scanned_recipe_pdf, "scan2.pdf", "application/pdf"),
) as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 201
# the images compiler describes how many images it was given in a single call
compile_message = ai.messages[ai.requested_schemas.index("OpenAICompiledSource")]
assert "2 images" in compile_message
def test_create_from_scanned_and_text_pdf_combines_content_and_images(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
"""A scanned PDF and a text-layer PDF each contribute through their own path, simultaneously."""
ai = AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_files(
(test_data.document_recipe_with_text_and_image_pdf, "recipe.pdf", "application/pdf"),
(test_data.document_scanned_recipe_pdf, "scanned.pdf", "application/pdf"),
) as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 201
# the scanned PDF's image went through the vision path
assert "OpenAICompiledSource" in ai.requested_schemas
# the text PDF's content reached the build step alongside it
build_message = ai.messages[ai.requested_schemas.index("OpenAIRecipe")]
assert "Grandma's Pancakes" in build_message
def test_create_from_scanned_pdf_routes_through_images(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
"""A PDF with no text layer falls back to its embedded images, going through the vision pipeline."""
ai = AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_file(test_data.document_scanned_recipe_pdf, "scanned_recipe.pdf", "application/pdf") as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 201
# unlike plain extracted text, images always have to be read by the provider first
assert ai.requested_schemas[:2] == ["OpenAICompiledSource", "OpenAIRecipe"]
slug = json.loads(r.text)
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_pdf_with_text_and_image_uses_text_not_images(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
recipe_name: str,
):
"""A successful text extraction short-circuits before the embedded-image fallback ever runs."""
ai = AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_file(test_data.document_recipe_with_text_and_image_pdf, "recipe.pdf", "application/pdf") as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 201
# text was extracted, so no vision call was needed to read the embedded image
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
def test_create_from_pdf_with_no_text_or_images_returns_400(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_file(test_data.document_blank_pdf, "blank.pdf", "application/pdf") as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 400
def test_create_from_scanned_pdf_exceeding_image_cap_returns_400(
api_client: TestClient,
unique_user: TestUser,
monkeypatch: pytest.MonkeyPatch,
openai_recipe: OpenAIRecipe,
):
monkeypatch.setattr(document_text_extraction_module, "MAX_PDF_IMAGES", 0)
AIResponses(recipe=openai_recipe).install(monkeypatch)
with document_file(test_data.document_scanned_recipe_pdf, "scanned_recipe.pdf", "application/pdf") as files:
r = post_ai(api_client, unique_user, files=files)
assert r.status_code == 400
def test_organizers_are_resolved_from_the_source_not_the_built_recipe(
api_client: TestClient,
unique_user: TestUser,
Generated
+49 -1
View File
@@ -1,5 +1,5 @@
version = 1
revision = 5
revision = 3
requires-python = "==3.14.*"
[options]
@@ -1232,6 +1232,7 @@ dependencies = [
{ name = "itsdangerous" },
{ name = "jinja2" },
{ name = "lxml" },
{ name = "odfpy" },
{ name = "openai" },
{ name = "orjson" },
{ name = "paho-mqtt" },
@@ -1242,7 +1243,9 @@ dependencies = [
{ name = "pydantic-settings" },
{ name = "pyhumps" },
{ name = "pyjwt" },
{ name = "pypdf" },
{ name = "python-dateutil" },
{ name = "python-docx" },
{ name = "python-dotenv" },
{ name = "python-ldap" },
{ name = "python-multipart" },
@@ -1252,6 +1255,7 @@ dependencies = [
{ name = "recipe-scrapers" },
{ name = "requests" },
{ name = "sqlalchemy" },
{ name = "striprtf" },
{ name = "text-unidecode" },
{ name = "typing-extensions" },
{ name = "tzdata" },
@@ -1309,6 +1313,7 @@ requires-dist = [
{ name = "itsdangerous", specifier = "==2.2.0" },
{ name = "jinja2", specifier = "==3.1.6" },
{ name = "lxml", specifier = "==6.1.3" },
{ name = "odfpy", specifier = "==1.4.1" },
{ name = "openai", specifier = "==3.57.0" },
{ name = "orjson", specifier = "==3.13.0" },
{ name = "paho-mqtt", specifier = "==2.2.0" },
@@ -1320,7 +1325,9 @@ requires-dist = [
{ name = "pydantic-settings", specifier = "==2.16.3" },
{ name = "pyhumps", specifier = "==3.8.0" },
{ name = "pyjwt", specifier = "==2.15.1" },
{ name = "pypdf", specifier = "==6.19.0" },
{ name = "python-dateutil", specifier = "==4.0.0" },
{ name = "python-docx", specifier = "==1.2.0" },
{ name = "python-dotenv", specifier = "==1.2.4" },
{ name = "python-ldap", specifier = "==3.4.8" },
{ name = "python-multipart", specifier = "==0.0.34" },
@@ -1330,6 +1337,7 @@ requires-dist = [
{ name = "recipe-scrapers", specifier = "==15.14.0" },
{ name = "requests", specifier = "==2.34.2" },
{ name = "sqlalchemy", specifier = "==2.1.9" },
{ name = "striprtf", specifier = "==0.0.33" },
{ name = "text-unidecode", specifier = "==1.3" },
{ name = "typing-extensions", specifier = "==4.16.0" },
{ name = "tzdata", specifier = "==2026.6" },
@@ -1477,6 +1485,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/df/ef/3b8adde1b32a6f540758bff734d3442c621734c83708e5f02b0ba2f43b84/oauthlib-4.0.1-py3-none-any.whl", hash = "sha256:498a298876e996301950a5b053d12c31628bb7b895db03666430c69ce182eb61", size = 161934, upload-time = "2026-10-31T09:52:56.206Z" },
]
[[package]]
name = "odfpy"
version = "1.4.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "defusedxml" },
]
sdist = { url = "https://files.pythonhosted.org/packages/97/73/8ade73f6749177003f7ce3304f524774adda96e6aaab30ea79fd8fda7934/odfpy-1.4.1.tar.gz", hash = "sha256:db766a6e59c5103212f3cc92ec8dd50a0f3a02790233ed0b52148b70d3c438ec", size = 717045, upload-time = "2020-01-18T16:55:48.852Z" }
[[package]]
name = "openai"
version = "3.57.0"
@@ -1856,6 +1873,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" },
]
[[package]]
name = "pypdf"
version = "6.19.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/1f/ac/63d71aaedb59acbcdef491e6ca6469165e3771c9c74358204818fd9bc5a6/pypdf-6.19.0.tar.gz", hash = "sha256:bbc43aca292369ccc6cbc8a921991ecf2538a3587ab5a116eff06c321d647155", size = 7033266, upload-time = "2026-09-16T09:32:05.946Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/3c/2c/c43c03eaf630435f023f1dc61ec4a4a78951ad5530a62c71cc89bde307b7/pypdf-6.19.0-py3-none-any.whl", hash = "sha256:7e5d6e730e7dae87d560a2cee218b852f6498c8be61966f3cd02ead971e48d14", size = 395480, upload-time = "2026-09-16T09:32:04.087Z" },
]
[[package]]
name = "pyrdfa3"
version = "3.6.5"
@@ -1935,6 +1961,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ac/35/25bd092ca8a7e71192afdca67fbff4f797da74408e74ac3626e13b409ec0/python_discovery-1.9.5-py3-none-any.whl", hash = "sha256:a1fae8fca11e4bc61e38491c2aafff29e430b3c5e272d51ae52fb895bc4c0fac", size = 44377, upload-time = "2026-11-06T15:32:09.821Z" },
]
[[package]]
name = "python-docx"
version = "1.2.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "lxml" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a9/f7/eddfe33871520adab45aaa1a71f0402a2252050c14c7e3009446c8f4701c/python_docx-1.2.0.tar.gz", hash = "sha256:7bc9d7b7d8a69c9c02ca09216118c86552704edc23bac179283f2e38f86220ce", size = 5723256, upload-time = "2025-06-16T20:46:27.921Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d0/00/1e03a4989fa5795da308cd774f05b704ace555a70f9bf9d3be057b680bcf/python_docx-1.2.0-py3-none-any.whl", hash = "sha256:3fd478f3250fbbbfd3b94fe1e985955737c145627498896a8a6bf81f4baf66c7", size = 252987, upload-time = "2025-06-16T20:46:22.506Z" },
]
[[package]]
name = "python-dotenv"
version = "1.2.4"
@@ -2242,6 +2281,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" },
]
[[package]]
name = "striprtf"
version = "0.0.33"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/3e/3b/c42830804cb2da515d0cb8aa200fb199ce57f7dcc344ff73db9dfe37cf3b/striprtf-0.0.33.tar.gz", hash = "sha256:c2d3d9ff3118df6dab558675f10a31ff8bb999ac1f8921f00c6dc9ea19961f18", size = 8010, upload-time = "2026-08-17T21:11:15.706Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f5/85/bee751fd2096accfc8b76186d49fbb2871163723e45f1e721e03c3f044ae/striprtf-0.0.33-py3-none-any.whl", hash = "sha256:f9637632a4414de05b1c399ee34d324dc336133ae45769992143a024e0f919ef", size = 8446, upload-time = "2026-08-17T21:11:14.696Z" },
]
[[package]]
name = "text-unidecode"
version = "1.3"