fix: keep line breaks inside imported recipe steps (#9010)

This commit is contained in:
Hayden authored and GitHub committed 2026-11-05 15:28:06 +00:00
1 parent d30ea632e6
commit eecb5cf713
4 files changed
+86 -3

No files matched your search

+10 -2
View File
@@ -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 `<p>Text</p>` -> `Text` """
MATCH_LINE_BREAK_TAGS = re.compile(r"</p\s*>|<br\s*/?>", re.IGNORECASE)
""" Matches tags that end a line `</p>`, `<br>`, `<br/>` """
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("</p>", "\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]:
+21 -1
View File
@@ -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:
@@ -87,6 +87,21 @@ clean_string_test_cases = (
input=[None, None],
expected="",
),
CleanerCase(
test_id="paragraphs_become_line_breaks",
input="<p>Boil a full kettle.</p><p>Make the stock.</p>",
expected="Boil a full kettle.\nMake the stock.",
),
CleanerCase(
test_id="br_becomes_line_break",
input="Boil a full kettle.<br>Make the stock.<br/>Stir in the paste.",
expected="Boil a full kettle.\nMake the stock.\nStir in the paste.",
),
CleanerCase(
test_id="spaces_around_line_breaks",
input="<p>Boil a full kettle. </p>\n<p> Make the stock.</p>",
expected="Boil a full kettle.\n\nMake the stock.",
),
CleanerCase(
test_id="unexpected type",
input={"key": "value"},
@@ -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 `<p>` 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": "<p>Boil a full kettle. </p>\n<p>Make the stock.</p>"},
{"@type": "HowToStep", "text": "<p>Chop the shallot.</p>"},
]
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