fix: classify create/url imports on the landing URL (#8547)

This commit is contained in:
Mike Xiao authored and GitHub committed 2026-09-27 03:48:47 +00:00
1 parent b228d131f6
commit 151be46326
7 files changed
+209 -18

No files matched your search

@@ -34,6 +34,8 @@ class WorkflowInput(BaseModel):
"""
The page's own content, for callers that have already fetched it. Unlike `content` this is
not a separate source, so supplying it skips the fetch rather than adding to the material.
Callers that followed redirects should also set `WorkflowContext.resolved_url` to the landing
URL; otherwise URL compilers still see only `url`.
"""
@property
+7 -3
View File
@@ -2,6 +2,7 @@ from collections.abc import Awaitable, Callable
from mealie.core.root_logger import get_logger
from mealie.lang.providers import Translator
from mealie.pkgs.safehttp import resilient_fetch
from mealie.repos.repository_factory import AllRepositories
from mealie.schema.recipe.recipe import Recipe
from mealie.services.scraper import cleaner
@@ -13,7 +14,6 @@ from .scraper_strategies import (
RecipeScraperOpenAITranscription,
RecipeScraperOpenGraph,
RecipeScraperPackage,
safe_scrape_html,
)
DEFAULT_SCRAPER_STRATEGIES: list[type[ABCScraperStrategy]] = [
@@ -60,13 +60,16 @@ class RecipeScraper:
organizers, so that strategies which have to ask a provider for them can skip the request.
"""
resolved_url: str | None = None
if not html:
if on_progress:
await on_progress(self.translator.t("recipe.create-progress.fetching-webpage"))
html = await safe_scrape_html(url)
if not html:
fetched = await resilient_fetch(url)
if not fetched or not fetched.text:
return None, None
html = fetched.text
resolved_url = fetched.url
for ScraperClass in self.scrapers:
scraper = ScraperClass(
@@ -76,6 +79,7 @@ class RecipeScraper:
raw_html=html,
include_tags=include_tags,
include_categories=include_categories,
resolved_url=resolved_url,
)
if not scraper.can_scrape():
self.logger.debug(f"Skipping {scraper.__class__.__name__}")
+11 -2
View File
@@ -87,6 +87,7 @@ class ABCScraperStrategy(ABC):
"""
url: str
resolved_url: str | None
def __init__(
self,
@@ -96,9 +97,11 @@ class ABCScraperStrategy(ABC):
raw_html: str | None = None,
include_tags: bool = False,
include_categories: bool = False,
resolved_url: str | None = None,
) -> None:
self.logger = get_logger()
self.url = url
self.resolved_url = resolved_url
self.raw_html = raw_html
self.translator = translator
self.repos = repos
@@ -108,6 +111,11 @@ class ABCScraperStrategy(ABC):
self.include_tags = include_tags
self.include_categories = include_categories
@property
def resource_url(self) -> str:
"""Landing URL after redirects, or the URL the user supplied if we have not fetched."""
return self.resolved_url or self.url
@abstractmethod
def can_scrape(self) -> bool: ...
@@ -358,6 +366,7 @@ class RecipeScraperOpenAI(ABCScraperStrategy):
# the HTML belongs to the URL, so it's passed as the page's content rather than as
# extra material, which would compile the same page twice
input=WorkflowInput(page_content=self.raw_html, url=self.url),
resolved_url=self.resolved_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
@@ -393,7 +402,7 @@ class RecipeScraperOpenAITranscription(ABCScraperStrategy):
return False
# Check if we can actually download something to transcribe
return transcription.is_video_url(self.url)
return transcription.is_video_url(self.resource_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
@@ -408,7 +417,7 @@ class RecipeScraperOpenAITranscription(ABCScraperStrategy):
if on_progress:
await on_progress(self.translator.t("recipe.create-progress.downloading-video"))
video_data = await asyncio.to_thread(transcription.download_video, self.url, temp_path)
video_data = await asyncio.to_thread(transcription.download_video, self.resource_url, temp_path)
async def report_transcribing() -> None:
if on_progress:
@@ -1,10 +1,12 @@
import json
import httpx
import pytest
from fastapi.testclient import TestClient
import mealie.services.recipe.import_workflow.steps.compile_source as compile_source_module
import mealie.services.scraper.recipe_scraper as recipe_scraper_module
from mealie.pkgs.safehttp.fetch import FetchResult
from mealie.schema.group.ai_providers import AIProviderCreate, AIProviderSettingsUpdate
from mealie.schema.openai.compiled_source import OpenAICompiledSource
from mealie.schema.openai.organizers import OpenAIOrganizers
@@ -56,10 +58,10 @@ def openai_scraper_setup(monkeypatch: pytest.MonkeyPatch, bare_html: str, unique
AIProviderSettingsUpdate(default_provider_id=provider.id, audio_provider_id=None, image_provider_id=None),
)
async def mock_safe_scrape_html(url: str) -> str:
return bare_html
async def mock_resilient_fetch(url: str) -> FetchResult:
return FetchResult(bare_html.encode(), 200, url, httpx.Headers(), "utf-8")
monkeypatch.setattr(recipe_scraper_module, "safe_scrape_html", mock_safe_scrape_html)
monkeypatch.setattr(recipe_scraper_module, "resilient_fetch", mock_resilient_fetch)
monkeypatch.setattr(RecipeDataService, "scrape_image", lambda *_: "TEST_IMAGE")
@@ -1,12 +1,14 @@
import json
from pathlib import Path
import httpx
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.pkgs.safehttp.fetch import FetchResult
from mealie.schema.group.ai_providers import AIProviderCreate, AIProviderSettingsUpdate
from mealie.schema.openai.recipe import OpenAIRecipe, OpenAIRecipeIngredient, OpenAIRecipeInstruction
from mealie.services.openai import OpenAIService
@@ -45,10 +47,10 @@ def video_scraper_setup(monkeypatch: pytest.MonkeyPatch, unique_user: TestUser):
)
# Prevent any real HTTP calls during scraping
async def mock_safe_scrape_html(url: str) -> str:
return "<html></html>"
async def mock_resilient_fetch(url: str) -> FetchResult:
return FetchResult(b"<html></html>", 200, url, httpx.Headers(), "utf-8")
monkeypatch.setattr(recipe_scraper_module, "safe_scrape_html", mock_safe_scrape_html)
monkeypatch.setattr(recipe_scraper_module, "resilient_fetch", mock_resilient_fetch)
def test_create_recipe_from_video(
@@ -11,7 +11,7 @@ from zipfile import ZipFile
import pytest
from bs4 import BeautifulSoup
from fastapi.testclient import TestClient
from httpx import Response
from httpx import Headers, Response
from pytest import MonkeyPatch
from recipe_scrapers._schemaorg import SchemaOrg
from recipe_scrapers.plugins import SchemaOrgFillPlugin
@@ -19,6 +19,7 @@ from slugify import slugify
import mealie.services.scraper.recipe_scraper as recipe_scraper_module
from mealie.db.models.recipe import RecipeModel
from mealie.pkgs.safehttp.fetch import FetchResult
from mealie.pkgs.safehttp.transport import AsyncSafeTransport
from mealie.schema.cookbook.cookbook import SaveCookBook
from mealie.schema.labels.multi_purpose_label import MultiPurposeLabelSave
@@ -112,10 +113,10 @@ def test_create_by_url(
):
for recipe_data in recipe_test_data:
# Prevent any real HTTP calls during scraping
async def mock_safe_scrape_html(url: str) -> str:
return "<html></html>"
async def mock_resilient_fetch(url: str) -> FetchResult:
return FetchResult(b"<html></html>", 200, url, Headers(), "utf-8")
monkeypatch.setattr(recipe_scraper_module, "safe_scrape_html", mock_safe_scrape_html)
monkeypatch.setattr(recipe_scraper_module, "resilient_fetch", mock_resilient_fetch)
# Override the get_html method of the RecipeScraperOpenGraph to return the test html
for scraper_cls in DEFAULT_SCRAPER_STRATEGIES:
@@ -232,10 +233,10 @@ def test_create_by_url_stream_done(
unique_user: TestUser,
monkeypatch: MonkeyPatch,
):
async def mock_safe_scrape_html(url: str) -> str:
return "<html></html>"
async def mock_resilient_fetch(url: str) -> FetchResult:
return FetchResult(b"<html></html>", 200, url, Headers(), "utf-8")
monkeypatch.setattr(recipe_scraper_module, "safe_scrape_html", mock_safe_scrape_html)
monkeypatch.setattr(recipe_scraper_module, "resilient_fetch", mock_resilient_fetch)
recipe_data = recipe_test_data[0]
for scraper_cls in DEFAULT_SCRAPER_STRATEGIES:
@@ -0,0 +1,171 @@
from pathlib import Path
from unittest.mock import MagicMock
import httpx
import pytest
import mealie.services.scraper.recipe_scraper as recipe_scraper_module
from mealie.lang.providers import get_locale_provider
from mealie.pkgs.safehttp.fetch import FetchResult
from mealie.schema.openai.recipe import OpenAIRecipe, OpenAIRecipeIngredient, OpenAIRecipeInstruction
from mealie.services.openai import OpenAIService, transcription
from mealie.services.scraper.recipe_scraper import RecipeScraper
from mealie.services.scraper.scraper_strategies import (
ABCScraperStrategy,
RecipeScraperOpenAI,
RecipeScraperOpenAITranscription,
RecipeScraperOpenGraph,
)
SHARE_URL = "https://www.facebook.com/share/r/1DWziuVHRi/"
REEL_URL = "https://www.facebook.com/reel/1433866715330175/"
def _html_fetch(url: str, html: str = "<html></html>") -> FetchResult:
return FetchResult(html.encode(), 200, url, httpx.Headers(), "utf-8")
def test_resource_url_prefers_landing_url():
strategy = RecipeScraperOpenGraph(
SHARE_URL,
get_locale_provider(),
repos=None, # type: ignore[arg-type]
resolved_url=REEL_URL,
)
assert strategy.resource_url == REEL_URL
assert strategy.url == SHARE_URL
def test_resource_url_falls_back_to_supplied_url():
strategy = RecipeScraperOpenGraph(
SHARE_URL,
get_locale_provider(),
repos=None, # type: ignore[arg-type]
)
assert strategy.resource_url == SHARE_URL
def test_transcription_classifies_the_landing_url(monkeypatch: pytest.MonkeyPatch):
classified: list[str] = []
monkeypatch.setattr(transcription, "is_video_url", lambda url: classified.append(url) or True)
repos = MagicMock()
repos.group_ai_provider_settings.get_one.return_value = MagicMock(audio_provider_enabled=True)
strategy = RecipeScraperOpenAITranscription(
SHARE_URL,
get_locale_provider(),
repos,
resolved_url=REEL_URL,
)
assert strategy.can_scrape() is True
assert classified == [REEL_URL]
def test_openai_strategy_passes_resolved_url_into_workflow():
strategy = RecipeScraperOpenAI(
SHARE_URL,
get_locale_provider(),
MagicMock(),
raw_html="<html></html>",
resolved_url=REEL_URL,
)
ctx = strategy.build_context()
assert ctx.input.url == SHARE_URL
assert ctx.resolved_url == REEL_URL
@pytest.mark.asyncio
async def test_transcription_downloads_landing_url_and_keeps_org_url(monkeypatch: pytest.MonkeyPatch):
downloaded: list[str] = []
def mock_download_video(url: str, temp_path: Path):
downloaded.append(url)
return {
"audio": temp_path / "mealie.mp3",
"subtitle": None,
"title": "A reel",
"description": "desc",
"thumbnail_url": None,
"transcription": "mix flour and water",
}
async def mock_resolve_transcription(video_data, openai_service, before_transcribe=None):
return video_data["transcription"]
async def mock_get_response(self, prompt, message, *args, **kwargs):
return OpenAIRecipe(
name="Reel recipe",
description="desc",
ingredients=[OpenAIRecipeIngredient(text="flour")],
instructions=[OpenAIRecipeInstruction(text="mix")],
)
monkeypatch.setattr(transcription, "download_video", mock_download_video)
monkeypatch.setattr(transcription, "resolve_transcription", mock_resolve_transcription)
monkeypatch.setattr(OpenAIService, "get_response", mock_get_response)
strategy = RecipeScraperOpenAITranscription(
SHARE_URL,
get_locale_provider(),
MagicMock(),
resolved_url=REEL_URL,
)
recipe, extras = await strategy.parse()
assert downloaded == [REEL_URL]
assert recipe is not None
assert recipe.org_url == SHARE_URL
assert extras is not None
@pytest.mark.asyncio
async def test_scrape_passes_landing_url_to_strategies(monkeypatch: pytest.MonkeyPatch):
seen: list[str | None] = []
class CaptureStrategy(ABCScraperStrategy):
def can_scrape(self) -> bool:
seen.append(self.resolved_url)
return False
async def get_html(self, url: str) -> str:
return ""
async def parse(self, on_progress=None):
return None, None
async def mock_resilient_fetch(url: str) -> FetchResult:
return _html_fetch(REEL_URL)
monkeypatch.setattr(recipe_scraper_module, "resilient_fetch", mock_resilient_fetch)
scraper = RecipeScraper(MagicMock(), get_locale_provider(), scrapers=[CaptureStrategy])
await scraper.scrape(SHARE_URL)
assert seen == [REEL_URL]
@pytest.mark.asyncio
async def test_scrape_without_fetch_does_not_invent_a_landing_url():
seen: list[str | None] = []
class CaptureStrategy(ABCScraperStrategy):
def can_scrape(self) -> bool:
seen.append(self.resolved_url)
return False
async def get_html(self, url: str) -> str:
return ""
async def parse(self, on_progress=None):
return None, None
scraper = RecipeScraper(MagicMock(), get_locale_provider(), scrapers=[CaptureStrategy])
await scraper.scrape(SHARE_URL, html="<html></html>")
assert seen == [None]