feat(patents): color OpenAlex topic and IPC/CPC classification tags by academic field, reusing the existing topic-chip color palette #205

Merged
khalti merged 1 commits from ts-136-patent-to-researchers-v2 into dev 2026-07-11 20:55:09 +02:00
13 changed files with 188 additions and 23 deletions
@@ -82,6 +82,14 @@ async def get_all_patents(
) from exc
await enrich_patents_classifications(patents, ipc_search_client)
try:
await enrich_patents_openalex_topics(
patents, PatentsOpenAlexKeywordsClient()
)
except Exception:
logger.warning(
"Failed to enrich patents with OpenAlex topics", exc_info=True
)
return model.AllPatentsResponse(
total=total,
@@ -12,6 +12,13 @@ class IpcClassification(BaseModel):
model_config = ConfigDict(populate_by_name=True)
class OpenAlexTopicTag(BaseModel):
topic_id: str | None = None
topic_display_name: str
field_name: str | None = None
domain_name: str | None = None
class PatentEntry(BaseModel):
patent_id: str
source: str
@@ -32,7 +39,7 @@ class PatentEntry(BaseModel):
cpc: list[str] = Field(default_factory=list)
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
country: str | None = None
openalex_topics: list[str] = Field(default_factory=list)
openalex_topics: list[OpenAlexTopicTag] = Field(default_factory=list)
class PatentsByAuthorResponse(BaseModel):
@@ -212,9 +212,14 @@ async def enrich_patents_openalex_topics(
*(keywords_client.lookup_symbol(symbol) for symbol in symbols),
return_exceptions=True,
)
topics_by_symbol: dict[str, list[str]] = {
topics_by_symbol: dict[str, list[model.OpenAlexTopicTag]] = {
symbol: [
match.get("topic_display_name")
model.OpenAlexTopicTag(
topic_id=match.get("topic_id"),
topic_display_name=match["topic_display_name"],
field_name=match.get("field"),
domain_name=match.get("domain"),
)
for match in doc.get("topic_matches") or []
if match.get("topic_display_name")
]
@@ -224,12 +229,13 @@ async def enrich_patents_openalex_topics(
for patent in patents:
seen: set[str] = set()
topics: list[str] = []
topics: list[model.OpenAlexTopicTag] = []
for raw in (*patent.ipc, *patent.cpc):
for name in topics_by_symbol.get(extract_ipc_symbol(raw), []):
if name not in seen:
seen.add(name)
topics.append(name)
for tag in topics_by_symbol.get(extract_ipc_symbol(raw), []):
dedup_key = tag.topic_id or tag.topic_display_name
if dedup_key not in seen:
seen.add(dedup_key)
topics.append(tag)
patent.openalex_topics = topics[:6]
@@ -18,18 +18,27 @@ def _patent(patent_id: str, ipc: list[str], cpc: list[str] | None = None) -> Pat
return PatentEntry(patent_id=patent_id, source="EPO", ipc=ipc, cpc=cpc or [])
def test_enrich_patents_openalex_topics_attaches_and_dedupes() -> None:
def test_enrich_patents_openalex_topics_attaches_field_and_domain() -> None:
client = _FakeKeywordsClient(
{
"C07K 11/02": {
"topic_matches": [
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
{"topic_id": "https://openalex.org/T2", "topic_display_name": "Peptide Chemistry"},
{
"topic_id": "https://openalex.org/T1",
"topic_display_name": "Peptide Chemistry",
"field": "Chemistry",
"domain": "Physical Sciences",
},
]
},
"A61K 38/00": {
"topic_matches": [
{"topic_id": "https://openalex.org/T3", "topic_display_name": "Drug Delivery"},
{
"topic_id": "https://openalex.org/T3",
"topic_display_name": "Drug Delivery",
"field": "Pharmacology, Toxicology and Pharmaceutics",
"domain": "Health Sciences",
},
]
},
}
@@ -38,7 +47,30 @@ def test_enrich_patents_openalex_topics_attaches_and_dedupes() -> None:
asyncio.run(enrich_patents_openalex_topics([patent], client))
assert patent.openalex_topics == ["Peptide Chemistry", "Drug Delivery"]
assert [t.topic_display_name for t in patent.openalex_topics] == [
"Peptide Chemistry",
"Drug Delivery",
]
assert patent.openalex_topics[0].field_name == "Chemistry"
assert patent.openalex_topics[0].domain_name == "Physical Sciences"
def test_enrich_patents_openalex_topics_dedupes_by_topic_id() -> None:
client = _FakeKeywordsClient(
{
"C07K 11/02": {
"topic_matches": [
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
]
},
}
)
patent = _patent("EP1", ipc=["C07K 11/02 20060101AFI"])
asyncio.run(enrich_patents_openalex_topics([patent], client))
assert len(patent.openalex_topics) == 1
def test_enrich_patents_openalex_topics_skips_unmatched_symbols() -> None:
@@ -68,5 +100,5 @@ def test_enrich_patents_openalex_topics_looks_up_each_symbol_once() -> None:
asyncio.run(enrich_patents_openalex_topics(patents, client))
assert client.lookup_calls == ["C07K 11/02"]
assert patents[0].openalex_topics == ["Peptide Chemistry"]
assert patents[1].openalex_topics == ["Peptide Chemistry"]
assert patents[0].openalex_topics[0].topic_display_name == "Peptide Chemistry"
assert patents[1].openalex_topics[0].topic_display_name == "Peptide Chemistry"
+1
View File
@@ -124,6 +124,7 @@ export * from './newsArticle';
export * from './newsArticleDetail';
export * from './newsPage';
export * from './openAccess';
export * from './openAlexTopicTag';
export * from './orgPatentEntry';
export * from './orgPatentsResponse';
export * from './organizationPage';
@@ -0,0 +1,16 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface OpenAlexTopicTag {
topic_id?: string | null;
topic_display_name: string;
field_name?: string | null;
domain_name?: string | null;
}
+2 -1
View File
@@ -9,6 +9,7 @@
*/
import { MatchedAuthor } from './matchedAuthor';
import { IpcClassification } from './ipcClassification';
import { OpenAlexTopicTag } from './openAlexTopicTag';
export interface OrgPatentEntry {
patent_id: string;
@@ -30,7 +31,7 @@ export interface OrgPatentEntry {
cpc?: Array<string>;
cpc_descriptions?: Array<IpcClassification>;
country?: string | null;
openalex_topics?: Array<string>;
openalex_topics?: Array<OpenAlexTopicTag>;
institution_id: string;
institution_name?: string | null;
match_type: OrgPatentEntry.MatchTypeEnum;
+2 -1
View File
@@ -8,6 +8,7 @@
* Do not edit the class manually.
*/
import { IpcClassification } from './ipcClassification';
import { OpenAlexTopicTag } from './openAlexTopicTag';
export interface PatentEntry {
@@ -30,6 +31,6 @@ export interface PatentEntry {
cpc?: Array<string>;
cpc_descriptions?: Array<IpcClassification>;
country?: string | null;
openalex_topics?: Array<string>;
openalex_topics?: Array<OpenAlexTopicTag>;
}
@@ -127,8 +127,14 @@
<h2>OpenAlex Themen</h2>
</div>
<div class="tags">
@for (topic of patent.openalex_topics; track topic) {
<span>{{ topic }}</span>
@for (topic of patent.openalex_topics; track topic.topic_id ?? topic.topic_display_name) {
<app-topic-chip
[label]="topic.topic_display_name"
[fieldName]="topic.field_name"
[domainName]="topic.domain_name"
[color]="topicColor(topic)"
size="mini">
</app-topic-chip>
}
</div>
</section>
@@ -149,7 +155,15 @@
<header class="classification-card__header">
<div class="classification-card__codes">
@for (symbol of card.symbols; track symbol) {
<span class="classification-code">{{ symbol }}</span>
<span
class="classification-code"
[style.border]="'1px solid ' + sectionColor(card)"
[style.color]="sectionColor(card)"
[style.background]="
'color-mix(in srgb, ' + sectionColor(card) + ' 12%, white)'
">
{{ symbol }}
</span>
}
</div>
<div class="classification-card__badges">
@@ -225,7 +239,15 @@
<header class="classification-card__header">
<div class="classification-card__codes">
@for (symbol of card.symbols; track symbol) {
<span class="classification-code">{{ symbol }}</span>
<span
class="classification-code"
[style.border]="'1px solid ' + sectionColor(card)"
[style.color]="sectionColor(card)"
[style.background]="
'color-mix(in srgb, ' + sectionColor(card) + ' 12%, white)'
">
{{ symbol }}
</span>
}
</div>
<div class="classification-card__badges">
@@ -9,6 +9,9 @@ import { finalize } from 'rxjs';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry } from '../../api/model/patentEntry';
import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag';
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import {
ClassificationCard,
ClassificationSystem,
@@ -28,6 +31,7 @@ import {
MatIconModule,
MatProgressSpinnerModule,
RouterLink,
TopicChipComponent,
],
templateUrl: './patent-detail.component.html',
styleUrl: './patent-detail.component.scss',
@@ -93,6 +97,19 @@ export class PatentDetailComponent implements OnInit {
return getClassificationCards(entries, system);
}
topicColor(topic: OpenAlexTopicTag): string {
return topicHierarchyColor({
id: topic.topic_id,
name: topic.topic_display_name,
field_name: topic.field_name,
domain_name: topic.domain_name,
});
}
sectionColor(card: ClassificationCard): string {
return topicHierarchyColor({ field_name: card.sectionName });
}
toggleClassificationExpanded(key: string): void {
if (this.expandedClassificationKeys.has(key)) {
this.expandedClassificationKeys.delete(key);
@@ -10,6 +10,7 @@ export interface ClassificationCard {
levelLabel: string;
primaryDescription: string | null;
hierarchy: { label: string; value: string }[];
sectionName: string | null;
}
export interface PatentMetadataRow {
@@ -153,6 +154,7 @@ function buildClassificationCard(
levelLabel: level.label,
primaryDescription,
hierarchy: buildHierarchyRows(entry, primaryDescription),
sectionName: entry.section ?? null,
};
}
@@ -142,6 +142,23 @@
</div>
}
@if ((selectedPatent.openalex_topics?.length ?? 0) > 0) {
<div class="detail-section">
<h4>OpenAlex Themen</h4>
<div class="tag-list">
@for (topic of selectedPatent.openalex_topics; track topic.topic_id ?? topic.topic_display_name) {
<app-topic-chip
[label]="topic.topic_display_name"
[fieldName]="topic.field_name"
[domainName]="topic.domain_name"
[color]="topicColor(topic)"
size="mini">
</app-topic-chip>
}
</div>
</div>
}
@if ((selectedPatent.ipc_descriptions?.length ?? 0) > 0) {
<div
class="detail-section classification-section classification-section--ipc">
@@ -158,7 +175,15 @@
<header class="classification-card__header">
<div class="classification-card__codes">
@for (sym of card.symbols; track sym) {
<span class="classification-code">{{ sym }}</span>
<span
class="classification-code"
[style.border]="'1px solid ' + sectionColor(card)"
[style.color]="sectionColor(card)"
[style.background]="
'color-mix(in srgb, ' + sectionColor(card) + ' 12%, white)'
">
{{ sym }}
</span>
}
</div>
<div class="classification-card__badges">
@@ -234,7 +259,15 @@
<header class="classification-card__header">
<div class="classification-card__codes">
@for (sym of card.symbols; track sym) {
<span class="classification-code">{{ sym }}</span>
<span
class="classification-code"
[style.border]="'1px solid ' + sectionColor(card)"
[style.color]="sectionColor(card)"
[style.background]="
'color-mix(in srgb, ' + sectionColor(card) + ' 12%, white)'
">
{{ sym }}
</span>
}
</div>
<div class="classification-card__badges">
@@ -15,6 +15,9 @@ import { debounceTime, distinctUntilChanged, Subject } from 'rxjs';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry } from '../../api/model/patentEntry';
import { IpcClassification } from '../../api';
import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag';
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
@@ -27,6 +30,7 @@ interface ClassificationCard {
levelLabel: string;
primaryDescription: string | null;
hierarchy: { label: string; value: string }[];
sectionName: string | null;
}
const DESCRIPTION_PREVIEW_LENGTH = 140;
@@ -46,6 +50,7 @@ const MIN_YEAR = 1978;
MatProgressSpinnerModule,
MatChipsModule,
MatDividerModule,
TopicChipComponent,
],
templateUrl: './patents.component.html',
styleUrl: './patents.component.scss',
@@ -342,9 +347,23 @@ export class PatentsComponent implements OnInit {
levelLabel: level.label,
primaryDescription,
hierarchy: this.buildHierarchyRows(entry, primaryDescription),
sectionName: entry.section ?? null,
};
}
topicColor(topic: OpenAlexTopicTag): string {
return topicHierarchyColor({
id: topic.topic_id,
name: topic.topic_display_name,
field_name: topic.field_name,
domain_name: topic.domain_name,
});
}
sectionColor(card: ClassificationCard): string {
return topicHierarchyColor({ field_name: card.sectionName });
}
private getClassificationLevel(entry: IpcClassification): { label: string; field: keyof IpcClassification } {
if (entry.subgroup) return { label: 'Untergruppe', field: 'subgroup' };
if (entry.main_group) return { label: 'Hauptgruppe', field: 'main_group' };