refactor(news-/works-keyword-search): extract snippet logic
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -4,7 +4,6 @@ Business logic for the "aktuell" news index on the INSE cluster.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
@@ -12,6 +11,12 @@ from inse.exceptions import ElasticsearchException
|
||||
|
||||
from ..integrations import elasticsearch, llm
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
from ..snippets import (
|
||||
FRAGMENT_FIELD,
|
||||
HIGHLIGHT_TAGS,
|
||||
SNIPPET_FRAGMENT_CHARS,
|
||||
snippet_with_context,
|
||||
)
|
||||
from ..topics.logic import vector_search_topics_batch
|
||||
from .model import (
|
||||
MatchedTopic,
|
||||
@@ -31,29 +36,16 @@ TOPICS_INDEX = "aktuell_openalex_topics"
|
||||
|
||||
_SESSION_TOPIC_CACHE: dict[str, list] = {}
|
||||
|
||||
SNIPPET_FRAGMENT_CHARS = 500
|
||||
SNIPPET_FRAGMENT_COUNT = 3
|
||||
SNIPPET_FRAGMENT_SEPARATOR = " … "
|
||||
|
||||
SNIPPET_CONTEXT_BEFORE_CHARS = 400
|
||||
SNIPPET_CONTEXT_AFTER_CHARS = 1100
|
||||
SNIPPET_BOUNDARY_CHARS = 150
|
||||
SNIPPET_ELLIPSIS = "…"
|
||||
|
||||
_EM_TAG = re.compile(r"<em>(.*?)</em>", re.DOTALL)
|
||||
|
||||
PREVIEW_WORD_COUNT = 80
|
||||
|
||||
CONTENT_HIGHLIGHT = {
|
||||
"fields": {
|
||||
"full_content": {
|
||||
"fragment_size": SNIPPET_FRAGMENT_CHARS,
|
||||
"number_of_fragments": SNIPPET_FRAGMENT_COUNT,
|
||||
**FRAGMENT_FIELD,
|
||||
"no_match_size": SNIPPET_FRAGMENT_CHARS,
|
||||
}
|
||||
},
|
||||
"pre_tags": ["<em>"],
|
||||
"post_tags": ["</em>"],
|
||||
**HIGHLIGHT_TAGS,
|
||||
"require_field_match": False,
|
||||
}
|
||||
|
||||
@@ -774,7 +766,7 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
fragments = hit.get("highlight", {}).get("full_content")
|
||||
|
||||
if fragments:
|
||||
snippet = _snippet_with_context(source, fragments)
|
||||
snippet = snippet_with_context(source.get("full_content"), fragments)
|
||||
else:
|
||||
snippet = _make_preview(source)
|
||||
|
||||
@@ -788,110 +780,6 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
)
|
||||
|
||||
|
||||
def _snippet_with_context(source: dict, fragments: list) -> str:
|
||||
|
||||
joined = SNIPPET_FRAGMENT_SEPARATOR.join(fragments)
|
||||
text = source.get("full_content")
|
||||
terms = _marked_terms(joined)
|
||||
|
||||
if not text or not terms:
|
||||
return joined
|
||||
|
||||
span = _first_term_span(text, terms)
|
||||
if span is None:
|
||||
return joined
|
||||
|
||||
start, end = _window_bounds(text, *span)
|
||||
window = _mark_terms(text[start:end], terms)
|
||||
|
||||
if start > 0:
|
||||
window = f"{SNIPPET_ELLIPSIS} {window}"
|
||||
if end < len(text):
|
||||
window = f"{window} {SNIPPET_ELLIPSIS}"
|
||||
|
||||
return window
|
||||
|
||||
|
||||
def _marked_terms(fragment_text: str) -> list:
|
||||
|
||||
by_key: dict[str, str] = {}
|
||||
for match in _EM_TAG.finditer(fragment_text):
|
||||
term = match.group(1).strip()
|
||||
if term:
|
||||
by_key.setdefault(term.lower(), term)
|
||||
return list(by_key.values())
|
||||
|
||||
|
||||
def _first_term_span(text: str, terms: list) -> tuple | None:
|
||||
|
||||
lowered = text.lower()
|
||||
spans = [
|
||||
(index, index + len(term))
|
||||
for term, index in ((term, lowered.find(term.lower())) for term in terms)
|
||||
if index >= 0
|
||||
]
|
||||
return min(spans) if spans else None
|
||||
|
||||
|
||||
def _window_bounds(text: str, match_start: int, match_end: int) -> tuple:
|
||||
|
||||
start = max(0, match_start - SNIPPET_CONTEXT_BEFORE_CHARS)
|
||||
end = min(len(text), match_end + SNIPPET_CONTEXT_AFTER_CHARS)
|
||||
|
||||
if start > 0:
|
||||
start = _forward_to_boundary(text, start, match_start)
|
||||
if end < len(text):
|
||||
end = _back_to_boundary(text, end, match_end)
|
||||
|
||||
return start, end
|
||||
|
||||
|
||||
def _forward_to_boundary(text: str, start: int, limit: int) -> int:
|
||||
|
||||
ahead = text[start : min(limit, start + SNIPPET_BOUNDARY_CHARS)]
|
||||
|
||||
sentence = ahead.find(". ")
|
||||
if sentence >= 0:
|
||||
return start + sentence + 2
|
||||
|
||||
space = ahead.find(" ")
|
||||
return start + space + 1 if space >= 0 else start
|
||||
|
||||
|
||||
def _back_to_boundary(text: str, end: int, floor: int) -> int:
|
||||
|
||||
ahead = text[end : end + SNIPPET_BOUNDARY_CHARS]
|
||||
|
||||
sentence = ahead.find(". ")
|
||||
if sentence >= 0:
|
||||
return end + sentence + 1
|
||||
|
||||
space = text.rfind(" ", floor, end)
|
||||
return space if space > floor else end
|
||||
|
||||
|
||||
def _mark_terms(window: str, terms: list) -> str:
|
||||
|
||||
lowered = window.lower()
|
||||
spans = sorted(
|
||||
(index, index + len(term))
|
||||
for term, index in ((term, lowered.find(term.lower())) for term in terms)
|
||||
if index >= 0
|
||||
)
|
||||
|
||||
marked = []
|
||||
cursor = 0
|
||||
for start, end in spans:
|
||||
if start < cursor:
|
||||
continue
|
||||
marked.append(window[cursor:start])
|
||||
marked.append(f"<em>{window[start:end]}</em>")
|
||||
cursor = end
|
||||
marked.append(window[cursor:])
|
||||
|
||||
return "".join(marked)
|
||||
|
||||
|
||||
def _make_preview(source: dict) -> str | None:
|
||||
text = source.get("full_content") or source.get("intro_content")
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import re
|
||||
|
||||
SNIPPET_FRAGMENT_CHARS = 500
|
||||
SNIPPET_FRAGMENT_COUNT = 3
|
||||
SNIPPET_FRAGMENT_SEPARATOR = " … "
|
||||
|
||||
SNIPPET_CONTEXT_BEFORE_CHARS = 400
|
||||
SNIPPET_CONTEXT_AFTER_CHARS = 1100
|
||||
SNIPPET_BOUNDARY_CHARS = 150
|
||||
SNIPPET_ELLIPSIS = "…"
|
||||
|
||||
_EM_TAG = re.compile(r"<em>(.*?)</em>", re.DOTALL)
|
||||
|
||||
_SENTENCE_BREAK = re.compile(r"(?<![0-9]\.)(?<=[.!?])\s+|\n+")
|
||||
|
||||
FRAGMENT_FIELD = {
|
||||
"fragment_size": SNIPPET_FRAGMENT_CHARS,
|
||||
"number_of_fragments": SNIPPET_FRAGMENT_COUNT,
|
||||
}
|
||||
|
||||
WHOLE_FIELD = {"number_of_fragments": 0}
|
||||
|
||||
HIGHLIGHT_TAGS = {"pre_tags": ["<em>"], "post_tags": ["</em>"]}
|
||||
|
||||
|
||||
def snippet_with_context(text: str | None, fragments: list) -> str:
|
||||
joined = SNIPPET_FRAGMENT_SEPARATOR.join(fragments)
|
||||
terms = marked_terms(joined)
|
||||
|
||||
if not text or not terms:
|
||||
return joined
|
||||
|
||||
span = _first_term_span(text, terms)
|
||||
if span is None:
|
||||
return joined
|
||||
|
||||
start, end = _window_bounds(text, *span)
|
||||
window = _mark_terms(text[start:end], terms)
|
||||
|
||||
if start > 0:
|
||||
window = f"{SNIPPET_ELLIPSIS} {window}"
|
||||
if end < len(text):
|
||||
window = f"{window} {SNIPPET_ELLIPSIS}"
|
||||
|
||||
return window
|
||||
|
||||
|
||||
def marked_terms(fragment_text: str) -> list:
|
||||
by_key: dict[str, str] = {}
|
||||
for match in _EM_TAG.finditer(fragment_text):
|
||||
term = match.group(1).strip()
|
||||
if term:
|
||||
by_key.setdefault(term.lower(), term)
|
||||
return list(by_key.values())
|
||||
|
||||
|
||||
def _first_term_span(text: str, terms: list) -> tuple | None:
|
||||
lowered = text.lower()
|
||||
spans = [
|
||||
(index, index + len(term))
|
||||
for term, index in ((term, lowered.find(term.lower())) for term in terms)
|
||||
if index >= 0
|
||||
]
|
||||
return min(spans) if spans else None
|
||||
|
||||
|
||||
def _window_bounds(text: str, match_start: int, match_end: int) -> tuple:
|
||||
start = max(0, match_start - SNIPPET_CONTEXT_BEFORE_CHARS)
|
||||
end = min(len(text), match_end + SNIPPET_CONTEXT_AFTER_CHARS)
|
||||
|
||||
if start > 0:
|
||||
start = _forward_to_boundary(text, start, match_start)
|
||||
if end < len(text):
|
||||
end = _back_to_boundary(text, end, match_end)
|
||||
|
||||
return start, end
|
||||
|
||||
|
||||
def _forward_to_boundary(text: str, start: int, limit: int) -> int:
|
||||
|
||||
ahead = _SENTENCE_BREAK.search(text, start, min(limit, start + SNIPPET_BOUNDARY_CHARS))
|
||||
if ahead:
|
||||
return ahead.end()
|
||||
|
||||
behind_from = max(0, start - SNIPPET_BOUNDARY_CHARS)
|
||||
behind = list(_SENTENCE_BREAK.finditer(text, behind_from, start))
|
||||
if behind:
|
||||
return behind[-1].end()
|
||||
|
||||
if behind_from == 0:
|
||||
return 0
|
||||
|
||||
space = text.find(" ", start, start + SNIPPET_BOUNDARY_CHARS)
|
||||
return space + 1 if space >= 0 else start
|
||||
|
||||
|
||||
def _back_to_boundary(text: str, end: int, floor: int) -> int:
|
||||
|
||||
sentence = _SENTENCE_BREAK.search(text, end, end + SNIPPET_BOUNDARY_CHARS)
|
||||
if sentence:
|
||||
return sentence.start()
|
||||
|
||||
space = text.rfind(" ", floor, end)
|
||||
return space if space > floor else end
|
||||
|
||||
|
||||
def _mark_terms(window: str, terms: list) -> str:
|
||||
lowered = window.lower()
|
||||
spans = sorted(
|
||||
(index, index + len(term))
|
||||
for term, index in ((term, lowered.find(term.lower())) for term in terms)
|
||||
if index >= 0
|
||||
)
|
||||
|
||||
marked = []
|
||||
cursor = 0
|
||||
for start, end in spans:
|
||||
if start < cursor:
|
||||
continue
|
||||
marked.append(window[cursor:start])
|
||||
marked.append(f"<em>{window[start:end]}</em>")
|
||||
cursor = end
|
||||
marked.append(window[cursor:])
|
||||
|
||||
return "".join(marked)
|
||||
@@ -6,6 +6,12 @@ from inse.exceptions import ElasticsearchNotFoundException, NotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex, SortDirection
|
||||
from inse.models.openalex.work import Work
|
||||
from inse.snippets import (
|
||||
FRAGMENT_FIELD,
|
||||
HIGHLIGHT_TAGS,
|
||||
WHOLE_FIELD,
|
||||
snippet_with_context,
|
||||
)
|
||||
from inse.works.v2.model import (
|
||||
PrimaryCategoryYearAggregation,
|
||||
PrimaryCategoryYearAggregationPage,
|
||||
@@ -378,12 +384,10 @@ async def get_works_by_keywords(
|
||||
# back only for the works that really do carry the phrase.
|
||||
highlight={
|
||||
"fields": {
|
||||
"title": {"number_of_fragments": 0},
|
||||
"abstract": {"fragment_size": 240, "number_of_fragments": 1},
|
||||
"title": WHOLE_FIELD,
|
||||
"abstract": FRAGMENT_FIELD,
|
||||
},
|
||||
"pre_tags": ["<em>"],
|
||||
"post_tags": ["</em>"],
|
||||
"encoder": "html",
|
||||
**HIGHLIGHT_TAGS,
|
||||
},
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
@@ -414,10 +418,14 @@ def _keyword_snippet(hit: dict) -> tuple[str | None, str | None]:
|
||||
"""Picks the passage to show for a hit, preferring the title over the abstract."""
|
||||
highlight = hit.get("highlight") or {}
|
||||
|
||||
for field in ("title", "abstract"):
|
||||
fragments = highlight.get(field)
|
||||
if fragments:
|
||||
return fragments[0], field
|
||||
title_fragments = highlight.get("title")
|
||||
if title_fragments:
|
||||
return title_fragments[0], "title"
|
||||
|
||||
abstract_fragments = highlight.get("abstract")
|
||||
if abstract_fragments:
|
||||
abstract = (hit.get("_source") or {}).get("abstract")
|
||||
return snippet_with_context(abstract, abstract_fragments), "abstract"
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user