feature/news-in-keywords #301

Merged
kallweit merged 3 commits from feature/news-in-keywords into dev 2026-08-24 16:45:27 +02:00
6 changed files with 274 additions and 178 deletions
+135 -19
View File
@@ -4,6 +4,7 @@ Business logic for the "aktuell" news index on the INSE cluster.
"""
import logging
import re
from pydantic import ValidationError
@@ -30,6 +31,32 @@ 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,
"no_match_size": SNIPPET_FRAGMENT_CHARS,
}
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"require_field_match": False,
}
KEYWORD_LIMIT = 6
KEYWORD_CONTENT_CHARS = 4000
KEYWORD_SYSTEM_PROMPT = """\
@@ -87,13 +114,6 @@ async def search_news(
) -> NewsPage:
offset = (page - 1) * page_size
highlight = {
"fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"encoder": "html",
}
# Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage).
clauses = await _filter_clauses(year_from, year_to, relevance_values)
exact_query = {
@@ -115,7 +135,7 @@ async def search_news(
size=page_size,
offset=offset,
sort=None,
highlight=highlight,
highlight=CONTENT_HIGHLIGHT,
)
news_page = await _build_page(response, page, page_size)
@@ -185,13 +205,6 @@ async def search_news_by_keywords(
}
}
highlight = {
"fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"encoder": "html",
}
sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None
response = await _run_search(
@@ -200,7 +213,7 @@ async def search_news_by_keywords(
size=page_size,
offset=(page - 1) * page_size,
sort=sort,
highlight=None if wanted_topic_ids else highlight,
highlight=None if wanted_topic_ids else CONTENT_HIGHLIGHT,
)
news_page = await _build_page(response, page, page_size)
@@ -761,7 +774,7 @@ def _parse_hit(hit: dict) -> NewsArticle:
fragments = hit.get("highlight", {}).get("full_content")
if fragments:
snippet = fragments[0]
snippet = _snippet_with_context(source, fragments)
else:
snippet = _make_preview(source)
@@ -775,15 +788,118 @@ 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("intro_content") or source.get("full_content")
text = source.get("full_content") or source.get("intro_content")
if not text:
return None
words = text.split()
PREVIEW_WORD_COUNT = 10
preview = " ".join(words[:PREVIEW_WORD_COUNT])
if len(words) > PREVIEW_WORD_COUNT:
preview = preview + " …"
@@ -65,38 +65,46 @@
class="title"
[routerLink]="['/news', article.id]"
(click)="$event.stopPropagation()">
{{ article.maintitle || 'Kein Titel' }}
<app-highlighted-text
[content]="article.maintitle || 'Kein Titel'"
[highlights]="titleHighlights().get(article.id) ?? []" />
</a>
</div>
</ng-template>
<ng-template #snippetTmp let-article>
<div class="snippet-detail">
@if (snippetSegments().get(article.id); as segments) {
<span class="snippet-label">Fundstelle im Artikel</span>
<p class="snippet">
@for (segment of segments; track $index) {
@if (segment.isSearchMatch) {
<mark
class="snippet-mark"
[class.has-topic]="!!segment.color"
[style.--t]="segment.color"
[matTooltip]="segment.tooltip ?? ''"
matTooltipPosition="above"
>{{ segment.text }}</mark
>
} @else {
<span>{{ segment.text }}</span>
}
}
</p>
} @else {
<span class="empty-text">
Für diesen Artikel liegt keine Textstelle zu den gesuchten Keywords
vor.
</span>
}
</div>
<app-table-detail-row>
<div table-detail-header>
<h4 class="panel-field__label">Fundstelle im Artikel</h4>
</div>
<ng-container table-detail-body>
@if (titleHighlights().get(article.id); as titleTerms) {
<article class="panel-field panel-field--full">
<h4 class="panel-field__label">Titel</h4>
<app-highlighted-text
class="panel-field__text"
[content]="article.maintitle"
[highlights]="titleTerms" />
</article>
}
@if (snippetHighlights().get(article.id); as snippet) {
<article class="panel-field panel-field--full">
<h4 class="panel-field__label">Artikeltext</h4>
<app-highlighted-text
class="panel-field__text"
[content]="snippet.content"
[highlights]="snippet.terms" />
</article>
} @else {
<span class="empty-text">
Für diesen Artikel liegt keine Textstelle zu den gesuchten Keywords
vor.
</span>
}
</ng-container>
</app-table-detail-row>
</ng-template>
<ng-template #dateTmp let-article>
@@ -115,6 +115,10 @@
color: var(--sg-text);
text-decoration: underline;
}
app-highlighted-text {
display: inline;
}
}
.expand-icon {
@@ -126,48 +130,6 @@
}
}
/* ============================================================
EXPANDED DETAIL ROW
============================================================ */
.snippet-detail {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.875rem 1rem 1rem 3rem;
background: var(--sg-surface-soft);
}
.snippet-label {
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.snippet {
margin: 0;
font-size: 12.5px;
line-height: 1.6;
color: var(--sg-text-secondary);
overflow-wrap: anywhere;
}
.snippet-mark {
background: transparent;
color: var(--sg-blue-highlight);
font-weight: 700;
cursor: help;
&.has-topic {
color: var(--t);
text-decoration: underline;
text-decoration-color: var(--t);
text-decoration-thickness: 2px;
text-underline-offset: 2px;
}
}
.date-text {
white-space: nowrap;
}
@@ -42,18 +42,17 @@ import {
SORT_ICON,
} from '../../../../shared/ui/icons';
import {
keywordTooltip,
splitByKeywords,
topicKeywordColors,
} from '../../../../resolvers/utils/keyword-highlight';
containsHighlightTerm,
HighlightedTextComponent,
HighlightTerm,
} from '../../../../shared/ui/highlighted-text/highlighted-text.component';
import { TableDetailRowComponent } from '../../../../shared/ui/table-detail-row/table-detail-row.component';
type NewsResult = NewsPage['results'][number];
interface SnippetSegment {
text: string;
color: string | null;
tooltip: string | null;
isSearchMatch: boolean;
interface SnippetHighlight {
content: string;
terms: HighlightTerm[];
}
@Component({
@@ -64,6 +63,8 @@ interface SnippetSegment {
MatIconModule,
MatTooltipModule,
DataTableComponent,
HighlightedTextComponent,
TableDetailRowComponent,
AppTopicChipComponent,
ChipOverflowToggleComponent,
FilterCardComponent,
@@ -264,79 +265,71 @@ export class KeywordsToNewsResultsComponent {
return this.dataTable()?.expandedElement() === article;
}
readonly snippetSegments = computed(() => {
const byArticleId = new Map<string, SnippetSegment[]>();
readonly snippetHighlights = computed(() => {
const byArticleId = new Map<string, SnippetHighlight>();
for (const article of this.elements()) {
const segments = this.buildSnippetSegments(article);
if (segments.length) {
byArticleId.set(article.id, segments);
const snippet = this.buildSnippetHighlight(article);
if (snippet) {
byArticleId.set(article.id, snippet);
}
}
return byArticleId;
});
private buildSnippetSegments(article: NewsResult): SnippetSegment[] {
readonly titleHighlights = computed(() => {
const byArticleId = new Map<string, HighlightTerm[]>();
const keywords = this.state.keywords();
for (const article of this.elements()) {
const found = keywords.filter((keyword) =>
containsHighlightTerm(article.maintitle, [keyword]),
);
if (found.length) {
byArticleId.set(article.id, this.toHighlightTerms(found));
}
}
return byArticleId;
});
private buildSnippetHighlight(article: NewsResult): SnippetHighlight | null {
const snippet = article.snippet;
if (!snippet) {
return [];
return null;
}
const keywordColors = topicKeywordColors(article.topics);
const searchMatch = /<em>([\s\S]*?)<\/em>/g;
const segments: SnippetSegment[] = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
const pushPlain = (raw: string) => {
const text = this.decodeHtml(raw);
if (text) {
segments.push({
text,
color: null,
tooltip: null,
isSearchMatch: false,
});
}
return {
content: snippet.replace(/<\/?em>/g, ''),
terms: this.toHighlightTerms([
...this.state.keywords(),
...this.markedTerms(snippet),
]),
};
while ((match = searchMatch.exec(snippet)) !== null) {
pushPlain(snippet.slice(lastIndex, match.index));
const term = this.decodeHtml(match[1]);
const parts = splitByKeywords(term, keywordColors);
const hasTopic = parts.some((part) => part.match);
for (const part of parts) {
segments.push({
text: part.text,
color: part.match?.color ?? null,
tooltip: part.match
? keywordTooltip(part.match.keyword, part.match.topicNames)
: hasTopic
? null
: keywordTooltip(term, []),
isSearchMatch: true,
});
}
lastIndex = searchMatch.lastIndex;
}
pushPlain(snippet.slice(lastIndex));
return segments;
}
private decodeHtml(value: string): string {
return value
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#(?:39|x27);/g, "'")
.replace(/&amp;/g, '&');
private markedTerms(snippet: string): string[] {
return [...snippet.matchAll(/<em>([\s\S]*?)<\/em>/g)].map((match) =>
match[1].trim(),
);
}
private toHighlightTerms(terms: string[]): HighlightTerm[] {
const seen = new Set<string>();
const result: HighlightTerm[] = [];
for (const raw of terms) {
const term = raw.trim();
const key = term.toLowerCase();
if (!term || seen.has(key)) {
continue;
}
seen.add(key);
result.push({ term, topic: this.state.resolveTopicForTerm(term) });
}
return result;
}
isTopicsExpanded(article: NewsResult): boolean {
@@ -18,10 +18,6 @@ import {
} from '../../shared/ui/highlighted-text/highlighted-text.component';
import { WorksService } from '../../api';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import {
highlightKeywords,
topicKeywordColors,
} from '../../resolvers/utils/keyword-highlight';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import {
ARROW_BACK_ICON,
@@ -85,24 +85,11 @@ export class HighlightedTextComponent {
);
}
/**
* Short/acronym-like terms (<=3 chars, or ALL CAPS) match exactly.
* Longer terms also swallow a trailing suffix (plural/case endings).
*/
private buildMatchRegex(terms: HighlightTerm[]): RegExp {
const before = '(?<![\\w\\u00C0-\\u024F])';
const alternatives = terms.map(({ term }) => {
const escaped = this.escapeRegex(this.escapeHtml(term));
const acronymLike =
term.length <= 3 ||
(term === term.toUpperCase() && term !== term.toLowerCase());
return acronymLike
? `${escaped}(?![\\w\\u00C0-\\u024F])`
: `${escaped}[\\w\\u00C0-\\u024F]*`;
});
return new RegExp(`${before}(?:${alternatives.join('|')})`, 'gi');
return termsRegex(
terms.map(({ term }) => this.escapeHtml(term)),
'gi',
);
}
private findOriginTerm(
@@ -122,8 +109,42 @@ export class HighlightedTextComponent {
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
}
private escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const WORD_CHAR = '[\\w\\u00C0-\\u024F]';
/**
* Short/acronym-like terms (<=3 chars, or ALL CAPS) match exactly.
* Longer terms also swallow a trailing suffix (plural/case endings).
*/
function termPattern(term: string): string {
const escaped = escapeRegex(term);
const acronymLike =
term.length <= 3 ||
(term === term.toUpperCase() && term !== term.toLowerCase());
return acronymLike ? `${escaped}(?!${WORD_CHAR})` : `${escaped}${WORD_CHAR}*`;
}
function termsRegex(terms: string[], flags: string): RegExp {
return new RegExp(
`(?<!${WORD_CHAR})(?:${terms.map(termPattern).join('|')})`,
flags,
);
}
export function containsHighlightTerm(
text: string | null | undefined,
terms: readonly string[],
): boolean {
const usable = terms.map((term) => term.trim()).filter(Boolean);
if (!text || !usable.length) {
return false;
}
return termsRegex(usable, 'i').test(text);
}
function escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}