diff --git a/mealie/services/scraper/cleaner.py b/mealie/services/scraper/cleaner.py
index 0a4d99214..1da3403a3 100644
--- a/mealie/services/scraper/cleaner.py
+++ b/mealie/services/scraper/cleaner.py
@@ -33,6 +33,12 @@ MATCH_GRAMS = re.compile(r"\d\s*(?:g|gm|gr|grams?)\b", re.IGNORECASE)
MATCH_HTML_TAGS = re.compile(r"<[^<]+?>")
""" Matches HTML tags `
Text
` -> `Text` """
+MATCH_LINE_BREAK_TAGS = re.compile(r"|
", re.IGNORECASE)
+""" Matches tags that end a line ``, `
`, `
` """
+
+MATCH_SPACES_AROUND_NEWLINE = re.compile(r" *\n *")
+""" Matches spaces next to a new line `Text \n Text` -> `Text\nText` """
+
MATCH_MULTI_SPACE = re.compile(r" +")
""" Matches multiple spaces `Hello World` -> `Hello World` """
@@ -107,12 +113,14 @@ def clean_string(text: str | list | int | float) -> str:
text = typing.cast(str, text) # at this point we know text is a string
cleaned_text = html.unescape(text)
+ cleaned_text = MATCH_LINE_BREAK_TAGS.sub("\n", cleaned_text)
cleaned_text = MATCH_HTML_TAGS.sub("", cleaned_text)
+ cleaned_text = cleaned_text.replace("\xa0", " ").replace("\t", " ")
cleaned_text = MATCH_MULTI_SPACE.sub(" ", cleaned_text)
+ cleaned_text = MATCH_SPACES_AROUND_NEWLINE.sub("\n", cleaned_text)
cleaned_text = MATCH_ERRONEOUS_WHITE_SPACE.sub("\n\n", cleaned_text)
- cleaned_text = cleaned_text.replace("", "\n").replace("\xa0", " ").replace("\t", " ").strip()
- return cleaned_text
+ return cleaned_text.strip()
def clean_image(image: str | list | dict | None = None, default: str = NO_IMAGE) -> list[str]:
diff --git a/mealie/services/scraper/scraper_strategies.py b/mealie/services/scraper/scraper_strategies.py
index 1275827ec..2a12b4287 100644
--- a/mealie/services/scraper/scraper_strategies.py
+++ b/mealie/services/scraper/scraper_strategies.py
@@ -56,16 +56,36 @@ def _is_stringified_mapping(text: str) -> bool:
return text.strip().startswith(("{'", '{"'))
+def _only_adds_line_breaks(structured: list[dict], flat: list[dict]) -> bool:
+ """True when the structured parse is the flat parse, step for step, plus line breaks.
+
+ recipe_scrapers collapses all whitespace inside a step, so a step that a site writes as
+ several paragraphs arrives as one run-on line. The structured data still has the breaks.
+ """
+ structured_texts = [step.get("text", "") for step in structured]
+ flat_texts = [step["text"] for step in flat if step.get("text")]
+
+ return (
+ any("\n" in text for text in structured_texts)
+ and len(structured_texts) == len(flat_texts)
+ and all(_comparable(a) == _comparable(b) for a, b in zip(structured_texts, flat_texts, strict=True))
+ )
+
+
def prefer_structured_instructions(structured: list[dict], flat: list[dict]) -> bool:
"""Decide whether the structured parse should replace the scraper's flattened text.
- Two things have to hold. The structured parse must gain a heading, otherwise there is
+ It does when it holds the same steps and only adds line breaks. Otherwise two things
+ have to hold. The structured parse must gain a heading, otherwise there is
nothing the flat text could not already express. And it must account for every piece of
text the flat parse produced, as either a step or a heading: a site specific scraper
reads the instructions off the page rather than out of the structured data, and its text
can differ from, or beat, what the page publishes as JSON-LD. That keeps the structured
data a refinement of the same content, never a replacement of better content.
"""
+ if _only_adds_line_breaks(structured, flat):
+ return True
+
headings = [step["title"] for step in structured if step.get("title")]
headings += [step["summary"] for step in structured if step.get("summary")]
if not headings:
diff --git a/tests/unit_tests/services_tests/scraper_tests/test_cleaner_parts.py b/tests/unit_tests/services_tests/scraper_tests/test_cleaner_parts.py
index 38384c7a4..ddf374df5 100644
--- a/tests/unit_tests/services_tests/scraper_tests/test_cleaner_parts.py
+++ b/tests/unit_tests/services_tests/scraper_tests/test_cleaner_parts.py
@@ -87,6 +87,21 @@ clean_string_test_cases = (
input=[None, None],
expected="",
),
+ CleanerCase(
+ test_id="paragraphs_become_line_breaks",
+ input="Boil a full kettle.
Make the stock.
",
+ expected="Boil a full kettle.\nMake the stock.",
+ ),
+ CleanerCase(
+ test_id="br_becomes_line_break",
+ input="Boil a full kettle.
Make the stock.
Stir in the paste.",
+ expected="Boil a full kettle.\nMake the stock.\nStir in the paste.",
+ ),
+ CleanerCase(
+ test_id="spaces_around_line_breaks",
+ input="Boil a full kettle.
\n Make the stock.
",
+ expected="Boil a full kettle.\n\nMake the stock.",
+ ),
CleanerCase(
test_id="unexpected type",
input={"key": "value"},
diff --git a/tests/unit_tests/services_tests/scraper_tests/test_scraper_strategies.py b/tests/unit_tests/services_tests/scraper_tests/test_scraper_strategies.py
index 8a0f493d6..f52dd0529 100644
--- a/tests/unit_tests/services_tests/scraper_tests/test_scraper_strategies.py
+++ b/tests/unit_tests/services_tests/scraper_tests/test_scraper_strategies.py
@@ -225,3 +225,43 @@ def test_prefer_structured_instructions_ignores_a_stringified_step_dict():
flat = [{"text": "{'@type': 'HowToStep', 'text': 'Dice the onion.'}"}]
assert prefer_structured_instructions(structured, flat) is True
+
+
+def test_structured_data_keeps_line_breaks_the_scraper_drops(monkeypatch):
+ """recipe_scrapers collapses the whitespace inside a step, so paragraphs run together.
+
+ HelloFresh writes each step as several `` paragraphs. The structured data still has
+ them, and when it holds the same text as the flat parse, it is the better source.
+ """
+ html = RecipeScraperPackage.ld_json_to_html(json.dumps(FLAT_RECIPE))
+ scraped_data = scrape_html(html, org_url="https://example.com", supported_only=False)
+ scraped_data.schema.data["recipeInstructions"] = [
+ {"@type": "HowToStep", "text": "
Boil a full kettle.
\nMake the stock.
"},
+ {"@type": "HowToStep", "text": "Chop the shallot.
"},
+ ]
+ monkeypatch.setattr(scraped_data, "instructions", lambda: "Boil a full kettle. Make the stock.\nChop the shallot.")
+
+ strategy = RecipeScraperPackage(
+ "https://example.com",
+ get_locale_provider(),
+ repos=None, # type: ignore[arg-type]
+ )
+ recipe, _ = strategy.clean_scraper(scraped_data, "https://example.com")
+ steps = recipe.recipe_instructions
+ assert steps is not None
+
+ assert [step.text for step in steps] == ["Boil a full kettle.\n\nMake the stock.", "Chop the shallot."]
+
+
+def test_prefer_structured_instructions_for_line_breaks_only_when_the_text_matches():
+ structured = [{"text": "Boil a full kettle.\nMake the stock."}]
+
+ assert prefer_structured_instructions(structured, [{"text": "Boil a full kettle. Make the stock."}]) is True
+ # a different split or different words means the scraper read something else
+ assert (
+ prefer_structured_instructions(structured, [{"text": "Boil a full kettle."}, {"text": "Make the stock."}])
+ is False
+ )
+ assert prefer_structured_instructions(structured, [{"text": "Boil a kettle. Make the stock."}]) is False
+ # with no line breaks there is nothing to gain
+ assert prefer_structured_instructions([{"text": "Boil a full kettle."}], [{"text": "Boil a full kettle."}]) is False