| 1 | """Best-window extraction for rerankable evidence snippets.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import re |
| 6 | |
| 7 | from . import relevance, schema |
| 8 | |
| 9 | |
| 10 | # Stored length of a quoted comment. Renderers shorten further at display |
| 11 | # time and add their own ellipsis, so none is added here. |
| 12 | QUOTE_LIMIT = 400 |
| 13 | # A sentence end is used when it falls in the last part of the allowed text; |
| 14 | # an earlier one would throw away most of the quote. |
| 15 | _QUOTE_SENTENCE_ZONE = 0.6 |
| 16 | _SENTENCE_END = re.compile(r"[.!?][\"'\u201d\u2019)\]]*(?=\s)") |
| 17 | |
| 18 | |
| 19 | def cut_quote(text: str, limit: int = QUOTE_LIMIT) -> str: |
| 20 | """Shorten a comment to ``limit`` characters without cutting a word. |
| 21 | |
| 22 | Cuts at the last sentence end inside the limit when one falls in its last |
| 23 | part, otherwise at the last word boundary, otherwise (one unbroken run of |
| 24 | characters) at the limit. Text that already fits is returned stripped. |
| 25 | """ |
| 26 | text = (text or "").strip() |
| 27 | if len(text) <= limit: |
| 28 | return text |
| 29 | # One character past the limit, so an end or a space right at it counts. |
| 30 | window = text[: limit + 1] |
| 31 | ends = [match.end() for match in _SENTENCE_END.finditer(window) if match.end() <= limit] |
| 32 | if ends and ends[-1] >= limit * _QUOTE_SENTENCE_ZONE: |
| 33 | return window[: ends[-1]].rstrip() |
| 34 | # Any whitespace is a word boundary: comments carry newlines and tabs. |
| 35 | space = next((i for i in range(len(window) - 1, -1, -1) if window[i].isspace()), -1) |
| 36 | if space > 0: |
| 37 | return window[:space].rstrip() |
| 38 | return text[:limit] |
| 39 | |
| 40 | |
| 41 | def _truncate_words(text: str, max_words: int) -> str: |
| 42 | words = text.split() |
| 43 | if len(words) <= max_words: |
| 44 | return text.strip() |
| 45 | return " ".join(words[:max_words]).strip() + "..." |
| 46 | |
| 47 | |
| 48 | def _windows(words: list[str], size: int, overlap: int) -> list[str]: |
| 49 | if not words: |
| 50 | return [] |
| 51 | if len(words) <= size: |
| 52 | return [" ".join(words)] |
| 53 | step = max(1, size - overlap) |
| 54 | return [ |
| 55 | " ".join(words[start:start + size]) |
| 56 | for start in range(0, len(words), step) |
| 57 | ] |
| 58 | |
| 59 | |
| 60 | def extract_best_snippet( |
| 61 | item: schema.SourceItem, |
| 62 | ranking_query: "str | relevance.PreparedQuery", |
| 63 | max_words: int = 120, |
| 64 | ) -> str: |
| 65 | """Prefer existing snippets, else extract the best matching evidence window.""" |
| 66 | preferred = item.snippet.strip() |
| 67 | if preferred: |
| 68 | return _truncate_words(preferred, max_words) |
| 69 | |
| 70 | body = item.body.strip() |
| 71 | if not body: |
| 72 | return _truncate_words(item.title, max_words) |
| 73 | |
| 74 | words = body.split() |
| 75 | candidates = _windows(words, size=min(max_words, 110), overlap=30) |
| 76 | if not candidates: |
| 77 | return _truncate_words(body, max_words) |
| 78 | |
| 79 | prepared_query = ranking_query if isinstance(ranking_query, relevance.PreparedQuery) else relevance.PreparedQuery(ranking_query) |
| 80 | best = max( |
| 81 | candidates, |
| 82 | key=lambda candidate: relevance.token_overlap_relevance(prepared_query, candidate), |
| 83 | ) |
| 84 | return _truncate_words(best, max_words) |
| 85 |