fix/trend_news_bug #312

Merged
kuzko merged 3 commits from fix/trend_news_bug into dev 2026-09-02 14:35:08 +02:00
5 changed files with 213 additions and 130 deletions
@@ -198,20 +198,23 @@ class TrendMetadataResolver:
for t in topic_names:
t_clean = clean_inst_id(t)
t_canonical = f"https://openalex.org/{t_clean}" if t_clean.startswith("T") else t
if (
is_exact_id = (
t == full_id
or t == short_id
or t == canonical_id
or t_canonical == canonical_id
or t_clean == short_id
or t.lower() in d_name.lower()
or d_name.lower() in t.lower()
):
)
is_exact_name = t.strip().lower() == d_name.strip().lower()
if is_exact_id or is_exact_name:
topic_ids[t] = canonical_id
topic_display_names[t] = d_name
topic_display_names[canonical_id] = d_name
topic_display_names[short_id] = d_name
topic_display_names[full_id] = d_name
elif t not in topic_display_names and (t.lower() in d_name.lower() or d_name.lower() in t.lower()):
topic_ids[t] = canonical_id
topic_display_names[t] = d_name
except Exception as e:
logger.warning("Failed to resolve topic IDs from ES: %s", e)
return topic_ids, topic_display_names
@@ -676,6 +676,7 @@ class ProjectsTrendStrategy(TrendStrategy):
query_institutions=ids_to_resolve,
query_countries=countries,
query_regions=regions,
topics=topics,
include_aliases=True,
)
@@ -685,6 +686,8 @@ class ProjectsTrendStrategy(TrendStrategy):
resolved_country_names = meta["country_names"]
resolved_continent_names = meta["continent_names"]
continent_country_codes = meta["continent_country_codes"]
resolved_topic_ids = meta["resolved_topic_ids"]
resolved_topic_names = meta["resolved_topic_names"]
location_mappings = continent_country_codes.copy()
@@ -755,7 +758,28 @@ class ProjectsTrendStrategy(TrendStrategy):
if fuzzy:
for t in topics:
topic_project_ids[t] = {ind: [] for ind in indices_mapping}
map_query = {"term": {"topic_matches.topic_display_name.keyword": t}}
canonical_id = resolved_topic_ids.get(t)
if not canonical_id:
clean_id = clean_inst_id(t)
canonical_id = f"https://openalex.org/{clean_id}" if clean_id.startswith("T") else t
display_name = resolved_topic_names.get(t) or resolved_topic_names.get(canonical_id)
should_clauses = [
{"term": {"topic_matches.topic_id": canonical_id}},
{"term": {"topic_matches.topic_id.keyword": canonical_id}},
]
if display_name:
should_clauses.append({"match_phrase": {"topic_matches.topic_display_name": display_name}})
elif not (t.startswith("https://openalex.org/") or (clean_inst_id(t).startswith("T") and clean_inst_id(t)[1:].isdigit())):
should_clauses.append({"match_phrase": {"topic_matches.topic_display_name": t}})
map_query = {
"bool": {
"should": should_clauses,
"minimum_should_match": 1,
}
}
async def scan_topic_projects(mapping_index: str) -> tuple[str, list[str]]:
p_ids = set()
@@ -1079,6 +1103,10 @@ class NewsTrendStrategy(TrendStrategy):
cc_news_enabled = self.include_cc_news and not fuzzy
meta = await TrendMetadataResolver.resolve_all(topics=topics)
resolved_topic_ids = meta["resolved_topic_ids"]
resolved_topic_names = meta["resolved_topic_names"]
accumulated_data = {
f"{NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
for t in topics
@@ -1088,7 +1116,7 @@ class NewsTrendStrategy(TrendStrategy):
f"{CC_NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
for t in topics
})
# Stop words are used to avoid match_phrase (get more partial results => tradeoff)
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
def resolve_keyword_term(idx: int, t_name: str) -> str:
@@ -1107,8 +1135,19 @@ class NewsTrendStrategy(TrendStrategy):
async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]:
news_ids: Set[str] = set()
if fuzzy:
term = t_name
es_query = {"match_phrase": {"topic_matches.topic_display_name": term}}
canonical_id = resolved_topic_ids.get(t_name)
if not canonical_id:
clean_id = clean_inst_id(t_name)
canonical_id = f"https://openalex.org/{clean_id}" if clean_id.startswith("T") else t_name
es_query = {
"bool": {
"should": [
{"term": {"topic_matches.topic_id": canonical_id}},
{"term": {"topic_matches.topic_id.keyword": canonical_id}},
],
"minimum_should_match": 1,
}
}
try:
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
@@ -1281,12 +1320,24 @@ class NewsTrendStrategy(TrendStrategy):
topic_data=topic_data_map,
)
def get_display_name(t_name: str) -> str:
clean = clean_inst_id(t_name)
is_id = t_name.startswith("https://openalex.org/") or (clean.startswith("T") and clean[1:].isdigit())
if is_id:
canonical_id = resolved_topic_ids.get(t_name)
return (
resolved_topic_names.get(t_name)
or (resolved_topic_names.get(canonical_id) if canonical_id else None)
or t_name
)
return t_name
series_list: list[TrendSeries] = [
build_series(f"{NEWS_ENTITY_PREFIX}{t_name}", t_name, t_name) for t_name in topics
build_series(f"{NEWS_ENTITY_PREFIX}{t_name}", t_name, get_display_name(t_name)) for t_name in topics
]
if cc_news_enabled:
series_list.extend(
build_series(f"{CC_NEWS_ENTITY_PREFIX}{t_name}", t_name, f"{t_name} (CC-News)")
build_series(f"{CC_NEWS_ENTITY_PREFIX}{t_name}", t_name, f"{get_display_name(t_name)} (CC-News)")
for t_name in topics
)
@@ -224,18 +224,21 @@ export class SearchResultsStateService {
return result;
}
// Parallel topic-name list for trend dashboard strategies. Entries
// without a resolvable keyword are skipped when building the lookup map
// so they can never collide on an `undefined` key and shadow a real one.
// Parallel topic-name list for trend dashboard strategies. Directly resolves
// from structured selectedKeywordEntries without fragile regex.
readonly topicsList = computed(() => {
const entries = this.selectedKeywordEntries();
const entryByKeyword = new Map<string, KeywordEntryWithTopic>();
for (const entry of entries) {
const kw = entry.llm_keyword?.keyword?.trim().toLowerCase();
if (kw) {
entryByKeyword.set(kw, entry);
}
}
const list = this.keywords()
.map((kw) => {
const normalized = this.normalize(kw);
const entry = this.selectedKeywordEntries().find(
(e) =>
e.llm_keyword?.keyword?.trim().toLowerCase() === normalized ||
e.topic_mapping?.topic?.id?.trim().toLowerCase() === normalized,
);
const entry = entryByKeyword.get(kw.trim().toLowerCase());
const displayName = entry?.topic_mapping?.topic?.display_name;
if (displayName && !displayName.startsWith('http')) {
return displayName;
@@ -246,9 +249,8 @@ export class SearchResultsStateService {
return kw;
})
.filter((t) => t.length > 0);
const uniqueTopics = Array.from(new Set(list));
return uniqueTopics;
return Array.from(new Set(list));
});
setPayload(payload: SearchResultsPayload): void {
@@ -4,6 +4,7 @@ import {
input,
computed,
signal,
linkedSignal,
effect,
untracked,
inject,
@@ -167,7 +168,62 @@ export class UniTrendParentComponent implements OnInit {
readonly selectedSearchType = signal<
'publications' | 'authors' | 'patents' | 'projects' | 'news' | 'all'
>('publications');
readonly selectedTrendTopics = signal<string[]>([]);
readonly selectedTrendTopics = linkedSignal<
{ fuzzy: boolean; topics: string[]; kws: string[] },
string[]
>({
source: () => ({
fuzzy: this.isFuzzy(),
topics: this.state?.topicsList() ?? [],
kws: this.keywords(),
}),
computation: (src, previous) => {
const target = src.fuzzy
? src.topics.length > 0
? src.topics
: src.kws
: src.kws;
if (previous?.value && previous.value.length > 0) {
const preserved = previous.value.filter((item) =>
target.some(
(t) =>
t.toLowerCase().trim() === item.toLowerCase().trim() ||
cleanEntityId(t) === cleanEntityId(item),
),
);
if (preserved.length > 0) {
return preserved;
}
}
return target;
},
});
readonly activeChartTopic = linkedSignal<
{ topics: string[]; raw: TrendResponse | null },
string
>({
source: () => ({
topics: this.selectedTrendTopics(),
raw: this.rawTrendResponse(),
}),
computation: (src, previous) => {
if (
previous?.value &&
src.topics.some(
(t) =>
t.toLowerCase().trim() === previous.value.toLowerCase().trim() ||
cleanEntityId(t) === cleanEntityId(previous.value),
)
) {
return previous.value;
}
const valid = this.findFirstNonEmptyTopic(src.topics);
return valid || (src.topics.length > 0 ? src.topics[0] : '');
},
});
readonly primaryInstitution = signal<string | null>('I62318514');
readonly primaryInstitutionName = signal<string>(
'Universität Duisburg-Essen',
@@ -191,12 +247,40 @@ export class UniTrendParentComponent implements OnInit {
readonly chartMode = signal<'normalized' | 'total' | 'cumulative'>(
'normalized',
);
readonly activeChartTopic = signal<string>('');
readonly selectedPieEntity = signal<{
id: string;
name: string;
type: 'institution' | 'author' | 'country' | 'region';
} | null>(null);
readonly selectedPieEntity = linkedSignal<
TrendResponse | null,
{
id: string;
name: string;
type: 'institution' | 'author' | 'country' | 'region';
} | null
>({
source: () => this.trendResponse(),
computation: (data, previous) => {
if (!data || !data.series || data.series.length === 0) {
return null;
}
if (previous?.value) {
const stillExists = data.series.some(
(s) =>
cleanEntityId(s.entity_id) === cleanEntityId(previous.value!.id),
);
if (stillExists) {
return previous.value;
}
}
const firstSeries = data.series[0];
if (firstSeries) {
return {
id: cleanEntityId(firstSeries.entity_id),
name: firstSeries.entity_name,
type: firstSeries.entity_type as any,
};
}
return null;
},
});
readonly activeConfig = computed(
() => TREND_CONFIGS[this.selectedSearchType()],
@@ -374,7 +458,7 @@ export class UniTrendParentComponent implements OnInit {
.reduce((sum, item) => sum + (item.raw || 0), 0);
return {
name: topicName,
name: this.getMappedTopic(topicName) || topicName,
value: totalRaw,
};
});
@@ -580,12 +664,24 @@ export class UniTrendParentComponent implements OnInit {
}
isTopicEmpty(topic: string): boolean {
const allSeries =
this.trendResponse()?.series || this.rawTrendResponse()?.series || [];
const allSeries = this.rawTrendResponse()?.series || [];
if (allSeries.length === 0) return true;
const targetLower = topic.toLowerCase().trim();
const targetMappedLower = this.getMappedTopic(topic).toLowerCase().trim();
const series =
this.selectedSearchType() === 'news'
? allSeries.filter((s) => this.seriesTopicName(s.entity_id) === topic)
? allSeries.filter((s) => {
const sTopic = this.seriesTopicName(s.entity_id)
.toLowerCase()
.trim();
const sMapped = this.getMappedTopic(sTopic).toLowerCase().trim();
return (
sTopic === targetLower ||
sTopic === targetMappedLower ||
sMapped === targetLower ||
sMapped === targetMappedLower
);
})
: allSeries;
return isTopicEmptyForSeries(
topic,
@@ -597,8 +693,7 @@ export class UniTrendParentComponent implements OnInit {
}
findFirstNonEmptyTopic(topics: string[]): string {
const allSeries =
this.trendResponse()?.series || this.rawTrendResponse()?.series || [];
const allSeries = this.rawTrendResponse()?.series || [];
if (!topics || topics.length === 0) return '';
return findFirstNonEmptyTopic(
topics,
@@ -777,14 +872,25 @@ export class UniTrendParentComponent implements OnInit {
if (type === 'news') {
const active = this.activeChartTopic() || topics[0] || '';
const wanted = new Set([
NEWS_ENTITY_PREFIX + active,
CC_NEWS_ENTITY_PREFIX + active,
]);
const activeLower = active.toLowerCase().trim();
const mappedActiveLower = this.getMappedTopic(active)
.toLowerCase()
.trim();
return {
...raw,
series: raw.series
.filter((s) => wanted.has(s.entity_id))
.filter((s) => {
const sTopic = this.seriesTopicName(s.entity_id)
.toLowerCase()
.trim();
const sMapped = this.getMappedTopic(sTopic).toLowerCase().trim();
return (
sTopic === activeLower ||
sTopic === mappedActiveLower ||
sMapped === activeLower ||
sMapped === mappedActiveLower
);
})
.map((s) => ({ ...normalizeTopicData(s), visible: true })),
};
}
@@ -925,63 +1031,6 @@ export class UniTrendParentComponent implements OnInit {
}
});
// Sync active topics list whenever keywords or fuzzy mode state changes
effect(() => {
const kws = this.keywords();
const fuzzy = this.isFuzzy();
const stateTopicsList = this.state?.topicsList();
const topics = fuzzy ? (stateTopicsList ?? kws) : kws;
if (topics.length > 0) {
const currentSelections = untracked(() => this.selectedTrendTopics());
const altTopics = fuzzy ? kws : (stateTopicsList ?? kws);
const mappedSelections: string[] = [];
currentSelections.forEach((item) => {
if (topics.includes(item)) {
mappedSelections.push(item);
} else {
const idx = altTopics.indexOf(item);
if (idx !== -1 && idx < topics.length && topics[idx]) {
mappedSelections.push(topics[idx]);
}
}
});
const targetSelections =
mappedSelections.length > 0
? Array.from(new Set(mappedSelections))
: topics;
// Only update selectedTrendTopics if array actually changed to prevent DOM re-creation
const current = untracked(() => this.selectedTrendTopics());
const hasChanged =
targetSelections.length !== current.length ||
targetSelections.some((t, i) => t !== current[i]);
if (hasChanged) {
this.selectedTrendTopics.set(targetSelections);
}
const currentActive = untracked(() => this.activeChartTopic());
const validSelections = untracked(() => this.selectedTrendTopics());
if (!currentActive || !validSelections.includes(currentActive)) {
const firstValid = this.findFirstNonEmptyTopic(validSelections);
if (firstValid) {
this.activeChartTopic.set(firstValid);
} else if (validSelections.length > 0) {
this.activeChartTopic.set(validSelections[0]);
}
}
} else {
const current = untracked(() => this.selectedTrendTopics());
if (current.length > 0) {
this.selectedTrendTopics.set([]);
}
}
});
// Effect: load suggestions when active topic or location filters change
effect(() => {
const topic = this.activeChartTopic();
@@ -994,39 +1043,6 @@ export class UniTrendParentComponent implements OnInit {
});
});
// Sync selectedPieEntity when trendResponse series update
effect(() => {
const data = this.trendResponse();
const currentPie = untracked(() => this.selectedPieEntity());
if (!data || data.series.length === 0) {
this.selectedPieEntity.set(null);
return;
}
if (currentPie) {
const stillExists = data.series.some((s) => {
const sId = cleanEntityId(s.entity_id);
const targetId = cleanEntityId(currentPie.id);
return sId === targetId;
});
if (stillExists) {
return;
}
}
const firstSeries = data.series[0];
if (firstSeries) {
this.selectedPieEntity.set({
id: cleanEntityId(firstSeries.entity_id),
name: firstSeries.entity_name,
type: firstSeries.entity_type as any,
});
} else {
this.selectedPieEntity.set(null);
}
});
// Load top 10 topics for selected pie entity
effect(() => {
const entity = this.selectedPieEntity();
+12 -1
View File
@@ -119,7 +119,11 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
return { id: cleanId, name };
});
if (parsedInstitutions.length === 0 && searchType !== 'authors') {
if (
parsedInstitutions.length === 0 &&
searchType !== 'authors' &&
searchType !== 'news'
) {
parsedInstitutions.push({ id: primaryInstId, name: primaryInstName });
}
@@ -128,6 +132,13 @@ export const uniTrendResolver: ResolveFn<UniTrendResolvedData> = (
const parts = c.split('|');
return { id: parts[0].toUpperCase(), name: parts[1] || parts[0] };
});
if (
parsedCountries.length === 0 &&
searchType !== 'authors' &&
searchType !== 'news'
) {
parsedCountries.push({ id: 'DE', name: 'Deutschland' });
}
const regionParams = params.getAll('regions');
const parsedRegions: CompareItem[] = regionParams.map((r) => {