diff --git a/frontend/app/components/Domain/Recipe/RecipeImportImages.vue b/frontend/app/components/Domain/Recipe/RecipeImportImages.vue index 42775acf1..c4d59a00f 100644 --- a/frontend/app/components/Domain/Recipe/RecipeImportImages.vue +++ b/frontend/app/components/Domain/Recipe/RecipeImportImages.vue @@ -1,18 +1,36 @@ Recipe', + 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, diff --git a/uv.lock b/uv.lock index 37db7b807..8e48c91f7 100644 --- a/uv.lock +++ b/uv.lock @@ -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"