feat/news_keyword_extraction #195
@@ -38,6 +38,7 @@ def add_entry(index: str, entry: dict):
|
||||
"news_id": entry["news_id"],
|
||||
"relevant": int(entry["relevant"]),
|
||||
"authors": entry["authors"],
|
||||
"keywords": entry.get("keywords", []),
|
||||
}
|
||||
|
||||
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
||||
@@ -47,6 +48,13 @@ def add_entry(index: str, entry: dict):
|
||||
|
||||
return created_id
|
||||
|
||||
def update_entry(index: str, document_id: str, partial_doc: dict):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
|
||||
|
||||
def get_entry(index: str, document_id: str) -> dict:
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
@@ -103,4 +111,18 @@ def delete_all_entries(index: str):
|
||||
"query": {"match_all": {}}
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
|
||||
def remove_field_all(index: str, field: str):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_update_by_query"
|
||||
|
||||
payload = {
|
||||
"query": {"exists": {"field": field}},
|
||||
"script": {
|
||||
"source": f"ctx._source.remove('{field}')",
|
||||
"lang": "painless",
|
||||
},
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
@@ -23,6 +23,17 @@ SYSTEM_PROMPT_NAMES = ("""
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
SYSTEM_PROMPT_KEYWORDS = ("""
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
_client = OpenAI(
|
||||
base_url=LLM_BASE_URL,
|
||||
api_key=LLM_API_KEY,
|
||||
@@ -62,3 +73,14 @@ def extract_names(text: str) -> list[str]:
|
||||
return data.get("person", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
def extract_keywords(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_KEYWORDS, text)
|
||||
if result is None:
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("keywords", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
@@ -16,10 +16,12 @@ def sync_single_news(news_id, max_retries=3):
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
is_news_relevant = llm_client.is_news_relevant(news_text)
|
||||
authors = llm_client.extract_names(news_text)
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
new_entry = {
|
||||
"news_id": news_id,
|
||||
"relevant": is_news_relevant,
|
||||
"authors": authors,
|
||||
"keywords": keywords,
|
||||
}
|
||||
es_client.add_entry("aktuell_postproc", new_entry)
|
||||
return True
|
||||
@@ -32,6 +34,25 @@ def sync_single_news(news_id, max_retries=3):
|
||||
print(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def update_keywords_single(postproc_entry, max_retries=3):
|
||||
doc_id = postproc_entry["_id"]
|
||||
news_id = postproc_entry["_source"]["news_id"]
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords})
|
||||
return True
|
||||
except Exception as error:
|
||||
attempt += 1
|
||||
print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||
if attempt < max_retries:
|
||||
time.sleep(1)
|
||||
else:
|
||||
print(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
|
||||
|
||||
@@ -47,6 +68,18 @@ def main():
|
||||
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--update-keywords",
|
||||
action="store_true",
|
||||
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--reset-keywords",
|
||||
action="store_true",
|
||||
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--stats",
|
||||
action="store_true",
|
||||
@@ -60,11 +93,22 @@ def main():
|
||||
help="Number of threads for --sync-delta (Default: 4).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.delete_all:
|
||||
es_client.delete_all_entries("aktuell_postproc")
|
||||
|
||||
if args.reset_keywords:
|
||||
result = es_client.remove_field_all("aktuell_postproc", "keywords")
|
||||
print(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
|
||||
|
||||
if args.sync_delta:
|
||||
start_time = time.time()
|
||||
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
@@ -96,23 +140,58 @@ def main():
|
||||
end_time = time.time()
|
||||
print(f"Sync DONE: {succeeded} entries synced.")
|
||||
print(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
|
||||
if args.update_keywords:
|
||||
start_time = time.time()
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"])
|
||||
|
||||
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
|
||||
print(f"Number of entries without keywords: {len(pending)}")
|
||||
|
||||
if args.limit is not None:
|
||||
pending = pending[:args.limit]
|
||||
|
||||
total = len(pending)
|
||||
print(f"Processing {total} entries.")
|
||||
|
||||
processed = 0
|
||||
succeeded = 0
|
||||
progress_lock = threading.Lock()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [executor.submit(update_keywords_single, entry) for entry in pending]
|
||||
for future in as_completed(futures):
|
||||
was_successful = future.result()
|
||||
with progress_lock:
|
||||
processed += 1
|
||||
if was_successful:
|
||||
succeeded += 1
|
||||
print(f"Update keywords: {processed} / {total}")
|
||||
|
||||
end_time = time.time()
|
||||
print(f"Update keywords DONE: {succeeded} entries updated.")
|
||||
print(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
if args.stats:
|
||||
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
print(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
||||
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors"])
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
|
||||
total_entries = len(postproc_entries)
|
||||
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
||||
irrelevant_count = total_entries - relevant_count
|
||||
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
|
||||
news_without_extracted_names = total_entries - news_with_extracted_names
|
||||
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
|
||||
news_without_keywords = total_entries - news_with_keywords
|
||||
|
||||
print(f"Total entries in 'aktuell_postproc': {total_entries}")
|
||||
print(f"Relevant entries: {relevant_count}")
|
||||
print(f"Irrelevant entries: {irrelevant_count}")
|
||||
print(f"Entries with extracted names: {news_with_extracted_names}")
|
||||
print(f"Entries without extracted names: {news_without_extracted_names}")
|
||||
print(f"Entries with keywords: {news_with_keywords}")
|
||||
print(f"Entries without keywords: {news_without_keywords}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because one or more lines are too long
@@ -12,7 +12,8 @@ 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 .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
from ..topics.logic import vector_search_topics
|
||||
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -20,14 +21,19 @@ TOPIC_LIMIT = 4
|
||||
TOPIC_QUERY_CONTENT_CHARS = 300
|
||||
TOPIC_NUM_CANDIDATES = 100
|
||||
TOPIC_SIMILARITY = 0.5
|
||||
TOPIC_MATCHES_PER_KEYWORD = 1
|
||||
|
||||
KEYWORD_LIMIT = 6
|
||||
KEYWORD_CONTENT_CHARS = 4000
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
|
||||
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
|
||||
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
|
||||
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
"""
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
@@ -247,7 +253,6 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
source = response.get("_source", {})
|
||||
|
||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
||||
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = await _get_article_keywords(
|
||||
news_id,
|
||||
postproc_id,
|
||||
@@ -255,6 +260,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
source.get("maintitle"),
|
||||
source.get("full_content"),
|
||||
)
|
||||
topics = await _match_topics_for_keywords(keywords)
|
||||
|
||||
return NewsArticleDetail(
|
||||
id=response.get("_id"),
|
||||
@@ -265,22 +271,11 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
full_content=source.get("full_content"),
|
||||
relevant=relevant,
|
||||
authors=await _build_mentioned_persons(authors),
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
topics=topics,
|
||||
)
|
||||
|
||||
|
||||
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
query = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not query:
|
||||
return []
|
||||
|
||||
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
async def _get_article_keywords(
|
||||
news_id: str,
|
||||
postproc_id: str | None,
|
||||
@@ -315,7 +310,12 @@ def _parse_keywords(raw: str) -> list:
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
candidates = parsed if isinstance(parsed, list) else []
|
||||
if isinstance(parsed, list):
|
||||
candidates = parsed
|
||||
elif isinstance(parsed, dict):
|
||||
candidates = parsed.get("keywords", [])
|
||||
else:
|
||||
candidates = []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
candidates = re.split(r"[,\n]", raw)
|
||||
|
||||
@@ -350,6 +350,35 @@ async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list)
|
||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||
|
||||
|
||||
async def _match_topics_for_keywords(keywords: list) -> list:
|
||||
matched = []
|
||||
seen_ids = set()
|
||||
|
||||
for keyword in keywords:
|
||||
try:
|
||||
response = await vector_search_topics(query=keyword, limit=TOPIC_MATCHES_PER_KEYWORD)
|
||||
except Exception:
|
||||
logger.exception(f"Topic-Matching fuer Keyword '{keyword}' fehlgeschlagen.")
|
||||
continue
|
||||
|
||||
for topic in response.results or []:
|
||||
if not topic.id or topic.id in seen_ids:
|
||||
continue
|
||||
seen_ids.add(topic.id)
|
||||
matched.append(
|
||||
MatchedTopic(
|
||||
id=topic.id,
|
||||
display_name=topic.display_name,
|
||||
subfield_name=topic.subfield.display_name if topic.subfield else None,
|
||||
field_name=topic.var_field.display_name if topic.var_field else None,
|
||||
domain_name=topic.domain.display_name if topic.domain else None,
|
||||
source_keyword=keyword,
|
||||
)
|
||||
)
|
||||
|
||||
return matched
|
||||
|
||||
|
||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
@@ -23,12 +23,21 @@ class MentionedPerson(BaseModel):
|
||||
person_id: Optional[str] = None
|
||||
|
||||
|
||||
class MatchedTopic(BaseModel):
|
||||
id: Optional[str] = None
|
||||
display_name: Optional[str] = None
|
||||
subfield_name: Optional[str] = None
|
||||
field_name: Optional[str] = None
|
||||
domain_name: Optional[str] = None
|
||||
source_keyword: Optional[str] = None
|
||||
|
||||
|
||||
class NewsArticleDetail(NewsArticle):
|
||||
full_content: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
authors: List[MentionedPerson] = []
|
||||
topics: List[str] = []
|
||||
keywords: List[str] = []
|
||||
topics: List[MatchedTopic] = []
|
||||
|
||||
|
||||
class NewsPage(BaseModel):
|
||||
|
||||
@@ -5,6 +5,7 @@ import { collaborationNetworkResolver } from './resolvers/collaboration-network.
|
||||
import { personListResolver } from './resolvers/person-list.resolver';
|
||||
import { personBioResolver } from './resolvers/person-bio.resolver';
|
||||
import { personResolver } from './resolvers/person.resolver';
|
||||
import { personNewsResolver } from './resolvers/person-news.resolver';
|
||||
import { institutionResolver } from './resolvers/institution.resolver';
|
||||
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
|
||||
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
|
||||
@@ -270,6 +271,23 @@ export const routes: Routes = [
|
||||
(mod) => mod.PersonFundingComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
loadComponent: () =>
|
||||
import('./modules/person-news/person-news.component').then(
|
||||
(mod) => mod.PersonNewsComponent,
|
||||
),
|
||||
resolve: {
|
||||
newsPage: personNewsResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'pageSize', 'sortOrder', 'query'];
|
||||
|
||||
return keys.some(
|
||||
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'patents',
|
||||
loadComponent: () =>
|
||||
@@ -383,6 +401,20 @@ export const routes: Routes = [
|
||||
(mod) => mod.PatentsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
|
||||
},
|
||||
{
|
||||
path: 'news/:id',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/news-detail/news-detail.component').then(
|
||||
(mod) => mod.NewsDetailComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'error',
|
||||
loadComponent: () =>
|
||||
|
||||
@@ -54,7 +54,10 @@
|
||||
|
||||
<div class="article-body">
|
||||
@if (article.full_content) {
|
||||
<p class="content">{{ article.full_content }}</p>
|
||||
<p
|
||||
#articleBody
|
||||
class="content"
|
||||
[innerHTML]="highlightedContent"></p>
|
||||
} @else {
|
||||
<p class="placeholder">Kein Inhalt verfügbar.</p>
|
||||
}
|
||||
@@ -76,55 +79,168 @@
|
||||
|
||||
<aside class="sidebar">
|
||||
<div class="sidebar-card">
|
||||
<h3>
|
||||
<mat-icon>group</mat-icon>
|
||||
Erwähnte Personen
|
||||
</h3>
|
||||
<div class="person-list">
|
||||
@if (article.authors && article.authors.length) {
|
||||
@for (person of article.authors; track person.name) {
|
||||
@if (person.is_ude && person.person_id) {
|
||||
<a
|
||||
class="person-item is-link"
|
||||
[routerLink]="['/person', person.person_id, 'overview']">
|
||||
<div class="avatar">{{ person.name.charAt(0) }}</div>
|
||||
<span class="person-name">{{ person.name }}</span>
|
||||
<span class="ude-badge">UDE</span>
|
||||
</a>
|
||||
} @else {
|
||||
<article class="person-item is-muted">
|
||||
<div class="avatar">{{ person.name.charAt(0) }}</div>
|
||||
<span class="person-name">{{ person.name }}</span>
|
||||
</article>
|
||||
}
|
||||
<div class="accordion-panel">
|
||||
<button
|
||||
type="button"
|
||||
class="accordion-header"
|
||||
(click)="openPanel = openPanel === 'persons' ? null : 'persons'"
|
||||
[attr.aria-expanded]="openPanel === 'persons'">
|
||||
<mat-icon>group</mat-icon>
|
||||
<span class="accordion-title">Erwähnte Personen</span>
|
||||
<mat-icon
|
||||
class="info-icon"
|
||||
matTooltip="Personen, die im Text erwähnt wurden. Klicke auf eine der UDE angehörige Person, um zu ihrem Profil zu gelangen."
|
||||
matTooltipPosition="above"
|
||||
(click)="$event.stopPropagation()"
|
||||
>info_outline</mat-icon
|
||||
>
|
||||
@if (article.authors?.length) {
|
||||
<span class="count-badge">{{ article.authors!.length }}</span>
|
||||
}
|
||||
} @else {
|
||||
<p class="placeholder">Keine erwähnten Personen gefunden.</p>
|
||||
<mat-icon
|
||||
class="chevron"
|
||||
[class.rotated]="openPanel !== 'persons'"
|
||||
>expand_more</mat-icon
|
||||
>
|
||||
</button>
|
||||
@if (openPanel === 'persons') {
|
||||
<div class="accordion-body">
|
||||
@if (article.authors && article.authors.length) {
|
||||
<div class="person-list">
|
||||
@for (person of pagedPersons; track person.name) {
|
||||
@if (person.is_ude && person.person_id) {
|
||||
<a
|
||||
class="person-item is-link"
|
||||
[routerLink]="[
|
||||
'/person',
|
||||
person.person_id,
|
||||
'overview',
|
||||
]">
|
||||
<div class="avatar">
|
||||
{{ personInitials(person.name) }}
|
||||
</div>
|
||||
<span class="person-name">{{ person.name }}</span>
|
||||
<span class="ude-badge">UDE</span>
|
||||
</a>
|
||||
} @else {
|
||||
<div class="person-item is-muted">
|
||||
<div class="avatar">
|
||||
{{ personInitials(person.name) }}
|
||||
</div>
|
||||
<span class="person-name">{{ person.name }}</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
@if (personsPageCount > 1) {
|
||||
<div class="persons-pagination">
|
||||
<button
|
||||
type="button"
|
||||
class="page-btn"
|
||||
[disabled]="personsPage === 0"
|
||||
(click)="personsPage = personsPage - 1">
|
||||
<mat-icon>chevron_left</mat-icon>
|
||||
</button>
|
||||
<span class="page-indicator"
|
||||
>{{ personsPage + 1 }} / {{ personsPageCount }}</span
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="page-btn"
|
||||
[disabled]="personsPage === personsPageCount - 1"
|
||||
(click)="personsPage = personsPage + 1">
|
||||
<mat-icon>chevron_right</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
} @else {
|
||||
<p class="placeholder">Keine erwähnten Personen gefunden.</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sidebar-card">
|
||||
<h3>
|
||||
<mat-icon>label</mat-icon>
|
||||
Schlüsselwörter
|
||||
</h3>
|
||||
<div class="chip-list">
|
||||
@if (article.keywords && article.keywords.length) {
|
||||
@for (
|
||||
keyword of article.keywords;
|
||||
track keyword;
|
||||
let i = $index
|
||||
) {
|
||||
<span
|
||||
class="topic-chip"
|
||||
(click)="onKeywordClick(keyword)"
|
||||
[ngClass]="chipColor(i)"
|
||||
>{{ keyword }}</span
|
||||
>
|
||||
<div class="accordion-panel">
|
||||
<button
|
||||
type="button"
|
||||
class="accordion-header"
|
||||
(click)="openPanel = openPanel === 'topics' ? null : 'topics'"
|
||||
[attr.aria-expanded]="openPanel === 'topics'">
|
||||
<mat-icon>label</mat-icon>
|
||||
<span class="accordion-title">Themen & Schlüsselwörter</span>
|
||||
<mat-icon
|
||||
class="info-icon"
|
||||
matTooltip="Themen, die mit den extrahierten Schlüsselwörtern des Artikels assoziiert werden. Klicke auf ein Schlüsselwort, um zum hervorgehobenen Begriff im Text zu springen."
|
||||
matTooltipPosition="above"
|
||||
(click)="$event.stopPropagation()"
|
||||
>info_outline</mat-icon
|
||||
>
|
||||
@if (article.topics?.length) {
|
||||
<span class="count-badge">{{ article.topics!.length }}</span>
|
||||
}
|
||||
} @else {
|
||||
<p class="placeholder">Keine Schlüsselwörter gefunden.</p>
|
||||
<mat-icon class="chevron" [class.rotated]="openPanel !== 'topics'"
|
||||
>expand_more</mat-icon
|
||||
>
|
||||
</button>
|
||||
@if (openPanel === 'topics') {
|
||||
<div class="accordion-body">
|
||||
@if (article.topics && article.topics.length) {
|
||||
<div class="topics-accordion">
|
||||
@for (
|
||||
topic of article.topics;
|
||||
track topic.id ?? topic.display_name
|
||||
) {
|
||||
<div
|
||||
class="topic-item"
|
||||
[style.--t]="getTopicColor(topic)">
|
||||
<button
|
||||
type="button"
|
||||
class="topic-item-header"
|
||||
[class.is-expanded]="expandedTopicId === topic.id"
|
||||
(click)="toggleTopic(topic.id)">
|
||||
<span class="topic-item-name">{{
|
||||
topic.display_name
|
||||
}}</span>
|
||||
<mat-icon>{{
|
||||
expandedTopicId === topic.id
|
||||
? 'expand_less'
|
||||
: 'expand_more'
|
||||
}}</mat-icon>
|
||||
</button>
|
||||
@if (expandedTopicId === topic.id) {
|
||||
<div class="topic-item-body">
|
||||
@if (topic.source_keyword) {
|
||||
<p class="kw-suggestion-label">
|
||||
Vorgeschlagen durch das Schlüsselwort im Text:
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="kw-pill"
|
||||
(click)="scrollToKeyword(topic.source_keyword)">
|
||||
»{{ topic.source_keyword }}«
|
||||
</button>
|
||||
<p class="kw-hint">
|
||||
Im Artikel hervorgehoben · klicken zum Suche zu
|
||||
öffnen
|
||||
</p>
|
||||
} @else {
|
||||
<p class="placeholder">
|
||||
Kein Schlüsselwort verknüpft.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
<p class="placeholder">
|
||||
Keine Themen oder Schlüsselwörter gefunden.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
|
||||
.detail-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 280px;
|
||||
grid-template-columns: 1fr 288px;
|
||||
gap: 40px;
|
||||
align-items: start;
|
||||
}
|
||||
@@ -137,60 +137,121 @@ main {
|
||||
margin: 0;
|
||||
color: var(--sg-text-muted);
|
||||
font-style: italic;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.article-actions {
|
||||
margin-top: 32px;
|
||||
}
|
||||
|
||||
// ── Sidebar ──────────────────────────────────────────────────────────────────
|
||||
|
||||
.sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
position: sticky;
|
||||
top: 24px;
|
||||
max-height: calc(100vh - 48px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sidebar-card {
|
||||
padding: 20px;
|
||||
border: 1px solid #d7e4ff;
|
||||
border-radius: 16px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
h3 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0 0 14px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--sg-text);
|
||||
// ── Accordion ────────────────────────────────────────────────────────────────
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
.accordion-panel {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.accordion-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 16px 20px;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--sg-text);
|
||||
transition: background 0.12s;
|
||||
|
||||
&:hover {
|
||||
background: #f6f9ff;
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: var(--sg-text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.accordion-title {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.count-badge {
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
background: #e8effe;
|
||||
color: #3b5bd6;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.info-icon {
|
||||
flex-shrink: 0;
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
color: var(--sg-text-muted);
|
||||
opacity: 0.7;
|
||||
cursor: default;
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.chevron {
|
||||
transition: transform 0.2s ease;
|
||||
color: var(--sg-text-muted) !important;
|
||||
|
||||
&.rotated {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
}
|
||||
|
||||
.accordion-body {
|
||||
padding: 0 20px 16px;
|
||||
}
|
||||
|
||||
// ── Persons ───────────────────────────────────────────────────────────────────
|
||||
|
||||
.person-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-height: 375px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.person-item {
|
||||
display: grid;
|
||||
grid-template-columns: 38px minmax(0, 1fr) auto;
|
||||
gap: 11px;
|
||||
grid-template-columns: 36px minmax(0, 1fr) auto;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
padding: 12px;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--sg-radius-sm);
|
||||
background: var(--sg-surface-muted);
|
||||
}
|
||||
@@ -232,32 +293,200 @@ main {
|
||||
.avatar {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
background: #e5ecfb;
|
||||
color: var(--sg-text);
|
||||
font-size: 15px;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.person-name {
|
||||
color: var(--sg-text);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
// ── Persons pagination ────────────────────────────────────────────────────────
|
||||
|
||||
.persons-pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.page-btn {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 1px solid #d7e4ff;
|
||||
border-radius: 8px;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
color: var(--sg-text-muted);
|
||||
transition: background 0.12s;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: #f0f6ff;
|
||||
color: var(--sg-text);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.page-indicator {
|
||||
font-size: 12px;
|
||||
color: var(--sg-text-muted);
|
||||
min-width: 36px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
// ── Topic accordion items ─────────────────────────────────────────────────────
|
||||
|
||||
.topics-accordion {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.topic-item {
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
border: 1.5px solid color-mix(in srgb, var(--t) 38%, #ffffff);
|
||||
}
|
||||
|
||||
.topic-item-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 11px 14px;
|
||||
background: color-mix(in srgb, var(--t) 13%, #ffffff);
|
||||
color: color-mix(in srgb, var(--t) 90%, #0f172a);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--t) 22%, #ffffff);
|
||||
}
|
||||
|
||||
&.is-expanded {
|
||||
background: var(--t);
|
||||
color: #ffffff;
|
||||
|
||||
mat-icon {
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
flex-shrink: 0;
|
||||
color: color-mix(in srgb, var(--t) 70%, #0f172a);
|
||||
}
|
||||
}
|
||||
|
||||
.topic-item-name {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.topic-item-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 14px 14px 14px;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.kw-suggestion-label {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.kw-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
padding: 6px 14px;
|
||||
border-radius: 999px;
|
||||
border: 1.5px solid color-mix(in srgb, var(--t) 50%, #ffffff);
|
||||
background: color-mix(in srgb, var(--t) 10%, #ffffff);
|
||||
color: color-mix(in srgb, var(--t) 90%, #0f172a);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.12s;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--t) 22%, #ffffff);
|
||||
}
|
||||
}
|
||||
|
||||
.kw-hint {
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
// ── Topics & Keywords ─────────────────────────────────────────────────────────
|
||||
|
||||
.chip-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
& + .chip-group {
|
||||
margin-top: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.chip-group-label {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.chip-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.topic-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 6px 12px;
|
||||
padding: 5px 11px;
|
||||
border: 1px solid var(--topic-border);
|
||||
border-radius: 8px;
|
||||
background: var(--topic-bg);
|
||||
@@ -267,6 +496,22 @@ main {
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.kw-chip {
|
||||
cursor: pointer;
|
||||
transition:
|
||||
box-shadow 0.12s,
|
||||
background 0.12s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 0 0 2px var(--topic-border);
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
box-shadow: 0 0 0 2px var(--topic-color);
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.purple {
|
||||
--topic-border: #d8cafe;
|
||||
--topic-bg: #f6f0ff;
|
||||
@@ -296,3 +541,39 @@ main {
|
||||
--topic-bg: #fff1f5;
|
||||
--topic-color: #d12f61;
|
||||
}
|
||||
|
||||
// ── Keyword highlights in article text ───────────────────────────────────────
|
||||
|
||||
@keyframes kw-flash {
|
||||
0% {
|
||||
background: color-mix(in srgb, var(--t) 45%, #ffffff);
|
||||
}
|
||||
40% {
|
||||
background: color-mix(in srgb, var(--t) 45%, #ffffff);
|
||||
}
|
||||
100% {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
:host ::ng-deep .kw-mark {
|
||||
background: transparent;
|
||||
color: var(--t);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: var(--t);
|
||||
text-decoration-style: solid;
|
||||
text-decoration-thickness: 2px;
|
||||
text-underline-offset: 2px;
|
||||
font-weight: inherit;
|
||||
border-radius: 2px;
|
||||
padding: 0 1px;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--t) 15%, #ffffff);
|
||||
}
|
||||
|
||||
&.kw-flash {
|
||||
animation: kw-flash 2.4s ease-out forwards;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
|
||||
import { Location, NgClass } from '@angular/common';
|
||||
import {
|
||||
Component,
|
||||
DestroyRef,
|
||||
ElementRef,
|
||||
OnInit,
|
||||
ViewChild,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { Location } from '@angular/common';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { Router } from '@angular/router';
|
||||
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
|
||||
|
||||
import { WorksService } from '../../api';
|
||||
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
|
||||
|
||||
interface MentionedPerson {
|
||||
name: string;
|
||||
@@ -15,6 +25,15 @@ interface MentionedPerson {
|
||||
person_id?: string | null;
|
||||
}
|
||||
|
||||
interface MatchedTopic {
|
||||
id?: string | null;
|
||||
display_name?: string | null;
|
||||
subfield_name?: string | null;
|
||||
field_name?: string | null;
|
||||
domain_name?: string | null;
|
||||
source_keyword?: string | null;
|
||||
}
|
||||
|
||||
interface NewsArticleDetail {
|
||||
id: string;
|
||||
date?: string | null;
|
||||
@@ -25,6 +44,7 @@ interface NewsArticleDetail {
|
||||
relevant?: boolean;
|
||||
authors?: MentionedPerson[];
|
||||
keywords?: string[];
|
||||
topics?: MatchedTopic[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -33,28 +53,83 @@ interface NewsArticleDetail {
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatTooltipModule,
|
||||
RouterLink,
|
||||
NgClass,
|
||||
],
|
||||
templateUrl: './news-detail.component.html',
|
||||
styleUrl: './news-detail.component.scss',
|
||||
})
|
||||
export class NewsDetailComponent implements OnInit {
|
||||
@ViewChild('articleBody') articleBodyRef?: ElementRef<HTMLElement>;
|
||||
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly httpClient = inject(HttpClient);
|
||||
private readonly worksService = inject(WorksService);
|
||||
private readonly location = inject(Location);
|
||||
private readonly router = inject(Router);
|
||||
private readonly sanitizer = inject(DomSanitizer);
|
||||
|
||||
article: NewsArticleDetail | null = null;
|
||||
highlightedContent: SafeHtml = this.sanitizer.bypassSecurityTrustHtml('');
|
||||
loading = false;
|
||||
notFound = false;
|
||||
|
||||
private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink'];
|
||||
openPanel: 'persons' | 'topics' | null = 'persons';
|
||||
expandedTopicId: string | null = null;
|
||||
|
||||
chipColor(index: number): string {
|
||||
return this.chipColors[index % this.chipColors.length];
|
||||
personsPage = 0;
|
||||
readonly personsPageSize = 5;
|
||||
|
||||
get pagedPersons(): MentionedPerson[] {
|
||||
const authors = this.article?.authors ?? [];
|
||||
return authors.slice(
|
||||
this.personsPage * this.personsPageSize,
|
||||
(this.personsPage + 1) * this.personsPageSize,
|
||||
);
|
||||
}
|
||||
|
||||
get personsPageCount(): number {
|
||||
return Math.ceil(
|
||||
(this.article?.authors?.length ?? 0) / this.personsPageSize,
|
||||
);
|
||||
}
|
||||
|
||||
getTopicColor(topic: MatchedTopic): string {
|
||||
return topicHierarchyColor({
|
||||
id: topic.id,
|
||||
name: topic.display_name,
|
||||
field_name: topic.field_name,
|
||||
domain_name: topic.domain_name,
|
||||
});
|
||||
}
|
||||
|
||||
personInitials(name: string): string {
|
||||
const parts = name.trim().split(/\s+/);
|
||||
if (parts.length === 1) return parts[0].charAt(0).toUpperCase();
|
||||
return (
|
||||
parts[0].charAt(0) + parts[parts.length - 1].charAt(0)
|
||||
).toUpperCase();
|
||||
}
|
||||
|
||||
toggleTopic(id: string | null | undefined): void {
|
||||
this.expandedTopicId = this.expandedTopicId === id ? null : (id ?? null);
|
||||
}
|
||||
|
||||
scrollToKeyword(keyword: string): void {
|
||||
const body = this.articleBodyRef?.nativeElement;
|
||||
if (!body) return;
|
||||
body
|
||||
.querySelectorAll<HTMLElement>('.kw-flash')
|
||||
.forEach((el) => el.classList.remove('kw-flash'));
|
||||
const marks = body.querySelectorAll<HTMLElement>('[data-kw]');
|
||||
for (const mark of Array.from(marks)) {
|
||||
if (mark.dataset['kw']?.toLowerCase() === keyword.toLowerCase()) {
|
||||
mark.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
mark.classList.add('kw-flash');
|
||||
setTimeout(() => mark.classList.remove('kw-flash'), 2400);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -71,11 +146,7 @@ export class NewsDetailComponent implements OnInit {
|
||||
navigateBack(): void {
|
||||
this.location.back();
|
||||
}
|
||||
onKeywordClick(keyword: string): void {
|
||||
this.router.navigate(['/keywords'], {
|
||||
queryParams: { selected: keyword, manual: keyword },
|
||||
});
|
||||
}
|
||||
|
||||
formatDate(dateStr?: string | null): string {
|
||||
if (!dateStr) return '-';
|
||||
const date = new Date(dateStr);
|
||||
@@ -97,6 +168,9 @@ export class NewsDetailComponent implements OnInit {
|
||||
.subscribe({
|
||||
next: (article) => {
|
||||
this.article = article;
|
||||
this.highlightedContent = this.buildHighlightedContent(article);
|
||||
this.expandedTopicId = null;
|
||||
this.personsPage = 0;
|
||||
this.loading = false;
|
||||
},
|
||||
error: () => {
|
||||
@@ -105,4 +179,63 @@ export class NewsDetailComponent implements OnInit {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private buildHighlightedContent(article: NewsArticleDetail): SafeHtml {
|
||||
const text = article.full_content;
|
||||
if (!text) return this.sanitizer.bypassSecurityTrustHtml('');
|
||||
const keywords = article.keywords ?? [];
|
||||
|
||||
const keywordColorMap = new Map<string, string>();
|
||||
for (const topic of article.topics ?? []) {
|
||||
if (topic.source_keyword) {
|
||||
keywordColorMap.set(
|
||||
topic.source_keyword.toLowerCase(),
|
||||
this.getTopicColor(topic),
|
||||
);
|
||||
}
|
||||
}
|
||||
const orphanColors = [
|
||||
'#7255d9',
|
||||
'#0b63ce',
|
||||
'#24834f',
|
||||
'#c67500',
|
||||
'#d12f61',
|
||||
];
|
||||
let orphanIdx = 0;
|
||||
|
||||
let html = this.escapeHtml(text);
|
||||
if (keywords.length) {
|
||||
[...keywords]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.forEach((kw) => {
|
||||
let color = keywordColorMap.get(kw.toLowerCase());
|
||||
if (!color) {
|
||||
color = orphanColors[orphanIdx % orphanColors.length];
|
||||
orphanIdx++;
|
||||
}
|
||||
const kwHtml = this.escapeHtml(kw);
|
||||
const re = new RegExp(
|
||||
`(${this.escapeRegex(kwHtml)}[\\w\\u00C0-\\u024F]*)`,
|
||||
'gi',
|
||||
);
|
||||
html = html.replace(
|
||||
re,
|
||||
`<mark class="kw-mark" style="--t:${color}" data-kw="${kwHtml}">$1</mark>`,
|
||||
);
|
||||
});
|
||||
}
|
||||
return this.sanitizer.bypassSecurityTrustHtml(html);
|
||||
}
|
||||
|
||||
private escapeHtml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
private escapeRegex(text: string): string {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user