Compare commits
142
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f71a4b56c | ||
|
|
77c7eeef8b | ||
|
|
5b894d8927 | ||
|
|
b352e5288a | ||
|
|
7bbfe1761d | ||
|
|
09cb54109a | ||
|
|
010e1c7f21 | ||
|
|
d1802fa1f8 | ||
|
|
4d0a6db3c3 | ||
|
|
db604feb37 | ||
|
|
cd0e98ec5f | ||
|
|
42685ae44f | ||
|
|
9be024bb13 | ||
|
|
87b7e207e3 | ||
|
|
8eaa9c2420 | ||
|
|
87b02ed0a4 | ||
|
|
a6d30dd897 | ||
|
|
134055b8b9 | ||
|
|
be72d28bda | ||
|
|
2bfb877e77 | ||
|
|
48e33e7fe5 | ||
|
|
f469594c17 | ||
|
|
3e115619a6 | ||
|
|
13b2fb3350 | ||
|
|
d26ddb8cb4 | ||
|
|
a8e582cf23 | ||
|
|
940c050cd7 | ||
|
|
e470b65b5a | ||
|
|
383c77134a | ||
|
|
bb941361a1 | ||
|
|
5d22b201e9 | ||
|
|
1c6dbb540f | ||
|
|
cf9a5df4e9 | ||
|
|
213edf8a5f | ||
|
|
c277fcfece | ||
|
|
8efbbf1f1a | ||
|
|
9ad6d5cd8c | ||
|
|
77540e4002 | ||
|
|
fd3ceb54aa | ||
|
|
7baeab92c2 | ||
|
|
0c526be983 | ||
|
|
53f5440d01 | ||
|
|
e86a19f800 | ||
|
|
61fd920a9f | ||
|
|
7eed7e6614 | ||
|
|
e34e1fe3d5 | ||
|
|
2418821691 | ||
|
|
058c92227a | ||
|
|
bf38147acc | ||
|
|
3f23845c89 | ||
|
|
52e70a5b24 | ||
|
|
d502431102 | ||
|
|
3533b994d0 | ||
|
|
5d22f4831a | ||
|
|
8130192a44 | ||
|
|
bda7aff447 | ||
|
|
82421c1040 | ||
|
|
0723bb5c5b | ||
|
|
e4dbe07436 | ||
|
|
19c6574945 | ||
|
|
0b750d27e7 | ||
|
|
398ea7b56c | ||
|
|
0176eea873 | ||
|
|
b0e8c86743 | ||
|
|
03a2954c72 | ||
|
|
b9d382c78a | ||
|
|
78a8e5d919 | ||
|
|
f9f6a58ad5 | ||
|
|
5cc110174a | ||
|
|
c3ec93fba1 | ||
|
|
169b825195 | ||
|
|
0a3bf72e14 | ||
|
|
eb94fc5942 | ||
|
|
e868c4a47e | ||
|
|
1cf80ae074 | ||
|
|
c74d0b5b87 | ||
|
|
a69f014413 | ||
|
|
cabf819e94 | ||
|
|
c243088752 | ||
|
|
1dd032a66c | ||
|
|
9f03c92bc1 | ||
|
|
86bced4940 | ||
|
|
4461b26270 | ||
|
|
19fd2ac86d | ||
|
|
e9ba874103 | ||
|
|
dfb1413b05 | ||
|
|
b5d03c84c4 | ||
|
|
ef41c0ad96 | ||
|
|
a07fadc30e | ||
|
|
4bf351cf66 | ||
|
|
f55a37867c | ||
|
|
ae42bc46ed | ||
|
|
c38355c817 | ||
|
|
0c004f0cdf | ||
|
|
16c0b399c8 | ||
|
|
3867540a4c | ||
|
|
32cab01a8b | ||
|
|
2b606b8473 | ||
|
|
e0ac41da91 | ||
|
|
86bed62ac0 | ||
|
|
1eaf8f8c8f | ||
|
|
0c3db967b0 | ||
|
|
04eb0f0185 | ||
|
|
b2d965d604 | ||
|
|
92c4edfb4f | ||
|
|
79f2aa0263 | ||
|
|
5878edc4cd | ||
|
|
f4122263dd | ||
|
|
20faff13ec | ||
|
|
73315457a6 | ||
|
|
2703f46575 | ||
|
|
261f97eee0 | ||
|
|
f4b8d0884c | ||
|
|
1ddc5c42c5 | ||
|
|
47fb41105a | ||
|
|
4394ced772 | ||
|
|
15fc57da51 | ||
|
|
3c910fa0e4 | ||
|
|
c1cba4bd4c | ||
|
|
d43c406820 | ||
|
|
398df55f50 | ||
|
|
5888a71b36 | ||
|
|
c707064dfb | ||
|
|
8e56b59122 | ||
|
|
6fa5792e5e | ||
|
|
116492baca | ||
|
|
b1fee136ce | ||
|
|
95ce3a47fc | ||
|
|
195fd2d55b | ||
|
|
5d13b07c73 | ||
|
|
d8aca8ee3e | ||
|
|
495c7d34e5 | ||
|
|
39fdb23942 | ||
|
|
0d2c7f93be | ||
|
|
7c68a5cd71 | ||
|
|
b69fe4e15c | ||
|
|
873e4bbbec | ||
|
|
f2cf83f63b | ||
|
|
512356e106 | ||
|
|
309fecf008 | ||
|
|
29c954227f | ||
|
|
1f70f9fe2d |
@@ -38,6 +38,7 @@ def add_entry(index: str, entry: dict):
|
|||||||
"news_id": entry["news_id"],
|
"news_id": entry["news_id"],
|
||||||
"relevant": int(entry["relevant"]),
|
"relevant": int(entry["relevant"]),
|
||||||
"authors": entry["authors"],
|
"authors": entry["authors"],
|
||||||
|
"keywords": entry.get("keywords", []),
|
||||||
}
|
}
|
||||||
|
|
||||||
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
||||||
@@ -47,6 +48,13 @@ def add_entry(index: str, entry: dict):
|
|||||||
|
|
||||||
return created_id
|
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:
|
def get_entry(index: str, document_id: str) -> dict:
|
||||||
|
|
||||||
encoded_document_id = quote(document_id, safe="")
|
encoded_document_id = quote(document_id, safe="")
|
||||||
@@ -104,3 +112,17 @@ def delete_all_entries(index: str):
|
|||||||
}
|
}
|
||||||
|
|
||||||
return _send_es_request("POST", endpoint, payload=payload)
|
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.
|
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(
|
_client = OpenAI(
|
||||||
base_url=LLM_BASE_URL,
|
base_url=LLM_BASE_URL,
|
||||||
api_key=LLM_API_KEY,
|
api_key=LLM_API_KEY,
|
||||||
@@ -62,3 +73,14 @@ def extract_names(text: str) -> list[str]:
|
|||||||
return data.get("person", [])
|
return data.get("person", [])
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
return []
|
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"]
|
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||||
is_news_relevant = llm_client.is_news_relevant(news_text)
|
is_news_relevant = llm_client.is_news_relevant(news_text)
|
||||||
authors = llm_client.extract_names(news_text)
|
authors = llm_client.extract_names(news_text)
|
||||||
|
keywords = llm_client.extract_keywords(news_text)
|
||||||
new_entry = {
|
new_entry = {
|
||||||
"news_id": news_id,
|
"news_id": news_id,
|
||||||
"relevant": is_news_relevant,
|
"relevant": is_news_relevant,
|
||||||
"authors": authors,
|
"authors": authors,
|
||||||
|
"keywords": keywords,
|
||||||
}
|
}
|
||||||
es_client.add_entry("aktuell_postproc", new_entry)
|
es_client.add_entry("aktuell_postproc", new_entry)
|
||||||
return True
|
return True
|
||||||
@@ -32,6 +34,25 @@ def sync_single_news(news_id, max_retries=3):
|
|||||||
print(f"Error: {news_id} - {error}")
|
print(f"Error: {news_id} - {error}")
|
||||||
return False
|
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():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
|
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'.",
|
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(
|
parser.add_argument(
|
||||||
"--stats",
|
"--stats",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -60,11 +93,22 @@ def main():
|
|||||||
help="Number of threads for --sync-delta (Default: 4).",
|
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()
|
args = parser.parse_args()
|
||||||
|
|
||||||
if args.delete_all:
|
if args.delete_all:
|
||||||
es_client.delete_all_entries("aktuell_postproc")
|
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:
|
if args.sync_delta:
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||||
@@ -97,22 +141,57 @@ def main():
|
|||||||
print(f"Sync DONE: {succeeded} entries synced.")
|
print(f"Sync DONE: {succeeded} entries synced.")
|
||||||
print(f"Time taken: {end_time - start_time} seconds.")
|
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:
|
if args.stats:
|
||||||
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||||
print(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
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)
|
total_entries = len(postproc_entries)
|
||||||
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
||||||
irrelevant_count = total_entries - relevant_count
|
irrelevant_count = total_entries - relevant_count
|
||||||
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
|
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_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"Total entries in 'aktuell_postproc': {total_entries}")
|
||||||
print(f"Relevant entries: {relevant_count}")
|
print(f"Relevant entries: {relevant_count}")
|
||||||
print(f"Irrelevant entries: {irrelevant_count}")
|
print(f"Irrelevant entries: {irrelevant_count}")
|
||||||
print(f"Entries with extracted names: {news_with_extracted_names}")
|
print(f"Entries with extracted names: {news_with_extracted_names}")
|
||||||
print(f"Entries without extracted names: {news_without_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__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
File diff suppressed because one or more lines are too long
@@ -4,6 +4,7 @@ from enum import StrEnum
|
|||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy import UniqueConstraint
|
||||||
from sqlmodel import Field, Relationship, SQLModel
|
from sqlmodel import Field, Relationship, SQLModel
|
||||||
|
|
||||||
|
|
||||||
@@ -20,6 +21,11 @@ class TokenType(StrEnum):
|
|||||||
ACCESS_TOKEN = "ACCESS_TOKEN"
|
ACCESS_TOKEN = "ACCESS_TOKEN"
|
||||||
|
|
||||||
|
|
||||||
|
class SecretPurpose(StrEnum):
|
||||||
|
LOGIN_OTK = "LOGIN_OTK"
|
||||||
|
PASSWORD_RESET = "PASSWORD_RESET"
|
||||||
|
|
||||||
|
|
||||||
class Durable(SQLModel):
|
class Durable(SQLModel):
|
||||||
deleted: bool = Field(
|
deleted: bool = Field(
|
||||||
default=False,
|
default=False,
|
||||||
@@ -106,6 +112,9 @@ class Account(Durable, table=True):
|
|||||||
|
|
||||||
|
|
||||||
class Secret(SQLModel, table=True):
|
class Secret(SQLModel, table=True):
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("account_id", "purpose", name="uq_secret_account_purpose"),
|
||||||
|
)
|
||||||
id: uuid.UUID | None = Field(
|
id: uuid.UUID | None = Field(
|
||||||
default_factory=uuid.uuid4,
|
default_factory=uuid.uuid4,
|
||||||
primary_key=True,
|
primary_key=True,
|
||||||
@@ -113,10 +122,16 @@ class Secret(SQLModel, table=True):
|
|||||||
)
|
)
|
||||||
account_id: uuid.UUID = Field(
|
account_id: uuid.UUID = Field(
|
||||||
foreign_key="account.id",
|
foreign_key="account.id",
|
||||||
unique=True, # Ensure that each account can have only one associated secret
|
index=True,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
description="The unique identifier of the account associated with this secret.",
|
description="The unique identifier of the account associated with this secret.",
|
||||||
)
|
)
|
||||||
|
purpose: SecretPurpose = Field(
|
||||||
|
default=SecretPurpose.LOGIN_OTK,
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The purpose of the secret, such as login OTK or password reset.",
|
||||||
|
)
|
||||||
secret_value: str = Field(
|
secret_value: str = Field(
|
||||||
index=False,
|
index=False,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
@@ -127,6 +142,16 @@ class Secret(SQLModel, table=True):
|
|||||||
nullable=False,
|
nullable=False,
|
||||||
description="The timestamp indicating when the secret will expire.",
|
description="The timestamp indicating when the secret will expire.",
|
||||||
)
|
)
|
||||||
|
request_count: int = Field(
|
||||||
|
default=0,
|
||||||
|
nullable=False,
|
||||||
|
description="The number of password reset requests in the current rate-limit window.",
|
||||||
|
)
|
||||||
|
request_window_started_at: datetime | None = Field(
|
||||||
|
default=None,
|
||||||
|
index=True,
|
||||||
|
description="The start timestamp of the current password reset request window.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class BaseTokenData(BaseModel):
|
class BaseTokenData(BaseModel):
|
||||||
|
|||||||
@@ -46,6 +46,46 @@ async def request_otk(
|
|||||||
return auth_service.request_otk(session=session, email=email, password=password)
|
return auth_service.request_otk(session=session, email=email, password=password)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/request-password-reset",
|
||||||
|
summary="Request Password Reset",
|
||||||
|
description="Request a one-time password reset link for the given email address.",
|
||||||
|
operation_id="requestPasswordReset",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {"description": "Password reset requested successfully."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
async def request_password_reset(
|
||||||
|
session: SessionDep,
|
||||||
|
email: Annotated[str, Body(embed=True, description="User's email address")],
|
||||||
|
):
|
||||||
|
return auth_service.request_password_reset(session=session, email=email)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/reset-password",
|
||||||
|
summary="Reset Password",
|
||||||
|
description="Reset the user's password using a one-time password reset token.",
|
||||||
|
operation_id="resetPassword",
|
||||||
|
responses={status.HTTP_200_OK: {"description": "Password reset successfully."}},
|
||||||
|
)
|
||||||
|
async def reset_password(
|
||||||
|
session: SessionDep,
|
||||||
|
reset_token: Annotated[
|
||||||
|
str, Body(description="Password reset token from the reset link")
|
||||||
|
],
|
||||||
|
new_password: Annotated[
|
||||||
|
str,
|
||||||
|
Body(description="New password", min_length=8, example="NewPassword123"),
|
||||||
|
],
|
||||||
|
):
|
||||||
|
return auth_service.reset_password(
|
||||||
|
session=session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password=new_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/login",
|
"/login",
|
||||||
summary="Login with One-Time Key",
|
summary="Login with One-Time Key",
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ from argon2 import PasswordHasher
|
|||||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||||
from fastapi import Cookie, Depends, HTTPException, Response, status
|
from fastapi import Cookie, Depends, HTTPException, Response, status
|
||||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
from sqlmodel import Session, func, select
|
||||||
|
|
||||||
|
from inse.auth.email_service import send_email
|
||||||
from inse.auth.model import (
|
from inse.auth.model import (
|
||||||
AccessResponse,
|
AccessResponse,
|
||||||
AccessToken,
|
AccessToken,
|
||||||
@@ -22,19 +25,21 @@ from inse.auth.model import (
|
|||||||
OtkResponse,
|
OtkResponse,
|
||||||
RefreshTokenMetadata,
|
RefreshTokenMetadata,
|
||||||
Secret,
|
Secret,
|
||||||
|
SecretPurpose,
|
||||||
TokenType,
|
TokenType,
|
||||||
UserRole,
|
UserRole,
|
||||||
)
|
)
|
||||||
from inse.config import get_settings
|
from inse.config import get_settings
|
||||||
from inse.database import get_session
|
from inse.database import get_session
|
||||||
from sqlmodel import Session, select, func
|
|
||||||
from inse.auth.email_service import send_email
|
|
||||||
|
|
||||||
ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days
|
ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days
|
||||||
REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day
|
REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day
|
||||||
ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes
|
ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes
|
||||||
|
|
||||||
OTK_EXPIRATION_MINUTES = 15 # 15 minutes
|
OTK_EXPIRATION_MINUTES = 15 # 15 minutes
|
||||||
|
PASSWORD_RESET_EXPIRATION_MINUTES = 5 # 5 minutes
|
||||||
|
PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES = 5 # 5 minutes
|
||||||
|
PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
|
||||||
|
|
||||||
REAL_ACCOUNT_ID_KEY = "real_account_id"
|
REAL_ACCOUNT_ID_KEY = "real_account_id"
|
||||||
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
|
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
|
||||||
@@ -160,7 +165,32 @@ def _verify_password(password: str, password_hash: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def request_otk(session: Session, email: str, password: str) -> OtkResponse:
|
def _hash_reset_token(reset_token: str) -> str:
|
||||||
|
"""Hashes a high-entropy password reset token for storage.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
reset_token (str): The raw reset token sent to the user.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: SHA-256 hash of the reset token.
|
||||||
|
"""
|
||||||
|
return hashlib.sha256(reset_token.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _build_password_reset_link(reset_token: str) -> str:
|
||||||
|
"""Builds the password reset link that will be sent to the user.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
reset_token (str): The raw reset token to include in the link.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The full password reset link.
|
||||||
|
"""
|
||||||
|
separator = "&" if "?" in settings.password_reset_url else "?"
|
||||||
|
return f"{settings.password_reset_url}{separator}token={reset_token}"
|
||||||
|
|
||||||
|
|
||||||
|
def request_otk(session: Session, email: str, password: str):
|
||||||
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
|
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -211,7 +241,12 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
|
|||||||
otk_code = f"{secrets.randbelow(1_000_000):06d}"
|
otk_code = f"{secrets.randbelow(1_000_000):06d}"
|
||||||
print(otk_code)
|
print(otk_code)
|
||||||
|
|
||||||
secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first()
|
secret = session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.account_id == account.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
|
||||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||||
minutes=OTK_EXPIRATION_MINUTES
|
minutes=OTK_EXPIRATION_MINUTES
|
||||||
@@ -220,6 +255,7 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
|
|||||||
if secret is None:
|
if secret is None:
|
||||||
secret = Secret(
|
secret = Secret(
|
||||||
account_id=account.id,
|
account_id=account.id,
|
||||||
|
purpose=SecretPurpose.LOGIN_OTK,
|
||||||
secret_value=otk_code,
|
secret_value=otk_code,
|
||||||
expires_at=expires_at,
|
expires_at=expires_at,
|
||||||
)
|
)
|
||||||
@@ -251,6 +287,210 @@ def request_otk(session: Session, email: str, password: str) -> OtkResponse:
|
|||||||
return OtkResponse(status="success", account_id=account.id)
|
return OtkResponse(status="success", account_id=account.id)
|
||||||
|
|
||||||
|
|
||||||
|
def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
|
||||||
|
"""Requests a one-time password reset link for the given email address.
|
||||||
|
|
||||||
|
For security reasons, this function always returns a successful response and
|
||||||
|
does not reveal whether the email address belongs to an active account.
|
||||||
|
"""
|
||||||
|
email = email.lower().strip()
|
||||||
|
now = datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
|
||||||
|
account = session.exec(
|
||||||
|
select(Account).where(
|
||||||
|
Account.email == email,
|
||||||
|
Account.deleted == False, # noqa: E712
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if account is None or account.deleted or account.id is None:
|
||||||
|
logger.info("Password reset requested for unknown email %s", email)
|
||||||
|
return {
|
||||||
|
"status": "ok",
|
||||||
|
"reset_link_created": False,
|
||||||
|
"rate_limited": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
secret = session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.account_id == account.id,
|
||||||
|
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if secret is not None:
|
||||||
|
if secret.request_window_started_at is not None:
|
||||||
|
window_started_at = secret.request_window_started_at
|
||||||
|
if getattr(window_started_at, "tzinfo", None) is None:
|
||||||
|
window_started_at = window_started_at.replace(
|
||||||
|
tzinfo=datetime.timezone.utc
|
||||||
|
)
|
||||||
|
|
||||||
|
window_ends_at = window_started_at + datetime.timedelta(
|
||||||
|
minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
|
||||||
|
)
|
||||||
|
|
||||||
|
if window_ends_at > now:
|
||||||
|
if secret.request_count >= PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW:
|
||||||
|
retry_after_seconds = max(
|
||||||
|
0,
|
||||||
|
int((window_ends_at - now).total_seconds()),
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Password reset request rate-limited for account %s.",
|
||||||
|
account.id,
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"status": "ok",
|
||||||
|
"reset_link_created": False,
|
||||||
|
"rate_limited": True,
|
||||||
|
"retry_after_seconds": retry_after_seconds,
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
secret.request_count = 0
|
||||||
|
secret.request_window_started_at = now
|
||||||
|
else:
|
||||||
|
secret.request_count = 0
|
||||||
|
secret.request_window_started_at = now
|
||||||
|
|
||||||
|
reset_token = secrets.token_urlsafe(32)
|
||||||
|
reset_token_hash = _hash_reset_token(reset_token)
|
||||||
|
|
||||||
|
expires_at = now + datetime.timedelta(minutes=PASSWORD_RESET_EXPIRATION_MINUTES)
|
||||||
|
|
||||||
|
if secret is None:
|
||||||
|
secret = Secret(
|
||||||
|
account_id=account.id,
|
||||||
|
purpose=SecretPurpose.PASSWORD_RESET,
|
||||||
|
secret_value=reset_token_hash,
|
||||||
|
expires_at=expires_at,
|
||||||
|
request_count=1,
|
||||||
|
request_window_started_at=now,
|
||||||
|
)
|
||||||
|
session.add(secret)
|
||||||
|
else:
|
||||||
|
secret.secret_value = reset_token_hash
|
||||||
|
secret.expires_at = expires_at
|
||||||
|
secret.request_count += 1
|
||||||
|
|
||||||
|
if secret.request_window_started_at is None:
|
||||||
|
secret.request_window_started_at = now
|
||||||
|
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
reset_link = _build_password_reset_link(reset_token)
|
||||||
|
|
||||||
|
if settings.send_password_reset_email:
|
||||||
|
try:
|
||||||
|
send_email(
|
||||||
|
recipient=account.email,
|
||||||
|
subject="Reset your SmartGUIDE password",
|
||||||
|
body=(
|
||||||
|
"Use the following link to reset your SmartGUIDE password:\n"
|
||||||
|
f"{reset_link}\n\n"
|
||||||
|
f"This link expires in {PASSWORD_RESET_EXPIRATION_MINUTES} minutes."
|
||||||
|
),
|
||||||
|
smtp_server=settings.smtp_server,
|
||||||
|
smtp_port=settings.smtp_port,
|
||||||
|
sender=settings.smtp_sender,
|
||||||
|
username=settings.smtp_username,
|
||||||
|
password=settings.smtp_password,
|
||||||
|
use_tls=settings.smtp_use_tls,
|
||||||
|
)
|
||||||
|
logger.info("Sent password reset email for account %s", account.id)
|
||||||
|
except Exception:
|
||||||
|
if settings.environment == "dev":
|
||||||
|
logger.exception(
|
||||||
|
"Failed to send password reset email for account %s. "
|
||||||
|
"Falling back to console reset link.",
|
||||||
|
account.id,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Password reset link for account %s: %s",
|
||||||
|
account.id,
|
||||||
|
reset_link,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise
|
||||||
|
elif settings.environment == "dev":
|
||||||
|
logger.info("Password reset link for account %s: %s", account.id, reset_link)
|
||||||
|
else:
|
||||||
|
logger.info("Password reset token generated for account %s", account.id)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"status": "ok",
|
||||||
|
"reset_link_created": True,
|
||||||
|
"rate_limited": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def reset_password(
|
||||||
|
session: Session,
|
||||||
|
reset_token: str,
|
||||||
|
new_password: str,
|
||||||
|
) -> Dict[str, str]:
|
||||||
|
"""Resets an account password using a one-time password reset token.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
session (Session): The database session used to query the account and secret.
|
||||||
|
reset_token (str): The raw reset token from the password reset link.
|
||||||
|
new_password (str): The new password to store for the account.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
HTTPException: If the reset token is invalid or expired.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, str]: A status response.
|
||||||
|
"""
|
||||||
|
now = datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
reset_token_hash = _hash_reset_token(reset_token.strip())
|
||||||
|
|
||||||
|
secret = session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||||
|
Secret.secret_value == reset_token_hash,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if secret is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid or expired password reset token",
|
||||||
|
)
|
||||||
|
|
||||||
|
secret_expires = secret.expires_at
|
||||||
|
if getattr(secret_expires, "tzinfo", None) is None:
|
||||||
|
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
|
||||||
|
|
||||||
|
if secret_expires <= now:
|
||||||
|
session.delete(secret)
|
||||||
|
session.commit()
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid or expired password reset token",
|
||||||
|
)
|
||||||
|
|
||||||
|
account = session.get(Account, secret.account_id)
|
||||||
|
|
||||||
|
if account is None or account.deleted or account.id is None:
|
||||||
|
session.delete(secret)
|
||||||
|
session.commit()
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid or expired password reset token",
|
||||||
|
)
|
||||||
|
|
||||||
|
account.password_hash = _hash_password(new_password)
|
||||||
|
account.epoch += 1
|
||||||
|
|
||||||
|
session.add(account)
|
||||||
|
session.delete(secret)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
def login(
|
def login(
|
||||||
session: Session, response: Response, account_id: uuid.UUID, email_code: str
|
session: Session, response: Response, account_id: uuid.UUID, email_code: str
|
||||||
) -> LoginResponse:
|
) -> LoginResponse:
|
||||||
@@ -274,6 +514,7 @@ def login(
|
|||||||
secret = session.exec(
|
secret = session.exec(
|
||||||
select(Secret).where(
|
select(Secret).where(
|
||||||
Secret.account_id == account_id,
|
Secret.account_id == account_id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
Secret.secret_value == email_code,
|
Secret.secret_value == email_code,
|
||||||
# Validating the code and ensuring it matches the account ID
|
# Validating the code and ensuring it matches the account ID
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from inse.auth.model import (
|
|||||||
Account,
|
Account,
|
||||||
Organization,
|
Organization,
|
||||||
Secret,
|
Secret,
|
||||||
|
SecretPurpose,
|
||||||
AccessToken,
|
AccessToken,
|
||||||
IdTokenMetadata,
|
IdTokenMetadata,
|
||||||
AccessTokenMetadata,
|
AccessTokenMetadata,
|
||||||
@@ -98,7 +99,10 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup):
|
|||||||
assert resp.account_id == acc.id
|
assert resp.account_id == acc.id
|
||||||
|
|
||||||
secret = in_memory_session.exec(
|
secret = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
assert secret is not None
|
assert secret is not None
|
||||||
|
|
||||||
@@ -281,7 +285,12 @@ def test_login_with_expired_secret(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||||
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
|
secret = Secret(
|
||||||
|
account_id=acc.id,
|
||||||
|
purpose=SecretPurpose.LOGIN_OTK,
|
||||||
|
secret_value="000000",
|
||||||
|
expires_at=expired_at,
|
||||||
|
)
|
||||||
in_memory_session.add(secret)
|
in_memory_session.add(secret)
|
||||||
in_memory_session.commit()
|
in_memory_session.commit()
|
||||||
|
|
||||||
@@ -426,14 +435,20 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
|||||||
|
|
||||||
auth_service.request_otk(in_memory_session, email, password)
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
secret1 = in_memory_session.exec(
|
secret1 = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
assert secret1 is not None
|
assert secret1 is not None
|
||||||
first_value = secret1.secret_value
|
first_value = secret1.secret_value
|
||||||
|
|
||||||
auth_service.request_otk(in_memory_session, email, password)
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
secret2 = in_memory_session.exec(
|
secret2 = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
|
|
||||||
assert secret2 is not None
|
assert secret2 is not None
|
||||||
@@ -460,13 +475,19 @@ def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
|||||||
|
|
||||||
auth_service.request_otk(in_memory_session, email, password)
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
secret = in_memory_session.exec(
|
secret = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
assert secret is not None
|
assert secret is not None
|
||||||
|
|
||||||
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
||||||
post = in_memory_session.exec(
|
post = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
assert post is None
|
assert post is None
|
||||||
|
|
||||||
@@ -551,3 +572,180 @@ def test_get_account_epoch_not_found(in_memory_session):
|
|||||||
random_id = uuid.uuid4()
|
random_id = uuid.uuid4()
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(Exception):
|
||||||
auth_service._get_account_epoch(in_memory_session, random_id)
|
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_password_reset_creates_secret(in_memory_session, settings_backup):
|
||||||
|
email = "reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
result = auth_service.request_password_reset(in_memory_session, email)
|
||||||
|
assert result["status"] == "ok"
|
||||||
|
|
||||||
|
secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
|
||||||
|
assert secret is not None
|
||||||
|
assert secret.secret_value is not None
|
||||||
|
assert secret.secret_value != ""
|
||||||
|
assert secret.secret_value != password
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_password_reset_unknown_email_is_safe(
|
||||||
|
in_memory_session, settings_backup, monkeypatch
|
||||||
|
):
|
||||||
|
sent_emails = []
|
||||||
|
|
||||||
|
def fake_send_email(**kwargs):
|
||||||
|
sent_emails.append(kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
|
||||||
|
config_module.settings.send_password_reset_email = True
|
||||||
|
|
||||||
|
result = auth_service.request_password_reset(
|
||||||
|
in_memory_session, "missing@example.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["status"] == "ok"
|
||||||
|
assert sent_emails == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_password_reset_sends_email(
|
||||||
|
in_memory_session, settings_backup, monkeypatch
|
||||||
|
):
|
||||||
|
email = "mail-reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
sent_emails = []
|
||||||
|
|
||||||
|
def fake_send_email(**kwargs):
|
||||||
|
sent_emails.append(kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
|
||||||
|
config_module.settings.send_password_reset_email = True
|
||||||
|
config_module.settings.password_reset_url = "http://localhost/reset-password"
|
||||||
|
|
||||||
|
result = auth_service.request_password_reset(in_memory_session, email)
|
||||||
|
|
||||||
|
assert result["status"] == "ok"
|
||||||
|
assert len(sent_emails) == 1
|
||||||
|
assert sent_emails[0]["recipient"] == email
|
||||||
|
assert "token=" in sent_emails[0]["body"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_changes_password_and_increments_epoch(in_memory_session):
|
||||||
|
email = "do-reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
new_password = "NewPassword123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
reset_token = "valid-reset-token"
|
||||||
|
secret = Secret(
|
||||||
|
account_id=acc.id,
|
||||||
|
purpose=SecretPurpose.PASSWORD_RESET,
|
||||||
|
secret_value=auth_service._hash_reset_token(reset_token),
|
||||||
|
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||||
|
)
|
||||||
|
in_memory_session.add(secret)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
old_epoch = acc.epoch
|
||||||
|
|
||||||
|
result = auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password=new_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["status"] == "ok"
|
||||||
|
in_memory_session.refresh(acc)
|
||||||
|
assert auth_service._verify_password(new_password, acc.password_hash)
|
||||||
|
assert acc.epoch == old_epoch + 1
|
||||||
|
|
||||||
|
deleted_secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
assert deleted_secret is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_rejects_reused_token(in_memory_session):
|
||||||
|
email = "reuse-reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
reset_token = "single-use-token"
|
||||||
|
secret = Secret(
|
||||||
|
account_id=acc.id,
|
||||||
|
purpose=SecretPurpose.PASSWORD_RESET,
|
||||||
|
secret_value=auth_service._hash_reset_token(reset_token),
|
||||||
|
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||||
|
)
|
||||||
|
in_memory_session.add(secret)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password="NewPassword123",
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password="AnotherPassword123",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_rejects_invalid_token(in_memory_session):
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token="invalid-token",
|
||||||
|
new_password="NewPassword123",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_rejects_expired_token(in_memory_session):
|
||||||
|
email = "expired-reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
reset_token = "expired-token"
|
||||||
|
secret = Secret(
|
||||||
|
account_id=acc.id,
|
||||||
|
purpose=SecretPurpose.PASSWORD_RESET,
|
||||||
|
secret_value=auth_service._hash_reset_token(reset_token),
|
||||||
|
expires_at=_dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=1),
|
||||||
|
)
|
||||||
|
in_memory_session.add(secret)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password="NewPassword123",
|
||||||
|
)
|
||||||
|
|
||||||
|
deleted_secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
assert deleted_secret is None
|
||||||
|
|||||||
@@ -70,6 +70,8 @@ class Settings(BaseSettings):
|
|||||||
skip_otk_validation: bool = True
|
skip_otk_validation: bool = True
|
||||||
# SMTP / email config
|
# SMTP / email config
|
||||||
send_otk_email: bool = False
|
send_otk_email: bool = False
|
||||||
|
send_password_reset_email: bool = True
|
||||||
|
password_reset_url: str = "http://localhost:4200/inse-webapp/reset-password"
|
||||||
smtp_server: str = "localhost"
|
smtp_server: str = "localhost"
|
||||||
smtp_port: int = 25
|
smtp_port: int = 25
|
||||||
smtp_sender: str = "no-reply@smartguide.local"
|
smtp_sender: str = "no-reply@smartguide.local"
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ def get_client() -> httpx.AsyncClient:
|
|||||||
global _client, _loop
|
global _client, _loop
|
||||||
try:
|
try:
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
current_loop = asyncio.get_running_loop()
|
current_loop = asyncio.get_running_loop()
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
current_loop = None
|
current_loop = None
|
||||||
@@ -108,8 +109,12 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
|||||||
def _wrap_exception(e: Exception) -> Exception:
|
def _wrap_exception(e: Exception) -> Exception:
|
||||||
if isinstance(e, httpx.HTTPStatusError):
|
if isinstance(e, httpx.HTTPStatusError):
|
||||||
if e.response.status_code == 404:
|
if e.response.status_code == 404:
|
||||||
return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
|
return ElasticsearchNotFoundException(
|
||||||
return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
|
f"Elasticsearch resource not found: {e}"
|
||||||
|
)
|
||||||
|
return ElasticsearchException(
|
||||||
|
f"Elasticsearch returned status {e.response.status_code}: {e}"
|
||||||
|
)
|
||||||
elif isinstance(e, httpx.RequestError):
|
elif isinstance(e, httpx.RequestError):
|
||||||
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
||||||
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
||||||
@@ -211,7 +216,9 @@ async def search(
|
|||||||
raise _wrap_exception(exc) from exc
|
raise _wrap_exception(exc) from exc
|
||||||
|
|
||||||
|
|
||||||
async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
async def open_point_in_time(
|
||||||
|
index: str, keep_alive: str = "1m", cluster: str = "nes"
|
||||||
|
) -> str:
|
||||||
"""Opens a point-in-time on the given index and returns its id."""
|
"""Opens a point-in-time on the given index and returns its id."""
|
||||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||||
@@ -316,6 +323,9 @@ async def get(
|
|||||||
cluster: ESCluster = ESCluster.NES,
|
cluster: ESCluster = ESCluster.NES,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
|
|
||||||
|
if isinstance(index, ESIndex):
|
||||||
|
cluster = _index_to_cluster(index) or cluster
|
||||||
|
|
||||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||||
|
|
||||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from openai import OpenAI, APIConnectionError
|
|||||||
from openai import AsyncOpenAI
|
from openai import AsyncOpenAI
|
||||||
from .. import config
|
from .. import config
|
||||||
from typing import Optional, Dict, Any
|
from typing import Optional, Dict, Any
|
||||||
|
import asyncio
|
||||||
def call(
|
def call(
|
||||||
system_prompt: str,
|
system_prompt: str,
|
||||||
user_prompt: str,
|
user_prompt: str,
|
||||||
@@ -62,7 +62,7 @@ def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str,
|
|||||||
async def call_stream(
|
async def call_stream(
|
||||||
system_prompt: str,
|
system_prompt: str,
|
||||||
user_prompt: str,
|
user_prompt: str,
|
||||||
emit, # EventCallback
|
emit,
|
||||||
model: str = None,
|
model: str = None,
|
||||||
json_schema=None,
|
json_schema=None,
|
||||||
schema_name=None,
|
schema_name=None,
|
||||||
@@ -98,15 +98,26 @@ async def call_stream(
|
|||||||
stream=True,
|
stream=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
async for chunk in stream:
|
try:
|
||||||
delta = chunk.choices[0].delta.content
|
async for chunk in stream:
|
||||||
if delta:
|
delta = chunk.choices[0].delta.content
|
||||||
full_content += delta
|
if delta:
|
||||||
await emit({"type": "llm_chunk", "content": delta})
|
full_content += delta
|
||||||
|
await emit({"type": "llm_chunk", "content": delta})
|
||||||
|
finally:
|
||||||
|
# Always release the underlying HTTP connection, whether we
|
||||||
|
# finished normally, timed out, were cancelled, or emit()
|
||||||
|
# failed because the client disconnected. This is what
|
||||||
|
# actually tells the backend to stop generating.
|
||||||
|
await stream.close()
|
||||||
|
|
||||||
except APIConnectionError as e:
|
except APIConnectionError as e:
|
||||||
print(f"Connection error: {e}")
|
print(f"Connection error: {e}")
|
||||||
return ""
|
return ""
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
# Real cancellation (e.g. asyncio.wait_for timeout, or task.cancel()
|
||||||
|
# from the router)
|
||||||
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
import traceback
|
import traceback
|
||||||
print(f"LLM streaming failed: {type(e).__name__}: {e}")
|
print(f"LLM streaming failed: {type(e).__name__}: {e}")
|
||||||
|
|||||||
@@ -126,141 +126,6 @@ async def _get_text_content(url: str) -> str:
|
|||||||
logger.error(f"Error processing {url}: {e}")
|
logger.error(f"Error processing {url}: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def extract_keywords_stream(
|
|
||||||
query: str,
|
|
||||||
mode: str,
|
|
||||||
limit: int,
|
|
||||||
emit: EventCallback,
|
|
||||||
) -> ExtractedKeywordsResponse:
|
|
||||||
start_time = time.time()
|
|
||||||
timeout_seconds = 60 # configurable
|
|
||||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
|
||||||
|
|
||||||
if mode == "url":
|
|
||||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
|
||||||
text = await _get_text_content(query)
|
|
||||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
|
||||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
|
||||||
else:
|
|
||||||
text = query
|
|
||||||
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
|
||||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
|
||||||
user_prompt = "\nNow analyze the following text and return ONLY the JSON object.\n"
|
|
||||||
if limit:
|
|
||||||
user_prompt += f"\nExtract exactly {limit} keywords for each level (broad, coarse, fine).\n"
|
|
||||||
user_prompt += f"\nInput:\n{text}"
|
|
||||||
|
|
||||||
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
|
||||||
|
|
||||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
|
||||||
|
|
||||||
# Holds only fully validated KeywordEntry dicts for each level
|
|
||||||
confirmed: Dict[str, List[Dict[str, Any]]] = {level: [] for level in LEVELS}
|
|
||||||
|
|
||||||
async def emit_full_results() -> None:
|
|
||||||
"""Attempt to build and validate the full ExtractedKeywordsLLM model and emit it."""
|
|
||||||
# Build a dict with all three fields, using empty lists for missing ones
|
|
||||||
data = {level: confirmed.get(level, []) for level in LEVELS}
|
|
||||||
try:
|
|
||||||
validated = ExtractedKeywordsLLM.model_validate(data)
|
|
||||||
except ValidationError:
|
|
||||||
# Should not happen if all items are valid, but guard against it
|
|
||||||
return
|
|
||||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
|
||||||
|
|
||||||
# adds completed keyword chunks to the confirmed dict and emits the full results when new valid items are found
|
|
||||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
|
||||||
if event["type"] != "llm_chunk":
|
|
||||||
await emit(event)
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
|
||||||
except Exception:
|
|
||||||
return
|
|
||||||
|
|
||||||
if not isinstance(partial, dict):
|
|
||||||
return
|
|
||||||
|
|
||||||
grew = False
|
|
||||||
|
|
||||||
for level in LEVELS:
|
|
||||||
current = partial.get(level) or []
|
|
||||||
idx = len(confirmed[level])
|
|
||||||
|
|
||||||
while idx < len(current):
|
|
||||||
raw_item = current[idx]
|
|
||||||
try:
|
|
||||||
validated_item = KeywordEntry.model_validate(raw_item)
|
|
||||||
except ValidationError:
|
|
||||||
break # item not complete yet
|
|
||||||
confirmed[level].append(validated_item.model_dump())
|
|
||||||
idx += 1
|
|
||||||
grew = True
|
|
||||||
|
|
||||||
if grew:
|
|
||||||
await emit_full_results()
|
|
||||||
|
|
||||||
# Accumulate full_content for incremental parsing
|
|
||||||
full_content_holder = {"value": ""}
|
|
||||||
|
|
||||||
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
|
||||||
if event["type"] == "llm_chunk":
|
|
||||||
full_content_holder["value"] += event["content"]
|
|
||||||
event = {**event, "_full_content": full_content_holder["value"]}
|
|
||||||
await on_chunk(event)
|
|
||||||
|
|
||||||
try:
|
|
||||||
keywords = await asyncio.wait_for(
|
|
||||||
llm.call_stream(
|
|
||||||
system_prompt=system_prompt,
|
|
||||||
user_prompt=user_prompt,
|
|
||||||
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
|
||||||
schema_name="extracted_keywords",
|
|
||||||
temperature=0.8,
|
|
||||||
top_p=0.95,
|
|
||||||
emit=emit_wrapper,
|
|
||||||
),
|
|
||||||
timeout=timeout_seconds,
|
|
||||||
)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
|
||||||
raise RuntimeError("LLM streaming call timed out")
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
|
||||||
raise
|
|
||||||
|
|
||||||
if not keywords:
|
|
||||||
await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
|
|
||||||
raise RuntimeError("LLM streaming call returned empty content")
|
|
||||||
|
|
||||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
|
||||||
|
|
||||||
try:
|
|
||||||
keywords_json = json.loads(keywords)
|
|
||||||
except json.JSONDecodeError as e:
|
|
||||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
|
||||||
raise RuntimeError("LLM response is not valid JSON")
|
|
||||||
|
|
||||||
# Final emission of the full results (in case the last chunk didn't trigger it)
|
|
||||||
final_data = {level: confirmed.get(level, []) for level in LEVELS}
|
|
||||||
try:
|
|
||||||
final_validated = ExtractedKeywordsLLM.model_validate(keywords_json)
|
|
||||||
except ValidationError:
|
|
||||||
# Fallback: use our confirmed data
|
|
||||||
final_validated = ExtractedKeywordsLLM.model_validate(final_data)
|
|
||||||
|
|
||||||
elapsed_time = time.time() - start_time
|
|
||||||
result = ExtractedKeywordsResponse(
|
|
||||||
results=final_validated,
|
|
||||||
source=mode,
|
|
||||||
source_url=query if mode == "url" else None,
|
|
||||||
source_content=text,
|
|
||||||
duration=elapsed_time,
|
|
||||||
)
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
async def extract_keywords_stream_enriched(
|
async def extract_keywords_stream_enriched(
|
||||||
query: str,
|
query: str,
|
||||||
@@ -275,7 +140,11 @@ async def extract_keywords_stream_enriched(
|
|||||||
if mode == "url":
|
if mode == "url":
|
||||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||||
text = await _get_text_content(query)
|
text = await _get_text_content(query)
|
||||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
if text:
|
||||||
|
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||||
|
else:
|
||||||
|
await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump())
|
||||||
|
raise RuntimeError(f"Failed to fetch content from {query}")
|
||||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||||
else:
|
else:
|
||||||
text = query
|
text = query
|
||||||
@@ -290,15 +159,10 @@ async def extract_keywords_stream_enriched(
|
|||||||
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
||||||
|
|
||||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||||
|
|
||||||
# Holds enriched keyword wrappers for each level
|
|
||||||
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
||||||
|
|
||||||
# Track background enrichment tasks
|
|
||||||
enrichment_tasks: List[asyncio.Task] = []
|
enrichment_tasks: List[asyncio.Task] = []
|
||||||
|
|
||||||
async def emit_full_results() -> None:
|
async def emit_full_results() -> None:
|
||||||
"""Attempt to build and emit the full enriched keyword model."""
|
|
||||||
try:
|
try:
|
||||||
validated = _build_enriched_snapshot(confirmed)
|
validated = _build_enriched_snapshot(confirmed)
|
||||||
except ValidationError:
|
except ValidationError:
|
||||||
@@ -306,29 +170,19 @@ async def extract_keywords_stream_enriched(
|
|||||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||||
|
|
||||||
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
|
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
|
||||||
"""
|
|
||||||
Fetch/enrich metadata for a single keyword.
|
|
||||||
Runs concurrently without blocking the LLM stream.
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
topic = await vector_search_topics_batch(
|
topic = await vector_search_topics_batch(
|
||||||
keywords=[item.keyword],
|
keywords=[item.keyword],
|
||||||
search_type="hybrid",
|
search_type="hybrid",
|
||||||
)
|
)
|
||||||
# Update the shared confirmed list in-place (safe in asyncio)
|
|
||||||
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
|
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
|
||||||
|
|
||||||
# Emit the full updated set after each enrichment so the frontend sees progress.
|
|
||||||
await emit_full_results()
|
await emit_full_results()
|
||||||
|
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
# If the whole request is cancelled, we can just re-raise
|
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
|
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
|
||||||
await emit_full_results()
|
await emit_full_results()
|
||||||
|
|
||||||
# ---------- on_chunk: parses LLM stream and appends new keywords ----------
|
|
||||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||||
if event["type"] != "llm_chunk":
|
if event["type"] != "llm_chunk":
|
||||||
await emit(event)
|
await emit(event)
|
||||||
@@ -338,7 +192,6 @@ async def extract_keywords_stream_enriched(
|
|||||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||||
except Exception:
|
except Exception:
|
||||||
return
|
return
|
||||||
|
|
||||||
if not isinstance(partial, dict):
|
if not isinstance(partial, dict):
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -346,19 +199,18 @@ async def extract_keywords_stream_enriched(
|
|||||||
|
|
||||||
for level in LEVELS:
|
for level in LEVELS:
|
||||||
current = partial.get(level) or []
|
current = partial.get(level) or []
|
||||||
start_idx = len(confirmed[level]) # Where we start appending
|
start_idx = len(confirmed[level])
|
||||||
|
|
||||||
while len(confirmed[level]) < len(current):
|
while len(confirmed[level]) < len(current):
|
||||||
raw_item = current[len(confirmed[level])]
|
raw_item = current[len(confirmed[level])]
|
||||||
try:
|
try:
|
||||||
validated_item = KeywordEntry.model_validate(raw_item)
|
validated_item = KeywordEntry.model_validate(raw_item)
|
||||||
except ValidationError:
|
except ValidationError:
|
||||||
break # item not complete yet
|
break
|
||||||
|
|
||||||
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
|
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
|
||||||
grew = True
|
grew = True
|
||||||
|
|
||||||
# Launch openalex topic mapping
|
|
||||||
for idx in range(start_idx, len(confirmed[level])):
|
for idx in range(start_idx, len(confirmed[level])):
|
||||||
keyword_text = confirmed[level][idx].llm_keyword.keyword
|
keyword_text = confirmed[level][idx].llm_keyword.keyword
|
||||||
await emit(
|
await emit(
|
||||||
@@ -374,7 +226,6 @@ async def extract_keywords_stream_enriched(
|
|||||||
if grew:
|
if grew:
|
||||||
await emit_full_results()
|
await emit_full_results()
|
||||||
|
|
||||||
# ---------- Accumulate full_content for incremental parsing ----------
|
|
||||||
full_content_holder = {"value": ""}
|
full_content_holder = {"value": ""}
|
||||||
|
|
||||||
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
||||||
@@ -384,6 +235,7 @@ async def extract_keywords_stream_enriched(
|
|||||||
await on_chunk(event)
|
await on_chunk(event)
|
||||||
|
|
||||||
# ---------- Call the LLM ----------
|
# ---------- Call the LLM ----------
|
||||||
|
keywords = ""
|
||||||
try:
|
try:
|
||||||
keywords = await asyncio.wait_for(
|
keywords = await asyncio.wait_for(
|
||||||
llm.call_stream(
|
llm.call_stream(
|
||||||
@@ -401,14 +253,24 @@ async def extract_keywords_stream_enriched(
|
|||||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
||||||
raise RuntimeError("LLM streaming call timed out")
|
raise RuntimeError("LLM streaming call timed out")
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
# Cancel all pending enrichment tasks to avoid dangling background work
|
|
||||||
for task in enrichment_tasks:
|
|
||||||
task.cancel()
|
|
||||||
if enrichment_tasks:
|
|
||||||
await asyncio.gather(*enrichment_tasks, return_exceptions=True)
|
|
||||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if enrichment_tasks:
|
||||||
|
done, pending = await asyncio.wait(enrichment_tasks, timeout=10)
|
||||||
|
for task in pending:
|
||||||
|
task.cancel()
|
||||||
|
if pending:
|
||||||
|
await asyncio.gather(*pending, return_exceptions=True)
|
||||||
|
|
||||||
|
if not keywords:
|
||||||
|
# Empty string covers: real empty completion, APIConnectionError,
|
||||||
|
# and disconnect-during-emit (call_stream currently swallows all
|
||||||
|
# three the same way). Treat as a failed extraction.
|
||||||
|
await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
|
||||||
|
raise RuntimeError("LLM streaming call returned empty content")
|
||||||
|
|
||||||
# ---------- Finalize ----------
|
# ---------- Finalize ----------
|
||||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||||
|
|
||||||
@@ -418,13 +280,8 @@ async def extract_keywords_stream_enriched(
|
|||||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
||||||
raise RuntimeError("LLM response is not valid JSON")
|
raise RuntimeError("LLM response is not valid JSON")
|
||||||
|
|
||||||
# ---------- Wait for ALL pending enrichments to complete ----------
|
|
||||||
if enrichment_tasks:
|
|
||||||
await asyncio.gather(*enrichment_tasks, return_exceptions=True)
|
|
||||||
|
|
||||||
await emit_full_results()
|
await emit_full_results()
|
||||||
|
|
||||||
# Build final response
|
|
||||||
try:
|
try:
|
||||||
final_validated = _build_enriched_snapshot(confirmed)
|
final_validated = _build_enriched_snapshot(confirmed)
|
||||||
except ValidationError:
|
except ValidationError:
|
||||||
|
|||||||
@@ -35,13 +35,118 @@ class KeywordsPrompt(StrEnum):
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
|
||||||
|
|
||||||
|
The output must be strictly extractive and grounded in the input text.
|
||||||
|
|
||||||
|
## Mandatory Rules
|
||||||
|
|
||||||
|
1. Extract ONLY keywords, terms, entities, concepts, technologies, methods, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the input text.
|
||||||
|
|
||||||
|
2. Do NOT introduce, infer, generalize, expand, normalize, summarize, classify, enrich, or extrapolate concepts beyond what is directly present in the text.
|
||||||
|
|
||||||
|
3. Do NOT generate parent categories, broader domains, scientific disciplines, industries, or technology areas unless those exact terms appear in the input text.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Input contains:
|
||||||
|
|
||||||
|
"transformer-based machine learning framework"
|
||||||
|
|
||||||
|
Allowed:
|
||||||
|
|
||||||
|
* transformer-based machine learning framework
|
||||||
|
* machine learning
|
||||||
|
* transformer
|
||||||
|
|
||||||
|
Not allowed:
|
||||||
|
|
||||||
|
* Artificial Intelligence
|
||||||
|
* Deep Learning
|
||||||
|
* Neural Networks
|
||||||
|
|
||||||
|
unless those exact terms appear in the text.
|
||||||
|
|
||||||
|
4. Do NOT generate synonyms, abbreviations, alternate phrasings, normalized forms, or related concepts that do not explicitly appear in the source text.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
"large language models"
|
||||||
|
|
||||||
|
Allowed:
|
||||||
|
|
||||||
|
* large language models
|
||||||
|
|
||||||
|
Not allowed:
|
||||||
|
|
||||||
|
* LLMs
|
||||||
|
* Generative AI
|
||||||
|
* Artificial Intelligence
|
||||||
|
|
||||||
|
unless explicitly present.
|
||||||
|
|
||||||
|
5. Do NOT generate implied concepts.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
"patient records"
|
||||||
|
|
||||||
|
Not allowed:
|
||||||
|
|
||||||
|
* Healthcare
|
||||||
|
* Medical Informatics
|
||||||
|
* Clinical Documentation
|
||||||
|
|
||||||
|
unless explicitly mentioned.
|
||||||
|
|
||||||
|
6. Every keyword must have direct textual evidence in the input.
|
||||||
|
|
||||||
|
7. If a keyword cannot be highlighted verbatim or as a contiguous phrase in the source text, it must NOT appear in the output.
|
||||||
|
|
||||||
|
8. Prefer exact surface forms from the text.
|
||||||
|
|
||||||
|
9. Preserve original capitalization when possible.
|
||||||
|
|
||||||
|
10. Do not invent keywords to satisfy target counts.
|
||||||
|
|
||||||
|
11. When insufficient keywords exist for a level, return fewer keywords.
|
||||||
|
|
||||||
|
12. Grounding accuracy is more important than completeness.
|
||||||
|
|
||||||
|
13. Any keyword not directly supported by the text is considered an extraction error.
|
||||||
|
|
||||||
|
## Hierarchy Assignment Rules
|
||||||
|
|
||||||
|
The hierarchy is only an organizational grouping.
|
||||||
|
|
||||||
|
Do NOT create broader concepts to populate broad_keywords.
|
||||||
|
|
||||||
|
If the source text contains only specific concepts, place those concepts into the most appropriate level while remaining faithful to the text.
|
||||||
|
|
||||||
|
Do not create abstraction layers that are not explicitly present in the document.
|
||||||
|
|
||||||
|
## Self-Validation Before Output
|
||||||
|
|
||||||
|
Before returning the final JSON, verify every keyword:
|
||||||
|
|
||||||
|
* Can this exact phrase be found in the input text?
|
||||||
|
* Can a user highlight the phrase directly in the source text?
|
||||||
|
|
||||||
|
If the answer is NO, remove the keyword.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
# Keyword Hierarchy
|
# Keyword Hierarchy
|
||||||
|
|
||||||
## 1. broad_keywords
|
## 1. broad_keywords
|
||||||
|
|
||||||
High-level domains, disciplines, industries, or technology areas.
|
High-level domains, disciplines, industries, technology areas, or major themes explicitly present in the text.
|
||||||
|
|
||||||
Examples:
|
Examples (only if explicitly mentioned):
|
||||||
|
|
||||||
* Artificial Intelligence
|
* Artificial Intelligence
|
||||||
* Healthcare
|
* Healthcare
|
||||||
@@ -50,15 +155,15 @@ class KeywordsPrompt(StrEnum):
|
|||||||
* Materials Science
|
* Materials Science
|
||||||
* Robotics
|
* Robotics
|
||||||
|
|
||||||
These should represent the major themes of the document.
|
These should represent the major themes of the document when those themes are explicitly stated.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. coarse_grained
|
## 2. coarse_grained
|
||||||
|
|
||||||
Mid-level concepts, technologies, research areas, methods, or applications.
|
Mid-level concepts, technologies, research areas, methods, applications, or technical topics explicitly present in the text.
|
||||||
|
|
||||||
Examples:
|
Examples (only if explicitly mentioned):
|
||||||
|
|
||||||
* Machine Learning
|
* Machine Learning
|
||||||
* Drug Discovery
|
* Drug Discovery
|
||||||
@@ -73,9 +178,9 @@ class KeywordsPrompt(StrEnum):
|
|||||||
|
|
||||||
## 3. fine_grained
|
## 3. fine_grained
|
||||||
|
|
||||||
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology.
|
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology explicitly present in the text.
|
||||||
|
|
||||||
Examples:
|
Examples (only if explicitly mentioned):
|
||||||
|
|
||||||
* Transformer Architecture
|
* Transformer Architecture
|
||||||
* CRISPR-Cas9
|
* CRISPR-Cas9
|
||||||
@@ -114,21 +219,56 @@ class KeywordsPrompt(StrEnum):
|
|||||||
|
|
||||||
# Extraction Rules
|
# Extraction Rules
|
||||||
|
|
||||||
* Extract only concepts explicitly mentioned or strongly implied.
|
* Extract only concepts explicitly mentioned in the text.
|
||||||
|
* Do not use concepts that are merely implied, inferred, generalized, or derived.
|
||||||
|
* Every keyword must be directly traceable to text spans in the input.
|
||||||
* Prefer noun phrases.
|
* Prefer noun phrases.
|
||||||
* Avoid complete sentences.
|
* Avoid complete sentences.
|
||||||
* Avoid duplicates across levels whenever possible.
|
* Avoid duplicates across levels whenever possible.
|
||||||
* Do not invent technologies not supported by the text.
|
* Do not invent technologies not supported by the text.
|
||||||
* Prefer terminology that can be searched in scientific literature databases such as OpenAlex.
|
* Prefer terminology that can be searched in scientific literature databases such as OpenAlex.
|
||||||
* Return between 5 and 15 keywords per level when sufficient information exists.
|
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||||
|
* If fewer valid keywords exist, return fewer.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# Output Schema
|
# Output Schema
|
||||||
|
|
||||||
Return ONLY valid JSON.
|
Return ONLY valid JSON using the following structure:
|
||||||
|
|
||||||
|
{
|
||||||
|
"broad_keywords": [
|
||||||
|
{
|
||||||
|
"keyword": "string",
|
||||||
|
"relevance_score": 0.0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"coarse_grained": [
|
||||||
|
{
|
||||||
|
"keyword": "string",
|
||||||
|
"relevance_score": 0.0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fine_grained": [
|
||||||
|
{
|
||||||
|
"keyword": "string",
|
||||||
|
"relevance_score": 0.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
|
||||||
|
* Return ONLY valid JSON.
|
||||||
|
* Do not include explanations.
|
||||||
|
* Do not include markdown.
|
||||||
|
* Do not include comments.
|
||||||
|
* Do not include reasoning.
|
||||||
|
* Do not include any text outside the JSON object.
|
||||||
|
* Every keyword must be directly supported by the input text.
|
||||||
|
* Any keyword not explicitly present in the source text must be excluded.
|
||||||
|
|
||||||
|
Return ONLY valid JSON matching the schema provided by the API.
|
||||||
---
|
---
|
||||||
|
|
||||||
# Example 1
|
# Example 1
|
||||||
@@ -136,11 +276,9 @@ class KeywordsPrompt(StrEnum):
|
|||||||
Input:
|
Input:
|
||||||
|
|
||||||
Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories.
|
Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories.
|
||||||
|
|
||||||
Output:
|
Output:
|
||||||
|
|
||||||
{"broad_keywords":[{"keyword":"ArtificialIntelligence","relevance_score":0.98},{"keyword":"Manufacturing","relevance_score":0.94},{"keyword":"IndustrialAutomation","relevance_score":0.90}],"coarse_grained":[{"keyword":"MachineLearning","relevance_score":0.96},{"keyword":"PredictiveMaintenance","relevance_score":0.95},{"keyword":"SmartFactories","relevance_score":0.88},{"keyword":"SensorFusion","relevance_score":0.86},{"keyword":"AnomalyDetection","relevance_score":0.85},{"keyword":"Time-SeriesForecasting","relevance_score":0.83}],"fine_grained":[{"keyword":"TransformerArchitecture","relevance_score":0.95},{"keyword":"IndustrialSensors","relevance_score":0.84},{"keyword":"MultimodalDataFusion","relevance_score":0.82},{"keyword":"PredictiveAnalytics","relevance_score":0.80}]}
|
broad_keywords":[{"keyword":"Industrial manufacturing","relevance_score":0.94}],"coarse_grained":[{"keyword":"Machine learning","relevance_score":0.97},{"keyword":"Predictive maintenance","relevance_score":0.95},{"keyword":"Sensor fusion","relevance_score":0.89},{"keyword":"Anomaly detection","relevance_score":0.88},{"keyword":"Time-series forecasting","relevance_score":0.87},{"keyword":"Smart factories","relevance_score":0.85}],"fine_grained":[{"keyword":"Transformer-based machine learning framework","relevance_score":0.96}]}
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# Example 2
|
# Example 2
|
||||||
@@ -148,257 +286,267 @@ class KeywordsPrompt(StrEnum):
|
|||||||
Input:
|
Input:
|
||||||
|
|
||||||
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
||||||
|
|
||||||
Output:
|
Output:
|
||||||
|
|
||||||
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.97},{"keyword":"ArtificialIntelligence","relevance_score":0.95},{"keyword":"DigitalHealth","relevance_score":0.89}],"coarse_grained":[{"keyword":"LargeLanguageModels","relevance_score":0.96},{"keyword":"ClinicalDecisionSupport","relevance_score":0.92},{"keyword":"MedicalRecordAnalysis","relevance_score":0.90},{"keyword":"NaturalLanguageProcessing","relevance_score":0.88}],"fine_grained":[{"keyword":"Retrieval-AugmentedGeneration","relevance_score":0.95},{"keyword":"PatientRecordSummarization","relevance_score":0.91},{"keyword":"ClinicalDocumentation","relevance_score":0.86},{"keyword":"MedicalTextProcessing","relevance_score":0.84}]}
|
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.96}],"coarse_grained":[{"keyword":"Large language models","relevance_score":0.95},{"keyword":"Clinical decision-making","relevance_score":0.91},{"keyword":"Patient records","relevance_score":0.90}],"fine_grained":[{"keyword":"Retrieval-augmented generation","relevance_score":0.94}]}
|
||||||
Return ONLY valid JSON matching the schema provided by the API.
|
Return ONLY valid JSON matching the schema provided by the API.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
EXTRACT_WEBSITE_KEYWORDS_PROMPT = """
|
EXTRACT_WEBSITE_KEYWORDS_PROMPT = """
|
||||||
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
|
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
|
||||||
|
|
||||||
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
||||||
|
|
||||||
The extracted text may contain:
|
The extracted text may contain:
|
||||||
|
|
||||||
* Navigation menus
|
* Navigation menus
|
||||||
* Headers and footers
|
* Headers and footers
|
||||||
* Cookie notices
|
* Cookie notices
|
||||||
* Marketing language
|
* Marketing language
|
||||||
* Contact information
|
* Contact information
|
||||||
* Repeated sections
|
* Repeated sections
|
||||||
* Calls to action
|
* Calls to action
|
||||||
* Legal disclaimers
|
* Legal disclaimers
|
||||||
* Product pages
|
* Product pages
|
||||||
* Blog articles
|
* Blog articles
|
||||||
* News articles
|
* News articles
|
||||||
* Landing pages
|
* Landing pages
|
||||||
|
|
||||||
Your first task is to identify the actual content and purpose of the webpage.
|
Your first task is to identify the actual content and purpose of the webpage.
|
||||||
|
|
||||||
Ignore:
|
Ignore:
|
||||||
|
|
||||||
* Navigation elements
|
* Navigation elements
|
||||||
* Cookie banners
|
* Cookie banners
|
||||||
* Legal notices
|
* Legal notices
|
||||||
* Copyright text
|
* Copyright text
|
||||||
* Generic marketing statements
|
* Generic marketing statements
|
||||||
* Contact information
|
* Contact information
|
||||||
* Login/signup content
|
* Login/signup content
|
||||||
* Careers pages unless they contain relevant technical information
|
* Careers pages unless they contain relevant technical information
|
||||||
* Repeated website boilerplate
|
* Repeated website boilerplate
|
||||||
|
|
||||||
Focus only on content that helps identify:
|
Focus only on the primary informational content of the webpage.
|
||||||
|
|
||||||
* Technologies
|
---
|
||||||
* Scientific concepts
|
|
||||||
* Research areas
|
|
||||||
* Technical methods
|
|
||||||
* Products
|
|
||||||
* Applications
|
|
||||||
* Industrial sectors
|
|
||||||
* Materials
|
|
||||||
* Standards
|
|
||||||
* Diseases
|
|
||||||
* Engineering disciplines
|
|
||||||
* Innovation domains
|
|
||||||
|
|
||||||
---
|
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
|
||||||
|
|
||||||
# Step 1: Determine Page Type
|
The output must be strictly extractive and grounded in the webpage text.
|
||||||
|
|
||||||
Determine which type of page is represented:
|
## Mandatory Rules
|
||||||
|
|
||||||
* Technology/Product Page
|
1. Extract ONLY keywords, entities, concepts, technologies, methods, products, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the webpage text.
|
||||||
* Company Page
|
|
||||||
* Research Article
|
|
||||||
* Scientific Blog Post
|
|
||||||
* News Article
|
|
||||||
* Technical Documentation
|
|
||||||
* White Paper
|
|
||||||
* Industry Report
|
|
||||||
* Other
|
|
||||||
|
|
||||||
Use this classification internally only.
|
2. Do NOT introduce, infer, generalize, normalize, classify, enrich, expand, summarize, or extrapolate concepts beyond what is directly present in the text.
|
||||||
|
|
||||||
Do not include it in the output.
|
3. Do NOT generate broader domains, scientific disciplines, industries, technology areas, research fields, or categories unless those exact terms appear in the webpage text.
|
||||||
|
|
||||||
---
|
Example:
|
||||||
|
|
||||||
# Step 2: Extract Searchable Concepts
|
Input:
|
||||||
|
|
||||||
Prioritize concepts that are useful for:
|
"The platform uses large language models and retrieval-augmented generation."
|
||||||
|
|
||||||
* OpenAlex retrieval
|
Allowed:
|
||||||
* Scientific literature discovery
|
|
||||||
* Patent scouting
|
|
||||||
* Technology scouting
|
|
||||||
* Innovation monitoring
|
|
||||||
|
|
||||||
Prefer canonical scientific terminology over marketing language.
|
* large language models
|
||||||
|
* retrieval-augmented generation
|
||||||
|
|
||||||
Examples:
|
Not allowed:
|
||||||
|
|
||||||
Prefer:
|
* Artificial Intelligence
|
||||||
|
* Generative AI
|
||||||
|
* Natural Language Processing
|
||||||
|
|
||||||
* Large Language Models
|
unless explicitly present.
|
||||||
|
|
||||||
Instead of:
|
4. Do NOT generate synonyms.
|
||||||
|
|
||||||
* AI Assistant
|
Example:
|
||||||
|
|
||||||
Prefer:
|
Input:
|
||||||
|
|
||||||
* Smart Manufacturing
|
"AI assistant"
|
||||||
|
|
||||||
Instead of:
|
Allowed:
|
||||||
|
|
||||||
* Factory Optimization Solution
|
* AI assistant
|
||||||
|
|
||||||
Prefer:
|
Not allowed:
|
||||||
|
|
||||||
* Retrieval-Augmented Generation
|
* large language models
|
||||||
|
* conversational AI
|
||||||
|
* generative AI
|
||||||
|
|
||||||
Instead of:
|
unless those exact terms appear.
|
||||||
|
|
||||||
* Intelligent Knowledge Assistant
|
5. Do NOT generate canonical scientific terminology when it does not appear in the source text.
|
||||||
|
|
||||||
Prefer:
|
6. Do NOT rewrite marketing terms into technical terms.
|
||||||
|
|
||||||
* Predictive Maintenance
|
7. Every keyword must have direct textual evidence in the webpage content.
|
||||||
|
|
||||||
Instead of:
|
8. If a keyword cannot be highlighted directly in the source text, it must NOT appear in the output.
|
||||||
|
|
||||||
* Equipment Performance Optimization
|
9. Preserve original wording whenever possible.
|
||||||
|
|
||||||
---
|
10. Do not invent keywords to satisfy target counts.
|
||||||
|
|
||||||
# Keyword Hierarchy
|
11. When insufficient keywords exist, return fewer keywords.
|
||||||
|
|
||||||
## broad_keywords
|
12. Grounding accuracy is more important than completeness.
|
||||||
|
|
||||||
High-level domains, industries, disciplines, or technology areas.
|
13. Any keyword not directly supported by the webpage text is considered an extraction error.
|
||||||
|
|
||||||
Examples:
|
---
|
||||||
|
|
||||||
* Artificial Intelligence
|
# Step 1: Determine Page Type
|
||||||
* Healthcare
|
|
||||||
* Manufacturing
|
|
||||||
* Energy Storage
|
|
||||||
* Biotechnology
|
|
||||||
* Robotics
|
|
||||||
|
|
||||||
---
|
Determine internally whether the page is:
|
||||||
|
|
||||||
## coarse_grained
|
* Technology/Product Page
|
||||||
|
* Company Page
|
||||||
|
* Research Article
|
||||||
|
* Scientific Blog Post
|
||||||
|
* News Article
|
||||||
|
* Technical Documentation
|
||||||
|
* White Paper
|
||||||
|
* Industry Report
|
||||||
|
* Other
|
||||||
|
|
||||||
Technologies, methods, research fields, and applications.
|
Use this classification only to identify the relevant content and remove boilerplate.
|
||||||
|
|
||||||
Examples:
|
Do NOT include the classification in the output.
|
||||||
|
|
||||||
* Machine Learning
|
---
|
||||||
* Predictive Maintenance
|
|
||||||
* Drug Discovery
|
|
||||||
* Smart Manufacturing
|
|
||||||
* Computer Vision
|
|
||||||
* Clinical Decision Support
|
|
||||||
|
|
||||||
---
|
# Step 2: Extract Searchable Concepts
|
||||||
|
|
||||||
## fine_grained
|
Extract concepts directly present in the page that are useful for:
|
||||||
|
|
||||||
Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols.
|
* OpenAlex retrieval
|
||||||
|
* Scientific literature discovery
|
||||||
|
* Patent scouting
|
||||||
|
* Technology scouting
|
||||||
|
* Innovation monitoring
|
||||||
|
|
||||||
Examples:
|
The extracted concepts must remain faithful to the wording used in the webpage.
|
||||||
|
|
||||||
* Transformer Architecture
|
Do NOT replace webpage terminology with your own preferred terminology.
|
||||||
* CRISPR-Cas9
|
|
||||||
* OPC UA
|
|
||||||
* Retrieval-Augmented Generation
|
|
||||||
* YOLOv8
|
|
||||||
* Lithium Iron Phosphate
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# Relevance Score
|
# Keyword Hierarchy
|
||||||
|
|
||||||
Assign a relevance score between 0.0 and 1.0.
|
## broad_keywords
|
||||||
|
|
||||||
Guidelines:
|
High-level domains, industries, disciplines, technology areas, products, services, or major themes that explicitly appear in the webpage.
|
||||||
|
|
||||||
* 1.00 = central topic of the webpage
|
Only use this level when such broad concepts are explicitly present.
|
||||||
* 0.90 = major topic
|
|
||||||
* 0.80 = highly relevant
|
|
||||||
* 0.70 = supporting concept
|
|
||||||
* 0.60 = secondary concept
|
|
||||||
|
|
||||||
Avoid scores below 0.60 unless necessary.
|
Examples:
|
||||||
|
|
||||||
---
|
* Healthcare
|
||||||
|
* Biotechnology
|
||||||
|
* Manufacturing
|
||||||
|
* Robotics
|
||||||
|
* Financial Technology
|
||||||
|
|
||||||
# Additional Rules
|
only if those exact concepts appear in the webpage.
|
||||||
|
|
||||||
* Extract only concepts supported by the page content.
|
---
|
||||||
* Do not hallucinate technologies.
|
|
||||||
* Avoid generic company descriptions.
|
|
||||||
* Avoid generic business terminology.
|
|
||||||
* Prefer terminology suitable for scientific literature search.
|
|
||||||
* Prefer concepts that could appear in OpenAlex, patents, technical reports, or academic publications.
|
|
||||||
* Remove duplicates across hierarchy levels whenever possible.
|
|
||||||
* Rank keywords by importance.
|
|
||||||
|
|
||||||
---
|
## coarse_grained
|
||||||
# Example 3 — News Article
|
|
||||||
|
|
||||||
## Input
|
Technologies, methods, research fields, applications, products, services, or technical topics explicitly present in the webpage.
|
||||||
|
|
||||||
Apple announced a new generation of custom AI chips designed for on-device inference. The chips will power future iPhone and Mac devices, improving privacy, latency, and energy efficiency for generative AI applications.
|
Examples:
|
||||||
|
|
||||||
## Output
|
* Machine Learning
|
||||||
|
* Predictive Maintenance
|
||||||
|
* Drug Discovery
|
||||||
|
* Smart Manufacturing
|
||||||
|
* Clinical Decision Support
|
||||||
|
|
||||||
```json{"broad_keywords":[{"keyword":"Technology","relevance_score":0.98},{"keyword":"ArtificialIntelligence","relevance_score":0.97},{"keyword":"ConsumerElectronics","relevance_score":0.92}],"coarse_grained":[{"keyword":"AIHardware","relevance_score":0.96},{"keyword":"SemiconductorDesign","relevance_score":0.93},{"keyword":"EdgeComputing","relevance_score":0.90},{"keyword":"GenerativeAI","relevance_score":0.88}],"fine_grained":[{"keyword":"On-DeviceInference","relevance_score":0.95},{"keyword":"CustomAIChips","relevance_score":0.94},{"keyword":"InferenceAcceleration","relevance_score":0.89},{"keyword":"Low-LatencyProcessing","relevance_score":0.86}]}```
|
only if explicitly present.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# Example 4 — Product Page
|
## fine_grained
|
||||||
|
|
||||||
## Input
|
Highly specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, protocols, model names, framework names, software packages, or specialized terminology explicitly present in the webpage.
|
||||||
|
|
||||||
The Sony WH-1000XM6 wireless headphones feature adaptive noise cancellation, Bluetooth 5.4 connectivity, 40-hour battery life, multipoint device pairing, and spatial audio support.
|
Examples:
|
||||||
|
|
||||||
## Output
|
* FastAPI
|
||||||
|
* OpenAPI
|
||||||
|
* Pydantic
|
||||||
|
* CRISPR-Cas9
|
||||||
|
* Retrieval-Augmented Generation
|
||||||
|
* OPC UA
|
||||||
|
|
||||||
```json{"broad_keywords":[{"keyword":"ConsumerElectronics","relevance_score":0.98},{"keyword":"AudioTechnology","relevance_score":0.95}],"coarse_grained":[{"keyword":"WirelessHeadphones","relevance_score":0.97},{"keyword":"NoiseCancellation","relevance_score":0.95},{"keyword":"BluetoothAudio","relevance_score":0.92}],"fine_grained":[{"keyword":"AdaptiveNoiseCancellation","relevance_score":0.96},{"keyword":"Bluetooth5.4","relevance_score":0.94},{"keyword":"MultipointPairing","relevance_score":0.89},{"keyword":"SpatialAudio","relevance_score":0.87}]}```
|
only if explicitly present.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# Example 5 — Technical Documentation
|
# Relevance Score
|
||||||
|
|
||||||
## Input
|
Assign a relevance score between 0.0 and 1.0.
|
||||||
|
|
||||||
FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models.
|
Guidelines:
|
||||||
|
|
||||||
## Output
|
* 1.00 = central topic of the webpage
|
||||||
|
* 0.90 = major topic
|
||||||
|
* 0.80 = highly relevant
|
||||||
|
* 0.70 = supporting concept
|
||||||
|
* 0.60 = secondary concept
|
||||||
|
|
||||||
```json{"broad_keywords":[{"keyword":"SoftwareDevelopment","relevance_score":0.98},{"keyword":"WebDevelopment","relevance_score":0.95}],"coarse_grained":[{"keyword":"PythonFrameworks","relevance_score":0.97},{"keyword":"APIDevelopment","relevance_score":0.95},{"keyword":"BackendEngineering","relevance_score":0.91}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"DependencyInjection","relevance_score":0.90},{"keyword":"Pydantic","relevance_score":0.89},{"keyword":"AsynchronousRequestHandling","relevance_score":0.87}]}```
|
Avoid scores below 0.60 unless necessary.
|
||||||
|
|
||||||
---
|
Rank keywords by importance.
|
||||||
|
|
||||||
# Example 6 — Company Website
|
---
|
||||||
|
|
||||||
## Input
|
# Extraction Rules
|
||||||
|
|
||||||
Stripe provides online payment infrastructure for businesses. Its platform supports payment processing, subscription billing, fraud prevention, financial reporting, and global commerce operations.
|
* Extract only concepts explicitly mentioned in the webpage text.
|
||||||
|
* Do not use concepts that are merely implied, inferred, generalized, or derived.
|
||||||
|
* Every keyword must be directly traceable to text spans in the webpage.
|
||||||
|
* Prefer noun phrases.
|
||||||
|
* Avoid complete sentences.
|
||||||
|
* Avoid duplicates across hierarchy levels whenever possible.
|
||||||
|
* Preserve original wording.
|
||||||
|
* Rank keywords by importance.
|
||||||
|
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||||
|
* If fewer valid keywords exist, return fewer.
|
||||||
|
|
||||||
## Output
|
---
|
||||||
|
|
||||||
```json{"broad_keywords":[{"keyword":"FinancialTechnology","relevance_score":0.98},{"keyword":"BusinessServices","relevance_score":0.91}],"coarse_grained":[{"keyword":"PaymentProcessing","relevance_score":0.97},{"keyword":"DigitalPayments","relevance_score":0.95},{"keyword":"SubscriptionManagement","relevance_score":0.90}],"fine_grained":[{"keyword":"StripePlatform","relevance_score":0.99},{"keyword":"FraudPrevention","relevance_score":0.91},{"keyword":"RecurringBilling","relevance_score":0.89},{"keyword":"GlobalPaymentInfrastructure","relevance_score":0.87}]}```
|
# Self-Validation Before Output
|
||||||
|
|
||||||
---
|
For every keyword, verify:
|
||||||
|
|
||||||
|
* Can this exact phrase be found in the webpage text?
|
||||||
|
* Can a user highlight the phrase directly in the extracted content?
|
||||||
|
|
||||||
|
If the answer is NO, remove the keyword.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Example — Technical Documentation
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models.
|
||||||
|
|
||||||
|
Output:
|
||||||
|
|
||||||
|
{"broad_keywords":[{"keyword":"Python web framework","relevance_score":0.95}],"coarse_grained":[{"keyword":"building APIs","relevance_score":0.93},{"keyword":"Data validation","relevance_score":0.90}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"Dependency Injection","relevance_score":0.91},{"keyword":"Asynchronous Request Handling","relevance_score":0.89},{"keyword":"Pydantic","relevance_score":0.88}]}
|
||||||
|
|
||||||
|
Return ONLY valid JSON matching the schema provided by the API.
|
||||||
|
|
||||||
Return ONLY valid JSON matching the schema provided by the API.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
SIMPLE_TEXT_PROMPT = """
|
SIMPLE_TEXT_PROMPT = """
|
||||||
|
|||||||
@@ -8,10 +8,13 @@ import asyncio
|
|||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
|
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
|
||||||
|
from uvicorn.protocols.utils import ClientDisconnected
|
||||||
|
|
||||||
from . import logic
|
from . import logic
|
||||||
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(
|
||||||
prefix="/api/inse-service",
|
prefix="/api/inse-service",
|
||||||
@@ -19,26 +22,35 @@ router = APIRouter(
|
|||||||
responses={404: {"description": "Not found"}},
|
responses={404: {"description": "Not found"}},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@router.websocket("/keywords/extract/ws")
|
@router.websocket("/keywords/extract/ws")
|
||||||
async def extract_keywords_ws(websocket: WebSocket):
|
async def extract_keywords_ws(websocket: WebSocket):
|
||||||
print("WebSocket connection established for keyword extraction.")
|
|
||||||
await websocket.accept()
|
await websocket.accept()
|
||||||
|
|
||||||
|
disconnected = asyncio.Event()
|
||||||
|
extraction_task: asyncio.Task | None = None
|
||||||
|
|
||||||
|
async def emit(event: dict):
|
||||||
|
if disconnected.is_set():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await websocket.send_json(event)
|
||||||
|
except (WebSocketDisconnect, ClientDisconnected):
|
||||||
|
disconnected.set()
|
||||||
|
|
||||||
|
async def safe_send(payload: dict):
|
||||||
|
if disconnected.is_set():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await websocket.send_json(payload)
|
||||||
|
except (WebSocketDisconnect, ClientDisconnected):
|
||||||
|
disconnected.set()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
raw = await websocket.receive_json()
|
raw = await websocket.receive_json()
|
||||||
request = KeywordsRequest(**raw)
|
request = KeywordsRequest(**raw)
|
||||||
disconnected = asyncio.Event()
|
|
||||||
|
|
||||||
async def emit(event: dict):
|
|
||||||
if disconnected.is_set():
|
|
||||||
return
|
|
||||||
await websocket.send_json(event)
|
|
||||||
|
|
||||||
async def watch_disconnect() -> None:
|
|
||||||
while True:
|
|
||||||
message = await websocket.receive()
|
|
||||||
if message["type"] == "websocket.disconnect":
|
|
||||||
disconnected.set()
|
|
||||||
return
|
|
||||||
|
|
||||||
extraction_task = asyncio.create_task(
|
extraction_task = asyncio.create_task(
|
||||||
logic.extract_keywords_stream_enriched(
|
logic.extract_keywords_stream_enriched(
|
||||||
@@ -48,61 +60,38 @@ async def extract_keywords_ws(websocket: WebSocket):
|
|||||||
emit=emit,
|
emit=emit,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
disconnect_task = asyncio.create_task(watch_disconnect())
|
|
||||||
|
|
||||||
done, pending = await asyncio.wait(
|
result = await extraction_task
|
||||||
{extraction_task, disconnect_task},
|
|
||||||
return_when=asyncio.FIRST_COMPLETED,
|
|
||||||
)
|
|
||||||
|
|
||||||
if disconnect_task in done:
|
await safe_send({
|
||||||
disconnected.set()
|
"type": "completed",
|
||||||
|
"result": result.model_dump(),
|
||||||
|
})
|
||||||
|
|
||||||
|
except (WebSocketDisconnect, ClientDisconnected):
|
||||||
|
disconnected.set()
|
||||||
|
logger.info("Client disconnected from keyword extraction ws")
|
||||||
|
print("Client disconnected from keyword extraction ws")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
disconnected.set()
|
||||||
|
logger.exception("Error in keyword extraction ws")
|
||||||
|
await safe_send({
|
||||||
|
"type": "error",
|
||||||
|
"message": str(e),
|
||||||
|
})
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if extraction_task is not None and not extraction_task.done():
|
||||||
extraction_task.cancel()
|
extraction_task.cancel()
|
||||||
try:
|
try:
|
||||||
await extraction_task
|
await extraction_task
|
||||||
except asyncio.CancelledError:
|
except (asyncio.CancelledError, Exception):
|
||||||
pass
|
pass
|
||||||
return
|
|
||||||
|
|
||||||
disconnect_task.cancel()
|
|
||||||
try:
|
|
||||||
await disconnect_task
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
result = extraction_task.result()
|
|
||||||
|
|
||||||
await websocket.send_json({"type": "completed", "result": result.model_dump()})
|
|
||||||
|
|
||||||
except WebSocketDisconnect:
|
|
||||||
print("WebSocket disconnected.")
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
await websocket.send_json({"type": "error", "message": str(e)})
|
|
||||||
finally:
|
|
||||||
if websocket.application_state.name != "DISCONNECTED":
|
if websocket.application_state.name != "DISCONNECTED":
|
||||||
await websocket.close()
|
await websocket.close()
|
||||||
|
|
||||||
# @router.post(
|
|
||||||
# "/keywords/extract",
|
|
||||||
# operation_id="extractKeywords",
|
|
||||||
# response_model=ExtractedKeywordsResponse,
|
|
||||||
# )
|
|
||||||
# async def extract_keywords(
|
|
||||||
# request: Annotated[
|
|
||||||
# KeywordsRequest,
|
|
||||||
# Body(description="Input text for keyword extraction"),
|
|
||||||
# ],
|
|
||||||
# ):
|
|
||||||
# async def noop(_: dict):
|
|
||||||
# pass
|
|
||||||
|
|
||||||
# return await logic.extract_keywords_stream(
|
|
||||||
# query=request.query,
|
|
||||||
# mode=request.mode,
|
|
||||||
# limit=request.limit,
|
|
||||||
# emit=noop,
|
|
||||||
# )
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/keywords/extract",
|
"/keywords/extract",
|
||||||
operation_id="extractKeywords",
|
operation_id="extractKeywords",
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ from inse.exceptions import (
|
|||||||
)
|
)
|
||||||
from inse.funders.service import router as funders_service_router
|
from inse.funders.service import router as funders_service_router
|
||||||
from inse.projects.router import router as projects_router
|
from inse.projects.router import router as projects_router
|
||||||
from inse.university_ranking.router import router as university_ranking_router
|
from inse.university_ranking.service import router as university_ranking_router
|
||||||
|
|
||||||
# caching
|
# caching
|
||||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||||
@@ -53,6 +53,8 @@ from inse.patents.service import (
|
|||||||
router as patents_service_router,
|
router as patents_service_router,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from inse.works.purpose_router import router as works_purpose_router
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
### startup
|
### startup
|
||||||
@@ -83,6 +85,7 @@ app.include_router(institution_patents_router)
|
|||||||
app.include_router(org_patents_router)
|
app.include_router(org_patents_router)
|
||||||
app.include_router(institutions_router)
|
app.include_router(institutions_router)
|
||||||
app.include_router(topics_service_router)
|
app.include_router(topics_service_router)
|
||||||
|
app.include_router(works_purpose_router)
|
||||||
app.include_router(works_service_router)
|
app.include_router(works_service_router)
|
||||||
app.include_router(persons_service_router)
|
app.include_router(persons_service_router)
|
||||||
app.include_router(funders_service_router)
|
app.include_router(funders_service_router)
|
||||||
@@ -100,6 +103,7 @@ app.include_router(auth_router)
|
|||||||
app.include_router(account_management_router)
|
app.include_router(account_management_router)
|
||||||
app.include_router(organization_management_router)
|
app.include_router(organization_management_router)
|
||||||
|
|
||||||
|
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
ETagCacheMiddleware,
|
ETagCacheMiddleware,
|
||||||
ttl=300, # 5 minutes expiration time
|
ttl=300, # 5 minutes expiration time
|
||||||
@@ -116,6 +120,7 @@ app.add_middleware(
|
|||||||
|
|
||||||
# exception handlers
|
# exception handlers
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(NotFoundException)
|
@app.exception_handler(NotFoundException)
|
||||||
async def handle_not_found(request: Request, exc: NotFoundException):
|
async def handle_not_found(request: Request, exc: NotFoundException):
|
||||||
return JSONResponse(status_code=404, content={"message": str(exc)})
|
return JSONResponse(status_code=404, content={"message": str(exc)})
|
||||||
@@ -124,13 +129,18 @@ async def handle_not_found(request: Request, exc: NotFoundException):
|
|||||||
@app.exception_handler(ElasticsearchException)
|
@app.exception_handler(ElasticsearchException)
|
||||||
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
||||||
logger.error("Elasticsearch integration error: %s", str(exc))
|
logger.error("Elasticsearch integration error: %s", str(exc))
|
||||||
return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
|
return JSONResponse(
|
||||||
|
status_code=502, content={"message": "Search service temporarily unavailable"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(MissingApiKeyError)
|
@app.exception_handler(MissingApiKeyError)
|
||||||
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
||||||
logger.error("Configuration error: %s", str(exc))
|
logger.error("Configuration error: %s", str(exc))
|
||||||
return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
|
return JSONResponse(
|
||||||
|
status_code=503,
|
||||||
|
content={"message": str(exc) or "Search service is not configured"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(UpstreamAPIException)
|
@app.exception_handler(UpstreamAPIException)
|
||||||
|
|||||||
@@ -34,6 +34,10 @@ class ESIndex(StrEnum):
|
|||||||
OPENALEX_AUTHORS = "openalex-authors"
|
OPENALEX_AUTHORS = "openalex-authors"
|
||||||
OPENALEX_INSTITUTIONS = "openalex-institutions"
|
OPENALEX_INSTITUTIONS = "openalex-institutions"
|
||||||
OPENALEX_PUBLICATIONS = "openalex-publications"
|
OPENALEX_PUBLICATIONS = "openalex-publications"
|
||||||
|
OPENALEX_COUNTRIES = "openalex-countries"
|
||||||
|
OPENALEX_CONTINENTS = "openalex-continents"
|
||||||
|
OPENALEX_TOPICS = "openalex-topics"
|
||||||
|
OPENALEX_TOPIC_VECTORS = "topicvectors"
|
||||||
|
|
||||||
EPO_INDEX = "epo_index_1.0"
|
EPO_INDEX = "epo_index_1.0"
|
||||||
USPTO_INDEX = "uspto_patents_3.0"
|
USPTO_INDEX = "uspto_patents_3.0"
|
||||||
|
|||||||
Binary file not shown.
@@ -39,6 +39,7 @@ class Topic(BaseModel):
|
|||||||
keywords: Optional[List[StrictStr]] = Field(default=None, description="Keywords representing the content of papers in the topic.")
|
keywords: Optional[List[StrictStr]] = Field(default=None, description="Keywords representing the content of papers in the topic.")
|
||||||
subfield: Optional[TopicSubfield] = None
|
subfield: Optional[TopicSubfield] = None
|
||||||
var_field: Optional[TopicField] = Field(default=None, alias="field")
|
var_field: Optional[TopicField] = Field(default=None, alias="field")
|
||||||
|
field: Optional[TopicField] = Field(default=None)
|
||||||
domain: Optional[TopicDomain] = None
|
domain: Optional[TopicDomain] = None
|
||||||
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this topic.")
|
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this topic.")
|
||||||
cited_by_count: Optional[StrictInt] = None
|
cited_by_count: Optional[StrictInt] = None
|
||||||
|
|||||||
@@ -33,11 +33,12 @@ class WorkTopic(BaseModel):
|
|||||||
""" # noqa: E501
|
""" # noqa: E501
|
||||||
id: Optional[StrictStr] = None
|
id: Optional[StrictStr] = None
|
||||||
display_name: Optional[StrictStr] = None
|
display_name: Optional[StrictStr] = None
|
||||||
|
description: Optional[StrictStr] = None
|
||||||
score: Optional[Union[StrictFloat, StrictInt]] = None
|
score: Optional[Union[StrictFloat, StrictInt]] = None
|
||||||
subfield: Optional[WorkTopicSubfield] = None
|
subfield: Optional[WorkTopicSubfield] = None
|
||||||
var_field: Optional[WorkTopicField] = Field(default=None, alias="field")
|
var_field: Optional[WorkTopicField] = Field(default=None, alias="field")
|
||||||
domain: Optional[WorkTopicDomain] = None
|
domain: Optional[WorkTopicDomain] = None
|
||||||
__properties: ClassVar[List[str]] = ["id", "display_name", "score", "subfield", "field", "domain"]
|
__properties: ClassVar[List[str]] = ["id", "display_name", "description", "score", "subfield", "field", "domain"]
|
||||||
|
|
||||||
model_config = ConfigDict(
|
model_config = ConfigDict(
|
||||||
validate_by_name=True,
|
validate_by_name=True,
|
||||||
@@ -101,6 +102,7 @@ class WorkTopic(BaseModel):
|
|||||||
_obj = cls.model_validate({
|
_obj = cls.model_validate({
|
||||||
"id": obj.get("id"),
|
"id": obj.get("id"),
|
||||||
"display_name": obj.get("display_name"),
|
"display_name": obj.get("display_name"),
|
||||||
|
"description": obj.get("description"),
|
||||||
"score": obj.get("score"),
|
"score": obj.get("score"),
|
||||||
"subfield": WorkTopicSubfield.from_dict(obj["subfield"]) if obj.get("subfield") is not None else None,
|
"subfield": WorkTopicSubfield.from_dict(obj["subfield"]) if obj.get("subfield") is not None else None,
|
||||||
"field": WorkTopicField.from_dict(obj["field"]) if obj.get("field") is not None else None,
|
"field": WorkTopicField.from_dict(obj["field"]) if obj.get("field") is not None else None,
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ from inse.exceptions import ElasticsearchException
|
|||||||
|
|
||||||
from ..integrations import elasticsearch, llm
|
from ..integrations import elasticsearch, llm
|
||||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -20,14 +21,19 @@ TOPIC_LIMIT = 4
|
|||||||
TOPIC_QUERY_CONTENT_CHARS = 300
|
TOPIC_QUERY_CONTENT_CHARS = 300
|
||||||
TOPIC_NUM_CANDIDATES = 100
|
TOPIC_NUM_CANDIDATES = 100
|
||||||
TOPIC_SIMILARITY = 0.5
|
TOPIC_SIMILARITY = 0.5
|
||||||
|
TOPIC_MATCHES_PER_KEYWORD = 1
|
||||||
|
|
||||||
KEYWORD_LIMIT = 6
|
KEYWORD_LIMIT = 6
|
||||||
KEYWORD_CONTENT_CHARS = 4000
|
KEYWORD_CONTENT_CHARS = 4000
|
||||||
KEYWORD_SYSTEM_PROMPT = """\
|
KEYWORD_SYSTEM_PROMPT = """\
|
||||||
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
|
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||||
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
|
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.
|
||||||
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
|
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||||
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
|
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
|
RELATED_BLOCK_SIZE = 5
|
||||||
@@ -80,7 +86,14 @@ async def search_news(
|
|||||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||||
exact_query = {
|
exact_query = {
|
||||||
"bool": {
|
"bool": {
|
||||||
"must": [{"match": {"full_content": query_text}}],
|
"must": [
|
||||||
|
{
|
||||||
|
"multi_match": {
|
||||||
|
"query": query_text,
|
||||||
|
"fields": ["maintitle^2", "full_content"],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
"filter": clauses,
|
"filter": clauses,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -240,7 +253,6 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
|||||||
source = response.get("_source", {})
|
source = response.get("_source", {})
|
||||||
|
|
||||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
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(
|
keywords = await _get_article_keywords(
|
||||||
news_id,
|
news_id,
|
||||||
postproc_id,
|
postproc_id,
|
||||||
@@ -248,6 +260,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
|||||||
source.get("maintitle"),
|
source.get("maintitle"),
|
||||||
source.get("full_content"),
|
source.get("full_content"),
|
||||||
)
|
)
|
||||||
|
topics = await _match_topics_for_keywords(keywords)
|
||||||
|
|
||||||
return NewsArticleDetail(
|
return NewsArticleDetail(
|
||||||
id=response.get("_id"),
|
id=response.get("_id"),
|
||||||
@@ -258,22 +271,11 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
|||||||
full_content=source.get("full_content"),
|
full_content=source.get("full_content"),
|
||||||
relevant=relevant,
|
relevant=relevant,
|
||||||
authors=await _build_mentioned_persons(authors),
|
authors=await _build_mentioned_persons(authors),
|
||||||
topics=topics,
|
|
||||||
keywords=keywords,
|
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(
|
async def _get_article_keywords(
|
||||||
news_id: str,
|
news_id: str,
|
||||||
postproc_id: str | None,
|
postproc_id: str | None,
|
||||||
@@ -308,7 +310,12 @@ def _parse_keywords(raw: str) -> list:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
parsed = json.loads(raw)
|
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):
|
except (json.JSONDecodeError, TypeError):
|
||||||
candidates = re.split(r"[,\n]", raw)
|
candidates = re.split(r"[,\n]", raw)
|
||||||
|
|
||||||
@@ -343,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}.")
|
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:
|
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||||
try:
|
try:
|
||||||
from ..util import get_model
|
from ..util import get_model
|
||||||
|
|||||||
@@ -23,12 +23,21 @@ class MentionedPerson(BaseModel):
|
|||||||
person_id: Optional[str] = None
|
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):
|
class NewsArticleDetail(NewsArticle):
|
||||||
full_content: Optional[str] = None
|
full_content: Optional[str] = None
|
||||||
relevant: Optional[bool] = None
|
relevant: Optional[bool] = None
|
||||||
authors: List[MentionedPerson] = []
|
authors: List[MentionedPerson] = []
|
||||||
topics: List[str] = []
|
|
||||||
keywords: List[str] = []
|
keywords: List[str] = []
|
||||||
|
topics: List[MatchedTopic] = []
|
||||||
|
|
||||||
|
|
||||||
class NewsPage(BaseModel):
|
class NewsPage(BaseModel):
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ from inse.persons.model import (
|
|||||||
CustomAuthorsListResponse,
|
CustomAuthorsListResponse,
|
||||||
CareerMetrics,
|
CareerMetrics,
|
||||||
)
|
)
|
||||||
|
from inse.works.logic import enrich_topic_descriptions
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
INDEX_NAME = "openalex-authors"
|
INDEX_NAME = "openalex-authors"
|
||||||
@@ -728,6 +729,10 @@ async def advanced_search_persons(
|
|||||||
)
|
)
|
||||||
results.append(custom_author)
|
results.append(custom_author)
|
||||||
|
|
||||||
|
await enrich_topic_descriptions(
|
||||||
|
[topic for author in results for topic in author.topics or []]
|
||||||
|
)
|
||||||
|
|
||||||
return CustomAuthorsListResponse(
|
return CustomAuthorsListResponse(
|
||||||
results=results, meta=Meta(count=total_count, page=page, per_page=page_size)
|
results=results, meta=Meta(count=total_count, page=page, per_page=page_size)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -12,3 +12,4 @@ class Tags(StrEnum):
|
|||||||
AUTH = "Auth"
|
AUTH = "Auth"
|
||||||
ACCOUNT = "Account"
|
ACCOUNT = "Account"
|
||||||
ORGANIZATION = "Organization"
|
ORGANIZATION = "Organization"
|
||||||
|
UNIVERSITY_RANKINGS = "University Rankings"
|
||||||
|
|||||||
@@ -4,13 +4,12 @@
|
|||||||
Business logic for OpenAlex topics.
|
Business logic for OpenAlex topics.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import logging
|
import logging
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
import asyncio
|
||||||
import httpx
|
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from inse.exceptions import (
|
from inse.exceptions import (
|
||||||
UpstreamAPIException,
|
UpstreamAPIException,
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
@@ -23,8 +22,8 @@ from inse.models.openalex.autocomplete_response_results_inner import (
|
|||||||
AutocompleteResponseResultsInner,
|
AutocompleteResponseResultsInner,
|
||||||
)
|
)
|
||||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||||
from inse.model import ESCluster
|
from inse.model import ESCluster, ESIndex
|
||||||
from .search_client import OpenAlexTopicsClient
|
from .search_client import TopicsSearchClient
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -40,15 +39,15 @@ async def list_topics(
|
|||||||
cursor: str | None = None,
|
cursor: str | None = None,
|
||||||
sample: int | None = None,
|
sample: int | None = None,
|
||||||
select: str | None = None,
|
select: str | None = None,
|
||||||
client: OpenAlexTopicsClient | None = None,
|
client: TopicsSearchClient | None = None,
|
||||||
) -> TopicsListResponse:
|
) -> TopicsListResponse:
|
||||||
if sample is not None and (sort or page not in (None, 1)):
|
if sample is not None and (sort or page not in (None, 1)):
|
||||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||||
|
|
||||||
openalex_client = client or OpenAlexTopicsClient()
|
topics_client = client or TopicsSearchClient()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
data = await openalex_client.list_topics(
|
data = await topics_client.list_topics(
|
||||||
search=search,
|
search=search,
|
||||||
filter=filter,
|
filter=filter,
|
||||||
sort=sort,
|
sort=sort,
|
||||||
@@ -59,25 +58,24 @@ async def list_topics(
|
|||||||
sample=sample,
|
sample=sample,
|
||||||
select=select,
|
select=select,
|
||||||
)
|
)
|
||||||
except httpx.HTTPStatusError as exc:
|
except ValueError as exc:
|
||||||
status_code = exc.response.status_code
|
raise BadRequestException(str(exc)) from exc
|
||||||
detail = "OpenAlex topics request failed."
|
except ElasticsearchException as exc:
|
||||||
try:
|
logger.exception("OpenAlex topics Elasticsearch request failed.")
|
||||||
error_body = exc.response.json()
|
|
||||||
detail = error_body.get("message") or error_body.get("error") or detail
|
|
||||||
except ValueError:
|
|
||||||
if exc.response.text:
|
|
||||||
detail = exc.response.text
|
|
||||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
|
||||||
except httpx.HTTPError as exc:
|
|
||||||
logger.exception("OpenAlex topics request failed.")
|
|
||||||
raise UpstreamAPIException(
|
raise UpstreamAPIException(
|
||||||
message="OpenAlex topics request failed.",
|
message="OpenAlex topics Elasticsearch request failed.",
|
||||||
status_code=502,
|
status_code=502,
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
try:
|
try:
|
||||||
normalized_data = _normalize_topics_response(data)
|
openalex_style_data = _elasticsearch_to_topics_response(
|
||||||
|
data,
|
||||||
|
per_page=per_page,
|
||||||
|
page=page,
|
||||||
|
cursor=cursor,
|
||||||
|
group_by=group_by,
|
||||||
|
)
|
||||||
|
normalized_data = _normalize_topics_response(openalex_style_data)
|
||||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||||
except ValidationError as exc:
|
except ValidationError as exc:
|
||||||
logger.exception("OpenAlex topics response could not be parsed.")
|
logger.exception("OpenAlex topics response could not be parsed.")
|
||||||
@@ -94,7 +92,7 @@ async def autocomplete_topics(
|
|||||||
field_id: str | None = None,
|
field_id: str | None = None,
|
||||||
subfield_id: str | None = None,
|
subfield_id: str | None = None,
|
||||||
limit: int = 10,
|
limit: int = 10,
|
||||||
client: OpenAlexTopicsClient | None = None,
|
client: TopicsSearchClient | None = None,
|
||||||
) -> AutocompleteResponse:
|
) -> AutocompleteResponse:
|
||||||
filters = []
|
filters = []
|
||||||
if domain_id:
|
if domain_id:
|
||||||
@@ -153,6 +151,99 @@ async def autocomplete_topics(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _elasticsearch_to_topics_response(
|
||||||
|
data: dict[str, Any],
|
||||||
|
*,
|
||||||
|
per_page: int,
|
||||||
|
page: int | None,
|
||||||
|
cursor: str | None,
|
||||||
|
group_by: str | None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Converts an Elasticsearch search response into the OpenAlex-style topics
|
||||||
|
response expected by TopicsListResponse.
|
||||||
|
|
||||||
|
Elasticsearch response shape:
|
||||||
|
|
||||||
|
{
|
||||||
|
"took": 12,
|
||||||
|
"hits": {
|
||||||
|
"total": {"value": 123},
|
||||||
|
"hits": [
|
||||||
|
{"_source": {...}, "sort": [...]}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"aggregations": {...}
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenAlex-style response shape:
|
||||||
|
|
||||||
|
{
|
||||||
|
"meta": {...},
|
||||||
|
"results": [...],
|
||||||
|
"group_by": [...]
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
hits_root = data.get("hits") or {}
|
||||||
|
raw_hits = hits_root.get("hits") or []
|
||||||
|
|
||||||
|
total = hits_root.get("total")
|
||||||
|
if isinstance(total, dict):
|
||||||
|
count = total.get("value")
|
||||||
|
else:
|
||||||
|
count = total
|
||||||
|
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
for hit in raw_hits:
|
||||||
|
if not isinstance(hit, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
source = hit.get("_source")
|
||||||
|
if isinstance(source, dict):
|
||||||
|
results.append(source)
|
||||||
|
|
||||||
|
groups = _extract_group_by_results(data) if group_by else []
|
||||||
|
|
||||||
|
meta = {
|
||||||
|
"count": count,
|
||||||
|
"db_response_time_ms": data.get("took"),
|
||||||
|
"page": page if cursor is None else None,
|
||||||
|
"per_page": per_page,
|
||||||
|
"groups_count": len(groups) if group_by else None,
|
||||||
|
"next_cursor": (data.get("meta") or {}).get("next_cursor"),
|
||||||
|
"cost_usd": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"meta": meta,
|
||||||
|
"results": results,
|
||||||
|
"group_by": groups,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_group_by_results(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
aggregations = data.get("aggregations") or {}
|
||||||
|
group_by_agg = aggregations.get("group_by") or {}
|
||||||
|
buckets = group_by_agg.get("buckets") or []
|
||||||
|
|
||||||
|
groups: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for bucket in buckets:
|
||||||
|
if not isinstance(bucket, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
key = bucket.get("key")
|
||||||
|
groups.append(
|
||||||
|
{
|
||||||
|
"key": key,
|
||||||
|
"key_display_name": bucket.get("key_as_string") or key,
|
||||||
|
"count": bucket.get("doc_count"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return groups
|
||||||
|
|
||||||
|
|
||||||
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||||
normalized = deepcopy(data)
|
normalized = deepcopy(data)
|
||||||
|
|
||||||
@@ -264,7 +355,6 @@ def _datetime_str_or_none(value: Any) -> str | None:
|
|||||||
return f"{text}T00:00:00Z"
|
return f"{text}T00:00:00Z"
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
# Configuration for vector search similarity thresholds and boosts
|
# Configuration for vector search similarity thresholds and boosts
|
||||||
SIMILARITY_THRESHOLD = (
|
SIMILARITY_THRESHOLD = (
|
||||||
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
||||||
@@ -388,7 +478,7 @@ async def vector_search_topics(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
raw_results = await elasticsearch.search(
|
raw_results = await elasticsearch.search(
|
||||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
||||||
@@ -458,7 +548,7 @@ async def vector_search_topics_batch(
|
|||||||
)
|
)
|
||||||
tasks.append(
|
tasks.append(
|
||||||
elasticsearch.search(
|
elasticsearch.search(
|
||||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,33 +1,200 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
HTTP client for OpenAlex topics.
|
Elasticsearch search client for OpenAlex topics.
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
from inse.model import ESCluster, ESIndex
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
|
from inse.integrations.elasticsearch import search as elasticsearch_search
|
||||||
|
|
||||||
|
|
||||||
class OpenAlexTopicsClient:
|
class TopicsSearchClient:
|
||||||
|
"""
|
||||||
|
Search client for OpenAlex topics backed by Elasticsearch.
|
||||||
|
|
||||||
|
This replaces the old OpenAlex HTTP API client and uses the internal
|
||||||
|
Elasticsearch wrapper instead.
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEFAULT_SEARCH_FIELDS = [
|
||||||
|
"display_name^5",
|
||||||
|
"description^3",
|
||||||
|
"keywords",
|
||||||
|
"domain.display_name^2",
|
||||||
|
"field.display_name^2",
|
||||||
|
"subfield.display_name^2",
|
||||||
|
]
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
base_url: str | None = None,
|
*,
|
||||||
api_key: str | None = None,
|
index: ESIndex | str | None = None,
|
||||||
timeout: float | None = None,
|
cluster: ESCluster = ESCluster.NES,
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
):
|
||||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
self.index = index or self._default_index()
|
||||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
self.cluster = cluster
|
||||||
self.timeout = (
|
|
||||||
timeout
|
|
||||||
if timeout is not None
|
|
||||||
else config.settings.openalex_api_timeout_seconds
|
|
||||||
)
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
def list_topics_params(
|
@staticmethod
|
||||||
|
def _default_index() -> str:
|
||||||
|
"""
|
||||||
|
Resolve the OpenAlex topics index name.
|
||||||
|
|
||||||
|
Prefer a configured value if present, otherwise fall back to a sensible
|
||||||
|
default string index name.
|
||||||
|
"""
|
||||||
|
return (
|
||||||
|
ESIndex.OPENALEX_TOPICS.value
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _split_csv(value: str | None) -> list[str]:
|
||||||
|
if not value:
|
||||||
|
return []
|
||||||
|
return [part.strip() for part in value.split(",") if part.strip()]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _encode_cursor(sort_values: list[Any]) -> str:
|
||||||
|
raw = json.dumps(sort_values).encode("utf-8")
|
||||||
|
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _decode_cursor(cursor: str | None) -> list[Any] | None:
|
||||||
|
if not cursor or cursor == "*":
|
||||||
|
return None
|
||||||
|
|
||||||
|
padding = "=" * (-len(cursor) % 4)
|
||||||
|
raw = base64.urlsafe_b64decode(cursor + padding)
|
||||||
|
return json.loads(raw.decode("utf-8"))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_select(select: str | None) -> list[str] | None:
|
||||||
|
fields = TopicsSearchClient._split_csv(select)
|
||||||
|
return fields or None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_sort(sort: str | None) -> list[dict[str, Any]] | None:
|
||||||
|
"""
|
||||||
|
Parses OpenAlex-style sort syntax into Elasticsearch sort syntax.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
"works_count:desc"
|
||||||
|
"cited_by_count:desc,display_name:asc"
|
||||||
|
"-works_count"
|
||||||
|
"""
|
||||||
|
parts = TopicsSearchClient._split_csv(sort)
|
||||||
|
if not parts:
|
||||||
|
return None
|
||||||
|
|
||||||
|
parsed: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for part in parts:
|
||||||
|
direction = "asc"
|
||||||
|
field = part
|
||||||
|
|
||||||
|
if part.startswith("-"):
|
||||||
|
direction = "desc"
|
||||||
|
field = part[1:]
|
||||||
|
elif ":" in part:
|
||||||
|
field, direction = part.split(":", 1)
|
||||||
|
field = field.strip()
|
||||||
|
direction = direction.strip().lower()
|
||||||
|
|
||||||
|
if direction not in {"asc", "desc"}:
|
||||||
|
direction = "asc"
|
||||||
|
|
||||||
|
if field in {"score", "_score", "relevance_score"}:
|
||||||
|
parsed.append({"_score": {"order": direction}})
|
||||||
|
else:
|
||||||
|
parsed.append({field: {"order": direction, "missing": "_last"}})
|
||||||
|
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_filter_clause(expression: str) -> tuple[dict[str, Any] | None, bool]:
|
||||||
|
"""
|
||||||
|
Parses a single simple OpenAlex-style filter expression.
|
||||||
|
|
||||||
|
Supported examples:
|
||||||
|
"works_count:>100"
|
||||||
|
"works_count:>=100"
|
||||||
|
"display_name:Physics"
|
||||||
|
"ids.openalex:T123"
|
||||||
|
"field.id:F1|F2"
|
||||||
|
"is_active:true"
|
||||||
|
"is_active:!true"
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple[clause, is_negative]
|
||||||
|
"""
|
||||||
|
if ":" not in expression:
|
||||||
|
return None, False
|
||||||
|
|
||||||
|
field, value = expression.split(":", 1)
|
||||||
|
field = field.strip()
|
||||||
|
value = value.strip()
|
||||||
|
|
||||||
|
if not field or not value:
|
||||||
|
return None, False
|
||||||
|
|
||||||
|
is_negative = False
|
||||||
|
if value.startswith("!"):
|
||||||
|
is_negative = True
|
||||||
|
value = value[1:].strip()
|
||||||
|
|
||||||
|
range_ops = {
|
||||||
|
">=": "gte",
|
||||||
|
"<=": "lte",
|
||||||
|
">": "gt",
|
||||||
|
"<": "lt",
|
||||||
|
}
|
||||||
|
|
||||||
|
for prefix, op in range_ops.items():
|
||||||
|
if value.startswith(prefix):
|
||||||
|
range_value = value[len(prefix):].strip()
|
||||||
|
return {"range": {field: {op: range_value}}}, is_negative
|
||||||
|
|
||||||
|
if "|" in value:
|
||||||
|
values = [v.strip() for v in value.split("|") if v.strip()]
|
||||||
|
return {"terms": {field: values}}, is_negative
|
||||||
|
|
||||||
|
lowered = value.lower()
|
||||||
|
if lowered == "true":
|
||||||
|
typed_value: Any = True
|
||||||
|
elif lowered == "false":
|
||||||
|
typed_value = False
|
||||||
|
else:
|
||||||
|
typed_value = value
|
||||||
|
|
||||||
|
return {"term": {field: typed_value}}, is_negative
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _parse_filters(
|
||||||
|
cls,
|
||||||
|
filter: str | None,
|
||||||
|
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||||
|
filter_clauses: list[dict[str, Any]] = []
|
||||||
|
must_not_clauses: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for expression in cls._split_csv(filter):
|
||||||
|
clause, is_negative = cls._parse_filter_clause(expression)
|
||||||
|
if clause is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if is_negative:
|
||||||
|
must_not_clauses.append(clause)
|
||||||
|
else:
|
||||||
|
filter_clauses.append(clause)
|
||||||
|
|
||||||
|
return filter_clauses, must_not_clauses
|
||||||
|
|
||||||
|
def build_search_body(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
@@ -40,28 +207,118 @@ class OpenAlexTopicsClient:
|
|||||||
sample: int | None = None,
|
sample: int | None = None,
|
||||||
select: str | None = None,
|
select: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
params: dict[str, Any] = {"per_page": per_page}
|
"""
|
||||||
|
Build the Elasticsearch search body from the previous OpenAlex-style API
|
||||||
|
parameters.
|
||||||
|
"""
|
||||||
|
filter_clauses, must_not_clauses = self._parse_filters(filter)
|
||||||
|
|
||||||
|
must_clauses: list[dict[str, Any]] = []
|
||||||
|
|
||||||
if search:
|
if search:
|
||||||
params["search"] = search
|
must_clauses.append(
|
||||||
if filter:
|
{
|
||||||
params["filter"] = filter
|
"multi_match": {
|
||||||
if sort:
|
"query": search,
|
||||||
params["sort"] = sort
|
"fields": self.DEFAULT_SEARCH_FIELDS,
|
||||||
if group_by:
|
"type": "best_fields",
|
||||||
params["group_by"] = group_by
|
"operator": "and",
|
||||||
if cursor:
|
}
|
||||||
params["cursor"] = cursor
|
}
|
||||||
elif page is not None:
|
)
|
||||||
params["page"] = page
|
|
||||||
if sample is not None:
|
|
||||||
params["sample"] = sample
|
|
||||||
if select:
|
|
||||||
params["select"] = select
|
|
||||||
if self.api_key:
|
|
||||||
params["api_key"] = self.api_key
|
|
||||||
|
|
||||||
return params
|
if must_clauses or filter_clauses or must_not_clauses:
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"must": must_clauses or [{"match_all": {}}],
|
||||||
|
"filter": filter_clauses,
|
||||||
|
"must_not": must_not_clauses,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
query = {"match_all": {}}
|
||||||
|
|
||||||
|
if sample is not None:
|
||||||
|
query = {
|
||||||
|
"function_score": {
|
||||||
|
"query": query,
|
||||||
|
"random_score": {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size = sample if sample is not None else per_page
|
||||||
|
|
||||||
|
body: dict[str, Any] = {
|
||||||
|
"query": query,
|
||||||
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
source = self._parse_select(select)
|
||||||
|
if source is not None:
|
||||||
|
body["_source"] = source
|
||||||
|
|
||||||
|
sort_clause = self._parse_sort(sort)
|
||||||
|
if sort_clause is not None:
|
||||||
|
body["sort"] = sort_clause
|
||||||
|
|
||||||
|
search_after = self._decode_cursor(cursor)
|
||||||
|
if search_after is not None:
|
||||||
|
body["search_after"] = search_after
|
||||||
|
elif cursor is None and page is not None:
|
||||||
|
body["from"] = max(page - 1, 0) * per_page
|
||||||
|
|
||||||
|
if group_by:
|
||||||
|
body["size"] = 0
|
||||||
|
body["aggs"] = {
|
||||||
|
"group_by": {
|
||||||
|
"terms": {
|
||||||
|
"field": group_by,
|
||||||
|
"size": per_page,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return body
|
||||||
|
|
||||||
|
async def search_topics(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
search: str | None = None,
|
||||||
|
filter: str | None = None,
|
||||||
|
sort: str | None = None,
|
||||||
|
group_by: str | None = None,
|
||||||
|
per_page: int = 25,
|
||||||
|
page: int | None = 1,
|
||||||
|
cursor: str | None = None,
|
||||||
|
sample: int | None = None,
|
||||||
|
select: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
body = self.build_search_body(
|
||||||
|
search=search,
|
||||||
|
filter=filter,
|
||||||
|
sort=sort,
|
||||||
|
group_by=group_by,
|
||||||
|
per_page=per_page,
|
||||||
|
page=page,
|
||||||
|
cursor=cursor,
|
||||||
|
sample=sample,
|
||||||
|
select=select,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await elasticsearch_search(
|
||||||
|
index=self.index,
|
||||||
|
body=body,
|
||||||
|
cluster=self.cluster,
|
||||||
|
)
|
||||||
|
|
||||||
|
hits = result.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
last_sort = hits[-1].get("sort")
|
||||||
|
if last_sort is not None:
|
||||||
|
result.setdefault("meta", {})["next_cursor"] = self._encode_cursor(last_sort)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
async def list_topics(
|
async def list_topics(
|
||||||
self,
|
self,
|
||||||
@@ -76,24 +333,17 @@ class OpenAlexTopicsClient:
|
|||||||
sample: int | None = None,
|
sample: int | None = None,
|
||||||
select: str | None = None,
|
select: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
async with httpx.AsyncClient(
|
"""
|
||||||
base_url=self.base_url,
|
Backwards-compatible alias for the old OpenAlex client method name.
|
||||||
timeout=self.timeout,
|
"""
|
||||||
transport=self.transport,
|
return await self.search_topics(
|
||||||
) as client:
|
search=search,
|
||||||
response = await client.get(
|
filter=filter,
|
||||||
"/topics",
|
sort=sort,
|
||||||
params=self.list_topics_params(
|
group_by=group_by,
|
||||||
search=search,
|
per_page=per_page,
|
||||||
filter=filter,
|
page=page,
|
||||||
sort=sort,
|
cursor=cursor,
|
||||||
group_by=group_by,
|
sample=sample,
|
||||||
per_page=per_page,
|
select=select,
|
||||||
page=page,
|
)
|
||||||
cursor=cursor,
|
|
||||||
sample=sample,
|
|
||||||
select=select,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
response.raise_for_status()
|
|
||||||
return response.json()
|
|
||||||
@@ -1,9 +1,7 @@
|
|||||||
import httpx
|
|
||||||
import pytest
|
import pytest
|
||||||
from inse.exceptions import BadRequestException
|
|
||||||
|
|
||||||
|
from inse.exceptions import BadRequestException
|
||||||
from inse.topics import logic
|
from inse.topics import logic
|
||||||
from inse.topics.search_client import OpenAlexTopicsClient
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -11,108 +9,144 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeTopicsSearchClient:
|
||||||
|
def __init__(self, response: dict):
|
||||||
|
self.response = response
|
||||||
|
self.calls: list[dict] = []
|
||||||
|
|
||||||
|
async def list_topics(self, **kwargs):
|
||||||
|
self.calls.append(kwargs)
|
||||||
|
return self.response
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_maps_openalex_response_to_model():
|
async def test_list_topics_maps_elasticsearch_response_to_model():
|
||||||
def handler(_: httpx.Request) -> httpx.Response:
|
client = FakeTopicsSearchClient(
|
||||||
return httpx.Response(
|
{
|
||||||
200,
|
"took": 12,
|
||||||
json={
|
"hits": {
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
"total": {"value": 1, "relation": "eq"},
|
||||||
"results": [
|
"hits": [
|
||||||
{
|
{
|
||||||
"id": "https://openalex.org/T12419",
|
"_id": "https://openalex.org/T12419",
|
||||||
"display_name": "Machine learning",
|
"_source": {
|
||||||
"description": "Methods that learn from data.",
|
"id": "https://openalex.org/T12419",
|
||||||
"keywords": ["machine learning", "classification"],
|
"display_name": "Machine learning",
|
||||||
"subfield": {
|
"description": "Methods that learn from data.",
|
||||||
"id": "https://openalex.org/subfields/1702",
|
"keywords": ["machine learning", "classification"],
|
||||||
"display_name": "Artificial Intelligence",
|
"subfield": {
|
||||||
|
"id": "https://openalex.org/subfields/1702",
|
||||||
|
"display_name": "Artificial Intelligence",
|
||||||
|
},
|
||||||
|
"field": {
|
||||||
|
"id": "https://openalex.org/fields/17",
|
||||||
|
"display_name": "Computer Science",
|
||||||
|
},
|
||||||
|
"domain": {
|
||||||
|
"id": "https://openalex.org/domains/4",
|
||||||
|
"display_name": "Physical Sciences",
|
||||||
|
},
|
||||||
|
"works_count": 123,
|
||||||
|
"cited_by_count": 456,
|
||||||
|
"ids": {
|
||||||
|
"openalex": "https://openalex.org/T12419",
|
||||||
|
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||||
|
},
|
||||||
|
"works_api_url": (
|
||||||
|
"https://api.openalex.org/works?"
|
||||||
|
"filter=topics.id:T12419"
|
||||||
|
),
|
||||||
|
"created_date": "2023-12-25",
|
||||||
|
"updated_date": "2023-11-07T05:31:56Z",
|
||||||
},
|
},
|
||||||
"field": {
|
|
||||||
"id": "https://openalex.org/fields/17",
|
|
||||||
"display_name": "Computer Science",
|
|
||||||
},
|
|
||||||
"domain": {
|
|
||||||
"id": "https://openalex.org/domains/4",
|
|
||||||
"display_name": "Physical Sciences",
|
|
||||||
},
|
|
||||||
"works_count": 123,
|
|
||||||
"cited_by_count": 456,
|
|
||||||
"ids": {
|
|
||||||
"openalex": "https://openalex.org/T12419",
|
|
||||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
|
||||||
},
|
|
||||||
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
|
|
||||||
"created_date": "2023-12-25",
|
|
||||||
"updated_date": "2023-11-07T05:31:56Z",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"group_by": [
|
|
||||||
{
|
|
||||||
"key": "https://openalex.org/domains/4",
|
|
||||||
"key_display_name": "Physical Sciences",
|
|
||||||
"count": 1,
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
)
|
"aggregations": {
|
||||||
|
"group_by": {
|
||||||
client = OpenAlexTopicsClient(
|
"buckets": [
|
||||||
api_key="test-key",
|
{
|
||||||
transport=httpx.MockTransport(handler),
|
"key": "https://openalex.org/domains/4",
|
||||||
|
"key_as_string": "Physical Sciences",
|
||||||
|
"doc_count": 1,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.list_topics(search="machine learning", client=client)
|
result = await logic.list_topics(
|
||||||
|
search="machine learning",
|
||||||
|
group_by="domain.id",
|
||||||
|
client=client,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert client.calls[0]["search"] == "machine learning"
|
||||||
|
assert client.calls[0]["group_by"] == "domain.id"
|
||||||
|
|
||||||
assert result.meta.count == 1
|
assert result.meta.count == 1
|
||||||
|
assert result.meta.db_response_time_ms == 12
|
||||||
|
|
||||||
topic = result.results[0]
|
topic = result.results[0]
|
||||||
assert topic.display_name == "Machine learning"
|
assert topic.display_name == "Machine learning"
|
||||||
assert topic.var_field.display_name == "Computer Science"
|
assert topic.var_field.display_name == "Computer Science"
|
||||||
assert topic.subfield.display_name == "Artificial Intelligence"
|
assert topic.subfield.display_name == "Artificial Intelligence"
|
||||||
assert topic.domain.display_name == "Physical Sciences"
|
assert topic.domain.display_name == "Physical Sciences"
|
||||||
assert topic.ids.openalex == "https://openalex.org/T12419"
|
assert topic.ids.openalex == "https://openalex.org/T12419"
|
||||||
|
|
||||||
|
assert result.group_by[0].key == "https://openalex.org/domains/4"
|
||||||
assert result.group_by[0].key_display_name == "Physical Sciences"
|
assert result.group_by[0].key_display_name == "Physical Sciences"
|
||||||
|
assert result.group_by[0].count == 1
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_rejects_sample_with_sort():
|
async def test_list_topics_rejects_sample_with_sort():
|
||||||
with pytest.raises(BadRequestException) as exc_info:
|
with pytest.raises(BadRequestException):
|
||||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||||
def handler(_: httpx.Request) -> httpx.Response:
|
client = FakeTopicsSearchClient(
|
||||||
return httpx.Response(
|
{
|
||||||
200,
|
"took": "10",
|
||||||
json={
|
"hits": {
|
||||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
"total": {"value": "1", "relation": "eq"},
|
||||||
"results": [
|
"hits": [
|
||||||
{
|
{
|
||||||
"id": 123,
|
"_id": "123",
|
||||||
"display_name": 456,
|
"_source": {
|
||||||
"description": True,
|
"id": 123,
|
||||||
"keywords": ["topic", 123],
|
"display_name": 456,
|
||||||
"subfield": {"id": 1, "display_name": 2},
|
"description": True,
|
||||||
"field": {"id": 3, "display_name": 4},
|
"keywords": ["topic", 123],
|
||||||
"domain": {"id": 5, "display_name": 6},
|
"subfield": {"id": 1, "display_name": 2},
|
||||||
"works_count": "12.0",
|
"field": {"id": 3, "display_name": 4},
|
||||||
"cited_by_count": False,
|
"domain": {"id": 5, "display_name": 6},
|
||||||
"ids": {"openalex": 123, "wikipedia": 456},
|
"works_count": "12.0",
|
||||||
"created_date": "2023-12-25T10:11:12Z",
|
"cited_by_count": False,
|
||||||
"updated_date": "2023-12-25",
|
"ids": {"openalex": 123, "wikipedia": 456},
|
||||||
|
"created_date": "2023-12-25T10:11:12Z",
|
||||||
|
"updated_date": "2023-12-25",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"group_by": [{"key": True, "count": "1"}],
|
|
||||||
},
|
},
|
||||||
)
|
"aggregations": {
|
||||||
|
"group_by": {
|
||||||
client = OpenAlexTopicsClient(
|
"buckets": [
|
||||||
api_key="test-key",
|
{
|
||||||
transport=httpx.MockTransport(handler),
|
"key": True,
|
||||||
|
"doc_count": "1",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.list_topics(client=client)
|
result = await logic.list_topics(group_by="domain.id", client=client)
|
||||||
|
|
||||||
topic = result.results[0]
|
topic = result.results[0]
|
||||||
assert topic.id == "123"
|
assert topic.id == "123"
|
||||||
@@ -131,42 +165,33 @@ async def test_list_topics_accepts_practical_openalex_type_variants():
|
|||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_autocomplete_topics_returns_frontend_options():
|
async def test_autocomplete_topics_returns_frontend_options():
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
client = FakeTopicsSearchClient(
|
||||||
assert request.url.params["search"] == "machine learning"
|
{
|
||||||
assert request.url.params["filter"] == (
|
"took": 12,
|
||||||
"domain.id:https://openalex.org/domains/4,"
|
"hits": {
|
||||||
"field.id:https://openalex.org/fields/17,"
|
"total": {"value": 1, "relation": "eq"},
|
||||||
"subfield.id:https://openalex.org/subfields/1702"
|
"hits": [
|
||||||
)
|
|
||||||
assert request.url.params["sort"] == "works_count:desc"
|
|
||||||
assert request.url.params["per_page"] == "5"
|
|
||||||
assert request.url.params["select"] == (
|
|
||||||
"id,display_name,description,keywords,subfield,field,domain,"
|
|
||||||
"works_count,cited_by_count,ids"
|
|
||||||
)
|
|
||||||
return httpx.Response(
|
|
||||||
200,
|
|
||||||
json={
|
|
||||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
|
||||||
"results": [
|
|
||||||
{
|
{
|
||||||
"id": "https://openalex.org/T12419",
|
"_id": "https://openalex.org/T12419",
|
||||||
"display_name": "Machine learning",
|
"_source": {
|
||||||
"description": "Methods that learn from data.",
|
"id": "https://openalex.org/T12419",
|
||||||
"field": {"display_name": "Computer Science"},
|
"display_name": "Machine learning",
|
||||||
"subfield": {"display_name": "Artificial Intelligence"},
|
"description": "Methods that learn from data.",
|
||||||
"domain": {"display_name": "Physical Sciences"},
|
"field": {"display_name": "Computer Science"},
|
||||||
"works_count": 123,
|
"subfield": {
|
||||||
"cited_by_count": 456,
|
"display_name": "Artificial Intelligence",
|
||||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
},
|
||||||
|
"domain": {"display_name": "Physical Sciences"},
|
||||||
|
"works_count": 123,
|
||||||
|
"cited_by_count": 456,
|
||||||
|
"ids": {
|
||||||
|
"openalex": "https://openalex.org/T12419",
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
)
|
}
|
||||||
|
|
||||||
client = OpenAlexTopicsClient(
|
|
||||||
api_key="test-key",
|
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.autocomplete_topics(
|
result = await logic.autocomplete_topics(
|
||||||
@@ -178,9 +203,24 @@ async def test_autocomplete_topics_returns_frontend_options():
|
|||||||
client=client,
|
client=client,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
assert client.calls[0]["search"] == "machine learning"
|
||||||
|
assert client.calls[0]["filter"] == (
|
||||||
|
"domain.id:https://openalex.org/domains/4,"
|
||||||
|
"field.id:https://openalex.org/fields/17,"
|
||||||
|
"subfield.id:https://openalex.org/subfields/1702"
|
||||||
|
)
|
||||||
|
assert client.calls[0]["sort"] == "works_count:desc"
|
||||||
|
assert client.calls[0]["per_page"] == 5
|
||||||
|
assert client.calls[0]["page"] == 1
|
||||||
|
assert client.calls[0]["select"] == (
|
||||||
|
"id,display_name,description,keywords,subfield,field,domain,"
|
||||||
|
"works_count,cited_by_count,ids"
|
||||||
|
)
|
||||||
|
|
||||||
assert result.meta.count == 1
|
assert result.meta.count == 1
|
||||||
assert result.meta.db_response_time_ms == 12
|
assert result.meta.db_response_time_ms == 12
|
||||||
assert len(result.results) == 1
|
assert len(result.results) == 1
|
||||||
|
|
||||||
option = result.results[0]
|
option = result.results[0]
|
||||||
assert option.id == "https://openalex.org/T12419"
|
assert option.id == "https://openalex.org/T12419"
|
||||||
assert option.display_name == "Machine learning"
|
assert option.display_name == "Machine learning"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import httpx
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from inse.topics.search_client import OpenAlexTopicsClient
|
from inse.model import ESCluster, ESIndex
|
||||||
|
from inse.topics.search_client import TopicsSearchClient
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -9,10 +9,10 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
def test_list_topics_params_include_openalex_query_parameters():
|
def test_build_search_body_includes_openalex_query_parameters():
|
||||||
client = OpenAlexTopicsClient(api_key="test-key")
|
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||||
|
|
||||||
params = client.list_topics_params(
|
body = client.build_search_body(
|
||||||
search="machine learning",
|
search="machine learning",
|
||||||
filter="domain.id:4,works_count:>1000",
|
filter="domain.id:4,works_count:>1000",
|
||||||
sort="works_count:desc",
|
sort="works_count:desc",
|
||||||
@@ -22,54 +22,128 @@ def test_list_topics_params_include_openalex_query_parameters():
|
|||||||
select="id,display_name",
|
select="id,display_name",
|
||||||
)
|
)
|
||||||
|
|
||||||
assert params == {
|
assert body["query"] == {
|
||||||
"search": "machine learning",
|
"bool": {
|
||||||
"filter": "domain.id:4,works_count:>1000",
|
"must": [
|
||||||
"sort": "works_count:desc",
|
{
|
||||||
"group_by": "domain.id",
|
"multi_match": {
|
||||||
"per_page": 10,
|
"query": "machine learning",
|
||||||
"page": 2,
|
"fields": client.DEFAULT_SEARCH_FIELDS,
|
||||||
"select": "id,display_name",
|
"type": "best_fields",
|
||||||
"api_key": "test-key",
|
"operator": "and",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"filter": [
|
||||||
|
{"term": {"domain.id": "4"}},
|
||||||
|
{"range": {"works_count": {"gt": "1000"}}},
|
||||||
|
],
|
||||||
|
"must_not": [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert body["_source"] == ["id", "display_name"]
|
||||||
|
assert body["sort"] == [
|
||||||
|
{"works_count": {"order": "desc", "missing": "_last"}}
|
||||||
|
]
|
||||||
|
|
||||||
|
# group_by queries use aggregations and no regular hits
|
||||||
|
assert body["size"] == 0
|
||||||
|
assert body["from"] == 10
|
||||||
|
assert body["track_total_hits"] is True
|
||||||
|
assert body["aggs"] == {
|
||||||
|
"group_by": {
|
||||||
|
"terms": {
|
||||||
|
"field": "domain.id",
|
||||||
|
"size": 10,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def test_list_topics_params_prefers_cursor_over_page():
|
def test_build_search_body_prefers_cursor_over_page():
|
||||||
client = OpenAlexTopicsClient(api_key="test-key")
|
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||||
|
|
||||||
params = client.list_topics_params(cursor="*", page=3)
|
cursor = client._encode_cursor(["Machine learning", "https://openalex.org/T12419"])
|
||||||
|
|
||||||
assert params["cursor"] == "*"
|
body = client.build_search_body(
|
||||||
assert "page" not in params
|
cursor=cursor,
|
||||||
|
page=3,
|
||||||
|
per_page=25,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert body["search_after"] == [
|
||||||
|
"Machine learning",
|
||||||
|
"https://openalex.org/T12419",
|
||||||
|
]
|
||||||
|
assert "from" not in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_search_body_with_plain_cursor_star_does_not_use_page_offset():
|
||||||
|
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||||
|
|
||||||
|
body = client.build_search_body(
|
||||||
|
cursor="*",
|
||||||
|
page=3,
|
||||||
|
per_page=25,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "search_after" not in body
|
||||||
|
assert "from" not in body
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_calls_openalex_topics_endpoint():
|
async def test_list_topics_calls_elasticsearch_search_wrapper(monkeypatch):
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
captured = {}
|
||||||
assert request.method == "GET"
|
|
||||||
assert request.url.path == "/topics"
|
async def fake_elasticsearch_search(*, index, body, cluster):
|
||||||
assert request.url.params["search"] == "machine learning"
|
captured["index"] = index
|
||||||
assert request.url.params["api_key"] == "test-key"
|
captured["body"] = body
|
||||||
return httpx.Response(
|
captured["cluster"] = cluster
|
||||||
200,
|
|
||||||
json={
|
return {
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
"took": 3,
|
||||||
"results": [
|
"hits": {
|
||||||
|
"total": {"value": 1, "relation": "eq"},
|
||||||
|
"hits": [
|
||||||
{
|
{
|
||||||
"id": "https://openalex.org/T12419",
|
"_id": "https://openalex.org/T12419",
|
||||||
"display_name": "Machine learning",
|
"_source": {
|
||||||
|
"id": "https://openalex.org/T12419",
|
||||||
|
"display_name": "Machine learning",
|
||||||
|
},
|
||||||
|
"sort": [1000, "https://openalex.org/T12419"],
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
)
|
}
|
||||||
|
|
||||||
client = OpenAlexTopicsClient(
|
monkeypatch.setattr(
|
||||||
base_url="https://api.openalex.org",
|
"inse.topics.search_client.elasticsearch_search",
|
||||||
api_key="test-key",
|
fake_elasticsearch_search,
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||||
|
|
||||||
result = await client.list_topics(search="machine learning")
|
result = await client.list_topics(search="machine learning")
|
||||||
|
|
||||||
assert result["meta"]["count"] == 1
|
assert captured["index"] == ESIndex.OPENALEX_TOPICS
|
||||||
assert result["results"][0]["display_name"] == "Machine learning"
|
assert captured["cluster"] == ESCluster.NES
|
||||||
|
|
||||||
|
assert captured["body"]["query"]["bool"]["must"] == [
|
||||||
|
{
|
||||||
|
"multi_match": {
|
||||||
|
"query": "machine learning",
|
||||||
|
"fields": client.DEFAULT_SEARCH_FIELDS,
|
||||||
|
"type": "best_fields",
|
||||||
|
"operator": "and",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
assert captured["body"]["size"] == 25
|
||||||
|
assert captured["body"]["from"] == 0
|
||||||
|
assert captured["body"]["track_total_hits"] is True
|
||||||
|
|
||||||
|
assert result["hits"]["total"]["value"] == 1
|
||||||
|
assert result["hits"]["hits"][0]["_source"]["display_name"] == "Machine learning"
|
||||||
|
assert result["meta"]["next_cursor"] is not None
|
||||||
@@ -1,65 +1,228 @@
|
|||||||
import logging
|
import logging
|
||||||
|
import datetime
|
||||||
from typing import List, Dict, Any
|
from typing import List, Dict, Any
|
||||||
from .model import UniversityTopicData, YearlyData, UniversityRanking, ResearchTopic, DashboardMetric, RankingResponse
|
from .model import UniversityTopicData, YearlyData, UniversityRanking, DashboardMetric, RankingResponse
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.models.openalex.topic import Topic
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
START_YEAR = 2015
|
START_YEAR = 2000
|
||||||
END_YEAR = 2026
|
END_YEAR = datetime.datetime.now().year - 1
|
||||||
|
|
||||||
async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
|
async def resolve_topic(topic_query: str) -> Topic:
|
||||||
|
"""Resolves a topic display name or ID using Elasticsearch with source whitelisting."""
|
||||||
|
if topic_query.startswith("https://openalex.org/"):
|
||||||
|
query = {"term": {"id": topic_query}}
|
||||||
|
else:
|
||||||
|
query = {"match_phrase": {"display_name": topic_query}}
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index="openalex-topics",
|
||||||
|
query=query,
|
||||||
|
size=1,
|
||||||
|
source=["id", "display_name", "description", "works_count", "cited_by_count"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
hits = res.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
return Topic.from_dict(hits[0]["_source"])
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve topic in ES: %s", e)
|
||||||
|
|
||||||
|
return Topic(display_name=topic_query)
|
||||||
|
|
||||||
|
async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> RankingResponse:
|
||||||
"""
|
"""
|
||||||
Fetches real data from Elasticsearch and computes metrics for the dashboard.
|
Fetches real data from Elasticsearch and computes metrics for the dashboard.
|
||||||
"""
|
"""
|
||||||
|
topic_obj = await resolve_topic(topic_query)
|
||||||
|
topic_name = topic_obj.display_name or topic_query
|
||||||
|
|
||||||
|
if topic_obj.id:
|
||||||
|
topic_filter = {"term": {"topics.id.keyword": topic_obj.id}}
|
||||||
|
else:
|
||||||
|
topic_filter = {"match_phrase": {"topics.display_name": topic_name}}
|
||||||
|
|
||||||
query = {
|
query = {
|
||||||
"bool": {
|
"bool": {
|
||||||
"must": [
|
"filter": [
|
||||||
{
|
{"term": {"type": "education"}},
|
||||||
"match_phrase": {
|
{"term": {"geo.country_code": "DE"}},
|
||||||
"topics.display_name": topic
|
topic_filter
|
||||||
}
|
]
|
||||||
},
|
|
||||||
{
|
|
||||||
"term": {
|
|
||||||
"geo.country_code": "DE"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# Fetch top institutions for the topic by works_count
|
|
||||||
res = await elasticsearch.search(
|
res = await elasticsearch.search(
|
||||||
index="openalex-institutions",
|
index="openalex-institutions",
|
||||||
query=query,
|
query=query,
|
||||||
size=10,
|
size=50,
|
||||||
sort=[{"works_count": "desc"}],
|
source=["id", "display_name", "topics"],
|
||||||
cluster="nes"
|
cluster="nes"
|
||||||
)
|
)
|
||||||
|
|
||||||
hits = res.get("hits", {}).get("hits", [])
|
hits = res.get("hits", {}).get("hits", [])
|
||||||
timeseries: List[UniversityTopicData] = []
|
candidates = []
|
||||||
|
|
||||||
for hit in hits:
|
for hit in hits:
|
||||||
source = hit["_source"]
|
source = hit["_source"]
|
||||||
# Map the counts_by_year from ES to our model
|
inst_id = source.get("id")
|
||||||
# We ensure every year from START_YEAR to END_YEAR is present, defaulting to 0
|
display_name = source.get("display_name", "Unknown")
|
||||||
es_counts = {c["year"]: c for c in source.get("counts_by_year", [])}
|
|
||||||
|
|
||||||
|
# Extract topic-specific works count
|
||||||
|
exact_topic_count = 0
|
||||||
|
for t in source.get("topics", []):
|
||||||
|
if t.get("display_name", "").lower() == topic_name.lower():
|
||||||
|
exact_topic_count = t.get("count", 0)
|
||||||
|
break
|
||||||
|
|
||||||
|
candidates.append({
|
||||||
|
"id": inst_id,
|
||||||
|
"display_name": display_name,
|
||||||
|
"exact_topic_count": exact_topic_count
|
||||||
|
})
|
||||||
|
|
||||||
|
# Sort in Python by exact topic count descending and take the top 10
|
||||||
|
candidates.sort(key=lambda x: x["exact_topic_count"], reverse=True)
|
||||||
|
top_10 = candidates[:10]
|
||||||
|
|
||||||
|
# Initialize timeseries map: inst_id -> year -> (publications, citations)
|
||||||
|
years_range = list(range(START_YEAR, END_YEAR + 1))
|
||||||
|
accumulated_data = {
|
||||||
|
inst["id"]: {yr: (0, 0) for yr in years_range}
|
||||||
|
for inst in top_10
|
||||||
|
}
|
||||||
|
|
||||||
|
if top_10:
|
||||||
|
# Build filter map for the single-pass aggregation query
|
||||||
|
filters_map = {}
|
||||||
|
for inst in top_10:
|
||||||
|
inst_id = inst["id"]
|
||||||
|
filters_map[inst_id] = {
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"term": {
|
||||||
|
"authorships.institutions.id": inst_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Topic filter clause (using topic ID if resolved, otherwise matching display name keyword)
|
||||||
|
topic_id = topic_obj.id
|
||||||
|
if topic_id:
|
||||||
|
topic_clause = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"nested": {"path": "topics", "query": {"term": {"topics.id": topic_id}}}},
|
||||||
|
{"term": {"primary_topic.id": topic_id}}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
topic_clause = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": topic_name}}}},
|
||||||
|
{"match_phrase": {"primary_topic.display_name": topic_name}}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Construct single-pass ES query on openalex-works in Filter Context
|
||||||
|
works_query = {
|
||||||
|
"bool": {
|
||||||
|
"filter": [
|
||||||
|
{
|
||||||
|
"range": {
|
||||||
|
"publication_year": {
|
||||||
|
"gte": START_YEAR,
|
||||||
|
"lte": END_YEAR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
topic_clause,
|
||||||
|
{
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.id": [inst["id"] for inst in top_10]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
aggregations = {
|
||||||
|
"institutions_agg": {
|
||||||
|
"filters": {
|
||||||
|
"filters": filters_map
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"by_year": {
|
||||||
|
"terms": {
|
||||||
|
"field": "publication_year",
|
||||||
|
"size": len(years_range) * 2
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"citations_sum": {
|
||||||
|
"sum": {
|
||||||
|
"field": "cited_by_count"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
works_res = await elasticsearch.search(
|
||||||
|
index="openalex-works*",
|
||||||
|
query=works_query,
|
||||||
|
body={"aggs": aggregations},
|
||||||
|
size=0,
|
||||||
|
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
|
||||||
|
inst_buckets = works_res.get("aggregations", {}).get("institutions_agg", {}).get("buckets", {})
|
||||||
|
for inst_id, inst_bucket in inst_buckets.items():
|
||||||
|
year_buckets = inst_bucket.get("by_year", {}).get("buckets", [])
|
||||||
|
for yr_bucket in year_buckets:
|
||||||
|
yr = int(yr_bucket.get("key"))
|
||||||
|
pubs = int(yr_bucket.get("doc_count", 0))
|
||||||
|
cits = int(yr_bucket.get("citations_sum", {}).get("value", 0))
|
||||||
|
if yr in years_range:
|
||||||
|
accumulated_data[inst_id][yr] = (pubs, cits)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error executing ranking aggregations on openalex-works: %s", e)
|
||||||
|
|
||||||
|
# Map the accumulated results back into the timeseries response model
|
||||||
|
timeseries: List[UniversityTopicData] = []
|
||||||
|
inst_name_map = {inst["id"]: inst["display_name"] for inst in top_10}
|
||||||
|
|
||||||
|
for inst_id, year_dict in accumulated_data.items():
|
||||||
yearly_data = []
|
yearly_data = []
|
||||||
for year in range(START_YEAR, END_YEAR + 1):
|
for yr in years_range:
|
||||||
count_item = es_counts.get(year, {})
|
pubs, cits = year_dict[yr]
|
||||||
yearly_data.append(YearlyData(
|
yearly_data.append(YearlyData(
|
||||||
year=year,
|
year=yr,
|
||||||
publications=count_item.get("works_count", 0),
|
publications=pubs,
|
||||||
citations=count_item.get("cited_by_count", 0)
|
citations=cits
|
||||||
))
|
))
|
||||||
|
|
||||||
timeseries.append(UniversityTopicData(
|
timeseries.append(UniversityTopicData(
|
||||||
university=source.get("display_name", "Unknown"),
|
university=inst_name_map[inst_id],
|
||||||
topic=topic,
|
topic=topic_obj,
|
||||||
yearly_data=yearly_data
|
yearly_data=yearly_data
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import List, Literal
|
from typing import List, Literal, Dict, Optional
|
||||||
|
from inse.models.openalex.topic import Topic
|
||||||
|
|
||||||
ResearchTopic = Literal['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology']
|
|
||||||
DashboardMetric = Literal['publications', 'citations']
|
DashboardMetric = Literal['publications', 'citations']
|
||||||
|
|
||||||
class YearlyData(BaseModel):
|
class YearlyData(BaseModel):
|
||||||
@@ -11,7 +11,7 @@ class YearlyData(BaseModel):
|
|||||||
|
|
||||||
class UniversityTopicData(BaseModel):
|
class UniversityTopicData(BaseModel):
|
||||||
university: str
|
university: str
|
||||||
topic: ResearchTopic
|
topic: Topic
|
||||||
yearly_data: List[YearlyData]
|
yearly_data: List[YearlyData]
|
||||||
|
|
||||||
class UniversityRanking(BaseModel):
|
class UniversityRanking(BaseModel):
|
||||||
@@ -28,3 +28,36 @@ class RankingResponse(BaseModel):
|
|||||||
timeseries: List[UniversityTopicData]
|
timeseries: List[UniversityTopicData]
|
||||||
# Computed metrics for the ranking table
|
# Computed metrics for the ranking table
|
||||||
rankings: List[UniversityRanking]
|
rankings: List[UniversityRanking]
|
||||||
|
|
||||||
|
# Trend Analysis Models
|
||||||
|
class TopicYearlyData(BaseModel):
|
||||||
|
year: int
|
||||||
|
raw: int
|
||||||
|
normalized: float
|
||||||
|
cumulative: float
|
||||||
|
institutions_count: int
|
||||||
|
|
||||||
|
class TrendSeries(BaseModel):
|
||||||
|
entity_id: str
|
||||||
|
entity_name: str
|
||||||
|
entity_type: Literal['institution', 'country', 'region']
|
||||||
|
country_code: Optional[str] = None
|
||||||
|
# Map topic display name to its yearly data
|
||||||
|
topic_data: Dict[str, List[TopicYearlyData]]
|
||||||
|
|
||||||
|
class TrendResponse(BaseModel):
|
||||||
|
series: List[TrendSeries]
|
||||||
|
years: List[int]
|
||||||
|
location_mappings: Optional[Dict[str, List[str]]] = None
|
||||||
|
|
||||||
|
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||||
|
|
||||||
|
class TopInstitutionItem(DehydratedInstitution):
|
||||||
|
works_count: Optional[int] = None
|
||||||
|
exact_topic_count: Optional[int] = None
|
||||||
|
|
||||||
|
class AutocompleteLocationItem(BaseModel):
|
||||||
|
id: str
|
||||||
|
display_name: str
|
||||||
|
code: str
|
||||||
|
type: Literal['country', 'continent']
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
from fastapi import APIRouter, Query
|
|
||||||
from . import service
|
|
||||||
from .model import RankingResponse, ResearchTopic, DashboardMetric
|
|
||||||
from inse.tags import Tags
|
|
||||||
|
|
||||||
router = APIRouter(
|
|
||||||
prefix="/api/inse-service/university-rankings",
|
|
||||||
tags=[Tags.INSTITUTIONS]
|
|
||||||
)
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"",
|
|
||||||
response_model=RankingResponse,
|
|
||||||
summary="Returns data for the University Ranking Dashboard."
|
|
||||||
)
|
|
||||||
async def get_rankings(
|
|
||||||
topic: ResearchTopic = Query(
|
|
||||||
...,
|
|
||||||
description="Research topic (e.g., 'Artificial Intelligence')"
|
|
||||||
),
|
|
||||||
metric: DashboardMetric = Query("publications", description="Metric to rank by")
|
|
||||||
):
|
|
||||||
return await service.get_university_dashboard_data(topic, metric)
|
|
||||||
@@ -1,6 +1,80 @@
|
|||||||
from . import logic
|
import logging
|
||||||
from .model import RankingResponse, ResearchTopic, DashboardMetric
|
from typing import List, Optional
|
||||||
|
from fastapi import APIRouter, Query
|
||||||
|
|
||||||
async def get_university_dashboard_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
|
from inse.tags import Tags
|
||||||
"""Orchestrates data retrieval and computation for the dashboard."""
|
from . import logic, trend_logic
|
||||||
|
from .model import (
|
||||||
|
RankingResponse,
|
||||||
|
DashboardMetric,
|
||||||
|
TrendResponse,
|
||||||
|
TopInstitutionItem,
|
||||||
|
AutocompleteLocationItem
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(
|
||||||
|
prefix="/api/inse-service/university-rankings",
|
||||||
|
tags=[Tags.UNIVERSITY_RANKINGS]
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"",
|
||||||
|
response_model=RankingResponse,
|
||||||
|
summary="Returns data for the University Ranking Dashboard."
|
||||||
|
)
|
||||||
|
async def get_rankings(
|
||||||
|
topic: str = Query(
|
||||||
|
...,
|
||||||
|
description="Research topic display name or OpenAlex ID (e.g., 'Artificial Intelligence')"
|
||||||
|
),
|
||||||
|
metric: DashboardMetric = Query("publications", description="Metric to rank by")
|
||||||
|
):
|
||||||
return await logic.get_ranking_data(topic, metric)
|
return await logic.get_ranking_data(topic, metric)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/trend",
|
||||||
|
response_model=TrendResponse,
|
||||||
|
summary="Returns timeseries publication data for compared institutions, countries and regions."
|
||||||
|
)
|
||||||
|
async def get_trend(
|
||||||
|
topics: List[str] = Query(..., description="List of topics to analyze"),
|
||||||
|
institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"),
|
||||||
|
countries: Optional[List[str]] = Query(None, description="List of country codes"),
|
||||||
|
regions: Optional[List[str]] = Query(None, description="List of region identifiers")
|
||||||
|
):
|
||||||
|
return await trend_logic.get_trend_data(
|
||||||
|
topics=topics,
|
||||||
|
institutions=institutions,
|
||||||
|
countries=countries,
|
||||||
|
regions=regions
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/top-institutions",
|
||||||
|
response_model=List[TopInstitutionItem],
|
||||||
|
summary="Returns top institutions filtered by country/region and sorted by topic-level publications count."
|
||||||
|
)
|
||||||
|
async def get_top_institutions(
|
||||||
|
topic: str = Query(..., description="Research topic"),
|
||||||
|
region: Optional[str] = Query(None, description="Region identifier (e.g. EU)"),
|
||||||
|
country: Optional[str] = Query(None, description="Country code (e.g. DE)"),
|
||||||
|
limit: int = Query(10, description="Max suggestions to return")
|
||||||
|
):
|
||||||
|
return await trend_logic.get_top_institutions_by_region(
|
||||||
|
topic=topic,
|
||||||
|
region=region,
|
||||||
|
country=country,
|
||||||
|
limit=limit
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/autocomplete-locations",
|
||||||
|
response_model=List[AutocompleteLocationItem],
|
||||||
|
summary="Returns country and continent options for autocomplete inputs."
|
||||||
|
)
|
||||||
|
async def get_autocomplete_locations(
|
||||||
|
query: str = Query(..., description="Query text to search for countries/continents")
|
||||||
|
):
|
||||||
|
return await trend_logic.autocomplete_locations(query)
|
||||||
@@ -0,0 +1,656 @@
|
|||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
import datetime
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
import numpy as np
|
||||||
|
from sklearn.preprocessing import MinMaxScaler
|
||||||
|
|
||||||
|
from sqlmodel import Session
|
||||||
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.model import ESIndex
|
||||||
|
from inse.auth.model import AccessToken, Organization
|
||||||
|
from .model import (
|
||||||
|
TrendResponse,
|
||||||
|
TrendSeries,
|
||||||
|
TopicYearlyData,
|
||||||
|
TopInstitutionItem,
|
||||||
|
AutocompleteLocationItem
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Default fallback institution: University of Duisburg-Essen
|
||||||
|
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
|
||||||
|
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
|
||||||
|
|
||||||
|
async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]:
|
||||||
|
stripped = query.strip()
|
||||||
|
if not stripped:
|
||||||
|
return []
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
# Query countries index (Idea: Instead of wildcard: use alternative names?)
|
||||||
|
country_query = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{
|
||||||
|
"wildcard": {
|
||||||
|
"display_name.keyword": {
|
||||||
|
"value": f"*{stripped}*",
|
||||||
|
"case_insensitive": True
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": {
|
||||||
|
"country_code": {
|
||||||
|
"query": stripped.upper(),
|
||||||
|
"boost": 5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Query continents index
|
||||||
|
continent_query = {
|
||||||
|
"wildcard": {
|
||||||
|
"display_name.keyword": {
|
||||||
|
"value": f"*{stripped}*",
|
||||||
|
"case_insensitive": True
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
countries_res, continents_res = await asyncio.gather(
|
||||||
|
elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_COUNTRIES),
|
||||||
|
query=country_query,
|
||||||
|
size=10,
|
||||||
|
source=["id", "display_name", "country_code", "wikidata_id"],
|
||||||
|
cluster="nes"
|
||||||
|
),
|
||||||
|
elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||||
|
query=continent_query,
|
||||||
|
size=5,
|
||||||
|
source=["id", "display_name", "wikidata_id"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to autocomplete locations in ES: %s", e)
|
||||||
|
return []
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
# Process continents
|
||||||
|
for hit in continents_res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
code_val = source.get("wikidata_id") or source["id"].split("/")[-1]
|
||||||
|
results.append(AutocompleteLocationItem(
|
||||||
|
id=code_val,
|
||||||
|
display_name=source["display_name"],
|
||||||
|
code=code_val,
|
||||||
|
type="continent"
|
||||||
|
))
|
||||||
|
|
||||||
|
# Process countries
|
||||||
|
for hit in countries_res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
results.append(AutocompleteLocationItem(
|
||||||
|
id=source["country_code"],
|
||||||
|
display_name=source["display_name"],
|
||||||
|
code=source["country_code"],
|
||||||
|
type="country"
|
||||||
|
))
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def get_top_institutions_by_region(
|
||||||
|
topic: str,
|
||||||
|
region: Optional[str] = None,
|
||||||
|
country: Optional[str] = None,
|
||||||
|
limit: int = 10
|
||||||
|
) -> List[TopInstitutionItem]:
|
||||||
|
"""
|
||||||
|
Search top educational institutions by region or country based on publication counts
|
||||||
|
for the specific topic, using a two-step Python-based sorting approach.
|
||||||
|
"""
|
||||||
|
country_codes = []
|
||||||
|
if country:
|
||||||
|
country_codes = [country.upper()]
|
||||||
|
elif region:
|
||||||
|
try:
|
||||||
|
# Query openalex-continents index to resolve continent country codes dynamically
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||||
|
query={
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"term": {"wikidata_id.keyword": region}},
|
||||||
|
{"term": {"id": f"https://openalex.org/continents/{region}"}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
size=1,
|
||||||
|
source=["countries"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
hits = res.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
source = hits[0]["_source"]
|
||||||
|
country_codes = [
|
||||||
|
c["id"].split("/")[-1].upper() for c in source.get("countries", [])
|
||||||
|
]
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve continent countries in get_top_institutions_by_region: %s", e)
|
||||||
|
|
||||||
|
# Resolve the topic to get the exact ID/display name
|
||||||
|
topic_filter = {"match_phrase": {"topics.display_name": topic}}
|
||||||
|
try:
|
||||||
|
topic_res = await elasticsearch.search(
|
||||||
|
index="openalex-topics",
|
||||||
|
query={"match_phrase": {"display_name": topic}},
|
||||||
|
size=1,
|
||||||
|
source=["id", "display_name"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
hits = topic_res.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
source = hits[0]["_source"]
|
||||||
|
topic_id = source["id"]
|
||||||
|
topic_filter = {"term": {"topics.id.keyword": topic_id}}
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve topic in get_top_institutions_by_region: %s", e)
|
||||||
|
|
||||||
|
# Query openalex-institutions for educational entities matching country and topic
|
||||||
|
must_clauses: List[Dict[str, Any]] = [
|
||||||
|
{"term": {"type": "education"}},
|
||||||
|
topic_filter
|
||||||
|
]
|
||||||
|
|
||||||
|
if country_codes:
|
||||||
|
must_clauses.append({"terms": {"geo.country_code": country_codes}})
|
||||||
|
|
||||||
|
query = {"bool": {"filter": must_clauses}}
|
||||||
|
|
||||||
|
# Fetch top 50 by overall works count to cover a good pool of institutions
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_INSTITUTIONS),
|
||||||
|
query=query,
|
||||||
|
size=50,
|
||||||
|
source=["id", "display_name", "country_code", "works_count", "topics"],
|
||||||
|
sort=[{"works_count": "desc"}],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
|
||||||
|
hits = res.get("hits", {}).get("hits", [])
|
||||||
|
candidates = []
|
||||||
|
|
||||||
|
for hit in hits:
|
||||||
|
source = hit["_source"]
|
||||||
|
inst_id = source.get("id")
|
||||||
|
display_name = source.get("display_name", "Unknown")
|
||||||
|
country_code = source.get("country_code")
|
||||||
|
works_count = source.get("works_count")
|
||||||
|
|
||||||
|
# Extract exact count for the selected topic
|
||||||
|
exact_topic_count = 0
|
||||||
|
for t in source.get("topics", []):
|
||||||
|
if t.get("display_name", "").lower() == topic.lower():
|
||||||
|
exact_topic_count = t.get("count", 0)
|
||||||
|
break
|
||||||
|
|
||||||
|
candidates.append(TopInstitutionItem(
|
||||||
|
id=inst_id,
|
||||||
|
display_name=display_name,
|
||||||
|
country_code=country_code,
|
||||||
|
works_count=works_count,
|
||||||
|
exact_topic_count=exact_topic_count
|
||||||
|
))
|
||||||
|
|
||||||
|
# Sort candidates by exact_topic_count descending
|
||||||
|
candidates.sort(key=lambda x: x.exact_topic_count or 0, reverse=True)
|
||||||
|
|
||||||
|
return candidates[:limit]
|
||||||
|
|
||||||
|
async def get_trend_data(
|
||||||
|
topics: List[str],
|
||||||
|
institutions: Optional[List[str]] = None,
|
||||||
|
countries: Optional[List[str]] = None,
|
||||||
|
regions: Optional[List[str]] = None
|
||||||
|
) -> TrendResponse:
|
||||||
|
"""
|
||||||
|
Traverses the openalex-works index to retrieve yearly contributions of selected/top
|
||||||
|
institutions, countries, and regions across multiple topics.
|
||||||
|
"""
|
||||||
|
if not topics:
|
||||||
|
return TrendResponse(series=[], years=[])
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
start_year = 2000
|
||||||
|
end_year = datetime.datetime.now().year - 1
|
||||||
|
years_range = list(range(start_year, end_year + 1))
|
||||||
|
|
||||||
|
# Resolve primary institution (default University of Duisburg-Essen for everyone)
|
||||||
|
primary_inst_id = DEFAULT_INSTITUTION_ID
|
||||||
|
primary_inst_name = DEFAULT_INSTITUTION_NAME
|
||||||
|
|
||||||
|
# Initialize institutions list and ensure primary is included
|
||||||
|
query_institutions = []
|
||||||
|
if institutions:
|
||||||
|
query_institutions = [i.strip() for i in institutions]
|
||||||
|
if primary_inst_id not in query_institutions:
|
||||||
|
query_institutions.insert(0, primary_inst_id)
|
||||||
|
|
||||||
|
# Prepare lists of countries and regions dynamically
|
||||||
|
query_countries = countries or []
|
||||||
|
query_regions = regions or []
|
||||||
|
|
||||||
|
clean_countries = [c.strip().upper() for c in query_countries]
|
||||||
|
clean_regions = [r.strip() for r in query_regions]
|
||||||
|
ids_to_resolve = list(set(query_institutions))
|
||||||
|
|
||||||
|
# Define concurrent metadata lookups
|
||||||
|
async def fetch_institutions():
|
||||||
|
names = {primary_inst_id: primary_inst_name}
|
||||||
|
codes = {}
|
||||||
|
if not ids_to_resolve:
|
||||||
|
return names, codes
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_INSTITUTIONS),
|
||||||
|
query={"terms": {"id": ids_to_resolve}},
|
||||||
|
size=len(ids_to_resolve),
|
||||||
|
source=["id", "display_name", "country_code"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
for hit in res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
names[source["id"]] = source.get("display_name", source["id"])
|
||||||
|
codes[source["id"]] = source.get("country_code", "")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve institution details from ES: %s", e)
|
||||||
|
return names, codes
|
||||||
|
|
||||||
|
async def fetch_countries():
|
||||||
|
names = {}
|
||||||
|
if not clean_countries:
|
||||||
|
return names
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_COUNTRIES),
|
||||||
|
query={"terms": {"country_code": clean_countries}},
|
||||||
|
size=len(clean_countries),
|
||||||
|
source=["country_code", "display_name"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
for hit in res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
names[source["country_code"]] = source["display_name"]
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve country names from ES: %s", e)
|
||||||
|
return names
|
||||||
|
|
||||||
|
async def fetch_continents():
|
||||||
|
names = {}
|
||||||
|
ccodes = {}
|
||||||
|
if not clean_regions:
|
||||||
|
return names, ccodes
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||||
|
query={
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"terms": {"wikidata_id.keyword": clean_regions}},
|
||||||
|
{"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
size=len(clean_regions),
|
||||||
|
source=["id", "display_name", "wikidata_id", "countries"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
for hit in res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
c_code = source.get("wikidata_id") or source["id"].split("/")[-1]
|
||||||
|
names[c_code] = source["display_name"]
|
||||||
|
ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])]
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve continent names from ES: %s", e)
|
||||||
|
return names, ccodes
|
||||||
|
|
||||||
|
async def fetch_topics():
|
||||||
|
t_ids = {}
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index="openalex-topics",
|
||||||
|
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}},
|
||||||
|
size=len(topics) * 2,
|
||||||
|
source=["id", "display_name"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
for hit in res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
for t in topics:
|
||||||
|
if t.lower() in source["display_name"].lower():
|
||||||
|
t_ids[t] = source["id"]
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve topic IDs from ES: %s", e)
|
||||||
|
return t_ids
|
||||||
|
|
||||||
|
# Execute all 4 queries concurrently
|
||||||
|
(
|
||||||
|
(resolved_names, resolved_country_codes),
|
||||||
|
resolved_country_names,
|
||||||
|
(resolved_continent_names, continent_country_codes),
|
||||||
|
resolved_topic_ids
|
||||||
|
) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents(), fetch_topics())
|
||||||
|
|
||||||
|
location_mappings = continent_country_codes.copy()
|
||||||
|
|
||||||
|
# Map of filters inside our Elasticsearch aggregation
|
||||||
|
filters_map: Dict[str, Dict[str, Any]] = {}
|
||||||
|
|
||||||
|
# 1. Institution Filters
|
||||||
|
for inst_id in query_institutions:
|
||||||
|
filters_map[f"inst_{inst_id}"] = {
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"term": {
|
||||||
|
"authorships.institutions.id": inst_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2. Country Filters
|
||||||
|
for cc in clean_countries:
|
||||||
|
filters_map[f"country_{cc}"] = {
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"term": {
|
||||||
|
"authorships.institutions.country_code": cc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 3. Continent/Region Filters
|
||||||
|
for r_code, member_ccs in continent_country_codes.items():
|
||||||
|
if member_ccs:
|
||||||
|
filters_map[f"region_{r_code}"] = {
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.country_code": member_ccs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# If no entities specified, return empty
|
||||||
|
if not filters_map:
|
||||||
|
return TrendResponse(series=[], years=years_range, location_mappings=location_mappings)
|
||||||
|
|
||||||
|
# We will accumulate results in a nested structure: entity_key -> topic -> year -> (count, inst_count)
|
||||||
|
accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = {
|
||||||
|
key: {t: {yr: (0, 1) for yr in years_range} for t in topics}
|
||||||
|
for key in filters_map
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build topic matching clauses and filters
|
||||||
|
topic_clauses = []
|
||||||
|
topic_filters = {}
|
||||||
|
for t in topics:
|
||||||
|
tid = resolved_topic_ids.get(t)
|
||||||
|
if tid:
|
||||||
|
clause = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}},
|
||||||
|
{"term": {"primary_topic.id": tid}}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
clause = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}},
|
||||||
|
{"match_phrase": {"primary_topic.display_name": t}}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
topic_clauses.append(clause)
|
||||||
|
topic_filters[t] = clause
|
||||||
|
|
||||||
|
# Build query-level entity filters to optimize search performance
|
||||||
|
entity_should_clauses = []
|
||||||
|
if query_institutions:
|
||||||
|
entity_should_clauses.append({
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.id": query_institutions
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if clean_countries:
|
||||||
|
entity_should_clauses.append({
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.country_code": clean_countries
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
all_continent_countries = []
|
||||||
|
for member_ccs in continent_country_codes.values():
|
||||||
|
all_continent_countries.extend(member_ccs)
|
||||||
|
if all_continent_countries:
|
||||||
|
entity_should_clauses.append({
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.country_code": list(set(all_continent_countries))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
# Construct the single-pass Elasticsearch query
|
||||||
|
filter_clauses = [
|
||||||
|
{
|
||||||
|
"range": {
|
||||||
|
"publication_year": {
|
||||||
|
"gte": start_year,
|
||||||
|
"lte": end_year
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bool": {
|
||||||
|
"should": topic_clauses,
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
if entity_should_clauses:
|
||||||
|
filter_clauses.append({
|
||||||
|
"bool": {
|
||||||
|
"should": entity_should_clauses,
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
query = {
|
||||||
|
"bool": {
|
||||||
|
"filter": filter_clauses
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build two-layer nested aggregations (topics -> entities -> publication_year)
|
||||||
|
aggregations = {
|
||||||
|
"topics_agg": {
|
||||||
|
"filters": {
|
||||||
|
"filters": topic_filters
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"entities_agg": {
|
||||||
|
"filters": {
|
||||||
|
"filters": filters_map
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"by_year": {
|
||||||
|
"terms": {
|
||||||
|
"field": "publication_year",
|
||||||
|
"size": len(years_range) * 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=f"{str(ESIndex.OPENALEX_WORKS)}*",
|
||||||
|
query=query,
|
||||||
|
body={"aggs": aggregations},
|
||||||
|
size=0,
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
|
||||||
|
topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {})
|
||||||
|
for t_name, t_bucket in topics_buckets.items():
|
||||||
|
entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {})
|
||||||
|
for entity_key, e_bucket in entities_buckets.items():
|
||||||
|
year_buckets = e_bucket.get("by_year", {}).get("buckets", [])
|
||||||
|
for yr_bucket in year_buckets:
|
||||||
|
yr = int(yr_bucket.get("key"))
|
||||||
|
count = int(yr_bucket.get("doc_count", 0))
|
||||||
|
inst_count = 1
|
||||||
|
if yr in years_range:
|
||||||
|
accumulated_data[entity_key][t_name][yr] = (count, inst_count)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error executing single-pass Elasticsearch query: %s", e)
|
||||||
|
|
||||||
|
# Construct lists of raw counts and S-Curves for all series to normalize in parallel
|
||||||
|
series_keys = []
|
||||||
|
raw_lists = []
|
||||||
|
cumsum_lists = []
|
||||||
|
inst_counts_map = {}
|
||||||
|
|
||||||
|
for entity_key, topic_dict in accumulated_data.items():
|
||||||
|
for topic, year_dict in topic_dict.items():
|
||||||
|
raw_counts = []
|
||||||
|
inst_counts = []
|
||||||
|
for yr in years_range:
|
||||||
|
count, inst_count = year_dict[yr]
|
||||||
|
raw_counts.append(count)
|
||||||
|
inst_counts.append(inst_count)
|
||||||
|
|
||||||
|
cumulative_counts = list(np.cumsum(raw_counts))
|
||||||
|
|
||||||
|
series_keys.append((entity_key, topic))
|
||||||
|
raw_lists.append(raw_counts)
|
||||||
|
cumsum_lists.append(cumulative_counts)
|
||||||
|
inst_counts_map[(entity_key, topic)] = inst_counts
|
||||||
|
|
||||||
|
normalized_lookup = {}
|
||||||
|
if raw_lists:
|
||||||
|
# Construct matrices of shape (n_years, n_series)
|
||||||
|
raw_matrix = np.array(raw_lists, dtype=float).T
|
||||||
|
cumsum_matrix = np.array(cumsum_lists, dtype=float).T
|
||||||
|
|
||||||
|
# Batch normalize columns in parallel using MinMaxScaler
|
||||||
|
scaler_raw = MinMaxScaler()
|
||||||
|
normalized_matrix = scaler_raw.fit_transform(raw_matrix)
|
||||||
|
|
||||||
|
scaler_cumsum = MinMaxScaler()
|
||||||
|
normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix)
|
||||||
|
|
||||||
|
# Transpose back to lists of shape (n_series, n_years)
|
||||||
|
normalized_lists = normalized_matrix.T.tolist()
|
||||||
|
normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist()
|
||||||
|
|
||||||
|
for idx, (entity_key, topic) in enumerate(series_keys):
|
||||||
|
normalized_lookup[(entity_key, topic)] = {
|
||||||
|
"normalized": normalized_lists[idx],
|
||||||
|
"cumulative": normalized_cumsum_lists[idx]
|
||||||
|
}
|
||||||
|
|
||||||
|
# Process and build TrendSeries list
|
||||||
|
series_list: List[TrendSeries] = []
|
||||||
|
|
||||||
|
for entity_key, topic_dict in accumulated_data.items():
|
||||||
|
# Resolve details for this entity
|
||||||
|
if entity_key.startswith("inst_"):
|
||||||
|
entity_id = entity_key[len("inst_"):]
|
||||||
|
entity_name = resolved_names.get(entity_id, entity_id)
|
||||||
|
entity_type = "institution"
|
||||||
|
elif entity_key.startswith("country_"):
|
||||||
|
entity_id = entity_key[len("country_"):]
|
||||||
|
entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}")
|
||||||
|
entity_type = "country"
|
||||||
|
elif entity_key.startswith("region_"):
|
||||||
|
entity_id = entity_key[len("region_"):]
|
||||||
|
entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}")
|
||||||
|
entity_type = "region"
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
topic_data_map: Dict[str, List[TopicYearlyData]] = {}
|
||||||
|
|
||||||
|
for topic, year_dict in topic_dict.items():
|
||||||
|
yearly_data_items: List[TopicYearlyData] = []
|
||||||
|
|
||||||
|
lookup = normalized_lookup.get((entity_key, topic), {})
|
||||||
|
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
||||||
|
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
||||||
|
inst_counts = inst_counts_map.get((entity_key, topic), [1] * len(years_range))
|
||||||
|
|
||||||
|
for idx, yr in enumerate(years_range):
|
||||||
|
count, _ = year_dict[yr]
|
||||||
|
yearly_data_items.append(TopicYearlyData(
|
||||||
|
year=yr,
|
||||||
|
raw=count,
|
||||||
|
normalized=norm_vals[idx],
|
||||||
|
cumulative=cum_vals[idx],
|
||||||
|
institutions_count=inst_counts[idx]
|
||||||
|
))
|
||||||
|
|
||||||
|
topic_data_map[topic] = yearly_data_items
|
||||||
|
|
||||||
|
series_list.append(TrendSeries(
|
||||||
|
entity_id=entity_id,
|
||||||
|
entity_name=entity_name,
|
||||||
|
entity_type=entity_type,
|
||||||
|
country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None,
|
||||||
|
topic_data=topic_data_map
|
||||||
|
))
|
||||||
|
|
||||||
|
return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings)
|
||||||
|
|
||||||
@@ -55,6 +55,7 @@ async def get_author_works(
|
|||||||
language: list[str] | None = None,
|
language: list[str] | None = None,
|
||||||
institution_id: list[str] | None = None,
|
institution_id: list[str] | None = None,
|
||||||
topic_id: list[str] | None = None,
|
topic_id: list[str] | None = None,
|
||||||
|
sort: str = "year",
|
||||||
client: OpenAlexWorksSearchClient | None = None,
|
client: OpenAlexWorksSearchClient | None = None,
|
||||||
) -> WorkPage:
|
) -> WorkPage:
|
||||||
search_client = client or OpenAlexWorksSearchClient()
|
search_client = client or OpenAlexWorksSearchClient()
|
||||||
@@ -68,9 +69,11 @@ async def get_author_works(
|
|||||||
language=language,
|
language=language,
|
||||||
institution_id=institution_id,
|
institution_id=institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
|
sort=sort,
|
||||||
)
|
)
|
||||||
|
|
||||||
elements, total = _parse_full_work_search_response(data)
|
elements, total = _parse_full_work_search_response(data)
|
||||||
|
await _enrich_work_topic_descriptions(elements)
|
||||||
offset = (page - 1) * size
|
offset = (page - 1) * size
|
||||||
last_page = offset + len(elements) >= total
|
last_page = offset + len(elements) >= total
|
||||||
|
|
||||||
@@ -166,6 +169,15 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
|||||||
"primary_topics": {
|
"primary_topics": {
|
||||||
"terms": {"field": "primary_topic.id", "size": 1000},
|
"terms": {"field": "primary_topic.id", "size": 1000},
|
||||||
},
|
},
|
||||||
|
"all_topics": {
|
||||||
|
"nested": {"path": "topics"},
|
||||||
|
"aggs": {
|
||||||
|
"topic_ids": {
|
||||||
|
"terms": {"field": "topics.id", "size": 1000},
|
||||||
|
"aggs": {"works": {"reverse_nested": {}}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,10 +192,25 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
|||||||
|
|
||||||
aggregations = response.get("aggregations", {})
|
aggregations = response.get("aggregations", {})
|
||||||
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
||||||
|
topic_buckets = (
|
||||||
|
aggregations.get("all_topics", {}).get("topic_ids", {}).get("buckets", [])
|
||||||
|
)
|
||||||
|
|
||||||
|
broad_counts = {
|
||||||
|
bucket["key"]: bucket.get("works", {}).get("doc_count", bucket["doc_count"])
|
||||||
|
for bucket in topic_buckets
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
counts = []
|
counts = []
|
||||||
for bucket in buckets:
|
for bucket in buckets:
|
||||||
counts.append({"id": bucket["key"], "count": bucket["doc_count"]})
|
topic_id = bucket["key"]
|
||||||
|
counts.append(
|
||||||
|
{
|
||||||
|
"id": topic_id,
|
||||||
|
"count": max(broad_counts.get(topic_id, 0), bucket["doc_count"]),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
return counts
|
return counts
|
||||||
|
|
||||||
@@ -202,9 +229,44 @@ async def get_work(
|
|||||||
elements, _ = _parse_full_work_search_response(response_by_title)
|
elements, _ = _parse_full_work_search_response(response_by_title)
|
||||||
if not elements:
|
if not elements:
|
||||||
return None
|
return None
|
||||||
|
await _enrich_work_topic_descriptions(elements[:1])
|
||||||
return elements[0]
|
return elements[0]
|
||||||
|
|
||||||
|
|
||||||
|
async def enrich_topic_descriptions(topics: List) -> None:
|
||||||
|
"""Batch-fill missing descriptions on dehydrated topics.
|
||||||
|
|
||||||
|
OpenAlex work and author documents carry dehydrated topics without a
|
||||||
|
description, so we batch-load the details from the openalex-topics index.
|
||||||
|
"""
|
||||||
|
pending = [topic for topic in topics if topic.id and not topic.description]
|
||||||
|
|
||||||
|
if not pending:
|
||||||
|
return
|
||||||
|
|
||||||
|
details = await _get_topic_details(list({topic.id for topic in pending}))
|
||||||
|
|
||||||
|
if not details:
|
||||||
|
return
|
||||||
|
|
||||||
|
for topic in pending:
|
||||||
|
info = details.get(topic.id)
|
||||||
|
if info:
|
||||||
|
topic.description = info.get("description")
|
||||||
|
|
||||||
|
|
||||||
|
async def _enrich_work_topic_descriptions(works: List[Work]) -> None:
|
||||||
|
topics = []
|
||||||
|
|
||||||
|
for work in works:
|
||||||
|
topics.extend(work.topics or [])
|
||||||
|
|
||||||
|
if work.primary_topic:
|
||||||
|
topics.append(work.primary_topic)
|
||||||
|
|
||||||
|
await enrich_topic_descriptions(topics)
|
||||||
|
|
||||||
|
|
||||||
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||||
if not topic_ids:
|
if not topic_ids:
|
||||||
return {}
|
return {}
|
||||||
@@ -869,6 +931,7 @@ async def _search_author_works_data(
|
|||||||
language: list[str] | None = None,
|
language: list[str] | None = None,
|
||||||
institution_id: list[str] | None = None,
|
institution_id: list[str] | None = None,
|
||||||
topic_id: list[str] | None = None,
|
topic_id: list[str] | None = None,
|
||||||
|
sort: str = "year",
|
||||||
) -> dict:
|
) -> dict:
|
||||||
return await search_client.search_author_works(
|
return await search_client.search_author_works(
|
||||||
author_id,
|
author_id,
|
||||||
@@ -879,6 +942,7 @@ async def _search_author_works_data(
|
|||||||
language=language,
|
language=language,
|
||||||
institution_id=institution_id,
|
institution_id=institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
|
sort=sort,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
Pydantic models for publication works.
|
Pydantic models for publication works.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from enum import StrEnum
|
||||||
from typing import List
|
from typing import List
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
@@ -41,3 +42,35 @@ class WorkPage(BaseModel):
|
|||||||
class WorkList(BaseModel):
|
class WorkList(BaseModel):
|
||||||
elements: List[Work] = Field(default_factory=list, description="All works.")
|
elements: List[Work] = Field(default_factory=list, description="All works.")
|
||||||
total: int = Field(default=0, description="The total number of works.")
|
total: int = Field(default=0, description="The total number of works.")
|
||||||
|
|
||||||
|
|
||||||
|
class WorkPurpose(StrEnum):
|
||||||
|
"""Represents the purpose of a work. Either a foundation work or an application work."""
|
||||||
|
|
||||||
|
FOUNDATION = "Foundation"
|
||||||
|
APPLICATION = "Application"
|
||||||
|
|
||||||
|
|
||||||
|
class SpecificWorkPurpose(BaseModel):
|
||||||
|
"""Represents the purpose of a specific work, including its ID, purpose, and optional reasoning."""
|
||||||
|
|
||||||
|
raw_oa_work_id: str = Field(description="The raw OpenAlex work id.")
|
||||||
|
publication_year: Optional[int] = Field(
|
||||||
|
default=None, description="The publication year of the work."
|
||||||
|
)
|
||||||
|
purpose: WorkPurpose = Field(description="The purpose of the work.")
|
||||||
|
reasoning: Optional[str] = Field(
|
||||||
|
default=None, description="The reasoning behind the purpose determination."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorWorkPurposes(BaseModel):
|
||||||
|
"""Represents the purposes of an author, including their ID and a list of specific work purposes."""
|
||||||
|
|
||||||
|
raw_oa_author_id: str = Field(description="The raw OpenAlex author id.")
|
||||||
|
total: int = Field(
|
||||||
|
default=0, description="The total number of works for the author."
|
||||||
|
)
|
||||||
|
purposes: List[SpecificWorkPurpose] = Field(
|
||||||
|
default_factory=list, description="The list of specific work purposes."
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Path
|
||||||
|
|
||||||
|
from inse.tags import Tags
|
||||||
|
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose
|
||||||
|
|
||||||
|
from inse.works import purpose_service
|
||||||
|
|
||||||
|
WORKS_PREFIX = "/api/purpose"
|
||||||
|
|
||||||
|
router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{raw_oa_work_id}/purpose",
|
||||||
|
operation_id="getWorkPurpose",
|
||||||
|
summary="Returns the purpose of a work based on its ID.",
|
||||||
|
)
|
||||||
|
async def get_work_purpose(
|
||||||
|
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
|
||||||
|
) -> SpecificWorkPurpose:
|
||||||
|
return await purpose_service.get_work_purpose(raw_oa_work_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{raw_oa_author_id}/purposes",
|
||||||
|
operation_id="getAuthorWorkPurposes",
|
||||||
|
summary="Returns the purposes of an author based on their ID.",
|
||||||
|
)
|
||||||
|
async def get_author_work_purposes(
|
||||||
|
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
|
||||||
|
) -> AuthorWorkPurposes:
|
||||||
|
return await purpose_service.get_author_work_purposes(raw_oa_author_id)
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import logging
|
||||||
|
import random
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from fastapi import HTTPException, status
|
||||||
|
|
||||||
|
from inse.exceptions import NotFoundException
|
||||||
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.model import ESIndex
|
||||||
|
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose:
|
||||||
|
raw_oa_work_id = raw_oa_work_id.strip().upper()
|
||||||
|
|
||||||
|
response = await elasticsearch.get(
|
||||||
|
index=ESIndex.OPENALEX_WORKS,
|
||||||
|
doc_id=raw_oa_work_id,
|
||||||
|
source=["title", "abstract"],
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(f"Elasticsearch response for work id {raw_oa_work_id}: {response}")
|
||||||
|
|
||||||
|
source = response.get("_source", {})
|
||||||
|
if not source:
|
||||||
|
raise NotFoundException(f"Work with id {raw_oa_work_id} not found.")
|
||||||
|
|
||||||
|
logger.debug(f"Found work source for id {raw_oa_work_id}: {source}")
|
||||||
|
|
||||||
|
return SpecificWorkPurpose(
|
||||||
|
raw_oa_work_id=raw_oa_work_id,
|
||||||
|
publication_year=source.get("publication_year"),
|
||||||
|
purpose=WorkPurpose.FOUNDATION, # TODO: Replace with actual purpose determination logic
|
||||||
|
reasoning="This is a placeholder reasoning for the purpose determination.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes:
|
||||||
|
raw_oa_author_id = raw_oa_author_id.strip().upper()
|
||||||
|
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=ESIndex.OPENALEX_WORKS,
|
||||||
|
source=["id", "publication_year"],
|
||||||
|
query={
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships",
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"filter": [
|
||||||
|
{
|
||||||
|
"term": {
|
||||||
|
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
size=10000,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(f"Elasticsearch response for author id {raw_oa_author_id}: {response}")
|
||||||
|
|
||||||
|
purposes: List[SpecificWorkPurpose] = []
|
||||||
|
|
||||||
|
# TODO: implement actual retrieval of previously determined purposes for the author's works
|
||||||
|
|
||||||
|
hits_block = response.get("hits", {})
|
||||||
|
hits = hits_block.get("hits", [])
|
||||||
|
total_hits = hits_block.get("total", {}).get("value", 0)
|
||||||
|
for hit in hits:
|
||||||
|
source = hit.get("_source", {})
|
||||||
|
work_id = source.get("id")
|
||||||
|
publication_year = source.get("publication_year")
|
||||||
|
if work_id:
|
||||||
|
# TODO: Remove random based purpose assignment
|
||||||
|
if random.choice([True, False]):
|
||||||
|
purpose = SpecificWorkPurpose(
|
||||||
|
raw_oa_work_id=work_id,
|
||||||
|
publication_year=publication_year,
|
||||||
|
purpose=WorkPurpose.FOUNDATION,
|
||||||
|
reasoning=f"Placeholder reasoning for work {work_id}.",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
purpose = SpecificWorkPurpose(
|
||||||
|
raw_oa_work_id=work_id,
|
||||||
|
publication_year=publication_year,
|
||||||
|
purpose=WorkPurpose.APPLICATION,
|
||||||
|
reasoning=f"Placeholder reasoning for work {work_id}.",
|
||||||
|
)
|
||||||
|
|
||||||
|
purposes.append(purpose)
|
||||||
|
else:
|
||||||
|
logger.warning(f"Work hit without id for author {raw_oa_author_id}: {hit}")
|
||||||
|
|
||||||
|
return AuthorWorkPurposes(
|
||||||
|
raw_oa_author_id=raw_oa_author_id, total=total_hits, purposes=purposes
|
||||||
|
)
|
||||||
@@ -35,6 +35,7 @@ class OpenAlexWorksSearchClient:
|
|||||||
language: list[str] | None = None,
|
language: list[str] | None = None,
|
||||||
institution_id: list[str] | None = None,
|
institution_id: list[str] | None = None,
|
||||||
topic_id: list[str] | None = None,
|
topic_id: list[str] | None = None,
|
||||||
|
sort: str = "year",
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||||
filters = self._work_filters(
|
filters = self._work_filters(
|
||||||
@@ -73,19 +74,27 @@ class OpenAlexWorksSearchClient:
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
if sort == "citations":
|
||||||
|
sort_clauses = [
|
||||||
|
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
sort_clauses = [
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||||
|
]
|
||||||
return {
|
return {
|
||||||
"from": (page - 1) * size,
|
"from": (page - 1) * size,
|
||||||
"size": size,
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
"query": {
|
"query": {
|
||||||
"bool": {
|
"bool": {
|
||||||
"must": must_clauses,
|
"must": must_clauses,
|
||||||
"filter": filters,
|
"filter": filters,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"sort": [
|
"sort": sort_clauses,
|
||||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
|
||||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
|
||||||
],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def _work_filters(
|
def _work_filters(
|
||||||
@@ -129,6 +138,7 @@ class OpenAlexWorksSearchClient:
|
|||||||
language: list[str] | None = None,
|
language: list[str] | None = None,
|
||||||
institution_id: list[str] | None = None,
|
institution_id: list[str] | None = None,
|
||||||
topic_id: list[str] | None = None,
|
topic_id: list[str] | None = None,
|
||||||
|
sort: str = "year",
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
if not self.api_key:
|
if not self.api_key:
|
||||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||||
@@ -142,6 +152,7 @@ class OpenAlexWorksSearchClient:
|
|||||||
language=language,
|
language=language,
|
||||||
institution_id=institution_id,
|
institution_id=institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
|
sort=sort,
|
||||||
)
|
)
|
||||||
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
|
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
REST API for publication works.
|
REST API for publication works.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Annotated, Optional
|
from typing import Annotated, Literal, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
from fastapi import Path
|
from fastapi import Path
|
||||||
@@ -54,6 +54,10 @@ async def get_author_works(
|
|||||||
list[str] | None,
|
list[str] | None,
|
||||||
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
||||||
] = None,
|
] = None,
|
||||||
|
sort: Annotated[
|
||||||
|
Literal["year", "citations"],
|
||||||
|
Query(description="Sort order: by publication year or by citation count."),
|
||||||
|
] = "year",
|
||||||
):
|
):
|
||||||
return await logic.get_author_works(
|
return await logic.get_author_works(
|
||||||
author_id,
|
author_id,
|
||||||
@@ -64,6 +68,7 @@ async def get_author_works(
|
|||||||
language=language,
|
language=language,
|
||||||
institution_id=institution_id,
|
institution_id=institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
|
sort=sort,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,28 @@ def test_author_works_query_searches_authorship_author_id():
|
|||||||
assert query["query"]["bool"]["filter"] == []
|
assert query["query"]["bool"]["filter"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_author_works_query_sorts_by_year_by_default():
|
||||||
|
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||||
|
|
||||||
|
query = client.author_works_query("A5023888391", page=1, size=20)
|
||||||
|
|
||||||
|
assert query["sort"] == [
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_author_works_query_sorts_by_citations():
|
||||||
|
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||||
|
|
||||||
|
query = client.author_works_query("A5023888391", page=1, size=20, sort="citations")
|
||||||
|
|
||||||
|
assert query["sort"] == [
|
||||||
|
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def test_author_works_query_adds_publication_filters():
|
def test_author_works_query_adds_publication_filters():
|
||||||
client = OpenAlexWorksSearchClient(api_key="test-key")
|
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||||
|
|
||||||
|
|||||||
@@ -1195,6 +1195,11 @@ Content-Type: application/json
|
|||||||
|
|
||||||
###
|
###
|
||||||
|
|
||||||
|
GET https://project.nes.uni-due.de/elastic/openalex-works/_mapping
|
||||||
|
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
|
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
|
||||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||||
Content-Type: application/json
|
Content-Type: application/json
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ api/personNetwork.service.ts
|
|||||||
api/persons.service.ts
|
api/persons.service.ts
|
||||||
api/projects.service.ts
|
api/projects.service.ts
|
||||||
api/topics.service.ts
|
api/topics.service.ts
|
||||||
|
api/universityRankings.service.ts
|
||||||
api/works.service.ts
|
api/works.service.ts
|
||||||
configuration.ts
|
configuration.ts
|
||||||
encoder.ts
|
encoder.ts
|
||||||
@@ -35,9 +36,11 @@ model/authorNetworkNode.ts
|
|||||||
model/authorParsedLongestName.ts
|
model/authorParsedLongestName.ts
|
||||||
model/authorPositionCount.ts
|
model/authorPositionCount.ts
|
||||||
model/authorSummaryStats.ts
|
model/authorSummaryStats.ts
|
||||||
|
model/authorWorkPurposes.ts
|
||||||
model/authorsFilterProperties.ts
|
model/authorsFilterProperties.ts
|
||||||
model/authorsListResponse.ts
|
model/authorsListResponse.ts
|
||||||
model/authorship.ts
|
model/authorship.ts
|
||||||
|
model/autocompleteLocationItem.ts
|
||||||
model/autocompleteResponse.ts
|
model/autocompleteResponse.ts
|
||||||
model/autocompleteResponseMeta.ts
|
model/autocompleteResponseMeta.ts
|
||||||
model/autocompleteResponseResultsInner.ts
|
model/autocompleteResponseResultsInner.ts
|
||||||
@@ -46,6 +49,8 @@ model/bodyChangePassword.ts
|
|||||||
model/bodyGetAccessToken.ts
|
model/bodyGetAccessToken.ts
|
||||||
model/bodyLogin.ts
|
model/bodyLogin.ts
|
||||||
model/bodyRequestOtk.ts
|
model/bodyRequestOtk.ts
|
||||||
|
model/bodyRequestPasswordReset.ts
|
||||||
|
model/bodyResetPassword.ts
|
||||||
model/bundProject.ts
|
model/bundProject.ts
|
||||||
model/bundProjectDetails.ts
|
model/bundProjectDetails.ts
|
||||||
model/bundProjectPage.ts
|
model/bundProjectPage.ts
|
||||||
@@ -138,6 +143,7 @@ model/loginResponse.ts
|
|||||||
model/longitude.ts
|
model/longitude.ts
|
||||||
model/matchedAuthor.ts
|
model/matchedAuthor.ts
|
||||||
model/matchedOfficer.ts
|
model/matchedOfficer.ts
|
||||||
|
model/matchedTopic.ts
|
||||||
model/mentionedPerson.ts
|
model/mentionedPerson.ts
|
||||||
model/meta.ts
|
model/meta.ts
|
||||||
model/model2YrMeanCitedness.ts
|
model/model2YrMeanCitedness.ts
|
||||||
@@ -163,17 +169,22 @@ model/publicationsByAuthorResponse.ts
|
|||||||
model/rankingResponse.ts
|
model/rankingResponse.ts
|
||||||
model/score.ts
|
model/score.ts
|
||||||
model/sortDirection.ts
|
model/sortDirection.ts
|
||||||
|
model/specificWorkPurpose.ts
|
||||||
model/tokenType.ts
|
model/tokenType.ts
|
||||||
|
model/topInstitutionItem.ts
|
||||||
model/topic.ts
|
model/topic.ts
|
||||||
model/topicCount.ts
|
model/topicCount.ts
|
||||||
model/topicDomain.ts
|
model/topicDomain.ts
|
||||||
model/topicField.ts
|
model/topicField.ts
|
||||||
model/topicIds.ts
|
model/topicIds.ts
|
||||||
model/topicSubfield.ts
|
model/topicSubfield.ts
|
||||||
|
model/topicYearlyData.ts
|
||||||
model/topics.ts
|
model/topics.ts
|
||||||
model/topicsByTime.ts
|
model/topicsByTime.ts
|
||||||
model/topicsByYear.ts
|
model/topicsByYear.ts
|
||||||
model/topicsListResponse.ts
|
model/topicsListResponse.ts
|
||||||
|
model/trendResponse.ts
|
||||||
|
model/trendSeries.ts
|
||||||
model/universityRanking.ts
|
model/universityRanking.ts
|
||||||
model/universityTopicData.ts
|
model/universityTopicData.ts
|
||||||
model/updateAccountRequest.ts
|
model/updateAccountRequest.ts
|
||||||
@@ -193,6 +204,7 @@ model/workKeyword.ts
|
|||||||
model/workMeshInner.ts
|
model/workMeshInner.ts
|
||||||
model/workNetworkNode.ts
|
model/workNetworkNode.ts
|
||||||
model/workPage.ts
|
model/workPage.ts
|
||||||
|
model/workPurpose.ts
|
||||||
model/workSustainableDevelopmentGoalsInner.ts
|
model/workSustainableDevelopmentGoalsInner.ts
|
||||||
model/workTopic.ts
|
model/workTopic.ts
|
||||||
model/workTopicDomain.ts
|
model/workTopicDomain.ts
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ export * from './projects.service';
|
|||||||
import { ProjectsService } from './projects.service';
|
import { ProjectsService } from './projects.service';
|
||||||
export * from './topics.service';
|
export * from './topics.service';
|
||||||
import { TopicsService } from './topics.service';
|
import { TopicsService } from './topics.service';
|
||||||
|
export * from './universityRankings.service';
|
||||||
|
import { UniversityRankingsService } from './universityRankings.service';
|
||||||
export * from './works.service';
|
export * from './works.service';
|
||||||
import { WorksService } from './works.service';
|
import { WorksService } from './works.service';
|
||||||
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService];
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ import { BodyLogin } from '../model/bodyLogin';
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
|
import { BodyRequestPasswordReset } from '../model/bodyRequestPasswordReset';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyResetPassword } from '../model/bodyResetPassword';
|
||||||
|
// @ts-ignore
|
||||||
import { CreateAccountRequest } from '../model/createAccountRequest';
|
import { CreateAccountRequest } from '../model/createAccountRequest';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
@@ -801,6 +805,138 @@ export class AuthService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request Password Reset
|
||||||
|
* Request a one-time password reset link for the given email address.
|
||||||
|
* @endpoint post /api/auth/v2/request-password-reset
|
||||||
|
* @param bodyRequestPasswordReset
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
|
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (bodyRequestPasswordReset === null || bodyRequestPasswordReset === undefined) {
|
||||||
|
throw new Error('Required parameter bodyRequestPasswordReset was null or undefined when calling requestPasswordReset.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// to determine the Content-Type header
|
||||||
|
const consumes: string[] = [
|
||||||
|
'application/json'
|
||||||
|
];
|
||||||
|
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||||
|
if (httpContentTypeSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/auth/v2/request-password-reset`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyRequestPasswordReset,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset Password
|
||||||
|
* Reset the user\'s password using a one-time password reset token.
|
||||||
|
* @endpoint post /api/auth/v2/reset-password
|
||||||
|
* @param bodyResetPassword
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
|
public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public resetPassword(bodyResetPassword: BodyResetPassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (bodyResetPassword === null || bodyResetPassword === undefined) {
|
||||||
|
throw new Error('Required parameter bodyResetPassword was null or undefined when calling resetPassword.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// to determine the Content-Type header
|
||||||
|
const consumes: string[] = [
|
||||||
|
'application/json'
|
||||||
|
];
|
||||||
|
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||||
|
if (httpContentTypeSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/auth/v2/reset-password`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyResetPassword,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update Account
|
* Update Account
|
||||||
* @endpoint put /api/accounts/{account_id}
|
* @endpoint put /api/accounts/{account_id}
|
||||||
|
|||||||
@@ -26,8 +26,6 @@ import { Institution } from '../model/institution';
|
|||||||
import { InstitutionPage } from '../model/institutionPage';
|
import { InstitutionPage } from '../model/institutionPage';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { InstitutionsListResponse } from '../model/institutionsListResponse';
|
import { InstitutionsListResponse } from '../model/institutionsListResponse';
|
||||||
// @ts-ignore
|
|
||||||
import { RankingResponse } from '../model/rankingResponse';
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
@@ -170,69 +168,6 @@ export class InstitutionsService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns data for the University Ranking Dashboard.
|
|
||||||
* @endpoint get /api/inse-service/university-rankings
|
|
||||||
* @param topic Research topic (e.g., \'Artificial Intelligence\')
|
|
||||||
* @param metric Metric to rank by
|
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
|
||||||
* @param reportProgress flag to report request and response progress.
|
|
||||||
*/
|
|
||||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<RankingResponse>;
|
|
||||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<RankingResponse>>;
|
|
||||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<RankingResponse>>;
|
|
||||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
|
||||||
if (topic === null || topic === undefined) {
|
|
||||||
throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.');
|
|
||||||
}
|
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
|
||||||
<any>topic, 'topic');
|
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
|
||||||
<any>metric, 'metric');
|
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
|
||||||
'application/json'
|
|
||||||
]);
|
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
|
||||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
|
||||||
}
|
|
||||||
|
|
||||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
|
||||||
|
|
||||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
|
||||||
|
|
||||||
|
|
||||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
|
||||||
if (localVarHttpHeaderAcceptSelected) {
|
|
||||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
|
||||||
responseType_ = 'text';
|
|
||||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
|
||||||
responseType_ = 'json';
|
|
||||||
} else {
|
|
||||||
responseType_ = 'blob';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let localVarPath = `/api/inse-service/university-rankings`;
|
|
||||||
const { basePath, withCredentials } = this.configuration;
|
|
||||||
return this.httpClient.request<RankingResponse>('get', `${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
params: localVarQueryParameters,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
|
||||||
reportProgress: reportProgress
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a list of OpenAlex institutions.
|
* Returns a list of OpenAlex institutions.
|
||||||
* @endpoint get /api/inse-service/institutions
|
* @endpoint get /api/inse-service/institutions
|
||||||
|
|||||||
@@ -0,0 +1,323 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
|
} from '@angular/common/http';
|
||||||
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { AutocompleteLocationItem } from '../model/autocompleteLocationItem';
|
||||||
|
// @ts-ignore
|
||||||
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
|
// @ts-ignore
|
||||||
|
import { RankingResponse } from '../model/rankingResponse';
|
||||||
|
// @ts-ignore
|
||||||
|
import { TopInstitutionItem } from '../model/topInstitutionItem';
|
||||||
|
// @ts-ignore
|
||||||
|
import { TrendResponse } from '../model/trendResponse';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
|
import { Configuration } from '../configuration';
|
||||||
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class UniversityRankingsService extends BaseService {
|
||||||
|
|
||||||
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
|
super(basePath, configuration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns country and continent options for autocomplete inputs.
|
||||||
|
* @endpoint get /api/inse-service/university-rankings/autocomplete-locations
|
||||||
|
* @param query Query text to search for countries/continents
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AutocompleteLocationItem>>;
|
||||||
|
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AutocompleteLocationItem>>>;
|
||||||
|
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AutocompleteLocationItem>>>;
|
||||||
|
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (query === null || query === undefined) {
|
||||||
|
throw new Error('Required parameter query was null or undefined when calling getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>query, 'query');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/university-rankings/autocomplete-locations`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<Array<AutocompleteLocationItem>>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns data for the University Ranking Dashboard.
|
||||||
|
* @endpoint get /api/inse-service/university-rankings
|
||||||
|
* @param topic Research topic display name or OpenAlex ID (e.g., \'Artificial Intelligence\')
|
||||||
|
* @param metric Metric to rank by
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<RankingResponse>;
|
||||||
|
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<RankingResponse>>;
|
||||||
|
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<RankingResponse>>;
|
||||||
|
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (topic === null || topic === undefined) {
|
||||||
|
throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>topic, 'topic');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>metric, 'metric');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/university-rankings`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<RankingResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns top institutions filtered by country/region and sorted by topic-level publications count.
|
||||||
|
* @endpoint get /api/inse-service/university-rankings/top-institutions
|
||||||
|
* @param topic Research topic
|
||||||
|
* @param region Region identifier (e.g. EU)
|
||||||
|
* @param country Country code (e.g. DE)
|
||||||
|
* @param limit Max suggestions to return
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<TopInstitutionItem>>;
|
||||||
|
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<TopInstitutionItem>>>;
|
||||||
|
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<TopInstitutionItem>>>;
|
||||||
|
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (topic === null || topic === undefined) {
|
||||||
|
throw new Error('Required parameter topic was null or undefined when calling getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>topic, 'topic');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>region, 'region');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>country, 'country');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>limit, 'limit');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/university-rankings/top-institutions`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<Array<TopInstitutionItem>>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns timeseries publication data for compared institutions, countries and regions.
|
||||||
|
* @endpoint get /api/inse-service/university-rankings/trend
|
||||||
|
* @param topics List of topics to analyze
|
||||||
|
* @param institutions List of OpenAlex Institution IDs
|
||||||
|
* @param countries List of country codes
|
||||||
|
* @param regions List of region identifiers
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TrendResponse>;
|
||||||
|
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TrendResponse>>;
|
||||||
|
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TrendResponse>>;
|
||||||
|
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (topics === null || topics === undefined) {
|
||||||
|
throw new Error('Required parameter topics was null or undefined when calling getTrendApiInseServiceUniversityRankingsTrendGet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
if (topics) {
|
||||||
|
topics.forEach((element) => {
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>element, 'topics');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (institutions) {
|
||||||
|
institutions.forEach((element) => {
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>element, 'institutions');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (countries) {
|
||||||
|
countries.forEach((element) => {
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>element, 'countries');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (regions) {
|
||||||
|
regions.forEach((element) => {
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>element, 'regions');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/university-rankings/trend`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<TrendResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -16,9 +16,13 @@ import { HttpClient, HttpHeaders, HttpParams,
|
|||||||
import { CustomHttpParameterCodec } from '../encoder';
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
import { Observable } from 'rxjs';
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { AuthorWorkPurposes } from '../model/authorWorkPurposes';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
|
import { SpecificWorkPurpose } from '../model/specificWorkPurpose';
|
||||||
|
// @ts-ignore
|
||||||
import { TopicCount } from '../model/topicCount';
|
import { TopicCount } from '../model/topicCount';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { TopicsByTime } from '../model/topicsByTime';
|
import { TopicsByTime } from '../model/topicsByTime';
|
||||||
@@ -100,6 +104,61 @@ export class WorksService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the purposes of an author based on their ID.
|
||||||
|
* @endpoint get /api/purpose/{raw_oa_author_id}/purposes
|
||||||
|
* @param rawOaAuthorId The raw OpenAlex author id.
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getAuthorWorkPurposes(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorWorkPurposes>;
|
||||||
|
public getAuthorWorkPurposes(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorWorkPurposes>>;
|
||||||
|
public getAuthorWorkPurposes(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorWorkPurposes>>;
|
||||||
|
public getAuthorWorkPurposes(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
|
||||||
|
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getAuthorWorkPurposes.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/purpose/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/purposes`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<AuthorWorkPurposes>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a page of works for an author.
|
* Returns a page of works for an author.
|
||||||
* @endpoint get /api/works/{author_id}
|
* @endpoint get /api/works/{author_id}
|
||||||
@@ -111,13 +170,14 @@ export class WorksService extends BaseService {
|
|||||||
* @param language Filter by language code. Can be repeated.
|
* @param language Filter by language code. Can be repeated.
|
||||||
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
|
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
|
||||||
* @param topicId Filter by OpenAlex topic id. Can be repeated.
|
* @param topicId Filter by OpenAlex topic id. Can be repeated.
|
||||||
|
* @param sort Sort order: by publication year or by citation count.
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPage>;
|
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, sort?: 'year' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPage>;
|
||||||
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPage>>;
|
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, sort?: 'year' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPage>>;
|
||||||
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPage>>;
|
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, sort?: 'year' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPage>>;
|
||||||
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, sort?: 'year' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (authorId === null || authorId === undefined) {
|
if (authorId === null || authorId === undefined) {
|
||||||
throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.');
|
throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.');
|
||||||
}
|
}
|
||||||
@@ -157,6 +217,8 @@ export class WorksService extends BaseService {
|
|||||||
<any>element, 'topic_id');
|
<any>element, 'topic_id');
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>sort, 'sort');
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
@@ -382,4 +444,59 @@ export class WorksService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the purpose of a work based on its ID.
|
||||||
|
* @endpoint get /api/purpose/{raw_oa_work_id}/purpose
|
||||||
|
* @param rawOaWorkId The raw OpenAlex work id.
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getWorkPurpose(rawOaWorkId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<SpecificWorkPurpose>;
|
||||||
|
public getWorkPurpose(rawOaWorkId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<SpecificWorkPurpose>>;
|
||||||
|
public getWorkPurpose(rawOaWorkId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<SpecificWorkPurpose>>;
|
||||||
|
public getWorkPurpose(rawOaWorkId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (rawOaWorkId === null || rawOaWorkId === undefined) {
|
||||||
|
throw new Error('Required parameter rawOaWorkId was null or undefined when calling getWorkPurpose.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/purpose/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/purpose`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<SpecificWorkPurpose>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
import { SpecificWorkPurpose } from './specificWorkPurpose';
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the purposes of an author, including their ID and a list of specific work purposes.
|
||||||
|
*/
|
||||||
|
export interface AuthorWorkPurposes {
|
||||||
|
/**
|
||||||
|
* The raw OpenAlex author id.
|
||||||
|
*/
|
||||||
|
raw_oa_author_id: string;
|
||||||
|
/**
|
||||||
|
* The total number of works for the author.
|
||||||
|
*/
|
||||||
|
total?: number;
|
||||||
|
/**
|
||||||
|
* The list of specific work purposes.
|
||||||
|
*/
|
||||||
|
purposes?: Array<SpecificWorkPurpose>;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/**
|
||||||
|
* 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 AutocompleteLocationItem {
|
||||||
|
id: string;
|
||||||
|
display_name: string;
|
||||||
|
code: string;
|
||||||
|
type: AutocompleteLocationItem.TypeEnum;
|
||||||
|
}
|
||||||
|
export namespace AutocompleteLocationItem {
|
||||||
|
export const TypeEnum = {
|
||||||
|
Country: 'country',
|
||||||
|
Continent: 'continent'
|
||||||
|
} as const;
|
||||||
|
export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
/**
|
||||||
|
* 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 BodyRequestPasswordReset {
|
||||||
|
/**
|
||||||
|
* User\'s email address
|
||||||
|
*/
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
/**
|
||||||
|
* 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 BodyResetPassword {
|
||||||
|
/**
|
||||||
|
* Password reset token from the reset link
|
||||||
|
*/
|
||||||
|
reset_token: string;
|
||||||
|
/**
|
||||||
|
* New password
|
||||||
|
*/
|
||||||
|
new_password: string;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/**
|
||||||
|
* 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 MatchedTopic {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
subfield_name?: string | null;
|
||||||
|
field_name?: string | null;
|
||||||
|
domain_name?: string | null;
|
||||||
|
source_keyword?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -11,9 +11,11 @@ export * from './authorNetworkNode';
|
|||||||
export * from './authorParsedLongestName';
|
export * from './authorParsedLongestName';
|
||||||
export * from './authorPositionCount';
|
export * from './authorPositionCount';
|
||||||
export * from './authorSummaryStats';
|
export * from './authorSummaryStats';
|
||||||
|
export * from './authorWorkPurposes';
|
||||||
export * from './authorsFilterProperties';
|
export * from './authorsFilterProperties';
|
||||||
export * from './authorsListResponse';
|
export * from './authorsListResponse';
|
||||||
export * from './authorship';
|
export * from './authorship';
|
||||||
|
export * from './autocompleteLocationItem';
|
||||||
export * from './autocompleteResponse';
|
export * from './autocompleteResponse';
|
||||||
export * from './autocompleteResponseMeta';
|
export * from './autocompleteResponseMeta';
|
||||||
export * from './autocompleteResponseResultsInner';
|
export * from './autocompleteResponseResultsInner';
|
||||||
@@ -22,6 +24,8 @@ export * from './bodyChangePassword';
|
|||||||
export * from './bodyGetAccessToken';
|
export * from './bodyGetAccessToken';
|
||||||
export * from './bodyLogin';
|
export * from './bodyLogin';
|
||||||
export * from './bodyRequestOtk';
|
export * from './bodyRequestOtk';
|
||||||
|
export * from './bodyRequestPasswordReset';
|
||||||
|
export * from './bodyResetPassword';
|
||||||
export * from './bundProject';
|
export * from './bundProject';
|
||||||
export * from './bundProjectDetails';
|
export * from './bundProjectDetails';
|
||||||
export * from './bundProjectPage';
|
export * from './bundProjectPage';
|
||||||
@@ -114,6 +118,7 @@ export * from './loginResponse';
|
|||||||
export * from './longitude';
|
export * from './longitude';
|
||||||
export * from './matchedAuthor';
|
export * from './matchedAuthor';
|
||||||
export * from './matchedOfficer';
|
export * from './matchedOfficer';
|
||||||
|
export * from './matchedTopic';
|
||||||
export * from './mentionedPerson';
|
export * from './mentionedPerson';
|
||||||
export * from './meta';
|
export * from './meta';
|
||||||
export * from './model2YrMeanCitedness';
|
export * from './model2YrMeanCitedness';
|
||||||
@@ -138,17 +143,22 @@ export * from './publicationsByAuthorResponse';
|
|||||||
export * from './rankingResponse';
|
export * from './rankingResponse';
|
||||||
export * from './score';
|
export * from './score';
|
||||||
export * from './sortDirection';
|
export * from './sortDirection';
|
||||||
|
export * from './specificWorkPurpose';
|
||||||
export * from './tokenType';
|
export * from './tokenType';
|
||||||
|
export * from './topInstitutionItem';
|
||||||
export * from './topic';
|
export * from './topic';
|
||||||
export * from './topicCount';
|
export * from './topicCount';
|
||||||
export * from './topicDomain';
|
export * from './topicDomain';
|
||||||
export * from './topicField';
|
export * from './topicField';
|
||||||
export * from './topicIds';
|
export * from './topicIds';
|
||||||
export * from './topicSubfield';
|
export * from './topicSubfield';
|
||||||
|
export * from './topicYearlyData';
|
||||||
export * from './topics';
|
export * from './topics';
|
||||||
export * from './topicsByTime';
|
export * from './topicsByTime';
|
||||||
export * from './topicsByYear';
|
export * from './topicsByYear';
|
||||||
export * from './topicsListResponse';
|
export * from './topicsListResponse';
|
||||||
|
export * from './trendResponse';
|
||||||
|
export * from './trendSeries';
|
||||||
export * from './universityRanking';
|
export * from './universityRanking';
|
||||||
export * from './universityTopicData';
|
export * from './universityTopicData';
|
||||||
export * from './updateAccountRequest';
|
export * from './updateAccountRequest';
|
||||||
@@ -168,6 +178,7 @@ export * from './workKeyword';
|
|||||||
export * from './workMeshInner';
|
export * from './workMeshInner';
|
||||||
export * from './workNetworkNode';
|
export * from './workNetworkNode';
|
||||||
export * from './workPage';
|
export * from './workPage';
|
||||||
|
export * from './workPurpose';
|
||||||
export * from './workSustainableDevelopmentGoalsInner';
|
export * from './workSustainableDevelopmentGoalsInner';
|
||||||
export * from './workTopic';
|
export * from './workTopic';
|
||||||
export * from './workTopicDomain';
|
export * from './workTopicDomain';
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
* https://openapi-generator.tech
|
* https://openapi-generator.tech
|
||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
|
import { MatchedTopic } from './matchedTopic';
|
||||||
import { MentionedPerson } from './mentionedPerson';
|
import { MentionedPerson } from './mentionedPerson';
|
||||||
|
|
||||||
|
|
||||||
@@ -21,7 +22,7 @@ export interface NewsArticleDetail {
|
|||||||
related?: boolean | null;
|
related?: boolean | null;
|
||||||
full_content?: string | null;
|
full_content?: string | null;
|
||||||
authors?: Array<MentionedPerson>;
|
authors?: Array<MentionedPerson>;
|
||||||
topics?: Array<string>;
|
|
||||||
keywords?: Array<string>;
|
keywords?: Array<string>;
|
||||||
|
topics?: Array<MatchedTopic>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
import { WorkPurpose } from './workPurpose';
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the purpose of a specific work, including its ID, purpose, and optional reasoning.
|
||||||
|
*/
|
||||||
|
export interface SpecificWorkPurpose {
|
||||||
|
/**
|
||||||
|
* The raw OpenAlex work id.
|
||||||
|
*/
|
||||||
|
raw_oa_work_id: string;
|
||||||
|
publication_year?: number | null;
|
||||||
|
/**
|
||||||
|
* The purpose of the work.
|
||||||
|
*/
|
||||||
|
purpose: WorkPurpose;
|
||||||
|
reasoning?: string | null;
|
||||||
|
}
|
||||||
|
export namespace SpecificWorkPurpose {
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
/**
|
||||||
|
* 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 TopInstitutionItem {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
ror?: string | null;
|
||||||
|
country_code?: string | null;
|
||||||
|
type?: string | null;
|
||||||
|
lineage?: Array<string> | null;
|
||||||
|
works_count?: number | null;
|
||||||
|
exact_topic_count?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
/**
|
||||||
|
* 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 TopicYearlyData {
|
||||||
|
year: number;
|
||||||
|
raw: number;
|
||||||
|
normalized: number;
|
||||||
|
cumulative: number;
|
||||||
|
institutions_count: number;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
import { TrendSeries } from './trendSeries';
|
||||||
|
|
||||||
|
|
||||||
|
export interface TrendResponse {
|
||||||
|
series: Array<TrendSeries>;
|
||||||
|
years: Array<number>;
|
||||||
|
location_mappings?: { [key: string]: Array<string>; } | null;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
import { TopicYearlyData } from './topicYearlyData';
|
||||||
|
|
||||||
|
|
||||||
|
export interface TrendSeries {
|
||||||
|
entity_id: string;
|
||||||
|
entity_name: string;
|
||||||
|
entity_type: TrendSeries.EntityTypeEnum;
|
||||||
|
country_code?: string | null;
|
||||||
|
topic_data: { [key: string]: Array<TopicYearlyData>; };
|
||||||
|
}
|
||||||
|
export namespace TrendSeries {
|
||||||
|
export const EntityTypeEnum = {
|
||||||
|
Institution: 'institution',
|
||||||
|
Country: 'country',
|
||||||
|
Region: 'region'
|
||||||
|
} as const;
|
||||||
|
export type EntityTypeEnum = typeof EntityTypeEnum[keyof typeof EntityTypeEnum];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -8,21 +8,12 @@
|
|||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
import { YearlyData } from './yearlyData';
|
import { YearlyData } from './yearlyData';
|
||||||
|
import { Topic } from './topic';
|
||||||
|
|
||||||
|
|
||||||
export interface UniversityTopicData {
|
export interface UniversityTopicData {
|
||||||
university: string;
|
university: string;
|
||||||
topic: UniversityTopicData.TopicEnum;
|
topic: Topic;
|
||||||
yearly_data: Array<YearlyData>;
|
yearly_data: Array<YearlyData>;
|
||||||
}
|
}
|
||||||
export namespace UniversityTopicData {
|
|
||||||
export const TopicEnum = {
|
|
||||||
ArtificialIntelligence: 'Artificial Intelligence',
|
|
||||||
QuantumComputing: 'Quantum Computing',
|
|
||||||
RenewableEnergy: 'Renewable Energy',
|
|
||||||
Biotechnology: 'Biotechnology'
|
|
||||||
} as const;
|
|
||||||
export type TopicEnum = typeof TopicEnum[keyof typeof TopicEnum];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the purpose of a work. Either a foundation work or an application work.
|
||||||
|
*/
|
||||||
|
export const WorkPurpose = {
|
||||||
|
Foundation: 'Foundation',
|
||||||
|
Application: 'Application'
|
||||||
|
} as const;
|
||||||
|
export type WorkPurpose = typeof WorkPurpose[keyof typeof WorkPurpose];
|
||||||
|
|
||||||
@@ -19,6 +19,7 @@ import { WorkTopicField } from './workTopicField';
|
|||||||
export interface WorkTopic {
|
export interface WorkTopic {
|
||||||
id?: string | null;
|
id?: string | null;
|
||||||
display_name?: string | null;
|
display_name?: string | null;
|
||||||
|
description?: string | null;
|
||||||
score?: Score | null;
|
score?: Score | null;
|
||||||
subfield?: WorkTopicSubfield | null;
|
subfield?: WorkTopicSubfield | null;
|
||||||
field?: WorkTopicField | null;
|
field?: WorkTopicField | null;
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { Routes } from '@angular/router';
|
import { Routes } from '@angular/router';
|
||||||
import { userGuard } from './shared/guards/user.guard';
|
import { userGuard } from './shared/guards/user.guard';
|
||||||
import { superAdminGuard } from './shared/guards/super-admin.guard';
|
import { superAdminGuard } from './shared/guards/super-admin.guard';
|
||||||
|
import { guestOnlyGuard } from './shared/guards/guest-only.guard';
|
||||||
import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver';
|
import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver';
|
||||||
import { personListResolver } from './resolvers/person-list.resolver';
|
import { personListResolver } from './resolvers/person-list.resolver';
|
||||||
import { personBioResolver } from './resolvers/person-bio.resolver';
|
import { personBioResolver } from './resolvers/person-bio.resolver';
|
||||||
import { personResolver } from './resolvers/person.resolver';
|
import { personResolver } from './resolvers/person.resolver';
|
||||||
|
import { personNewsResolver } from './resolvers/person-news.resolver';
|
||||||
import { institutionResolver } from './resolvers/institution.resolver';
|
import { institutionResolver } from './resolvers/institution.resolver';
|
||||||
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
|
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
|
||||||
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
|
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
|
||||||
@@ -22,7 +24,12 @@ import { accountViewerGuard } from './shared/guards/account-viewer.guard';
|
|||||||
import { accountsPageResolver } from './resolvers/accounts-page.resolver';
|
import { accountsPageResolver } from './resolvers/accounts-page.resolver';
|
||||||
import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver';
|
import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver';
|
||||||
import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver';
|
import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver';
|
||||||
|
import { KeywordsToPersonsResultsComponent } from './modules/keywords-search/search-results/persons-results/persons-results.component';
|
||||||
|
import { KeywordsToProjectsResultsComponent } from './modules/keywords-search/search-results/projects-results/projects-results.component';
|
||||||
|
import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/search-results/patents-results/patents-results.component';
|
||||||
|
import { KeywordsToNewsResultsComponent } from './modules/keywords-search/search-results/news-results/news-results.component';
|
||||||
|
import { KeywordsToWorksResultsComponent } from './modules/keywords-search/search-results/works-results/works-results.component';
|
||||||
|
import { authorWorkPurposesResolver } from './resolvers/author-work-purposes.resolver';
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
@@ -37,10 +44,19 @@ export const routes: Routes = [
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'register',
|
path: 'forgot-password',
|
||||||
|
canActivate: [guestOnlyGuard],
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./modules/app-register/app-register.component').then(
|
import('./modules/forgot-password/forgot-password.component').then(
|
||||||
(mod) => mod.AppRegisterComponent,
|
(mod) => mod.ForgotPasswordComponent,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'reset-password',
|
||||||
|
canActivate: [guestOnlyGuard],
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./modules/reset-password/reset-password.component').then(
|
||||||
|
(mod) => mod.ResetPasswordComponent,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -92,6 +108,21 @@ export const routes: Routes = [
|
|||||||
(mod) => mod.KeywordsSearchComponent,
|
(mod) => mod.KeywordsSearchComponent,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'keywords/search-results',
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./modules/keywords-search/search-results/search-results.component').then(
|
||||||
|
(mod) => mod.KeywordsSearchResultsComponent,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
{ path: '', pathMatch: 'full', redirectTo: 'persons' },
|
||||||
|
{ path: 'persons', component: KeywordsToPersonsResultsComponent },
|
||||||
|
{ path: 'projects', component: KeywordsToProjectsResultsComponent },
|
||||||
|
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
|
||||||
|
{ path: 'works', component: KeywordsToWorksResultsComponent },
|
||||||
|
{ path: 'news', component: KeywordsToNewsResultsComponent },
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'news',
|
path: 'news',
|
||||||
canActivate: [userGuard],
|
canActivate: [userGuard],
|
||||||
@@ -238,6 +269,9 @@ export const routes: Routes = [
|
|||||||
import('./modules/person-publications/person-publications.component').then(
|
import('./modules/person-publications/person-publications.component').then(
|
||||||
(mod) => mod.PersonPublicationsComponent,
|
(mod) => mod.PersonPublicationsComponent,
|
||||||
),
|
),
|
||||||
|
resolve: {
|
||||||
|
authorWorkPurposes: authorWorkPurposesResolver,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'network',
|
path: 'network',
|
||||||
@@ -270,6 +304,23 @@ export const routes: Routes = [
|
|||||||
(mod) => mod.PersonFundingComponent,
|
(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',
|
path: 'patents',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
@@ -383,6 +434,20 @@ export const routes: Routes = [
|
|||||||
(mod) => mod.PatentsComponent,
|
(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',
|
path: 'error',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ export class SkTextDirective implements OnChanges {
|
|||||||
// measure natural width before blanking text
|
// measure natural width before blanking text
|
||||||
const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60);
|
const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60);
|
||||||
const height = 20;
|
const height = 20;
|
||||||
|
this.renderer.addClass(el, 'sk-text-loading');
|
||||||
this.renderer.setStyle(el, 'color', 'transparent');
|
this.renderer.setStyle(el, 'color', 'transparent');
|
||||||
this.renderer.setStyle(
|
this.renderer.setStyle(
|
||||||
el,
|
el,
|
||||||
@@ -47,10 +48,17 @@ export class SkTextDirective implements OnChanges {
|
|||||||
this.renderer.setStyle(el, 'min-width', `${width}px`);
|
this.renderer.setStyle(el, 'min-width', `${width}px`);
|
||||||
this.renderer.setStyle(el, 'max-height', `${height}px`);
|
this.renderer.setStyle(el, 'max-height', `${height}px`);
|
||||||
this.renderer.setStyle(el, 'display', 'inline-block');
|
this.renderer.setStyle(el, 'display', 'inline-block');
|
||||||
|
this.renderer.setStyle(el, 'overflow', 'hidden');
|
||||||
|
this.renderer.setStyle(el, 'pointer-events', 'none');
|
||||||
|
|
||||||
|
Array.from(el.children).forEach((child) => {
|
||||||
|
this.renderer.setStyle(child, 'visibility', 'hidden');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private hideSkeleton() {
|
private hideSkeleton() {
|
||||||
const el: HTMLElement = this.el.nativeElement;
|
const el: HTMLElement = this.el.nativeElement;
|
||||||
|
this.renderer.removeClass(el, 'sk-text-loading');
|
||||||
this.renderer.removeStyle(el, 'color');
|
this.renderer.removeStyle(el, 'color');
|
||||||
this.renderer.removeStyle(el, 'background');
|
this.renderer.removeStyle(el, 'background');
|
||||||
this.renderer.removeStyle(el, 'background-size');
|
this.renderer.removeStyle(el, 'background-size');
|
||||||
@@ -59,5 +67,11 @@ export class SkTextDirective implements OnChanges {
|
|||||||
this.renderer.removeStyle(el, 'min-width');
|
this.renderer.removeStyle(el, 'min-width');
|
||||||
this.renderer.removeStyle(el, 'max-height');
|
this.renderer.removeStyle(el, 'max-height');
|
||||||
this.renderer.removeStyle(el, 'display');
|
this.renderer.removeStyle(el, 'display');
|
||||||
|
this.renderer.removeStyle(el, 'overflow');
|
||||||
|
this.renderer.removeStyle(el, 'pointer-events');
|
||||||
|
|
||||||
|
Array.from(el.children).forEach((child) => {
|
||||||
|
this.renderer.removeStyle(child, 'visibility');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,7 +63,13 @@
|
|||||||
[formField]="changePasswordForm.showPasswords"
|
[formField]="changePasswordForm.showPasswords"
|
||||||
>Passwörter anzeigen</mat-slide-toggle
|
>Passwörter anzeigen</mat-slide-toggle
|
||||||
>
|
>
|
||||||
<button mat-raised-button color="primary" type="submit">
|
<button
|
||||||
|
mat-raised-button
|
||||||
|
color="primary"
|
||||||
|
type="submit"
|
||||||
|
[disabled]="
|
||||||
|
changePasswordForm().invalid() || changePasswordForm().submitting()
|
||||||
|
">
|
||||||
Passwort ändern
|
Passwort ändern
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { MatButtonModule } from '@angular/material/button';
|
|||||||
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
|
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
|
||||||
import { CredentialService } from '../../shared/services/credential.service';
|
import { CredentialService } from '../../shared/services/credential.service';
|
||||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
|
||||||
interface ChangePasswordForm {
|
interface ChangePasswordForm {
|
||||||
oldPassword: string;
|
oldPassword: string;
|
||||||
@@ -62,6 +63,7 @@ export class AccountComponent {
|
|||||||
|
|
||||||
private readonly _credentialService = inject(CredentialService);
|
private readonly _credentialService = inject(CredentialService);
|
||||||
private readonly _snackBar = inject(MatSnackBar);
|
private readonly _snackBar = inject(MatSnackBar);
|
||||||
|
private readonly _router = inject(Router);
|
||||||
|
|
||||||
roles: UserRole[] = [];
|
roles: UserRole[] = [];
|
||||||
|
|
||||||
@@ -143,21 +145,36 @@ export class AccountComponent {
|
|||||||
const newPassword = field.newPassword().value().trim();
|
const newPassword = field.newPassword().value().trim();
|
||||||
|
|
||||||
if (!oldPassword || !newPassword) {
|
if (!oldPassword || !newPassword) {
|
||||||
return;
|
return {} as any;
|
||||||
}
|
|
||||||
try {
|
|
||||||
await this._credentialService.changePassword(
|
|
||||||
oldPassword,
|
|
||||||
newPassword,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error changing password:', error);
|
|
||||||
this._snackBar.open(
|
|
||||||
'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.',
|
|
||||||
'OK',
|
|
||||||
{ duration: 7000 },
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
this._credentialService
|
||||||
|
.changePassword(oldPassword, newPassword)
|
||||||
|
.subscribe({
|
||||||
|
next: () => {
|
||||||
|
this._credentialService.refreshAccessToken().subscribe({
|
||||||
|
next: () => {
|
||||||
|
this._router.navigate(['/dashboard']);
|
||||||
|
},
|
||||||
|
error: (error) => {
|
||||||
|
this._snackBar.open(
|
||||||
|
'Fehler beim Aktualisieren des Zugriffstokens. Bitte melden Sie sich erneut an.',
|
||||||
|
'OK',
|
||||||
|
{ duration: 7000 },
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
error: (error) => {
|
||||||
|
console.error('Error changing password:', error);
|
||||||
|
this._snackBar.open(
|
||||||
|
'Fehler beim Ändern des Passworts. Bitte versuchen Sie es erneut.',
|
||||||
|
'OK',
|
||||||
|
{ duration: 7000 },
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {} as any;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -46,11 +46,7 @@
|
|||||||
|
|
||||||
<mat-form-field appearance="outline">
|
<mat-form-field appearance="outline">
|
||||||
<mat-label>
|
<mat-label>
|
||||||
{{
|
{{ data.mode === 'create' ? 'Initiales Passwort' : 'Neues Passwort' }}
|
||||||
data.mode === 'create'
|
|
||||||
? 'Initiales Passwort'
|
|
||||||
: 'Neues Passwort'
|
|
||||||
}}
|
|
||||||
</mat-label>
|
</mat-label>
|
||||||
<input matInput type="password" formControlName="password" />
|
<input matInput type="password" formControlName="password" />
|
||||||
@if (form.controls.password.hasError('required')) {
|
@if (form.controls.password.hasError('required')) {
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ import { StatusPipe } from '../../shared/pipes/status.pipe';
|
|||||||
QueryParamInputComponent,
|
QueryParamInputComponent,
|
||||||
QueryParamSelectorComponent,
|
QueryParamSelectorComponent,
|
||||||
MatCardModule,
|
MatCardModule,
|
||||||
StatusPipe
|
StatusPipe,
|
||||||
],
|
],
|
||||||
templateUrl: './accounts.component.html',
|
templateUrl: './accounts.component.html',
|
||||||
styleUrl: './accounts.component.scss',
|
styleUrl: './accounts.component.scss',
|
||||||
|
|||||||
@@ -53,9 +53,13 @@
|
|||||||
mat-icon-button
|
mat-icon-button
|
||||||
matSuffix
|
matSuffix
|
||||||
type="button"
|
type="button"
|
||||||
[attr.aria-label]="showPassword ? 'Passwort verbergen' : 'Passwort anzeigen'"
|
[attr.aria-label]="
|
||||||
|
showPassword ? 'Passwort verbergen' : 'Passwort anzeigen'
|
||||||
|
"
|
||||||
(click)="showPassword = !showPassword">
|
(click)="showPassword = !showPassword">
|
||||||
<mat-icon>{{ showPassword ? 'visibility' : 'visibility_off' }}</mat-icon>
|
<mat-icon>{{
|
||||||
|
showPassword ? 'visibility' : 'visibility_off'
|
||||||
|
}}</mat-icon>
|
||||||
</button>
|
</button>
|
||||||
@if (credentialsForm.controls.password.hasError('required')) {
|
@if (credentialsForm.controls.password.hasError('required')) {
|
||||||
<mat-error>Passwort ist erforderlich.</mat-error>
|
<mat-error>Passwort ist erforderlich.</mat-error>
|
||||||
@@ -78,8 +82,10 @@
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div class="form-actions">
|
<div class="form-actions">
|
||||||
<a routerLink="/login">Passwort vergessen?</a>
|
<span></span>
|
||||||
<a routerLink="/register">Konto erstellen</a>
|
<a class="auth-link" routerLink="/forgot-password"
|
||||||
|
>Passwort vergessen?</a
|
||||||
|
>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
} @else {
|
} @else {
|
||||||
@@ -90,7 +96,9 @@
|
|||||||
<strong>Code eingeben</strong>
|
<strong>Code eingeben</strong>
|
||||||
<span>
|
<span>
|
||||||
Wir haben den Code an
|
Wir haben den Code an
|
||||||
{{ credentialsForm.controls.email.value || 'Deine E-Mail-Adresse' }}
|
{{
|
||||||
|
credentialsForm.controls.email.value || 'Deine E-Mail-Adresse'
|
||||||
|
}}
|
||||||
gesendet.
|
gesendet.
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,7 +4,11 @@
|
|||||||
place-items: center;
|
place-items: center;
|
||||||
padding: 48px 20px;
|
padding: 48px 20px;
|
||||||
background:
|
background:
|
||||||
radial-gradient(circle at top left, rgba(61, 124, 255, 0.12), transparent 34%),
|
radial-gradient(
|
||||||
|
circle at top left,
|
||||||
|
rgba(61, 124, 255, 0.12),
|
||||||
|
transparent 34%
|
||||||
|
),
|
||||||
linear-gradient(160deg, #f7f9ff 0%, #ffffff 64%);
|
linear-gradient(160deg, #f7f9ff 0%, #ffffff 64%);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { MatInputModule } from '@angular/material/input';
|
|||||||
import { CredentialService } from '../../shared/services/credential.service';
|
import { CredentialService } from '../../shared/services/credential.service';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { Subscription } from 'rxjs';
|
import { finalize, Subscription } from 'rxjs';
|
||||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||||
import { Router, RouterLink } from '@angular/router';
|
import { Router, RouterLink } from '@angular/router';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
@@ -103,35 +103,39 @@ export class AppLoginComponent implements OnDestroy {
|
|||||||
const email = this.credentialsForm.controls.email.value ?? '';
|
const email = this.credentialsForm.controls.email.value ?? '';
|
||||||
const password = this.credentialsForm.controls.password.value ?? '';
|
const password = this.credentialsForm.controls.password.value ?? '';
|
||||||
|
|
||||||
this.credentialService.requestOtk(email, password).subscribe({
|
this.credentialService
|
||||||
next: (otkResponse) => {
|
.requestOtk(email, password)
|
||||||
const accountId = otkResponse.account_id;
|
.pipe(
|
||||||
this.accountId = accountId;
|
finalize(() => {
|
||||||
this.currentStep = 'otk';
|
this.isSubmitting = false;
|
||||||
this.otkForm.reset();
|
this.credentialsForm.enable();
|
||||||
this.startCountdown();
|
}),
|
||||||
this.snackBar.open(
|
)
|
||||||
'OTK-Code wurde an die E-Mail-Adresse gesendet.',
|
.subscribe({
|
||||||
'OK',
|
next: (otkResponse) => {
|
||||||
{
|
const accountId = otkResponse.account_id;
|
||||||
duration: 4000,
|
this.accountId = accountId;
|
||||||
},
|
this.currentStep = 'otk';
|
||||||
);
|
this.otkForm.reset();
|
||||||
},
|
this.startCountdown();
|
||||||
error: (error: unknown) => {
|
this.snackBar.open(
|
||||||
this.snackBar.open(
|
'OTK-Code wurde an die E-Mail-Adresse gesendet.',
|
||||||
this.getLoginErrorMessage(error as HttpErrorResponse),
|
'OK',
|
||||||
'OK',
|
{
|
||||||
{
|
duration: 4000,
|
||||||
duration: 5000,
|
},
|
||||||
},
|
);
|
||||||
);
|
},
|
||||||
},
|
error: (error: unknown) => {
|
||||||
complete: () => {
|
this.snackBar.open(
|
||||||
this.isSubmitting = false;
|
this.getLoginErrorMessage(error as HttpErrorResponse),
|
||||||
this.credentialsForm.enable();
|
'OK',
|
||||||
},
|
{
|
||||||
});
|
duration: 5000,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
resendCode() {
|
resendCode() {
|
||||||
@@ -169,30 +173,34 @@ export class AppLoginComponent implements OnDestroy {
|
|||||||
|
|
||||||
const code = this.otkForm.controls.code.value ?? '';
|
const code = this.otkForm.controls.code.value ?? '';
|
||||||
|
|
||||||
this.credentialService.loginWithOtk(this.accountId, code).subscribe({
|
this.credentialService
|
||||||
next: () => {
|
.loginWithOtk(this.accountId, code)
|
||||||
this.credentialService.reauthenticateViaIdToken().subscribe({
|
.pipe(
|
||||||
next: () => {
|
finalize(() => {
|
||||||
this.checkEnter();
|
this.isSubmitting = false;
|
||||||
this.stopCountdown();
|
this.otkForm.enable();
|
||||||
this.router.navigate(['/dashboard']);
|
}),
|
||||||
},
|
)
|
||||||
});
|
.subscribe({
|
||||||
},
|
next: () => {
|
||||||
error: (error: unknown) => {
|
this.credentialService.reauthenticateViaIdToken().subscribe({
|
||||||
this.snackBar.open(
|
next: () => {
|
||||||
this.getLoginErrorMessage(error as HttpErrorResponse),
|
this.checkEnter();
|
||||||
'OK',
|
this.stopCountdown();
|
||||||
{
|
this.router.navigate(['/dashboard']);
|
||||||
duration: 5000,
|
},
|
||||||
},
|
});
|
||||||
);
|
},
|
||||||
},
|
error: (error: unknown) => {
|
||||||
complete: () => {
|
this.snackBar.open(
|
||||||
this.isSubmitting = false;
|
this.getLoginErrorMessage(error as HttpErrorResponse),
|
||||||
this.otkForm.enable();
|
'OK',
|
||||||
},
|
{
|
||||||
});
|
duration: 5000,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
editCredentials() {
|
editCredentials() {
|
||||||
|
|||||||
@@ -1,100 +0,0 @@
|
|||||||
<div class="container">
|
|
||||||
<form class="form" [formGroup]="registerForm">
|
|
||||||
<h3>Konto erstellen</h3>
|
|
||||||
<p class="field">Bitte gib Deine Daten ein, um Dich zu registrieren.</p>
|
|
||||||
|
|
||||||
<mat-form-field class="field">
|
|
||||||
<mat-label>Benutzername</mat-label>
|
|
||||||
<input matInput formControlName="username" />
|
|
||||||
@if (registerForm.controls['username'].hasError('required')) {
|
|
||||||
<mat-error>Fehler: <b>Benutzername</b> erforderlich.</mat-error>
|
|
||||||
} @else if (registerForm.controls['username'].hasError('minlength')) {
|
|
||||||
<mat-error>Fehler: <b>Benutzername</b> ist unvollständig.</mat-error>
|
|
||||||
}
|
|
||||||
</mat-form-field>
|
|
||||||
|
|
||||||
<mat-form-field class="field">
|
|
||||||
<mat-label>E-Mail</mat-label>
|
|
||||||
<input matInput type="email" formControlName="email" />
|
|
||||||
@if (registerForm.controls['email'].hasError('required')) {
|
|
||||||
<mat-error>Fehler: <b>E-Mail</b> erforderlich.</mat-error>
|
|
||||||
} @else if (registerForm.controls['email'].hasError('email')) {
|
|
||||||
<mat-error>Fehler: Ungültige <b>E-Mail</b> Adresse.</mat-error>
|
|
||||||
}
|
|
||||||
</mat-form-field>
|
|
||||||
|
|
||||||
<mat-form-field class="field">
|
|
||||||
<mat-label>Passwort</mat-label>
|
|
||||||
<input
|
|
||||||
matInput
|
|
||||||
[type]="showPassword ? 'text' : 'password'"
|
|
||||||
formControlName="password" />
|
|
||||||
@if (showPassword) {
|
|
||||||
<mat-icon matSuffix (click)="showPassword = false">visibility</mat-icon>
|
|
||||||
} @else {
|
|
||||||
<mat-icon matSuffix (click)="showPassword = true"
|
|
||||||
>visibility_off</mat-icon
|
|
||||||
>
|
|
||||||
}
|
|
||||||
@if (registerForm.controls['password'].hasError('required')) {
|
|
||||||
<mat-error>Fehler: <b>Passwort</b> erforderlich.</mat-error>
|
|
||||||
} @else if (registerForm.controls['password'].hasError('minlength')) {
|
|
||||||
<mat-error>Fehler: <b>Passwort</b> ist unvollständig.</mat-error>
|
|
||||||
}
|
|
||||||
</mat-form-field>
|
|
||||||
|
|
||||||
<mat-form-field class="field">
|
|
||||||
<mat-label>Institution</mat-label>
|
|
||||||
|
|
||||||
<mat-icon matPrefix>apartment</mat-icon>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
matInput
|
|
||||||
formControlName="institution"
|
|
||||||
[matAutocomplete]="auto"
|
|
||||||
placeholder="Institution suchen..." />
|
|
||||||
@if (registerForm.controls['institution'].hasError('required')) {
|
|
||||||
<mat-error>Fehler: <b>Institution</b> erforderlich.</mat-error>
|
|
||||||
}
|
|
||||||
<mat-autocomplete
|
|
||||||
#auto="matAutocomplete"
|
|
||||||
(optionSelected)="onInstitutionSelected($event)">
|
|
||||||
@for (institution of institutionOptions(); track institution.id) {
|
|
||||||
<mat-option
|
|
||||||
[value]="institution.display_name"
|
|
||||||
style="font-size: 16px">
|
|
||||||
<div>
|
|
||||||
<span>{{ institution.display_name }}</span>
|
|
||||||
</div>
|
|
||||||
@if (institution.hint) {
|
|
||||||
<small>{{ institution.hint }}</small>
|
|
||||||
}
|
|
||||||
</mat-option>
|
|
||||||
}
|
|
||||||
</mat-autocomplete>
|
|
||||||
</mat-form-field>
|
|
||||||
|
|
||||||
<div class="field checkbox-container">
|
|
||||||
<mat-checkbox formControlName="superadmin"
|
|
||||||
>Superadmin Rechte</mat-checkbox
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
mat-raised-button
|
|
||||||
class="button"
|
|
||||||
(click)="submit()"
|
|
||||||
[disabled]="!registerForm.valid || credentialService.isValidating()">
|
|
||||||
Registrieren
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div class="field" style="text-align: center; margin-top: -10px">
|
|
||||||
<button mat-button type="button" routerLink="/login">
|
|
||||||
Bereits ein Konto? <b>Anmelden</b>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
<p class="progress">
|
|
||||||
<!-- Statusanzeige analog zum Login-Formular -->
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
.container {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
background: linear-gradient(160deg, #f4f6fb, #e8ecf7);
|
|
||||||
}
|
|
||||||
|
|
||||||
.form {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
background: #fff;
|
|
||||||
border: none;
|
|
||||||
border-radius: 12px;
|
|
||||||
box-shadow:
|
|
||||||
0 2px 12px #1a3a6e1a,
|
|
||||||
0 1px 4px #0000000f;
|
|
||||||
gap: 20px;
|
|
||||||
padding: 36px 32px 28px;
|
|
||||||
|
|
||||||
h3 {
|
|
||||||
margin: 0 0 4px;
|
|
||||||
font-weight: 600;
|
|
||||||
color: #1a3a6e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.button {
|
|
||||||
min-height: 48px;
|
|
||||||
min-width: 140px;
|
|
||||||
border-radius: 8px;
|
|
||||||
font-weight: 500;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.field {
|
|
||||||
width: 400px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.checkbox-container {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: flex-start;
|
|
||||||
}
|
|
||||||
|
|
||||||
.progress {
|
|
||||||
padding-top: 5px;
|
|
||||||
width: 300px;
|
|
||||||
height: 2em;
|
|
||||||
text-align: center;
|
|
||||||
font-size: small;
|
|
||||||
color: #585f71;
|
|
||||||
}
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
import {
|
|
||||||
Component,
|
|
||||||
inject,
|
|
||||||
OnDestroy,
|
|
||||||
signal,
|
|
||||||
DestroyRef,
|
|
||||||
effect,
|
|
||||||
} from '@angular/core';
|
|
||||||
import { CommonModule } from '@angular/common';
|
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
||||||
import { Router, RouterLink } from '@angular/router';
|
|
||||||
import {
|
|
||||||
FormBuilder,
|
|
||||||
FormGroup,
|
|
||||||
ReactiveFormsModule,
|
|
||||||
Validators,
|
|
||||||
} from '@angular/forms';
|
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
|
||||||
import { MatInputModule } from '@angular/material/input';
|
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
|
||||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
|
||||||
import { CredentialService } from '../../shared/services/credential.service';
|
|
||||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
|
||||||
import {
|
|
||||||
Subscription,
|
|
||||||
map,
|
|
||||||
switchMap,
|
|
||||||
debounceTime,
|
|
||||||
distinctUntilChanged,
|
|
||||||
catchError,
|
|
||||||
of,
|
|
||||||
} from 'rxjs';
|
|
||||||
import {
|
|
||||||
MatAutocompleteModule,
|
|
||||||
MatAutocompleteSelectedEvent,
|
|
||||||
} from '@angular/material/autocomplete';
|
|
||||||
import { InstitutionsService } from '../../api';
|
|
||||||
@Component({
|
|
||||||
selector: 'app-register',
|
|
||||||
standalone: true,
|
|
||||||
imports: [
|
|
||||||
CommonModule,
|
|
||||||
ReactiveFormsModule,
|
|
||||||
MatButtonModule,
|
|
||||||
MatFormFieldModule,
|
|
||||||
MatInputModule,
|
|
||||||
MatIconModule,
|
|
||||||
MatCheckboxModule,
|
|
||||||
RouterLink,
|
|
||||||
MatSnackBarModule,
|
|
||||||
MatAutocompleteModule,
|
|
||||||
],
|
|
||||||
templateUrl: './app-register.component.html',
|
|
||||||
styleUrl: './app-register.component.scss',
|
|
||||||
})
|
|
||||||
export class AppRegisterComponent implements OnDestroy {
|
|
||||||
private readonly fb = inject(FormBuilder);
|
|
||||||
protected readonly credentialService = inject(CredentialService);
|
|
||||||
private readonly router = inject(Router);
|
|
||||||
private readonly snackBar = inject(MatSnackBar);
|
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
|
||||||
private subscription?: Subscription;
|
|
||||||
private institutionsService = inject(InstitutionsService);
|
|
||||||
registerForm: FormGroup = this.fb.group({
|
|
||||||
username: ['', [Validators.required, Validators.minLength(4)]],
|
|
||||||
email: ['', [Validators.required, Validators.email]],
|
|
||||||
password: ['', [Validators.required, Validators.minLength(8)]],
|
|
||||||
institution: ['', [Validators.required]],
|
|
||||||
superadmin: [false],
|
|
||||||
});
|
|
||||||
readonly institutionOptions = signal<any[]>([]);
|
|
||||||
showPassword = false;
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
effect(() => {
|
|
||||||
if (this.credentialService.isValidating()) {
|
|
||||||
this.registerForm.disable();
|
|
||||||
} else {
|
|
||||||
this.registerForm.enable();
|
|
||||||
this.checkEnter();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.setupInstitutionAutocomplete();
|
|
||||||
}
|
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
this.subscription?.unsubscribe();
|
|
||||||
}
|
|
||||||
|
|
||||||
checkEnter(): void {
|
|
||||||
if (this.credentialService.isAuthenticated()) {
|
|
||||||
this.router.navigate(['/dashboard']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
submit() {
|
|
||||||
if (this.registerForm.valid) {
|
|
||||||
this.credentialService.isValidating.set(true);
|
|
||||||
this.registerForm.disable();
|
|
||||||
|
|
||||||
this.subscription = this.credentialService
|
|
||||||
.registerAccount(this.registerForm.value)
|
|
||||||
.subscribe({
|
|
||||||
next: () => {
|
|
||||||
this.credentialService.isValidating.set(false);
|
|
||||||
this.snackBar.open(
|
|
||||||
'Konto erfolgreich erstellt! Du kannst Dich jetzt anmelden.',
|
|
||||||
'OK',
|
|
||||||
{ duration: 5000 },
|
|
||||||
);
|
|
||||||
this.router.navigate(['/login']);
|
|
||||||
},
|
|
||||||
error: (err) => {
|
|
||||||
this.credentialService.isValidating.set(false);
|
|
||||||
this.registerForm.enable();
|
|
||||||
const message =
|
|
||||||
err.error?.message ||
|
|
||||||
'Fehler bei der Registrierung. Bitte versuche es später erneut.';
|
|
||||||
this.snackBar.open(message, 'Schließen', {
|
|
||||||
panelClass: ['error-snackbar'],
|
|
||||||
duration: 5000,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private setupInstitutionAutocomplete(): void {
|
|
||||||
this.registerForm.controls['institution'].valueChanges
|
|
||||||
.pipe(
|
|
||||||
debounceTime(250),
|
|
||||||
map((value) => (typeof value === 'string' ? value.trim() : '')),
|
|
||||||
distinctUntilChanged(),
|
|
||||||
switchMap((query) => {
|
|
||||||
if (query.length < 2) {
|
|
||||||
this.institutionOptions.set([]);
|
|
||||||
return of([]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.searchInstitutions(query).pipe(
|
|
||||||
catchError((ev) => {
|
|
||||||
console.log(ev);
|
|
||||||
return of([]);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
takeUntilDestroyed(this.destroyRef),
|
|
||||||
)
|
|
||||||
.subscribe((options) => {
|
|
||||||
this.institutionOptions.set(options);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private searchInstitutions(query: string) {
|
|
||||||
return this.institutionsService
|
|
||||||
.autocompleteInstitutions(query, undefined, undefined, 10)
|
|
||||||
.pipe(map((response) => response.results ?? []));
|
|
||||||
}
|
|
||||||
|
|
||||||
onInstitutionSelected(event: MatAutocompleteSelectedEvent): void {
|
|
||||||
const val = event.option.value;
|
|
||||||
this.registerForm.controls['institution'].setValue(val, {
|
|
||||||
emitEvent: false,
|
|
||||||
});
|
|
||||||
this.institutionOptions.set([]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,9 @@
|
|||||||
<header class="dashboard-header">
|
<header class="dashboard-header">
|
||||||
<h2>University Performance Dashboard</h2>
|
<h2>University Performance Dashboard</h2>
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
<select (change)="onTopicChange($any($event.target).value)">
|
<select
|
||||||
|
[value]="selectedTopic"
|
||||||
|
(change)="onTopicChange($any($event.target).value)">
|
||||||
@for (t of topics; track t) {
|
@for (t of topics; track t) {
|
||||||
<option [value]="t">{{ t }}</option>
|
<option [value]="t">{{ t }}</option>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, inject, OnInit } from '@angular/core';
|
||||||
import { UniversityRankingService } from '../university-ranking/services/uni-ranking-service';
|
|
||||||
import { UniversityLineChartComponent } from '../university-ranking/uni-line-chart/uni-line-chart.component';
|
import { UniversityLineChartComponent } from '../university-ranking/uni-line-chart/uni-line-chart.component';
|
||||||
import { UniversityRankingTableComponent } from '../university-ranking/uni-ranking-table/uni-ranking-table.component';
|
import { UniversityRankingTableComponent } from '../university-ranking/uni-ranking-table/uni-ranking-table.component';
|
||||||
import { UniversityTopicData, UniversityRanking } from '../../api';
|
import {
|
||||||
export type ResearchTopic =
|
UniversityTopicData,
|
||||||
| 'Artificial Intelligence'
|
UniversityRanking,
|
||||||
| 'Quantum Computing'
|
UniversityRankingsService,
|
||||||
| 'Renewable Energy'
|
} from '../../api';
|
||||||
| 'Biotechnology';
|
|
||||||
|
export type ResearchTopic = string;
|
||||||
export type DashboardMetric = 'publications' | 'citations';
|
export type DashboardMetric = 'publications' | 'citations';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -17,21 +17,20 @@ export type DashboardMetric = 'publications' | 'citations';
|
|||||||
styleUrl: './dashboard.component.scss',
|
styleUrl: './dashboard.component.scss',
|
||||||
})
|
})
|
||||||
export class DashboardComponent implements OnInit {
|
export class DashboardComponent implements OnInit {
|
||||||
|
private readonly dataService = inject(UniversityRankingsService);
|
||||||
|
|
||||||
topics: ResearchTopic[] = [
|
topics: ResearchTopic[] = [
|
||||||
'Artificial Intelligence',
|
|
||||||
'Quantum Computing',
|
'Quantum Computing',
|
||||||
'Renewable Energy',
|
'Renewable Energy',
|
||||||
'Biotechnology',
|
'Artificial Intelligence and Decision Support Systems',
|
||||||
];
|
];
|
||||||
selectedTopic: ResearchTopic = 'Artificial Intelligence';
|
selectedTopic: ResearchTopic = 'Quantum Computing';
|
||||||
metric: DashboardMetric = 'publications';
|
metric: DashboardMetric = 'publications';
|
||||||
|
|
||||||
rawDataSource: UniversityTopicData[] = [];
|
rawDataSource: UniversityTopicData[] = [];
|
||||||
computedRankings: UniversityRanking[] = [];
|
computedRankings: UniversityRanking[] = [];
|
||||||
isLoading = false;
|
isLoading = false;
|
||||||
|
|
||||||
constructor(private dataService: UniversityRankingService) {}
|
|
||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.loadData();
|
this.loadData();
|
||||||
}
|
}
|
||||||
@@ -49,14 +48,21 @@ export class DashboardComponent implements OnInit {
|
|||||||
private loadData() {
|
private loadData() {
|
||||||
this.isLoading = true;
|
this.isLoading = true;
|
||||||
this.dataService
|
this.dataService
|
||||||
.getRankingData(this.selectedTopic, this.metric)
|
.getRankingsApiInseServiceUniversityRankingsGet(
|
||||||
.subscribe((response) => {
|
this.selectedTopic,
|
||||||
// Map backend snake_case properties to frontend camelCase if necessary,
|
this.metric,
|
||||||
// though OpenAPI Generator usually handles this.
|
)
|
||||||
console.log(response);
|
.subscribe({
|
||||||
this.rawDataSource = (response.timeseries as any) || [];
|
next: (response) => {
|
||||||
this.computedRankings = (response.rankings as any) || [];
|
this.rawDataSource = (response.timeseries as any) || [];
|
||||||
this.isLoading = false;
|
this.computedRankings = (response.rankings as any) || [];
|
||||||
|
this.isLoading = false;
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.rawDataSource = [];
|
||||||
|
this.computedRankings = [];
|
||||||
|
this.isLoading = false;
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
<section class="login-page">
|
||||||
|
<div class="login-panel">
|
||||||
|
<div class="brand-block">
|
||||||
|
<span class="eyebrow">SmartGuide Account Portal</span>
|
||||||
|
<h1>Passwort vergessen</h1>
|
||||||
|
<p>
|
||||||
|
Gib Deine E-Mail-Adresse ein. Wenn ein Konto existiert, senden wir Dir
|
||||||
|
einen Link zum Zurücksetzen des Passworts.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (emailSent()) {
|
||||||
|
<div class="login-form">
|
||||||
|
<div class="code-intro">
|
||||||
|
<mat-icon>
|
||||||
|
{{ rateLimited() ? 'hourglass_empty' : 'mark_email_unread' }}
|
||||||
|
</mat-icon>
|
||||||
|
<div>
|
||||||
|
@if (rateLimited()) {
|
||||||
|
<strong>Zu viele Anfragen</strong>
|
||||||
|
<span>
|
||||||
|
Es wurden bereits mehrere Links angefordert. Bitte prüfe Dein
|
||||||
|
Postfach oder versuche es in {{ retryAfterText() }} erneut.
|
||||||
|
</span>
|
||||||
|
} @else {
|
||||||
|
<strong>E-Mail wurde versendet</strong>
|
||||||
|
<span>
|
||||||
|
Falls ein Konto mit dieser E-Mail-Adresse existiert, wurde ein
|
||||||
|
Link zum Zurücksetzen des Passworts versendet. Bitte prüfe Dein
|
||||||
|
Postfach.
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (errorMessage()) {
|
||||||
|
<div class="code-intro">
|
||||||
|
<mat-icon>error_outline</mat-icon>
|
||||||
|
<div>
|
||||||
|
<strong>Fehler</strong>
|
||||||
|
<span>{{ errorMessage() }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="form-actions">
|
||||||
|
<a class="auth-link" routerLink="/login">Zurück zum Login</a>
|
||||||
|
|
||||||
|
<a
|
||||||
|
class="auth-link"
|
||||||
|
href="#"
|
||||||
|
(click)="$event.preventDefault(); requestPasswordResetAgain()">
|
||||||
|
E-Mail nicht bekommen?
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<form
|
||||||
|
class="login-form"
|
||||||
|
[formGroup]="form"
|
||||||
|
(ngSubmit)="requestPasswordReset()">
|
||||||
|
<mat-form-field class="field" appearance="outline">
|
||||||
|
<mat-label>E-Mail-Adresse</mat-label>
|
||||||
|
<input
|
||||||
|
matInput
|
||||||
|
type="email"
|
||||||
|
autocomplete="email"
|
||||||
|
formControlName="email" />
|
||||||
|
@if (form.controls.email.hasError('required')) {
|
||||||
|
<mat-error>E-Mail-Adresse ist erforderlich.</mat-error>
|
||||||
|
} @else if (form.controls.email.hasError('email')) {
|
||||||
|
<mat-error>Bitte gib eine gültige E-Mail-Adresse ein.</mat-error>
|
||||||
|
}
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
@if (errorMessage()) {
|
||||||
|
<div class="code-intro">
|
||||||
|
<mat-icon>error_outline</mat-icon>
|
||||||
|
<div>
|
||||||
|
<strong>Fehler</strong>
|
||||||
|
<span>{{ errorMessage() }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<button
|
||||||
|
mat-flat-button
|
||||||
|
color="primary"
|
||||||
|
class="submit-button"
|
||||||
|
type="submit"
|
||||||
|
[disabled]="form.invalid || isSubmitting()">
|
||||||
|
@if (isSubmitting()) {
|
||||||
|
Link wird gesendet...
|
||||||
|
} @else {
|
||||||
|
Link zum Zurücksetzen senden
|
||||||
|
}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div class="form-actions">
|
||||||
|
<a class="auth-link" routerLink="/login">Zurück zum Login</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import { Component, inject, signal } from '@angular/core';
|
||||||
|
import {
|
||||||
|
FormControl,
|
||||||
|
FormGroup,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
Validators,
|
||||||
|
} from '@angular/forms';
|
||||||
|
import { RouterLink } from '@angular/router';
|
||||||
|
import { finalize } from 'rxjs';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { MatInputModule } from '@angular/material/input';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { CredentialService } from '../../shared/services/credential.service';
|
||||||
|
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-forgot-password',
|
||||||
|
imports: [
|
||||||
|
ReactiveFormsModule,
|
||||||
|
RouterLink,
|
||||||
|
MatFormFieldModule,
|
||||||
|
MatInputModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatSnackBarModule,
|
||||||
|
],
|
||||||
|
templateUrl: './forgot-password.component.html',
|
||||||
|
styleUrl: '../app-login/app-login.component.scss',
|
||||||
|
standalone: true,
|
||||||
|
})
|
||||||
|
export class ForgotPasswordComponent {
|
||||||
|
private readonly credentialService = inject(CredentialService);
|
||||||
|
private readonly snackBar = inject(MatSnackBar);
|
||||||
|
|
||||||
|
form = new FormGroup({
|
||||||
|
email: new FormControl<string>('', [Validators.required, Validators.email]),
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly isSubmitting = signal(false);
|
||||||
|
readonly emailSent = signal(false);
|
||||||
|
readonly rateLimited = signal(false);
|
||||||
|
readonly retryAfterSeconds = signal<number | undefined>(undefined);
|
||||||
|
readonly requestedEmail = signal('');
|
||||||
|
readonly errorMessage = signal<string | undefined>(undefined);
|
||||||
|
|
||||||
|
requestPasswordReset(): void {
|
||||||
|
if (this.form.invalid || this.isSubmitting()) {
|
||||||
|
this.form.markAllAsTouched();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const email = this.form.controls.email.value ?? '';
|
||||||
|
this.sendPasswordResetRequest(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
requestPasswordResetAgain(): void {
|
||||||
|
const email = this.requestedEmail();
|
||||||
|
|
||||||
|
if (!email || this.isSubmitting()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.sendPasswordResetRequest(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
retryAfterText(): string {
|
||||||
|
const seconds = this.retryAfterSeconds();
|
||||||
|
|
||||||
|
if (!seconds) {
|
||||||
|
return 'einigen Minuten';
|
||||||
|
}
|
||||||
|
|
||||||
|
const minutes = Math.max(1, Math.ceil(seconds / 60));
|
||||||
|
return `${minutes} ${minutes === 1 ? 'Minute' : 'Minuten'}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendPasswordResetRequest(email: string): void {
|
||||||
|
const wasAlreadySent = this.emailSent();
|
||||||
|
|
||||||
|
this.isSubmitting.set(true);
|
||||||
|
this.errorMessage.set(undefined);
|
||||||
|
|
||||||
|
if (!wasAlreadySent) {
|
||||||
|
this.form.disable();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.credentialService
|
||||||
|
.requestPasswordReset(email)
|
||||||
|
.pipe(
|
||||||
|
finalize(() => {
|
||||||
|
this.isSubmitting.set(false);
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.subscribe({
|
||||||
|
next: (response) => {
|
||||||
|
this.requestedEmail.set(email);
|
||||||
|
this.emailSent.set(true);
|
||||||
|
|
||||||
|
this.rateLimited.set(response.rate_limited);
|
||||||
|
this.retryAfterSeconds.set(response.retry_after_seconds);
|
||||||
|
|
||||||
|
if (response.rate_limited) {
|
||||||
|
this.snackBar.open(
|
||||||
|
`Es wurden bereits mehrere Links angefordert. Bitte versuche es in ${this.retryAfterText()} erneut.`,
|
||||||
|
'OK',
|
||||||
|
{ duration: 7000 },
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasAlreadySent) {
|
||||||
|
this.snackBar.open(
|
||||||
|
'Wir haben Dir einen neuen Link zum Zurücksetzen des Passworts gesendet.',
|
||||||
|
'OK',
|
||||||
|
{ duration: 5000 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.errorMessage.set(
|
||||||
|
'Der Link zum Zurücksetzen des Passworts konnte nicht angefordert werden. Bitte versuche es später erneut.',
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!wasAlreadySent) {
|
||||||
|
this.form.enable();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.snackBar.open(
|
||||||
|
'Die Anfrage konnte nicht gesendet werden. Bitte versuche es später erneut.',
|
||||||
|
'OK',
|
||||||
|
{ duration: 7000 },
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -316,7 +316,10 @@
|
|||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: border-color 0.15s, background 0.15s, box-shadow 0.15s;
|
transition:
|
||||||
|
border-color 0.15s,
|
||||||
|
background 0.15s,
|
||||||
|
box-shadow 0.15s;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
border-color: #0b63ce;
|
border-color: #0b63ce;
|
||||||
|
|||||||
@@ -3,102 +3,89 @@
|
|||||||
|
|
||||||
<mat-divider />
|
<mat-divider />
|
||||||
|
|
||||||
<div class="search-and-sorting">
|
<app-card-search
|
||||||
<app-query-param-input
|
[page]="page()"
|
||||||
[label]="'Suche nach Namen'"
|
[cardMinWidth]="300"
|
||||||
[debounceTime]="400"
|
[cardTmp]="cardTmp"
|
||||||
[queryParamKey]="'search'" />
|
[cardMinWidth]="550"
|
||||||
|
searchLabel="Suche nach Namen"
|
||||||
<div class="sorting">
|
[sortingOptions]="sortingOptions"
|
||||||
<app-query-param-selector
|
[sortingDirectionOptions]="sortingDirectionOptions" />
|
||||||
[options]="sortingOptions"
|
|
||||||
[queryParamKey]="'sort_by'" />
|
|
||||||
|
|
||||||
<app-query-param-selector
|
|
||||||
[options]="sortingDirectionOptions"
|
|
||||||
[queryParamKey]="'sorting_order'" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<mat-divider />
|
|
||||||
|
|
||||||
@let institutionPageValue = institutionPage();
|
|
||||||
|
|
||||||
@if (
|
|
||||||
institutionPageValue.elements && institutionPageValue.elements.length > 0
|
|
||||||
) {
|
|
||||||
<div class="cards">
|
|
||||||
@for (institution of institutionPageValue.elements; track $index) {
|
|
||||||
@let institutionId = extractInstitutionId(institution);
|
|
||||||
<mat-card
|
|
||||||
class="card"
|
|
||||||
appearance="outlined"
|
|
||||||
[routerLink]="
|
|
||||||
institution.id
|
|
||||||
? ['/institution', institution.id.split('/').pop() ?? '']
|
|
||||||
: null
|
|
||||||
">
|
|
||||||
<mat-card-header>
|
|
||||||
<mat-card-title>{{ getDisplayName(institution) }}</mat-card-title>
|
|
||||||
<mat-card-subtitle
|
|
||||||
>{{ institution.geo?.city }},
|
|
||||||
{{ institution.geo?.country }}</mat-card-subtitle
|
|
||||||
>
|
|
||||||
</mat-card-header>
|
|
||||||
|
|
||||||
<mat-card-content class="card-content">
|
|
||||||
<mat-divider />
|
|
||||||
<div class="card-metadata">
|
|
||||||
<span>Publikationen: {{ institution.works_count }}</span>
|
|
||||||
<span>Zitationen: {{ institution.cited_by_count }}</span>
|
|
||||||
</div>
|
|
||||||
<mat-divider />
|
|
||||||
</mat-card-content>
|
|
||||||
|
|
||||||
<mat-card-footer>
|
|
||||||
<mat-card-actions>
|
|
||||||
<a
|
|
||||||
mat-button
|
|
||||||
[routerLink]="['/institution', institutionId, 'overview']"
|
|
||||||
(click)="$event.stopPropagation()">
|
|
||||||
<mat-icon>info</mat-icon>
|
|
||||||
Übersicht
|
|
||||||
</a>
|
|
||||||
<a
|
|
||||||
mat-button
|
|
||||||
[routerLink]="['/institution', institutionId, 'publications']"
|
|
||||||
(click)="$event.stopPropagation()">
|
|
||||||
<mat-icon>article</mat-icon>
|
|
||||||
Publikationen
|
|
||||||
</a>
|
|
||||||
<a
|
|
||||||
mat-button
|
|
||||||
[routerLink]="['/institution', institutionId, 'projects']"
|
|
||||||
(click)="$event.stopPropagation()">
|
|
||||||
<mat-icon>work</mat-icon>
|
|
||||||
Projekte
|
|
||||||
</a>
|
|
||||||
<a
|
|
||||||
mat-button
|
|
||||||
[routerLink]="['/institution', institutionId, 'patents']"
|
|
||||||
(click)="$event.stopPropagation()">
|
|
||||||
<mat-icon>verified</mat-icon>
|
|
||||||
Patente
|
|
||||||
</a>
|
|
||||||
</mat-card-actions>
|
|
||||||
</mat-card-footer>
|
|
||||||
</mat-card>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
} @else {
|
|
||||||
<div class="no-results">
|
|
||||||
<p>Keine passenden Institutionen gefunden.</p>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
<mat-divider />
|
|
||||||
|
|
||||||
<app-query-param-paginator
|
|
||||||
[total]="institutionPageValue.total ?? 0"
|
|
||||||
[pageSizeOptions]="[10, 20, 50]" />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ng-template #cardTmp let-institution>
|
||||||
|
<mat-card
|
||||||
|
class="card"
|
||||||
|
appearance="outlined"
|
||||||
|
[routerLink]="
|
||||||
|
institution.id
|
||||||
|
? ['/institution', institution.id.split('/').pop() ?? '']
|
||||||
|
: null
|
||||||
|
">
|
||||||
|
<mat-card-header>
|
||||||
|
<mat-card-title>{{ getDisplayName(institution) }}</mat-card-title>
|
||||||
|
<mat-card-subtitle
|
||||||
|
>{{ institution.geo?.city }},
|
||||||
|
{{ institution.geo?.country }}</mat-card-subtitle
|
||||||
|
>
|
||||||
|
</mat-card-header>
|
||||||
|
|
||||||
|
<mat-card-content class="card-content">
|
||||||
|
<mat-divider />
|
||||||
|
<div class="card-metadata">
|
||||||
|
<span>Publikationen: {{ institution.works_count }}</span>
|
||||||
|
<span>Zitationen: {{ institution.cited_by_count }}</span>
|
||||||
|
</div>
|
||||||
|
<mat-divider />
|
||||||
|
</mat-card-content>
|
||||||
|
|
||||||
|
<mat-card-footer>
|
||||||
|
<mat-card-actions>
|
||||||
|
<a
|
||||||
|
mat-button
|
||||||
|
[routerLink]="[
|
||||||
|
'/institution',
|
||||||
|
extractInstitutionId(institution),
|
||||||
|
'overview',
|
||||||
|
]"
|
||||||
|
(click)="$event.stopPropagation()">
|
||||||
|
<mat-icon>info</mat-icon>
|
||||||
|
Übersicht
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
mat-button
|
||||||
|
[routerLink]="[
|
||||||
|
'/institution',
|
||||||
|
extractInstitutionId(institution),
|
||||||
|
'publications',
|
||||||
|
]"
|
||||||
|
(click)="$event.stopPropagation()">
|
||||||
|
<mat-icon>article</mat-icon>
|
||||||
|
Publikationen
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
mat-button
|
||||||
|
[routerLink]="[
|
||||||
|
'/institution',
|
||||||
|
extractInstitutionId(institution),
|
||||||
|
'projects',
|
||||||
|
]"
|
||||||
|
(click)="$event.stopPropagation()">
|
||||||
|
<mat-icon>work</mat-icon>
|
||||||
|
Projekte
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
mat-button
|
||||||
|
[routerLink]="[
|
||||||
|
'/institution',
|
||||||
|
extractInstitutionId(institution),
|
||||||
|
'patents',
|
||||||
|
]"
|
||||||
|
(click)="$event.stopPropagation()">
|
||||||
|
<mat-icon>verified</mat-icon>
|
||||||
|
Patente
|
||||||
|
</a>
|
||||||
|
</mat-card-actions>
|
||||||
|
</mat-card-footer>
|
||||||
|
</mat-card>
|
||||||
|
</ng-template>
|
||||||
|
|||||||
@@ -5,27 +5,10 @@
|
|||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.sorting {
|
|
||||||
display: flex;
|
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sorting select {
|
|
||||||
padding: 0.75rem;
|
|
||||||
border: 1px solid var(--sg-border);
|
|
||||||
border-radius: var(--sg-radius-sm);
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sorting select:hover {
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cards {
|
.cards {
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 1.5rem;
|
gap: 1.5rem;
|
||||||
grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(550px, 1fr));
|
||||||
padding: 0 1rem;
|
padding: 0 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,13 +54,3 @@ mat-card-actions a {
|
|||||||
border: 1px solid var(--sg-border);
|
border: 1px solid var(--sg-border);
|
||||||
border-radius: var(--sg-radius-sm);
|
border-radius: var(--sg-radius-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
.no-results {
|
|
||||||
text-align: center;
|
|
||||||
padding: 2rem;
|
|
||||||
color: var(--sg-text-secondary);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-and-sorting {
|
|
||||||
padding: 0 1rem;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
import { Component, input } from '@angular/core';
|
import { Component, computed, input } from '@angular/core';
|
||||||
import { Institution, InstitutionPage } from '../../api';
|
import { Institution, InstitutionPage } from '../../api';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatCardModule } from '@angular/material/card';
|
import { MatCardModule } from '@angular/material/card';
|
||||||
import { RouterModule } from '@angular/router';
|
import { RouterModule } from '@angular/router';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { MatDividerModule } from '@angular/material/divider';
|
import { MatDividerModule } from '@angular/material/divider';
|
||||||
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
|
||||||
|
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
|
||||||
import {
|
import {
|
||||||
QueryParamSelectorComponent,
|
Page,
|
||||||
SelectorOption,
|
CardSearchComponent,
|
||||||
} from '../../shared/ui/query-param-selector/query-param-selector.component';
|
} from '../../shared/ui/card-search/card-search.component';
|
||||||
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-institutions',
|
selector: 'app-institutions',
|
||||||
@@ -20,9 +20,7 @@ import { QueryParamInputComponent } from '../../shared/ui/query-param-input/quer
|
|||||||
MatIconModule,
|
MatIconModule,
|
||||||
MatDividerModule,
|
MatDividerModule,
|
||||||
RouterModule,
|
RouterModule,
|
||||||
QueryParamPaginatorComponent,
|
CardSearchComponent,
|
||||||
QueryParamSelectorComponent,
|
|
||||||
QueryParamInputComponent,
|
|
||||||
],
|
],
|
||||||
templateUrl: './institutions.component.html',
|
templateUrl: './institutions.component.html',
|
||||||
styleUrl: './institutions.component.scss',
|
styleUrl: './institutions.component.scss',
|
||||||
@@ -30,6 +28,13 @@ import { QueryParamInputComponent } from '../../shared/ui/query-param-input/quer
|
|||||||
export class InstitutionsComponent {
|
export class InstitutionsComponent {
|
||||||
institutionPage = input.required<InstitutionPage>();
|
institutionPage = input.required<InstitutionPage>();
|
||||||
|
|
||||||
|
page = computed<Page>(() => ({
|
||||||
|
page: this.institutionPage().page || 0,
|
||||||
|
size: this.institutionPage().size || 10,
|
||||||
|
total: this.institutionPage().total || 0,
|
||||||
|
elements: this.institutionPage().elements || [],
|
||||||
|
}));
|
||||||
|
|
||||||
sortingOptions: SelectorOption[] = [
|
sortingOptions: SelectorOption[] = [
|
||||||
{ value: 'relevance', display_name: 'Relevanz' },
|
{ value: 'relevance', display_name: 'Relevanz' },
|
||||||
{ value: 'name', display_name: 'Name' },
|
{ value: 'name', display_name: 'Name' },
|
||||||
|
|||||||
@@ -1,22 +1,50 @@
|
|||||||
<div class="content">
|
<div class="content">
|
||||||
<!-- Tabs and Extract Button -->
|
<!-- Tabs and Extract Button -->
|
||||||
<div>
|
<mat-tab-group
|
||||||
<mat-tab-group
|
[selectedIndex]="selectedTabIndex()"
|
||||||
[selectedIndex]="selectedTabIndex()"
|
(selectedIndexChange)="onTabChange($event)">
|
||||||
(selectedIndexChange)="onTabChange($event)">
|
<mat-tab label="URL">
|
||||||
<mat-tab label="URL">
|
<div class="tab-content">
|
||||||
<div class="tab-content">
|
<mat-form-field appearance="outline" class="full-width">
|
||||||
<mat-form-field appearance="outline" class="full-width">
|
<mat-label>Füge eine URL ein, um Keywords zu extrahieren</mat-label>
|
||||||
<mat-label>Füge eine URL ein, um Keywords zu extrahieren</mat-label>
|
<input
|
||||||
<input
|
matInput
|
||||||
matInput
|
placeholder="https://example.com/article"
|
||||||
placeholder="https://example.com/article"
|
[formControl]="form.controls.urlInput"
|
||||||
[formControl]="form.controls.urlInput" />
|
(keydown.enter)="
|
||||||
</mat-form-field>
|
onExtractKeywordsClick(); $event.preventDefault()
|
||||||
|
" />
|
||||||
|
</mat-form-field>
|
||||||
|
<button
|
||||||
|
mat-flat-button
|
||||||
|
type="button"
|
||||||
|
class="extract-btn"
|
||||||
|
[color]="isExtracting() ? 'warn' : 'primary'"
|
||||||
|
(click)="onExtractKeywordsClick()">
|
||||||
|
<mat-icon>
|
||||||
|
{{ isExtracting() ? 'close' : 'troubleshoot' }}
|
||||||
|
</mat-icon>
|
||||||
|
{{ isExtracting() ? 'Abbrechen' : 'Keywords extrahieren' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab label="Text">
|
||||||
|
<div class="tab-content">
|
||||||
|
<mat-form-field appearance="outline" class="full-width">
|
||||||
|
<mat-label>Schreibe einen Text, um Keywords zu extrahieren</mat-label>
|
||||||
|
<textarea
|
||||||
|
matInput
|
||||||
|
rows="10"
|
||||||
|
placeholder="Large language models are transforming innovation scouting..."
|
||||||
|
[formControl]="form.controls.textInput"></textarea>
|
||||||
|
</mat-form-field>
|
||||||
|
<div class="actions">
|
||||||
<button
|
<button
|
||||||
mat-flat-button
|
mat-flat-button
|
||||||
type="button"
|
type="button"
|
||||||
[color]="isExtracting() ? 'warn' : 'primary'"
|
[color]="isExtracting() ? 'warn' : 'primary'"
|
||||||
|
class="extract-btn"
|
||||||
(click)="onExtractKeywordsClick()">
|
(click)="onExtractKeywordsClick()">
|
||||||
<mat-icon>
|
<mat-icon>
|
||||||
{{ isExtracting() ? 'close' : 'troubleshoot' }}
|
{{ isExtracting() ? 'close' : 'troubleshoot' }}
|
||||||
@@ -24,210 +52,356 @@
|
|||||||
{{ isExtracting() ? 'Abbrechen' : 'Keywords extrahieren' }}
|
{{ isExtracting() ? 'Abbrechen' : 'Keywords extrahieren' }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</mat-tab>
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
</mat-tab-group>
|
||||||
|
<!-- Extraction Table -->
|
||||||
|
<mat-card
|
||||||
|
class="keyword-card progress-container"
|
||||||
|
[class.loading]="isExtracting()">
|
||||||
|
<mat-card-content>
|
||||||
|
<!-- View toggle: Topic Mapping vs. LLM Keywords -->
|
||||||
|
<div class="keywords-toolbar">
|
||||||
|
@if (topicLegendGroups.length > 0) {
|
||||||
|
<app-topic-legend
|
||||||
|
[groups]="topicLegendGroups"
|
||||||
|
[visible]="subfieldLegendVisible()"
|
||||||
|
[expanded]="subfieldLegendExpanded()"
|
||||||
|
[collapsedGroupLimit]="3"
|
||||||
|
variant="default"
|
||||||
|
(visibleChange)="onSubfieldLegendVisibleChange($event)"
|
||||||
|
(expandedChange)="onSubfieldLegendExpandedChange($event)">
|
||||||
|
</app-topic-legend>
|
||||||
|
}
|
||||||
|
|
||||||
<mat-tab label="Text">
|
<!-- Manual input is ALWAYS available, independent of extraction state -->
|
||||||
<div class="tab-content">
|
<div class="toolbar-wrapper">
|
||||||
<mat-form-field appearance="outline" class="full-width">
|
<div class="toolbar-controls thick-border">
|
||||||
<mat-label
|
<div class="toolbar-group toolbar-group--view">
|
||||||
>Schreibe einen Text, um Keywords zu extrahieren</mat-label
|
@if (areAllSelected()) {
|
||||||
>
|
|
||||||
<textarea
|
|
||||||
matInput
|
|
||||||
rows="10"
|
|
||||||
placeholder="Large language models are transforming innovation scouting..."
|
|
||||||
[formControl]="form.controls.textInput"></textarea>
|
|
||||||
</mat-form-field>
|
|
||||||
<div class="actions">
|
|
||||||
<button
|
|
||||||
mat-flat-button
|
|
||||||
type="button"
|
|
||||||
color="primary"
|
|
||||||
(click)="onExtractKeywordsClick()">
|
|
||||||
<mat-icon>troubleshoot</mat-icon>
|
|
||||||
{{ isExtracting() ? 'Abbrechen' : 'Keywords extrahieren' }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</mat-tab>
|
|
||||||
</mat-tab-group>
|
|
||||||
|
|
||||||
<!-- Extraction Table -->
|
|
||||||
<div class="extraction-grid">
|
|
||||||
<mat-card appearance="outlined" class="keyword-card extracted-card">
|
|
||||||
<mat-card-content>
|
|
||||||
<!-- Table-like keyword grid -->
|
|
||||||
<div class="keyword-table">
|
|
||||||
<!-- Header: group title + own-keyword input as column subheader -->
|
|
||||||
<div class="table-head">
|
|
||||||
<div class="head-cell sub-cell broad-sub">Breite Keywords</div>
|
|
||||||
<div class="head-cell sub-cell coarse-sub">Coarse Keywords</div>
|
|
||||||
<div class="head-cell sub-cell fine-sub">Fine Keywords</div>
|
|
||||||
<div class="head-cell sub-cell manual-sub">Eigene Keywords</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Body: 4 aligned columns -->
|
|
||||||
<div class="table-body">
|
|
||||||
<div class="table-col broad-col">
|
|
||||||
@if (broadKeywords().length > 0) {
|
|
||||||
<mat-chip-listbox
|
|
||||||
multiple
|
|
||||||
[value]="selectedBroadKeywords()"
|
|
||||||
(change)="onCategoryChange('broad', $event)">
|
|
||||||
@for (keyword of broadKeywords(); track keyword) {
|
|
||||||
<mat-chip-option
|
|
||||||
[value]="keyword"
|
|
||||||
class="compact-chip broad-chip">
|
|
||||||
{{ keyword }}
|
|
||||||
</mat-chip-option>
|
|
||||||
}
|
|
||||||
</mat-chip-listbox>
|
|
||||||
} @else {
|
|
||||||
<p class="empty-state small">–</p>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="table-col coarse-col">
|
|
||||||
@if (coarseKeywords().length > 0) {
|
|
||||||
<mat-chip-listbox
|
|
||||||
multiple
|
|
||||||
[value]="selectedCoarseKeywords()"
|
|
||||||
(change)="onCategoryChange('coarse', $event)">
|
|
||||||
@for (keyword of coarseKeywords(); track keyword) {
|
|
||||||
<mat-chip-option
|
|
||||||
[value]="keyword"
|
|
||||||
class="compact-chip coarse-chip">
|
|
||||||
{{ keyword }}
|
|
||||||
</mat-chip-option>
|
|
||||||
}
|
|
||||||
</mat-chip-listbox>
|
|
||||||
} @else {
|
|
||||||
<p class="empty-state small">–</p>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="table-col fine-col">
|
|
||||||
@if (fineKeywords().length > 0) {
|
|
||||||
<mat-chip-listbox
|
|
||||||
multiple
|
|
||||||
[value]="selectedFineKeywords()"
|
|
||||||
(change)="onCategoryChange('fine', $event)">
|
|
||||||
@for (keyword of fineKeywords(); track keyword) {
|
|
||||||
<mat-chip-option
|
|
||||||
[value]="keyword"
|
|
||||||
class="compact-chip fine-chip">
|
|
||||||
{{ keyword }}
|
|
||||||
</mat-chip-option>
|
|
||||||
}
|
|
||||||
</mat-chip-listbox>
|
|
||||||
} @else {
|
|
||||||
<p class="empty-state small">–</p>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="table-col own-col">
|
|
||||||
<app-topic-autocomplete
|
|
||||||
label="z. B. Knowledge Graphs"
|
|
||||||
placeholder="Thema suchen oder eintippen..."
|
|
||||||
(topicSelected)="addKeywordFromInput($event)" />
|
|
||||||
<mat-chip-listbox
|
|
||||||
multiple
|
|
||||||
[value]="selectedManualKeywords()"
|
|
||||||
(change)="onCategoryChange('manual', $event)">
|
|
||||||
@if (manualKeywords().length > 0) {
|
|
||||||
@for (keyword of manualKeywords(); track keyword) {
|
|
||||||
<mat-chip-option
|
|
||||||
[value]="keyword"
|
|
||||||
(removed)="onKeywordRemoved('manual', keyword)"
|
|
||||||
class="compact-chip manual-chip">
|
|
||||||
{{ keyword }}
|
|
||||||
<mat-icon matChipRemove>cancel</mat-icon>
|
|
||||||
</mat-chip-option>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</mat-chip-listbox>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Select/Deselect All Extracted -->
|
|
||||||
@if (extractedKeywordsExist()) {
|
|
||||||
<div class="select-all-container">
|
|
||||||
@if (areAllExtractedSelected()) {
|
|
||||||
<button
|
<button
|
||||||
mat-stroked-button
|
mat-stroked-button
|
||||||
color="primary"
|
color="primary"
|
||||||
size="small"
|
(click)="deselectAll()"
|
||||||
(click)="deselectAllExtracted()">
|
[disabled]="isExtracting()"
|
||||||
<mat-icon>select_all</mat-icon> Alle extrahierten Keywords
|
matTooltip="Alle extrahierten Keywords abwählen">
|
||||||
abwählen
|
<mat-icon>select_all</mat-icon>
|
||||||
|
<span>Alle abwählen</span>
|
||||||
</button>
|
</button>
|
||||||
} @else {
|
} @else {
|
||||||
<button
|
<button
|
||||||
mat-stroked-button
|
mat-stroked-button
|
||||||
color="primary"
|
color="primary"
|
||||||
size="small"
|
|
||||||
[disabled]="isExtracting()"
|
[disabled]="isExtracting()"
|
||||||
(click)="selectAllExtracted()">
|
(click)="selectAll()"
|
||||||
<mat-icon>select_all</mat-icon> Alle extrahierten Keywords
|
matTooltip="Alle extrahierten Keywords auswählen">
|
||||||
auswählen
|
<mat-icon>select_all</mat-icon>
|
||||||
|
<span>Alle auswählen</span>
|
||||||
</button>
|
</button>
|
||||||
}
|
}
|
||||||
<button
|
<button
|
||||||
mat-stroked-button
|
mat-stroked-button
|
||||||
color="warn"
|
color="warn"
|
||||||
size="small"
|
|
||||||
[disabled]="isExtracting()"
|
[disabled]="isExtracting()"
|
||||||
(click)="clearExtractedKeywords()">
|
(click)="clearKeywords()"
|
||||||
<mat-icon>delete_outline</mat-icon> Lösche alle extrahierten
|
matTooltip="Alle extrahierten Keywords löschen">
|
||||||
Keywords
|
<mat-icon>delete_outline</mat-icon>
|
||||||
|
<span>Alle löschen</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
}
|
<div class="toolbar-divider"></div>
|
||||||
|
<mat-button-toggle-group
|
||||||
|
[value]="keywordView()"
|
||||||
|
(change)="onViewToggleChange($event.value)"
|
||||||
|
aria-label="Keyword Ansicht wählen">
|
||||||
|
<mat-button-toggle
|
||||||
|
[disabled]="isExtracting()"
|
||||||
|
value="llm"
|
||||||
|
matTooltip="Extrahierte Keywords">
|
||||||
|
<mat-icon>text_fields</mat-icon>
|
||||||
|
<span>Extrahierte Keywords</span>
|
||||||
|
</mat-button-toggle>
|
||||||
|
@if (topicMappingSearch()) {
|
||||||
|
<mat-button-toggle
|
||||||
|
[disabled]="isExtracting()"
|
||||||
|
value="topic"
|
||||||
|
matTooltip="Topic Mapping">
|
||||||
|
<mat-icon>account_tree</mat-icon>
|
||||||
|
<span>Topic Mapping</span>
|
||||||
|
</mat-button-toggle>
|
||||||
|
}
|
||||||
|
</mat-button-toggle-group>
|
||||||
|
<div class="toolbar-divider"></div>
|
||||||
|
|
||||||
@if (isExtracting()) {
|
<div class="toolbar-group toolbar-group--view">
|
||||||
<div class="progress-container">
|
<mat-slide-toggle
|
||||||
<mat-progress-bar
|
(change)="onToggleTopicMappingSearch($event)"
|
||||||
mode="determinate"
|
labelPosition="before"
|
||||||
[value]="progress()"
|
[checked]="topicMappingSearch()"
|
||||||
color="primary">
|
class="mapping-toggle">
|
||||||
</mat-progress-bar>
|
Topic Mapping
|
||||||
<div class="status-message">{{ statusMessage() }}</div>
|
</mat-slide-toggle>
|
||||||
</div>
|
</div>
|
||||||
} @else if (
|
</div>
|
||||||
!extractedKeywordsExist() && manualKeywords().length === 0
|
|
||||||
) {
|
|
||||||
<p class="empty-state">
|
|
||||||
Keine Keywords vorhanden. Extrahiere Keywords oder füge eigene
|
|
||||||
hinzu.
|
|
||||||
</p>
|
|
||||||
}
|
|
||||||
<!-- Source content display -->
|
|
||||||
@if (sourceContent().length > 0) {
|
|
||||||
<mat-divider></mat-divider>
|
|
||||||
<mat-expansion-panel class="source-expansion">
|
|
||||||
<mat-expansion-panel-header>
|
|
||||||
<mat-panel-title
|
|
||||||
>Quellentext: {{ sourceUrl() }}</mat-panel-title
|
|
||||||
>
|
|
||||||
</mat-expansion-panel-header>
|
|
||||||
<div class="source-text">{{ sourceContent() }}</div>
|
|
||||||
</mat-expansion-panel>
|
|
||||||
}
|
|
||||||
</mat-card-content>
|
|
||||||
</mat-card>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Search Button -->
|
<div class="spacer toolbar-controls manual-input-controls">
|
||||||
<div class="search-container">
|
<app-topic-autocomplete
|
||||||
<button
|
label="z. B. Knowledge Graphs"
|
||||||
mat-flat-button
|
placeholder="Thema suchen oder eintippen..."
|
||||||
color="primary"
|
(topicSelected)="addKeywordFromInput($event)" />
|
||||||
[disabled]="isSearchDisabled()"
|
</div>
|
||||||
(click)="search()">
|
</div>
|
||||||
<mat-icon>search</mat-icon>
|
</div>
|
||||||
Suchen
|
|
||||||
</button>
|
<!-- ===== Reusable chip stack templates ===== -->
|
||||||
</div>
|
<ng-template
|
||||||
</div>
|
#keywordChipStack
|
||||||
|
let-keywords="keywords"
|
||||||
|
let-emptyText="emptyText">
|
||||||
|
@if (keywords.length > 0) {
|
||||||
|
<div class="keyword-chip-stack">
|
||||||
|
@for (keyword of keywords; track keyword.llm_keyword.keyword) {
|
||||||
|
<app-topic-chip
|
||||||
|
[label]="getChipLabel(keyword)"
|
||||||
|
[count]="
|
||||||
|
keywordView() === 'topic' ? getChipCount(keyword) : null
|
||||||
|
"
|
||||||
|
[description]="getChipDescription(keyword)"
|
||||||
|
[subfieldName]="getChipSubfieldName(keyword)"
|
||||||
|
[fieldName]="getChipFieldName(keyword)"
|
||||||
|
[domainName]="getChipDomainName(keyword)"
|
||||||
|
[color]="getTopicColor(keyword.topic_mapping?.topic)"
|
||||||
|
[active]="isKeywordSelected(keyword)"
|
||||||
|
countIcon="article"
|
||||||
|
descriptionTooltipTarget="button"
|
||||||
|
(chipClick)="toggleKeywordSelection(keyword)">
|
||||||
|
</app-topic-chip>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<p class="empty-state small">{{ emptyText }}</p>
|
||||||
|
}
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
|
<ng-template #manualChipStack>
|
||||||
|
<div class="keyword-chip-stack manual-stack">
|
||||||
|
@if (manualKeywords().length > 0) {
|
||||||
|
@for (
|
||||||
|
keyword of manualKeywords();
|
||||||
|
track keyword.llm_keyword.keyword
|
||||||
|
) {
|
||||||
|
<div class="manual-chip-row">
|
||||||
|
<app-topic-chip
|
||||||
|
[label]="getChipLabel(keyword)"
|
||||||
|
[count]="
|
||||||
|
keywordView() === 'topic' ? getChipCount(keyword) : null
|
||||||
|
"
|
||||||
|
[description]="getChipDescription(keyword)"
|
||||||
|
[subfieldName]="getChipSubfieldName(keyword)"
|
||||||
|
[fieldName]="getChipFieldName(keyword)"
|
||||||
|
[domainName]="getChipDomainName(keyword)"
|
||||||
|
[color]="getTopicColor(keyword.topic_mapping?.topic)"
|
||||||
|
[active]="isKeywordSelected(keyword)"
|
||||||
|
countIcon="article"
|
||||||
|
descriptionTooltipTarget="button"
|
||||||
|
(chipClick)="toggleKeywordSelection(keyword)">
|
||||||
|
</app-topic-chip>
|
||||||
|
<button
|
||||||
|
mat-icon-button
|
||||||
|
type="button"
|
||||||
|
color="warn"
|
||||||
|
aria-label="Manuelles Keyword entfernen"
|
||||||
|
(click)="removeManualKeyword(keyword)">
|
||||||
|
<mat-icon>cancel</mat-icon>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<p class="empty-state small">Nichts hinzugefügt</p>
|
||||||
|
}
|
||||||
|
@if (loadingNewKeyword()) {
|
||||||
|
<div class="manual-chip-row">
|
||||||
|
<app-topic-chip [label]="'Neues Keyword wird hinzugefügt...'">
|
||||||
|
</app-topic-chip>
|
||||||
|
<button mat-icon-button></button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
|
<!-- ===== Desktop / tablet table view ===== -->
|
||||||
|
@if (!isMobile()) {
|
||||||
|
<div class="keyword-table">
|
||||||
|
<div class="table-head">
|
||||||
|
<div class="head-cell sub-cell broad-sub">Breite Keywords</div>
|
||||||
|
<div class="head-cell sub-cell coarse-sub">Coarse Keywords</div>
|
||||||
|
<div class="head-cell sub-cell fine-sub thick-border">
|
||||||
|
Fine Keywords
|
||||||
|
</div>
|
||||||
|
<div class="head-cell sub-cell manual-sub">Eigene Keywords</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-body">
|
||||||
|
<div class="table-col broad-col">
|
||||||
|
<ng-container
|
||||||
|
*ngTemplateOutlet="
|
||||||
|
keywordChipStack;
|
||||||
|
context: {
|
||||||
|
keywords: broadKeywords(),
|
||||||
|
emptyText: 'Nichts extrahiert',
|
||||||
|
}
|
||||||
|
"></ng-container>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-col coarse-col">
|
||||||
|
<ng-container
|
||||||
|
*ngTemplateOutlet="
|
||||||
|
keywordChipStack;
|
||||||
|
context: {
|
||||||
|
keywords: coarseKeywords(),
|
||||||
|
emptyText: 'Nichts extrahiert',
|
||||||
|
}
|
||||||
|
"></ng-container>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-col fine-col thick-border">
|
||||||
|
<ng-container
|
||||||
|
*ngTemplateOutlet="
|
||||||
|
keywordChipStack;
|
||||||
|
context: {
|
||||||
|
keywords: fineKeywords(),
|
||||||
|
emptyText: 'Nichts extrahiert',
|
||||||
|
}
|
||||||
|
"></ng-container>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-col own-col">
|
||||||
|
<ng-container *ngTemplateOutlet="manualChipStack"></ng-container>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<!-- ===== Mobile: tabbed view instead of squashed columns ===== -->
|
||||||
|
<mat-tab-group class="mobile-keyword-tabs" animationDuration="150ms">
|
||||||
|
<mat-tab>
|
||||||
|
<ng-template mat-tab-label>
|
||||||
|
<span>Breit</span>
|
||||||
|
<span class="tab-count">{{ broadKeywords().length }}</span>
|
||||||
|
</ng-template>
|
||||||
|
<div class="mobile-tab-panel">
|
||||||
|
<ng-container
|
||||||
|
*ngTemplateOutlet="
|
||||||
|
keywordChipStack;
|
||||||
|
context: {
|
||||||
|
keywords: broadKeywords(),
|
||||||
|
emptyText: 'Nichts extrahiert',
|
||||||
|
}
|
||||||
|
"></ng-container>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab>
|
||||||
|
<ng-template mat-tab-label>
|
||||||
|
<span>Coarse</span>
|
||||||
|
<span class="tab-count">{{ coarseKeywords().length }}</span>
|
||||||
|
</ng-template>
|
||||||
|
<div class="mobile-tab-panel">
|
||||||
|
<ng-container
|
||||||
|
*ngTemplateOutlet="
|
||||||
|
keywordChipStack;
|
||||||
|
context: {
|
||||||
|
keywords: coarseKeywords(),
|
||||||
|
emptyText: 'Nichts extrahiert',
|
||||||
|
}
|
||||||
|
"></ng-container>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab>
|
||||||
|
<ng-template mat-tab-label>
|
||||||
|
<span>Fine</span>
|
||||||
|
<span class="tab-count">{{ fineKeywords().length }}</span>
|
||||||
|
</ng-template>
|
||||||
|
<div class="mobile-tab-panel">
|
||||||
|
<ng-container
|
||||||
|
*ngTemplateOutlet="
|
||||||
|
keywordChipStack;
|
||||||
|
context: {
|
||||||
|
keywords: fineKeywords(),
|
||||||
|
emptyText: 'Nichts extrahiert',
|
||||||
|
}
|
||||||
|
"></ng-container>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
|
||||||
|
<mat-tab>
|
||||||
|
<ng-template mat-tab-label>
|
||||||
|
<span>Eigene</span>
|
||||||
|
<span class="tab-count">{{ manualKeywords().length }}</span>
|
||||||
|
</ng-template>
|
||||||
|
<div class="mobile-tab-panel">
|
||||||
|
<ng-container *ngTemplateOutlet="manualChipStack"></ng-container>
|
||||||
|
</div>
|
||||||
|
</mat-tab>
|
||||||
|
</mat-tab-group>
|
||||||
|
}
|
||||||
|
|
||||||
|
<!-- Source content display -->
|
||||||
|
@if (sourceContent().length > 0) {
|
||||||
|
<mat-divider></mat-divider>
|
||||||
|
<mat-expansion-panel class="source-expansion">
|
||||||
|
<mat-expansion-panel-header>
|
||||||
|
<mat-panel-title>Quellentext: {{ sourceUrl() }}</mat-panel-title>
|
||||||
|
</mat-expansion-panel-header>
|
||||||
|
<div
|
||||||
|
class="source-text"
|
||||||
|
[innerHTML]="highlightedSourceContent()"></div>
|
||||||
|
</mat-expansion-panel>
|
||||||
|
}
|
||||||
|
</mat-card-content>
|
||||||
|
@if (isExtracting() && !keywordsExist()) {
|
||||||
|
<app-loading
|
||||||
|
text="{{ statusMessage() }}"
|
||||||
|
icon="manage_search"
|
||||||
|
[size]="200"
|
||||||
|
[diameter]="200" />
|
||||||
|
}
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
@if (isExtracting() && keywordsExist()) {
|
||||||
|
<div class="status-message">{{ statusMessage() }}</div>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@if (keywordsExist()) {
|
||||||
|
<!-- Search buttons -->
|
||||||
|
<div class="search-actions">
|
||||||
|
<button
|
||||||
|
mat-flat-button
|
||||||
|
color="primary"
|
||||||
|
class="search-btn"
|
||||||
|
[disabled]="isSearchDisabled()"
|
||||||
|
(click)="search()">
|
||||||
|
<mat-icon>search</mat-icon>
|
||||||
|
Suchen
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
mat-flat-button
|
||||||
|
color="accent"
|
||||||
|
class="visualize-btn"
|
||||||
|
[disabled]="isSearchDisabled()"
|
||||||
|
(click)="visualize()">
|
||||||
|
<mat-icon>show_chart</mat-icon>
|
||||||
|
Visualisierung
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<!-- Trend Comparison Section -->
|
||||||
|
@if (showVisualization() && selectedKeywords().length > 0) {
|
||||||
|
<div style="margin-top: 2rem">
|
||||||
|
<app-uni-trend-parent
|
||||||
|
[keywords]="selectedKeywords()"></app-uni-trend-parent>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,26 +1,210 @@
|
|||||||
|
/* ============================================================
|
||||||
|
DESIGN TOKENS / LOCAL VARIABLES
|
||||||
|
============================================================ */
|
||||||
|
$phone: 599px;
|
||||||
|
$tablet: 900px;
|
||||||
|
$touch-target: 44px;
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
BASE LAYOUT — container becomes the responsive anchor
|
||||||
|
============================================================ */
|
||||||
.content {
|
.content {
|
||||||
|
container-type: inline-size;
|
||||||
|
container-name: keyword-tool;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 0.75rem;
|
gap: clamp(0.5rem, 1.5vw, 0.75rem);
|
||||||
padding: 1rem;
|
padding: clamp(0.5rem, 2vw, 1rem);
|
||||||
}
|
}
|
||||||
|
|
||||||
.tab-content {
|
.tab-content {
|
||||||
padding: 0.5rem 0;
|
display: flex;
|
||||||
display: grid;
|
flex-direction: column;
|
||||||
grid-template-columns: 5fr 1fr;
|
margin-top: 0.5rem;
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.full-width {
|
.full-width {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.extract-btn {
|
||||||
|
white-space: nowrap;
|
||||||
|
min-width: 240px;
|
||||||
|
min-height: $touch-target;
|
||||||
|
}
|
||||||
|
|
||||||
.actions {
|
.actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
TOOLBAR
|
||||||
|
============================================================ */
|
||||||
|
.keywords-toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: var(--sg-background-muted, #f4f5f7);
|
||||||
|
|
||||||
|
::ng-deep app-topic-legend .topic-legend {
|
||||||
|
width: 100%;
|
||||||
|
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||||
|
border-bottom: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-controls {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-around;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
background: var(--sg-background-muted, #f4f5f7);
|
||||||
|
}
|
||||||
|
.toolbar-wrapper {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 3fr 1.3fr;
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-controls--placeholder {
|
||||||
|
/* invisible spacer, preserves grid column width/position */
|
||||||
|
visibility: hidden;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.manual-input-controls {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.toolbar-group {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-around;
|
||||||
|
gap: auto;
|
||||||
|
|
||||||
|
::ng-deep .mdc-switch {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
::ng-deep .mdc-form-field {
|
||||||
|
position: relative;
|
||||||
|
min-width: 90px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
::ng-deep .mdc-label {
|
||||||
|
position: absolute;
|
||||||
|
top: 30px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@container keyword-tool (max-width: #{$tablet}) {
|
||||||
|
.toolbar-wrapper {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-controls--placeholder {
|
||||||
|
display: none; /* no need for a spacer once stacked */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-group {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
flex-wrap: nowrap; /* fixed: was invalid "no-wrap" */
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-group button {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
line-height: 30px;
|
||||||
|
border-radius: 20px;
|
||||||
|
padding: 0 14px;
|
||||||
|
min-height: $touch-target;
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
font-size: 20px;
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-divider {
|
||||||
|
width: 1px;
|
||||||
|
align-self: stretch;
|
||||||
|
background: var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||||
|
}
|
||||||
|
|
||||||
|
mat-button-toggle-group {
|
||||||
|
border-radius: 20px;
|
||||||
|
overflow: hidden;
|
||||||
|
justify-content: space-around;
|
||||||
|
|
||||||
|
::ng-deep .mat-button-toggle-label-content {
|
||||||
|
line-height: $touch-target;
|
||||||
|
}
|
||||||
|
::ng-deep mat-button-toggle {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Container-query driven toolbar collapse (tablet/phone) */
|
||||||
|
@container keyword-tool (min-width: #{$phone + 1}) {
|
||||||
|
.toolbar-divider {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@container keyword-tool (max-width: #{$tablet}) {
|
||||||
|
.toolbar-controls {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-group {
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-group button {
|
||||||
|
width: 100%;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-wrapper {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
border-left: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-wrapper .spacer {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Phone: icon-only toolbar buttons to save space */
|
||||||
|
@container keyword-tool (max-width: #{$phone}) {
|
||||||
|
.btn-label {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-group button {
|
||||||
|
width: auto;
|
||||||
|
padding: 0;
|
||||||
|
min-width: $touch-target;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
EXTRACTION GRID / CARD
|
||||||
|
============================================================ */
|
||||||
.extraction-grid {
|
.extraction-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
@@ -28,183 +212,164 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.keyword-card {
|
.keyword-card {
|
||||||
background-color: var(--sg-background);
|
padding: 0 !important;
|
||||||
padding: 0.5rem;
|
background: var(--sg-background-muted, #f4f5f7);
|
||||||
|
|
||||||
.mat-card-header {
|
.mat-card-header {
|
||||||
padding: 0 0 0.5rem 0;
|
padding: 0 0 0.5rem 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.mat-card-content {
|
.mat-mdc-card-content {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* === Table-like keyword grid === */
|
/* ============================================================
|
||||||
|
DESKTOP TABLE-LIKE KEYWORD GRID
|
||||||
|
============================================================ */
|
||||||
.keyword-table {
|
.keyword-table {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 0.5rem;
|
|
||||||
margin: 0.5rem 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.table-head {
|
.table-head {
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||||
|
padding-top: 0.5rem;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(3, 1fr) 1.3fr;
|
grid-template-columns: repeat(3, 1fr) 1.3fr;
|
||||||
grid-template-rows: auto;
|
|
||||||
column-gap: 1rem;
|
column-gap: 1rem;
|
||||||
border-bottom: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||||
padding-bottom: 0.5rem;
|
padding-bottom: 0.5rem;
|
||||||
|
background: var(--sg-background-muted, #f4f5f7);
|
||||||
}
|
}
|
||||||
|
|
||||||
.head-cell {
|
.head-cell {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
text-align: center; /* Center header text */
|
text-align: center;
|
||||||
}
|
|
||||||
|
|
||||||
.extracted-header {
|
|
||||||
grid-column: 1 / span 3;
|
|
||||||
grid-row: 0;
|
|
||||||
font-size: 0.95rem;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--sg-text-primary);
|
|
||||||
align-self: end;
|
|
||||||
}
|
|
||||||
|
|
||||||
.own-header {
|
|
||||||
grid-column: 4;
|
|
||||||
grid-row: 1 / span 2;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.35rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.own-header-title {
|
|
||||||
font-size: 0.95rem;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--sg-text-primary);
|
|
||||||
text-align: center; /* Center own header title */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.sub-cell {
|
.sub-cell {
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--sg-text-secondary);
|
color: var(--sg-text-secondary);
|
||||||
font-size: 1rem;
|
font-size: clamp(0.8rem, 1.2vw, 1rem);
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 0.05em;
|
letter-spacing: 0.05em;
|
||||||
align-self: end;
|
align-self: end;
|
||||||
grid-row: 2;
|
text-align: center;
|
||||||
text-align: center; /* Center sub-cell text */
|
|
||||||
}
|
|
||||||
|
|
||||||
.broad-sub {
|
|
||||||
grid-column: 1;
|
|
||||||
}
|
|
||||||
.coarse-sub {
|
|
||||||
grid-column: 2;
|
|
||||||
}
|
|
||||||
.fine-sub {
|
|
||||||
grid-column: 3;
|
|
||||||
}
|
|
||||||
.manual-sub {
|
|
||||||
grid-column: 4;
|
|
||||||
}
|
|
||||||
.keyword-input-row {
|
|
||||||
margin-left: 0.5rem;
|
|
||||||
width: 100%;
|
|
||||||
display: grid;
|
|
||||||
grid-column: 1 / span 4;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.35rem;
|
|
||||||
|
|
||||||
&.compact {
|
|
||||||
.small-field {
|
|
||||||
flex: 10;
|
|
||||||
// collapse the outline field to a compact, chip-like height
|
|
||||||
::ng-deep .mat-mdc-text-field-wrapper {
|
|
||||||
padding: 0 0.6rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .mat-mdc-form-field-flex {
|
|
||||||
min-height: 8px;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .mat-mdc-form-field-infix {
|
|
||||||
min-height: 8px;
|
|
||||||
padding: 1rem 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// hide the hint/error subscript strip to remove extra height
|
|
||||||
::ng-deep .mat-mdc-form-field-subscript-wrapper {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep input.mat-mdc-input-element {
|
|
||||||
font-size: 0.8rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .mat-mdc-form-field-label,
|
|
||||||
::ng-deep mat-label {
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
button.mat-mdc-icon-button {
|
|
||||||
width: 28px;
|
|
||||||
height: 28px;
|
|
||||||
padding: 0;
|
|
||||||
line-height: 28px;
|
|
||||||
flex: 1;
|
|
||||||
|
|
||||||
.mat-icon {
|
|
||||||
font-size: 18px;
|
|
||||||
width: 18px;
|
|
||||||
height: 18px;
|
|
||||||
line-height: 18px;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .mat-mdc-button-touch-target {
|
|
||||||
width: 28px;
|
|
||||||
height: 28px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.table-body {
|
.table-body {
|
||||||
|
min-height: 200px;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(3, 1fr) 1.3fr;
|
grid-template-columns: repeat(3, 1fr) 1.3fr;
|
||||||
column-gap: 1rem;
|
column-gap: 1rem;
|
||||||
row-gap: 0.4rem;
|
row-gap: 0.4rem;
|
||||||
align-items: start;
|
align-items: start;
|
||||||
border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); /* Left border for columns */
|
//border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Add vertical separators between columns */
|
|
||||||
.table-col {
|
.table-col {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
|
border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8));
|
||||||
|
|
||||||
&:last-child {
|
&:last-child {
|
||||||
border-right: none;
|
border-right: none;
|
||||||
}
|
}
|
||||||
&:nth-child(3) {
|
|
||||||
border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
|
::ng-deep app-topic-chip {
|
||||||
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
mat-chip-listbox {
|
::ng-deep app-topic-chip:not(.topic-chip--active) {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
margin-top: 0.5rem;
|
opacity: 0.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep app-topic-chip .topic-chip__count {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.thick-border {
|
||||||
|
border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.08)) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
@container keyword-tool (max-width: #{$tablet}) {
|
||||||
|
.table-head,
|
||||||
|
.table-body {
|
||||||
|
column-gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-col {
|
||||||
|
padding: 0.4rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
MOBILE KEYWORD TABS (structural replacement for stacked table)
|
||||||
|
============================================================ */
|
||||||
|
.mobile-keyword-tabs {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
|
||||||
|
::ng-deep .mat-mdc-tab-labels {
|
||||||
|
justify-content: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .mat-mdc-tab {
|
||||||
|
flex: 1;
|
||||||
|
min-height: $touch-target;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-count {
|
||||||
|
margin-left: 0.35rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--sg-text-secondary);
|
||||||
|
background: var(--sg-background-muted, #eceff1);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 0 6px;
|
||||||
|
min-width: 18px;
|
||||||
|
display: inline-block;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-tab-panel {
|
||||||
|
padding: 0.75rem 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
CHIP STACKS
|
||||||
|
============================================================ */
|
||||||
|
.keyword-chip-stack {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.manual-chip-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
width: 100%;
|
||||||
|
gap: 0.25rem;
|
||||||
|
|
||||||
|
app-topic-chip {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
button[mat-icon-button] {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
min-width: $touch-target;
|
||||||
|
min-height: $touch-target;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Make chips removable and add hover effect */
|
|
||||||
.compact-chip {
|
.compact-chip {
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
padding: 0.2rem 0.6rem;
|
padding: 0.2rem 0.6rem;
|
||||||
@@ -215,11 +380,9 @@
|
|||||||
animation: popIn 0.2s ease-in-out;
|
animation: popIn 0.2s ease-in-out;
|
||||||
cursor: default;
|
cursor: default;
|
||||||
|
|
||||||
// Add removable indicator and hover effect
|
|
||||||
&.mat-mdc-chip-option {
|
&.mat-mdc-chip-option {
|
||||||
.mat-mdc-chip-action {
|
.mat-mdc-chip-action {
|
||||||
padding: 0 4px;
|
padding: 0 4px;
|
||||||
|
|
||||||
.mat-mdc-chip-action-label {
|
.mat-mdc-chip-action-label {
|
||||||
padding: 0 4px;
|
padding: 0 4px;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -227,8 +390,6 @@
|
|||||||
gap: 4px;
|
gap: 4px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show remove button on hover for removable chips
|
|
||||||
&:hover {
|
&:hover {
|
||||||
::ng-deep .mat-mdc-chip-remove {
|
::ng-deep .mat-mdc-chip-remove {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
@@ -236,7 +397,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Style for removable chips
|
|
||||||
::ng-deep .mat-mdc-chip-remove {
|
::ng-deep .mat-mdc-chip-remove {
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transition: opacity 0.2s ease;
|
transition: opacity 0.2s ease;
|
||||||
@@ -262,12 +422,9 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
::ng-deep .mat-mdc-chip-option.compact-chip {
|
@container keyword-tool (max-width: #{$tablet}) {
|
||||||
.mat-mdc-chip-action-label {
|
.compact-chip {
|
||||||
padding: 0 4px;
|
width: 100%;
|
||||||
}
|
|
||||||
.mat-mdc-chip-action {
|
|
||||||
padding: 0 4px;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,86 +439,135 @@
|
|||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/* ============================================================
|
||||||
.select-all-container {
|
SEARCH BUTTONS
|
||||||
|
============================================================ */
|
||||||
|
.search-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
justify-content: center;
|
||||||
gap: 0.5rem;
|
align-items: center;
|
||||||
justify-content: flex-end;
|
gap: 1rem;
|
||||||
margin-top: 0.5rem;
|
margin-top: 1rem;
|
||||||
|
padding: 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
button {
|
.search-actions {
|
||||||
font-size: 0.75rem;
|
display: flex;
|
||||||
padding: 0 12px;
|
justify-content: center;
|
||||||
line-height: 30px;
|
align-items: center;
|
||||||
mat-icon {
|
gap: 0.75rem;
|
||||||
font-size: 18px;
|
}
|
||||||
width: 18px;
|
|
||||||
height: 18px;
|
.search-btn,
|
||||||
}
|
.visualize-btn {
|
||||||
|
min-width: 220px;
|
||||||
|
min-height: $touch-target;
|
||||||
|
align-self: center;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tablet */
|
||||||
|
@media (max-width: $tablet) {
|
||||||
|
.search-container {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-actions {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-btn,
|
||||||
|
.visualize-btn {
|
||||||
|
width: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.search-container {
|
/* Phone */
|
||||||
display: flex;
|
@media (max-width: $phone) {
|
||||||
justify-content: flex-end;
|
.search-container {
|
||||||
margin-top: 0.5rem;
|
position: sticky;
|
||||||
}
|
bottom: 0;
|
||||||
|
z-index: 5;
|
||||||
|
background: var(--sg-background, #fff);
|
||||||
|
padding: 0.75rem 0.5rem;
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
/* Responsive: stack columns on small screens */
|
.search-actions {
|
||||||
@media (max-width: 768px) {
|
flex-direction: column;
|
||||||
.table-head,
|
width: 100%;
|
||||||
.table-body {
|
}
|
||||||
|
|
||||||
|
.search-btn,
|
||||||
|
.visualize-btn {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* ============================================================
|
||||||
|
TABS (URL / Text) — stretch on smaller containers
|
||||||
|
============================================================ */
|
||||||
|
@container keyword-tool (max-width: #{$tablet}) {
|
||||||
|
.content ::ng-deep .mat-mdc-tab-labels {
|
||||||
|
justify-content: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content ::ng-deep .mat-mdc-tab {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-content {
|
||||||
|
display: grid;
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
|
|
||||||
.extracted-header {
|
.extract-btn {
|
||||||
grid-column: 1;
|
width: 100%;
|
||||||
grid-row: 1;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
.search-btn {
|
||||||
.own-header {
|
width: 100%;
|
||||||
grid-column: 1;
|
|
||||||
grid-row: 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
.broad-sub {
|
|
||||||
grid-column: 1;
|
|
||||||
grid-row: 3;
|
|
||||||
}
|
|
||||||
.coarse-sub {
|
|
||||||
grid-column: 1;
|
|
||||||
grid-row: 4;
|
|
||||||
}
|
|
||||||
.fine-sub {
|
|
||||||
grid-column: 1;
|
|
||||||
grid-row: 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
.actions {
|
|
||||||
align-self: center;
|
|
||||||
justify-content: flex-start;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-container {
|
|
||||||
justify-content: flex-start;
|
|
||||||
}
|
|
||||||
|
|
||||||
.table-col {
|
|
||||||
border-right: none; /* Remove column borders on mobile */
|
|
||||||
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
|
|
||||||
|
|
||||||
&:last-child {
|
|
||||||
border-bottom: none;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Source expansion panel */
|
|
||||||
|
/* ============================================================
|
||||||
|
PHONE-SPECIFIC FINE-TUNING
|
||||||
|
============================================================ */
|
||||||
|
@container keyword-tool (max-width: #{$phone}) {
|
||||||
|
.content {
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.keyword-card {
|
||||||
|
padding: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sub-cell {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.compact-chip {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
min-height: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-message {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
SOURCE EXPANSION PANEL
|
||||||
|
============================================================ */
|
||||||
.source-expansion {
|
.source-expansion {
|
||||||
margin: 0.75rem 0;
|
margin: 0.75rem 0;
|
||||||
background: var(--sg-background-muted, #f5f5f5);
|
background: var(--sg-background-muted, #f5f5f5);
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
border-left: 4px solid var(--sg-primary, #1976d2);
|
//border-left: 4px solid var(--sg-primary, #1976d2);
|
||||||
|
|
||||||
.mat-expansion-panel-header {
|
.mat-expansion-panel-header {
|
||||||
padding: 0.5rem 0.75rem;
|
padding: 0.5rem 0.75rem;
|
||||||
@@ -406,54 +612,80 @@
|
|||||||
background: rgba(0, 0, 0, 0.03);
|
background: rgba(0, 0, 0, 0.03);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
PROGRESS BAR
|
||||||
|
============================================================ */
|
||||||
.progress-container {
|
.progress-container {
|
||||||
margin-top: 1rem;
|
margin-top: 0.5rem;
|
||||||
padding: 0.5rem 0;
|
position: relative;
|
||||||
|
padding: 1rem;
|
||||||
|
background: var(--sg-surface);
|
||||||
|
border-radius: 4px;
|
||||||
|
|
||||||
// Make the progress bar container relative for the shimmer overlay
|
&.loading {
|
||||||
mat-progress-bar {
|
border-color: transparent;
|
||||||
position: relative;
|
|
||||||
overflow: hidden; // keeps the shimmer inside the bar
|
|
||||||
|
|
||||||
// --- Set the bar fill to a constant blue ---
|
|
||||||
// Using the primary blue (adjust to your preferred "hell blue")
|
|
||||||
::ng-deep .mat-progress-bar-fill::after {
|
|
||||||
background-color: #2196f3; // bright blue
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Shimmer overlay (a moving highlight) ---
|
|
||||||
&::after {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
pointer-events: none; // allow clicks to pass through
|
|
||||||
background: linear-gradient(
|
|
||||||
105deg,
|
|
||||||
transparent 0%,
|
|
||||||
rgba(5, 65, 230, 0.4) 100%,
|
|
||||||
transparent 0%
|
|
||||||
);
|
|
||||||
animation: shimmer 2s ease-in-out infinite;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.status-message {
|
&.loading::before {
|
||||||
margin-top: 0.5rem;
|
content: '';
|
||||||
font-size: 0.9rem;
|
position: absolute;
|
||||||
color: var(--sg-text-secondary);
|
inset: 0;
|
||||||
text-align: center;
|
border-radius: inherit;
|
||||||
font-weight: 500;
|
padding: 2px;
|
||||||
|
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
transparent 0%,
|
||||||
|
transparent 35%,
|
||||||
|
#2196f3 50%,
|
||||||
|
transparent 65%,
|
||||||
|
transparent 100%
|
||||||
|
);
|
||||||
|
|
||||||
|
background-size: 200% 100%;
|
||||||
|
animation: border-loading 1.5s linear infinite;
|
||||||
|
|
||||||
|
-webkit-mask:
|
||||||
|
linear-gradient(#fff 0 0) content-box,
|
||||||
|
linear-gradient(#fff 0 0);
|
||||||
|
-webkit-mask-composite: xor;
|
||||||
|
mask-composite: exclude;
|
||||||
|
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.status-message {
|
||||||
|
align-self: center;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--sg-text-secondary);
|
||||||
|
text-align: center;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
@keyframes border-loading {
|
||||||
|
from {
|
||||||
|
background-position: 200% 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
background-position: -200% 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* ============================================================
|
||||||
|
ACCESSIBILITY
|
||||||
|
============================================================ */
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.compact-chip,
|
||||||
|
.progress-container mat-progress-bar::after {
|
||||||
|
animation: none !important;
|
||||||
|
transition: none !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes shimmer {
|
button:focus-visible,
|
||||||
0% {
|
.mat-button-toggle:focus-visible,
|
||||||
transform: translateX(-100%);
|
::ng-deep .mat-mdc-tab:focus-visible {
|
||||||
}
|
outline: 2px solid var(--sg-primary, #1976d2);
|
||||||
100% {
|
outline-offset: 2px;
|
||||||
transform: translateX(100%);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,9 @@
|
|||||||
import {
|
import { Component, computed, signal, inject } from '@angular/core';
|
||||||
Component,
|
import { BreakpointObserver } from '@angular/cdk/layout';
|
||||||
computed,
|
|
||||||
signal,
|
|
||||||
Signal,
|
|
||||||
WritableSignal,
|
|
||||||
} from '@angular/core';
|
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
|
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatCardModule } from '@angular/material/card';
|
import { MatCardModule } from '@angular/material/card';
|
||||||
import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips';
|
|
||||||
import { MatDividerModule } from '@angular/material/divider';
|
import { MatDividerModule } from '@angular/material/divider';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
@@ -28,10 +22,36 @@ import { TopicsService } from '../../api/api/topics.service';
|
|||||||
import { KeywordsTopicsRequest } from '../../api/model/keywordsTopicsRequest';
|
import { KeywordsTopicsRequest } from '../../api/model/keywordsTopicsRequest';
|
||||||
import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic';
|
import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic';
|
||||||
import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.component';
|
import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.component';
|
||||||
|
import { UniTrendParentComponent } from '../university-ranking/uni-trend-parent/uni-trend-parent.component';
|
||||||
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
|
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
|
||||||
|
import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component';
|
||||||
|
import { Topic } from '../../api/model/topic';
|
||||||
|
import { NgTemplateOutlet } from '@angular/common';
|
||||||
|
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
|
||||||
|
import { map } from 'rxjs/operators';
|
||||||
|
import { toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import { MatSliderModule } from '@angular/material/slider';
|
||||||
|
import {
|
||||||
|
MatButtonToggleModule,
|
||||||
|
MatButtonToggleGroup,
|
||||||
|
} from '@angular/material/button-toggle';
|
||||||
|
import {
|
||||||
|
topicHierarchyColor,
|
||||||
|
TopicHierarchyColorInput,
|
||||||
|
} from '../../resolvers/utils/topic-colors';
|
||||||
|
import {
|
||||||
|
buildTopicLegendGroups,
|
||||||
|
TopicLegendGroup,
|
||||||
|
TopicLegendTopic,
|
||||||
|
} from '../../resolvers/utils/topic-legend';
|
||||||
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
|
import { A11yModule } from '@angular/cdk/a11y';
|
||||||
|
import { DomSanitizer } from '@angular/platform-browser';
|
||||||
|
import { SearchResultsPayload } from './search-results/search-results-state.service';
|
||||||
type InputMode = 'url' | 'text';
|
type InputMode = 'url' | 'text';
|
||||||
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
|
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
|
||||||
|
type KeywordView = 'llm' | 'topic';
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-keywords-search',
|
selector: 'app-keywords-search',
|
||||||
imports: [
|
imports: [
|
||||||
@@ -41,17 +61,35 @@ type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
|
|||||||
MatInputModule,
|
MatInputModule,
|
||||||
MatButtonModule,
|
MatButtonModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
MatChipsModule,
|
|
||||||
MatDividerModule,
|
MatDividerModule,
|
||||||
MatCardModule,
|
MatCardModule,
|
||||||
MatExpansionModule,
|
MatExpansionModule,
|
||||||
MatProgressBarModule,
|
MatProgressBarModule,
|
||||||
TopicAutocompleteComponent,
|
TopicAutocompleteComponent,
|
||||||
|
UniTrendParentComponent,
|
||||||
|
TopicChipComponent,
|
||||||
|
TopicLegendComponent,
|
||||||
|
MatButtonToggleModule,
|
||||||
|
MatButtonToggleGroup,
|
||||||
|
MatTooltipModule,
|
||||||
|
A11yModule,
|
||||||
|
NgTemplateOutlet,
|
||||||
|
LoadingComponent,
|
||||||
|
MatSlideToggleModule,
|
||||||
|
MatSliderModule,
|
||||||
],
|
],
|
||||||
templateUrl: './keywords-search.component.html',
|
templateUrl: './keywords-search.component.html',
|
||||||
styleUrl: './keywords-search.component.scss',
|
styleUrl: './keywords-search.component.scss',
|
||||||
})
|
})
|
||||||
export class KeywordsSearchComponent {
|
export class KeywordsSearchComponent {
|
||||||
|
private readonly formBuilder = inject(FormBuilder);
|
||||||
|
private readonly sanitizer = inject(DomSanitizer);
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
private readonly websocketService = inject(KeywordWebSocketService);
|
||||||
|
private readonly topicsService = inject(TopicsService);
|
||||||
|
|
||||||
readonly form = this.formBuilder.nonNullable.group({
|
readonly form = this.formBuilder.nonNullable.group({
|
||||||
selectedInputType: 'url' as InputMode,
|
selectedInputType: 'url' as InputMode,
|
||||||
urlInput: '',
|
urlInput: '',
|
||||||
@@ -59,7 +97,17 @@ export class KeywordsSearchComponent {
|
|||||||
});
|
});
|
||||||
|
|
||||||
private readonly SESSION_KEY = 'keywords-search-source';
|
private readonly SESSION_KEY = 'keywords-search-source';
|
||||||
|
private readonly SEARCH_RESULTS_HANDOFF_KEY = 'search-results-handoff';
|
||||||
|
|
||||||
|
// in component class:
|
||||||
|
private breakpointObserver = inject(BreakpointObserver);
|
||||||
|
|
||||||
|
isMobile = toSignal(
|
||||||
|
this.breakpointObserver
|
||||||
|
.observe('(max-width: 768px)')
|
||||||
|
.pipe(map((r) => r.matches)),
|
||||||
|
{ initialValue: false },
|
||||||
|
);
|
||||||
// Category signals - the full backend entries are the source of truth;
|
// Category signals - the full backend entries are the source of truth;
|
||||||
// the *Keywords() computed signals below just project the label out of them.
|
// the *Keywords() computed signals below just project the label out of them.
|
||||||
private readonly broadKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
|
private readonly broadKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
|
||||||
@@ -67,60 +115,78 @@ export class KeywordsSearchComponent {
|
|||||||
private readonly fineKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
|
private readonly fineKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
|
||||||
private readonly manualKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
|
private readonly manualKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
|
||||||
|
|
||||||
readonly broadKeywords = computed(() =>
|
readonly broadKeywords = computed(() => this.broadKeywordEntries());
|
||||||
this.broadKeywordEntries().map((item) => this.getKeywordLabel(item)),
|
readonly coarseKeywords = computed(() => this.coarseKeywordEntries());
|
||||||
);
|
readonly fineKeywords = computed(() => this.fineKeywordEntries());
|
||||||
readonly coarseKeywords = computed(() =>
|
readonly manualKeywords = computed(() => this.manualKeywordEntries());
|
||||||
this.coarseKeywordEntries().map((item) => this.getKeywordLabel(item)),
|
|
||||||
);
|
|
||||||
readonly fineKeywords = computed(() =>
|
|
||||||
this.fineKeywordEntries().map((item) => this.getKeywordLabel(item)),
|
|
||||||
);
|
|
||||||
readonly manualKeywords = computed(() =>
|
|
||||||
this.manualKeywordEntries().map((item) => this.getKeywordLabel(item)),
|
|
||||||
);
|
|
||||||
|
|
||||||
readonly selectedKeywords = signal<string[]>([]);
|
readonly selectedKeywords = signal<string[]>([]);
|
||||||
readonly isExtracting = signal(false);
|
readonly isExtracting = signal(false);
|
||||||
|
readonly loadingNewKeyword = signal(false);
|
||||||
readonly extractionSource = signal<InputMode | null>(null);
|
readonly extractionSource = signal<InputMode | null>(null);
|
||||||
|
readonly showVisualization = signal<boolean>(false);
|
||||||
|
readonly topicMappingSearch = signal<boolean>(false);
|
||||||
|
|
||||||
// Single place mapping a category name to its label signal and its
|
readonly keywordsExist = computed(
|
||||||
// backing entries signal. Replaces four near-identical computed()s and
|
|
||||||
// a category switch statement that used to live below.
|
|
||||||
private readonly categoryKeywordsMap: Record<
|
|
||||||
KeywordCategory,
|
|
||||||
Signal<string[]>
|
|
||||||
> = {
|
|
||||||
broad: this.broadKeywords,
|
|
||||||
coarse: this.coarseKeywords,
|
|
||||||
fine: this.fineKeywords,
|
|
||||||
manual: this.manualKeywords,
|
|
||||||
};
|
|
||||||
private readonly categoryEntriesMap: Record<
|
|
||||||
KeywordCategory,
|
|
||||||
WritableSignal<KeywordEntryWithTopic[]>
|
|
||||||
> = {
|
|
||||||
broad: this.broadKeywordEntries,
|
|
||||||
coarse: this.coarseKeywordEntries,
|
|
||||||
fine: this.fineKeywordEntries,
|
|
||||||
manual: this.manualKeywordEntries,
|
|
||||||
};
|
|
||||||
|
|
||||||
readonly selectedBroadKeywords = this.selectedInCategory('broad');
|
|
||||||
readonly selectedCoarseKeywords = this.selectedInCategory('coarse');
|
|
||||||
readonly selectedFineKeywords = this.selectedInCategory('fine');
|
|
||||||
readonly selectedManualKeywords = this.selectedInCategory('manual');
|
|
||||||
|
|
||||||
readonly extractedKeywordsExist = computed(
|
|
||||||
() =>
|
() =>
|
||||||
this.broadKeywords().length > 0 ||
|
this.broadKeywords().length > 0 ||
|
||||||
this.coarseKeywords().length > 0 ||
|
this.coarseKeywords().length > 0 ||
|
||||||
this.fineKeywords().length > 0,
|
this.fineKeywords().length > 0 ||
|
||||||
|
this.manualKeywords().length > 0,
|
||||||
);
|
);
|
||||||
|
|
||||||
readonly sourceContent = signal<string>('');
|
readonly sourceContent = signal<string>('');
|
||||||
readonly sourceUrl = signal<string | null>(null);
|
readonly sourceUrl = signal<string | null>(null);
|
||||||
|
|
||||||
|
readonly highlightedSourceContent = computed(() => {
|
||||||
|
const content = this.sourceContent();
|
||||||
|
if (!content) return '';
|
||||||
|
|
||||||
|
const selectedKeywords = this.selectedKeywords();
|
||||||
|
if (selectedKeywords.length === 0) return content;
|
||||||
|
|
||||||
|
let highlightedContent = content;
|
||||||
|
|
||||||
|
// replace the keyword with highlighted spans
|
||||||
|
for (const keyword of selectedKeywords) {
|
||||||
|
const normalizedKeyword = this.normalizeKeyword(keyword);
|
||||||
|
|
||||||
|
// Find the first keyword entry that matches this normalized keyword
|
||||||
|
const entry = this.allKeywordEntries().find(
|
||||||
|
(e) =>
|
||||||
|
this.normalizeKeyword(this.getKeywordLabel(e)) === normalizedKeyword,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (entry) {
|
||||||
|
const topic = this.getTopic(entry);
|
||||||
|
if (topic) {
|
||||||
|
const color = this.getTopicColor(topic);
|
||||||
|
// Escape HTML special characters in the keyword before using it in HTML
|
||||||
|
const escapedKeyword = keyword
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>');
|
||||||
|
|
||||||
|
// Create the replacement span HTML
|
||||||
|
const replacement = `<span style="text-decoration: underline; background-color: color-mix(in srgb, ${color} 27%, #ffffff); 100%); font-weight: bold;" title="Keyword: ${keyword}">${escapedKeyword}</span>`;
|
||||||
|
|
||||||
|
const escapedRegexKeyword = keyword.replace(
|
||||||
|
/[.*+?^${}()|[\]\\]/g,
|
||||||
|
'\\$&',
|
||||||
|
);
|
||||||
|
const regex = new RegExp(escapedRegexKeyword, 'g');
|
||||||
|
|
||||||
|
highlightedContent = highlightedContent.replace(regex, replacement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
'Highlighted content:',
|
||||||
|
this.sanitizer.bypassSecurityTrustHtml(highlightedContent),
|
||||||
|
);
|
||||||
|
return this.sanitizer.bypassSecurityTrustHtml(highlightedContent);
|
||||||
|
});
|
||||||
|
|
||||||
private isRestoringState = false;
|
private isRestoringState = false;
|
||||||
|
|
||||||
// Set right before we call router.navigate() ourselves (from
|
// Set right before we call router.navigate() ourselves (from
|
||||||
@@ -133,20 +199,27 @@ export class KeywordsSearchComponent {
|
|||||||
|
|
||||||
readonly progress = signal(0);
|
readonly progress = signal(0);
|
||||||
readonly statusMessage = signal('');
|
readonly statusMessage = signal('');
|
||||||
|
readonly keywordView = signal<KeywordView>('llm');
|
||||||
|
readonly subfieldLegendVisible = signal(true);
|
||||||
|
readonly subfieldLegendExpanded = signal(false);
|
||||||
|
|
||||||
constructor(
|
get topicLegendGroups(): TopicLegendGroup[] {
|
||||||
private readonly formBuilder: FormBuilder,
|
const topics = [
|
||||||
private readonly route: ActivatedRoute,
|
...this.broadKeywordEntries(),
|
||||||
private readonly router: Router,
|
...this.coarseKeywordEntries(),
|
||||||
private readonly destroyRef: DestroyRef,
|
...this.fineKeywordEntries(),
|
||||||
private readonly websocketService: KeywordWebSocketService,
|
...this.manualKeywordEntries(),
|
||||||
private readonly topicsService: TopicsService,
|
]
|
||||||
) {
|
.map((entry) => entry.topic_mapping?.topic)
|
||||||
|
.filter((topic): topic is Topic => Boolean(topic))
|
||||||
|
.map((topic) => this.toTopicLegendTopic(topic));
|
||||||
|
|
||||||
|
return buildTopicLegendGroups(topics);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor() {
|
||||||
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(() => {
|
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(() => {
|
||||||
if (this.isOwnNavigation) {
|
if (this.isOwnNavigation) {
|
||||||
// This emission is just the router confirming the navigation we
|
|
||||||
// triggered ourselves in updateQueryParams(); our signals are
|
|
||||||
// already correct, so skip re-deriving state from the URL.
|
|
||||||
this.isOwnNavigation = false;
|
this.isOwnNavigation = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -169,15 +242,13 @@ export class KeywordsSearchComponent {
|
|||||||
.getMessages()
|
.getMessages()
|
||||||
.subscribe((event: WsEvent) => this.handleWsEvent(event));
|
.subscribe((event: WsEvent) => this.handleWsEvent(event));
|
||||||
|
|
||||||
// Clear session storage on component destroy, unless this is a page
|
// this.destroyRef.onDestroy(() => {
|
||||||
// reload (in which case we want the cache to survive).
|
// this.websocketService.close();
|
||||||
this.destroyRef.onDestroy(() => {
|
// const isReload = this.router.lastSuccessfulNavigation === null;
|
||||||
this.websocketService.close();
|
// if (!isReload) {
|
||||||
const isReload = this.router.lastSuccessfulNavigation === null;
|
// this.clearStateFromSession();
|
||||||
if (!isReload) {
|
// }
|
||||||
this.clearSourceFromSession();
|
// });
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Websocket event handling ---------------------------------------
|
// --- Websocket event handling ---------------------------------------
|
||||||
@@ -220,9 +291,12 @@ export class KeywordsSearchComponent {
|
|||||||
this.fineKeywordEntries.set([]);
|
this.fineKeywordEntries.set([]);
|
||||||
this.websocketService.close();
|
this.websocketService.close();
|
||||||
this.isExtracting.set(false);
|
this.isExtracting.set(false);
|
||||||
|
this.loadingNewKeyword.set(false);
|
||||||
// Keep manual, but remove selected that are not in manual
|
// Keep manual, but remove selected that are not in manual
|
||||||
this.selectedKeywords.set(
|
this.selectedKeywords.set(
|
||||||
this.selectedKeywords().filter((k) => this.manualKeywords().includes(k)),
|
this.selectedKeywords().filter((k) =>
|
||||||
|
this.getKeywordLabels(this.manualKeywords()).includes(k),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
}
|
}
|
||||||
@@ -295,16 +369,14 @@ export class KeywordsSearchComponent {
|
|||||||
private keywordExists(keyword: string): boolean {
|
private keywordExists(keyword: string): boolean {
|
||||||
const normalized = this.normalizeKeyword(keyword);
|
const normalized = this.normalizeKeyword(keyword);
|
||||||
return [
|
return [
|
||||||
...this.broadKeywords(),
|
...this.getKeywordLabels(this.broadKeywords()),
|
||||||
...this.coarseKeywords(),
|
...this.getKeywordLabels(this.coarseKeywords()),
|
||||||
...this.fineKeywords(),
|
...this.getKeywordLabels(this.fineKeywords()),
|
||||||
...this.manualKeywords(),
|
...this.getKeywordLabels(this.manualKeywords()),
|
||||||
].some((k) => this.normalizeKeyword(k) === normalized);
|
].some((k) => this.normalizeKeyword(k) === normalized);
|
||||||
}
|
}
|
||||||
|
addKeywordFromInput(keyword: Topic): void {
|
||||||
// Add manually from Keywords tab
|
const normalizedKeyword = keyword.display_name?.trim() ?? '';
|
||||||
addKeywordFromInput(keyword: string): void {
|
|
||||||
const normalizedKeyword = keyword.trim();
|
|
||||||
if (!normalizedKeyword) return;
|
if (!normalizedKeyword) return;
|
||||||
|
|
||||||
if (this.keywordExists(normalizedKeyword)) {
|
if (this.keywordExists(normalizedKeyword)) {
|
||||||
@@ -312,35 +384,54 @@ export class KeywordsSearchComponent {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.topicsService.vectorSearchTopics(normalizedKeyword).subscribe({
|
this.loadingNewKeyword.set(true);
|
||||||
next: ({ results }) => {
|
|
||||||
const newEntry: KeywordEntryWithTopic = {
|
|
||||||
llm_keyword: {
|
|
||||||
keyword: normalizedKeyword,
|
|
||||||
relevance_score: 1,
|
|
||||||
},
|
|
||||||
topic_mapping: {
|
|
||||||
keyword: normalizedKeyword,
|
|
||||||
topic: results?.[0],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const updated = this.uniqueKeywordEntries([
|
if (keyword.id === null) {
|
||||||
...this.manualKeywordEntries(),
|
console.log('Adding new keyword without topic:', normalizedKeyword);
|
||||||
newEntry,
|
this.topicsService.vectorSearchTopics(normalizedKeyword).subscribe({
|
||||||
]);
|
next: ({ results }) => {
|
||||||
|
const newEntry: KeywordEntryWithTopic = {
|
||||||
|
llm_keyword: { keyword: normalizedKeyword, relevance_score: 1 },
|
||||||
|
topic_mapping: { keyword: normalizedKeyword, topic: results?.[0] },
|
||||||
|
};
|
||||||
|
|
||||||
this.manualKeywordEntries.set(updated);
|
this.manualKeywordEntries.set(
|
||||||
this.selectedKeywords.set([
|
this.uniqueKeywordEntries([
|
||||||
...this.selectedKeywords(),
|
...this.manualKeywordEntries(),
|
||||||
normalizedKeyword,
|
newEntry,
|
||||||
]);
|
]),
|
||||||
|
);
|
||||||
// Explicit enrichment trigger for new keywords
|
this.selectedKeywords.set([
|
||||||
this.enrichManualKeywordsWithTopics([normalizedKeyword]);
|
...this.selectedKeywords(),
|
||||||
this.updateQueryParams();
|
normalizedKeyword,
|
||||||
},
|
]);
|
||||||
});
|
this.loadingNewKeyword.set(false);
|
||||||
|
this.updateQueryParams(); // now fires after state is actually updated
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
console.error('vectorSearchTopics failed', err);
|
||||||
|
this.loadingNewKeyword.set(false);
|
||||||
|
this.statusMessage.set(
|
||||||
|
`Fehler beim Hinzufügen von "${normalizedKeyword}".`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log('topic was already there', keyword);
|
||||||
|
const newEntry: KeywordEntryWithTopic = {
|
||||||
|
llm_keyword: { keyword: normalizedKeyword, relevance_score: 1 },
|
||||||
|
topic_mapping: { keyword: normalizedKeyword, topic: keyword },
|
||||||
|
};
|
||||||
|
this.manualKeywordEntries.set(
|
||||||
|
this.uniqueKeywordEntries([...this.manualKeywordEntries(), newEntry]),
|
||||||
|
);
|
||||||
|
this.selectedKeywords.set([
|
||||||
|
...this.selectedKeywords(),
|
||||||
|
normalizedKeyword,
|
||||||
|
]);
|
||||||
|
this.loadingNewKeyword.set(false);
|
||||||
|
this.updateQueryParams();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
removeSelectedKeyword(keyword: string): void {
|
removeSelectedKeyword(keyword: string): void {
|
||||||
@@ -350,50 +441,72 @@ export class KeywordsSearchComponent {
|
|||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
}
|
}
|
||||||
|
|
||||||
onCategoryChange(
|
toggleKeywordSelection(keyword: KeywordEntryWithTopic): void {
|
||||||
category: KeywordCategory,
|
const label = this.getKeywordLabel(keyword);
|
||||||
event: MatChipListboxChange,
|
const nextSelection = this.selectedKeywords().includes(label)
|
||||||
): void {
|
? this.selectedKeywords().filter((value) => value !== label)
|
||||||
const newSelection = (event.value as string[]) || [];
|
: [...this.selectedKeywords(), label];
|
||||||
const otherCategories = (
|
|
||||||
Object.keys(this.categoryKeywordsMap) as KeywordCategory[]
|
this.selectedKeywords.set(this.uniqueKeywords(nextSelection));
|
||||||
).filter((c) => c !== category);
|
|
||||||
const otherSelected = otherCategories.flatMap((c) => {
|
|
||||||
const keywords = this.categoryKeywordsMap[c]();
|
|
||||||
return this.selectedKeywords().filter((k) => keywords.includes(k));
|
|
||||||
});
|
|
||||||
const updated = [...otherSelected, ...newSelection];
|
|
||||||
this.selectedKeywords.set(this.uniqueKeywords(updated));
|
|
||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
}
|
}
|
||||||
|
|
||||||
selectAllExtracted(): void {
|
isKeywordSelected(keyword: KeywordEntryWithTopic): boolean {
|
||||||
const all = [
|
const normalized = this.normalizeKeyword(this.getKeywordLabel(keyword));
|
||||||
...this.selectedManualKeywords(),
|
return this.selectedKeywords().some(
|
||||||
...this.broadKeywords(),
|
(value) => this.normalizeKeyword(value) === normalized,
|
||||||
...this.coarseKeywords(),
|
);
|
||||||
...this.fineKeywords(),
|
|
||||||
];
|
|
||||||
this.selectedKeywords.set(this.uniqueKeywords(all));
|
|
||||||
this.updateQueryParams();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
deselectAllExtracted(): void {
|
removeManualKeyword(keyword: KeywordEntryWithTopic): void {
|
||||||
|
const label = this.getKeywordLabel(keyword);
|
||||||
|
this.manualKeywordEntries.set(
|
||||||
|
this.filterKeywordEntries(this.manualKeywordEntries(), label),
|
||||||
|
);
|
||||||
this.selectedKeywords.set(
|
this.selectedKeywords.set(
|
||||||
this.uniqueKeywords(this.selectedManualKeywords()),
|
this.selectedKeywords().filter((value) => value !== label),
|
||||||
);
|
);
|
||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
}
|
}
|
||||||
|
allKeywordEntries = computed(() => [
|
||||||
|
...this.manualKeywords(),
|
||||||
|
...this.broadKeywords(),
|
||||||
|
...this.coarseKeywords(),
|
||||||
|
...this.fineKeywords(),
|
||||||
|
]);
|
||||||
|
|
||||||
clearExtractedKeywords(): void {
|
selectAll(): void {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const result: string[] = [];
|
||||||
|
|
||||||
|
for (const entry of this.allKeywordEntries()) {
|
||||||
|
const label = entry.llm_keyword.keyword;
|
||||||
|
const normalized = this.normalizeKeyword(label);
|
||||||
|
if (!seen.has(normalized)) {
|
||||||
|
seen.add(normalized);
|
||||||
|
result.push(label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.selectedKeywords.set(result);
|
||||||
|
this.updateQueryParams();
|
||||||
|
}
|
||||||
|
|
||||||
|
deselectAll(): void {
|
||||||
|
this.selectedKeywords.set([]);
|
||||||
|
this.updateQueryParams();
|
||||||
|
}
|
||||||
|
|
||||||
|
clearKeywords(): void {
|
||||||
this.broadKeywordEntries.set([]);
|
this.broadKeywordEntries.set([]);
|
||||||
this.coarseKeywordEntries.set([]);
|
this.coarseKeywordEntries.set([]);
|
||||||
this.fineKeywordEntries.set([]);
|
this.fineKeywordEntries.set([]);
|
||||||
|
this.manualKeywordEntries.set([]);
|
||||||
this.sourceContent.set('');
|
this.sourceContent.set('');
|
||||||
this.sourceUrl.set(null);
|
this.sourceUrl.set(null);
|
||||||
|
|
||||||
// Keep only selected keywords that are in the manual list
|
// Keep only selected keywords that are in the manual list
|
||||||
const manualSet = new Set(this.manualKeywords());
|
const manualSet = new Set(this.getKeywordLabels(this.manualKeywords()));
|
||||||
this.selectedKeywords.set(
|
this.selectedKeywords.set(
|
||||||
this.selectedKeywords().filter((k) => manualSet.has(k)),
|
this.selectedKeywords().filter((k) => manualSet.has(k)),
|
||||||
);
|
);
|
||||||
@@ -402,16 +515,17 @@ export class KeywordsSearchComponent {
|
|||||||
this.extractionSource.set(null);
|
this.extractionSource.set(null);
|
||||||
|
|
||||||
// updateQueryParams() persists this cleared state to sessionStorage too
|
// updateQueryParams() persists this cleared state to sessionStorage too
|
||||||
// (see saveSourceToSession() call inside it), so there's no need to
|
// (see saveStateToSession() call inside it), so there's no need to
|
||||||
// separately wipe the session key here.
|
// separately wipe the session key here.
|
||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
}
|
}
|
||||||
|
|
||||||
areAllExtractedSelected(): boolean {
|
areAllSelected(): boolean {
|
||||||
const allExtracted = [
|
const allExtracted = [
|
||||||
...this.broadKeywords(),
|
...this.getKeywordLabels(this.broadKeywords()),
|
||||||
...this.coarseKeywords(),
|
...this.getKeywordLabels(this.coarseKeywords()),
|
||||||
...this.fineKeywords(),
|
...this.getKeywordLabels(this.fineKeywords()),
|
||||||
|
...this.getKeywordLabels(this.manualKeywords()),
|
||||||
];
|
];
|
||||||
return allExtracted.every((k) => this.selectedKeywords().includes(k));
|
return allExtracted.every((k) => this.selectedKeywords().includes(k));
|
||||||
}
|
}
|
||||||
@@ -432,16 +546,6 @@ export class KeywordsSearchComponent {
|
|||||||
this.applyExtractedKeywords(keywords);
|
this.applyExtractedKeywords(keywords);
|
||||||
}
|
}
|
||||||
|
|
||||||
onKeywordRemoved(category: KeywordCategory, keyword: string): void {
|
|
||||||
const entries = this.categoryEntriesMap[category];
|
|
||||||
entries.set(this.filterKeywordEntries(entries(), keyword));
|
|
||||||
|
|
||||||
this.selectedKeywords.set(
|
|
||||||
this.selectedKeywords().filter((k) => k !== keyword),
|
|
||||||
);
|
|
||||||
this.updateQueryParams();
|
|
||||||
}
|
|
||||||
|
|
||||||
processExtractedKeywords(result: ExtractedKeywordsResponse): void {
|
processExtractedKeywords(result: ExtractedKeywordsResponse): void {
|
||||||
if (result === undefined || !result.results) return;
|
if (result === undefined || !result.results) return;
|
||||||
|
|
||||||
@@ -454,22 +558,22 @@ export class KeywordsSearchComponent {
|
|||||||
|
|
||||||
// Keep only selected keywords that still exist in any category (including manual)
|
// Keep only selected keywords that still exist in any category (including manual)
|
||||||
const allExtracted = [
|
const allExtracted = [
|
||||||
...this.broadKeywords(),
|
...this.getKeywordLabels(this.broadKeywords()),
|
||||||
...this.coarseKeywords(),
|
...this.getKeywordLabels(this.coarseKeywords()),
|
||||||
...this.fineKeywords(),
|
...this.getKeywordLabels(this.fineKeywords()),
|
||||||
...this.manualKeywords(),
|
...this.getKeywordLabels(this.manualKeywords()),
|
||||||
];
|
];
|
||||||
this.selectedKeywords.set(
|
this.selectedKeywords.set(
|
||||||
this.selectedKeywords().filter((k) => allExtracted.includes(k)),
|
this.selectedKeywords().filter((k) => allExtracted.includes(k)),
|
||||||
);
|
);
|
||||||
|
|
||||||
// updateQueryParams() also calls saveSourceToSession() - no need to call
|
// updateQueryParams() also calls saveStateToSession() - no need to call
|
||||||
// it separately here.
|
// it separately here.
|
||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
}
|
}
|
||||||
|
|
||||||
async extractKeywords(): Promise<void> {
|
async extractKeywords(): Promise<void> {
|
||||||
this.clearExtractedKeywords();
|
this.clearKeywords();
|
||||||
const query = this.getCurrentExtractionQuery();
|
const query = this.getCurrentExtractionQuery();
|
||||||
if (!query) return;
|
if (!query) return;
|
||||||
|
|
||||||
@@ -503,30 +607,48 @@ export class KeywordsSearchComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
search(): void {
|
search(): void {
|
||||||
const payload = {
|
this.showVisualization.set(false);
|
||||||
|
|
||||||
|
const payload: SearchResultsPayload = {
|
||||||
extractedKeywords: this.getSelectedExtractedKeywordEntries(),
|
extractedKeywords: this.getSelectedExtractedKeywordEntries(),
|
||||||
manualKeywords: this.getSelectedManualKeywordEntries(),
|
manualKeywords: this.getSelectedManualKeywordEntries(),
|
||||||
keywords: this.selectedKeywords(),
|
keywords: this.selectedKeywords(),
|
||||||
|
options: {
|
||||||
|
softSearch: this.topicMappingSearch(),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log('searching for keywords:', payload);
|
// Best-effort cache for the heavier, topic-enriched entries.
|
||||||
// e.g. navigate to search results page with the full payload in navigation state
|
// Not authoritative — search-results must work without it.
|
||||||
// this.router.navigate(['/search'], { state: payload });
|
try {
|
||||||
|
sessionStorage.setItem(
|
||||||
|
this.SEARCH_RESULTS_HANDOFF_KEY,
|
||||||
|
JSON.stringify(payload),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to cache search-results handoff:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authoritative, reload-safe, shareable.
|
||||||
|
this.router.navigate(['keywords/search-results'], {
|
||||||
|
queryParams: {
|
||||||
|
keywords: this.serializeKeywords(payload.keywords),
|
||||||
|
softSearch: payload.options.softSearch ? true : false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
visualize(): void {
|
||||||
|
this.showVisualization.set(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Helpers --------------------------------------------------------------
|
// --- Helpers --------------------------------------------------------------
|
||||||
|
|
||||||
private selectedInCategory(category: KeywordCategory): Signal<string[]> {
|
|
||||||
return computed(() =>
|
|
||||||
this.selectedKeywords().filter((k) =>
|
|
||||||
this.categoryKeywordsMap[category]().includes(k),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private applyExtractedKeywords(keywords: ExtractedKeywords): void {
|
private applyExtractedKeywords(keywords: ExtractedKeywords): void {
|
||||||
const seenKeywords = new Set(
|
const seenKeywords = new Set(
|
||||||
this.manualKeywords().map((keyword) => this.normalizeKeyword(keyword)),
|
this.getKeywordLabels(this.manualKeywords()).map((keyword) =>
|
||||||
|
this.normalizeKeyword(keyword),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
this.broadKeywordEntries.set(
|
this.broadKeywordEntries.set(
|
||||||
this.uniqueKeywordEntries(keywords.broad_keywords, seenKeywords),
|
this.uniqueKeywordEntries(keywords.broad_keywords, seenKeywords),
|
||||||
@@ -537,6 +659,7 @@ export class KeywordsSearchComponent {
|
|||||||
this.fineKeywordEntries.set(
|
this.fineKeywordEntries.set(
|
||||||
this.uniqueKeywordEntries(keywords.fine_grained, seenKeywords),
|
this.uniqueKeywordEntries(keywords.fine_grained, seenKeywords),
|
||||||
);
|
);
|
||||||
|
this.selectAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
private getSelectedExtractedKeywordEntries(): KeywordEntryWithTopic[] {
|
private getSelectedExtractedKeywordEntries(): KeywordEntryWithTopic[] {
|
||||||
@@ -571,9 +694,96 @@ export class KeywordsSearchComponent {
|
|||||||
this.normalizeKeyword(this.getKeywordLabel(item)) !== normalized,
|
this.normalizeKeyword(this.getKeywordLabel(item)) !== normalized,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
onViewToggleChange(value: KeywordView): void {
|
||||||
|
if (this.keywordView() !== value) {
|
||||||
|
this.keywordView.set(value);
|
||||||
|
}
|
||||||
|
this.updateQueryParams();
|
||||||
|
}
|
||||||
|
onToggleTopicMappingSearch(event: any): void {
|
||||||
|
this.topicMappingSearch.set(event.checked);
|
||||||
|
this.updateQueryParams();
|
||||||
|
}
|
||||||
|
onSubfieldLegendVisibleChange(visible: boolean): void {
|
||||||
|
this.subfieldLegendVisible.set(visible);
|
||||||
|
this.updateQueryParams();
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubfieldLegendExpandedChange(expanded: boolean): void {
|
||||||
|
this.subfieldLegendExpanded.set(expanded);
|
||||||
|
this.updateQueryParams();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use this instead of directly binding keyword.topic_mapping?.topic?.display_name
|
||||||
|
getChipLabel(keyword: KeywordEntryWithTopic): string {
|
||||||
|
if (this.keywordView() == 'llm') {
|
||||||
|
return keyword.llm_keyword?.keyword ?? '';
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
keyword.topic_mapping?.topic?.display_name ??
|
||||||
|
keyword.llm_keyword?.keyword ??
|
||||||
|
''
|
||||||
|
);
|
||||||
|
}
|
||||||
private getKeywordLabel(item: KeywordEntryWithTopic): string {
|
private getKeywordLabel(item: KeywordEntryWithTopic): string {
|
||||||
return item.llm_keyword.keyword.trim();
|
return item.llm_keyword.keyword;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getKeywordLabels(items: KeywordEntryWithTopic[]): string[] {
|
||||||
|
return items.map((item) => this.getKeywordLabel(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
private getTopic(item: KeywordEntryWithTopic) {
|
||||||
|
return item.topic_mapping?.topic ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipDescription(item: KeywordEntryWithTopic): string | null {
|
||||||
|
return this.getTopic(item)?.description ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipSubfieldName(item: KeywordEntryWithTopic): string | null {
|
||||||
|
return this.getTopic(item)?.subfield?.display_name ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipFieldName(item: KeywordEntryWithTopic): string | null {
|
||||||
|
return this.getTopic(item)?.field?.display_name ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipDomainName(item: KeywordEntryWithTopic): string | null {
|
||||||
|
return this.getTopic(item)?.domain?.display_name ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipCount(item: KeywordEntryWithTopic): number | null {
|
||||||
|
const topic = this.getTopic(item);
|
||||||
|
return topic?.works_count ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private toTopicLegendTopic(topic: Topic): TopicLegendTopic {
|
||||||
|
return {
|
||||||
|
id: topic.id ?? topic.display_name ?? '',
|
||||||
|
name: topic.display_name ?? '',
|
||||||
|
field_id: topic.field?.id ?? null,
|
||||||
|
field_name: topic.field?.display_name ?? null,
|
||||||
|
field_description: null,
|
||||||
|
domain_id: topic.domain?.id ?? null,
|
||||||
|
domain_name: topic.domain?.display_name ?? null,
|
||||||
|
domain_description: null,
|
||||||
|
subfield_id: topic.subfield?.id ?? null,
|
||||||
|
subfield_name: topic.subfield?.display_name ?? null,
|
||||||
|
subfield_description: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
getTopicColor(topic: Topic | undefined | null): string {
|
||||||
|
const topicInput: TopicHierarchyColorInput = {
|
||||||
|
id: topic?.id ?? null,
|
||||||
|
name: topic?.display_name ?? null,
|
||||||
|
field_id: topic?.field?.id ?? null,
|
||||||
|
field_name: topic?.field?.display_name ?? null,
|
||||||
|
domain_id: topic?.domain?.id ?? null,
|
||||||
|
domain_name: topic?.domain?.display_name ?? null,
|
||||||
|
};
|
||||||
|
return topicHierarchyColor(topicInput);
|
||||||
}
|
}
|
||||||
|
|
||||||
private keywordEntriesFromStrings(
|
private keywordEntriesFromStrings(
|
||||||
@@ -621,16 +831,26 @@ export class KeywordsSearchComponent {
|
|||||||
const manual = this.parseKeywordList(queryParams.get('manual'));
|
const manual = this.parseKeywordList(queryParams.get('manual'));
|
||||||
const selected = this.parseKeywordList(queryParams.get('selected'));
|
const selected = this.parseKeywordList(queryParams.get('selected'));
|
||||||
const source = queryParams.get('source') ?? '';
|
const source = queryParams.get('source') ?? '';
|
||||||
|
const view = queryParams.get('view') ?? 'llm';
|
||||||
|
const legend = queryParams.get('legend') ?? 'on';
|
||||||
|
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
|
||||||
|
const softSearch = queryParams.get('softSearch') === 'true';
|
||||||
this.isRestoringState = true;
|
this.isRestoringState = true;
|
||||||
|
|
||||||
this.form.patchValue(
|
this.form.patchValue(
|
||||||
{ selectedInputType: mode, urlInput, textInput },
|
{
|
||||||
|
selectedInputType: mode,
|
||||||
|
urlInput,
|
||||||
|
textInput,
|
||||||
|
},
|
||||||
{ emitEvent: false },
|
{ emitEvent: false },
|
||||||
);
|
);
|
||||||
|
this.keywordView.set(view as KeywordView);
|
||||||
|
this.subfieldLegendVisible.set(legend === 'on');
|
||||||
|
this.subfieldLegendExpanded.set(legendExpanded === 'on');
|
||||||
this.extractionSource.set(source as InputMode);
|
this.extractionSource.set(source as InputMode);
|
||||||
this.restoreSourceFromSession();
|
this.topicMappingSearch.set(softSearch);
|
||||||
|
this.restoreStateFromSession();
|
||||||
|
|
||||||
const merged = this.uniqueKeywordEntries([
|
const merged = this.uniqueKeywordEntries([
|
||||||
...this.manualKeywordEntries(), // session restored entries
|
...this.manualKeywordEntries(), // session restored entries
|
||||||
@@ -649,18 +869,26 @@ export class KeywordsSearchComponent {
|
|||||||
|
|
||||||
// clean up the selection to only include keywords that actually exist in
|
// clean up the selection to only include keywords that actually exist in
|
||||||
const manualKeywordSet = new Set(
|
const manualKeywordSet = new Set(
|
||||||
this.manualKeywords().map((k) => this.normalizeKeyword(k)),
|
this.getKeywordLabels(this.manualKeywords()).map((k) =>
|
||||||
|
this.normalizeKeyword(k),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
const broadKeywordSet = new Set(
|
const broadKeywordSet = new Set(
|
||||||
this.broadKeywords().map((k) => this.normalizeKeyword(k)),
|
this.getKeywordLabels(this.broadKeywords()).map((k) =>
|
||||||
|
this.normalizeKeyword(k),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
const coarseKeywordSet = new Set(
|
const coarseKeywordSet = new Set(
|
||||||
this.coarseKeywords().map((k) => this.normalizeKeyword(k)),
|
this.getKeywordLabels(this.coarseKeywords()).map((k) =>
|
||||||
|
this.normalizeKeyword(k),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
const fineKeywordSet = new Set(
|
const fineKeywordSet = new Set(
|
||||||
this.fineKeywords().map((k) => this.normalizeKeyword(k)),
|
this.getKeywordLabels(this.fineKeywords()).map((k) =>
|
||||||
|
this.normalizeKeyword(k),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
const validSelected = selected.filter(
|
const validSelected = [...this.selectedKeywords(), ...selected].filter(
|
||||||
(k) =>
|
(k) =>
|
||||||
manualKeywordSet.has(this.normalizeKeyword(k)) ||
|
manualKeywordSet.has(this.normalizeKeyword(k)) ||
|
||||||
broadKeywordSet.has(this.normalizeKeyword(k)) ||
|
broadKeywordSet.has(this.normalizeKeyword(k)) ||
|
||||||
@@ -680,14 +908,26 @@ export class KeywordsSearchComponent {
|
|||||||
updateQueryParams(): void {
|
updateQueryParams(): void {
|
||||||
if (this.isRestoringState) return;
|
if (this.isRestoringState) return;
|
||||||
|
|
||||||
|
this.showVisualization.set(false);
|
||||||
|
|
||||||
const queryParams = {
|
const queryParams = {
|
||||||
mode: this.form.controls.selectedInputType.value,
|
mode: this.form.controls.selectedInputType.value,
|
||||||
url: this.toNullableParam(this.form.controls.urlInput.value),
|
url: this.toNullableParam(this.form.controls.urlInput.value),
|
||||||
text: this.toNullableParam(this.form.controls.textInput.value),
|
text: this.toNullableParam(this.form.controls.textInput.value),
|
||||||
broad: this.serializeKeywords(this.broadKeywords()),
|
view: this.keywordView(),
|
||||||
coarse: this.serializeKeywords(this.coarseKeywords()),
|
legend: this.subfieldLegendVisible() ? 'on' : 'off',
|
||||||
fine: this.serializeKeywords(this.fineKeywords()),
|
legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off',
|
||||||
manual: this.serializeKeywords(this.manualKeywords()),
|
softSearch: this.topicMappingSearch() ? true : false,
|
||||||
|
broad: this.serializeKeywords(
|
||||||
|
this.getKeywordLabels(this.broadKeywords()),
|
||||||
|
),
|
||||||
|
coarse: this.serializeKeywords(
|
||||||
|
this.getKeywordLabels(this.coarseKeywords()),
|
||||||
|
),
|
||||||
|
fine: this.serializeKeywords(this.getKeywordLabels(this.fineKeywords())),
|
||||||
|
manual: this.serializeKeywords(
|
||||||
|
this.getKeywordLabels(this.manualKeywords()),
|
||||||
|
),
|
||||||
selected: this.serializeKeywords(this.selectedKeywords()),
|
selected: this.serializeKeywords(this.selectedKeywords()),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -714,13 +954,13 @@ export class KeywordsSearchComponent {
|
|||||||
// session cache was only saved after a full extraction completed, so
|
// session cache was only saved after a full extraction completed, so
|
||||||
// adding a manual keyword (or removing one, etc.) never updated it. The
|
// adding a manual keyword (or removing one, etc.) never updated it. The
|
||||||
// *next* query-param change then triggered restoreStateFromQueryParams()
|
// *next* query-param change then triggered restoreStateFromQueryParams()
|
||||||
// -> restoreSourceFromSession(), which overwrote the fresh manual
|
// -> restoreStateFromSession(), which overwrote the fresh manual
|
||||||
// keyword with that stale snapshot - making manually added keywords
|
// keyword with that stale snapshot - making manually added keywords
|
||||||
// seem to vanish immediately. Saving here fixes that race.
|
// seem to vanish immediately. Saving here fixes that race.
|
||||||
this.saveSourceToSession();
|
this.saveStateToSession();
|
||||||
}
|
}
|
||||||
|
|
||||||
private saveSourceToSession(): void {
|
private saveStateToSession(): void {
|
||||||
const data = {
|
const data = {
|
||||||
source: this.extractionSource(),
|
source: this.extractionSource(),
|
||||||
sourceContent: this.sourceContent(),
|
sourceContent: this.sourceContent(),
|
||||||
@@ -729,6 +969,7 @@ export class KeywordsSearchComponent {
|
|||||||
coarseKeywordEntries: this.coarseKeywordEntries(),
|
coarseKeywordEntries: this.coarseKeywordEntries(),
|
||||||
fineKeywordEntries: this.fineKeywordEntries(),
|
fineKeywordEntries: this.fineKeywordEntries(),
|
||||||
manualKeywordEntries: this.manualKeywordEntries(),
|
manualKeywordEntries: this.manualKeywordEntries(),
|
||||||
|
selectedKeywords: this.selectedKeywords(),
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -738,7 +979,7 @@ export class KeywordsSearchComponent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private restoreSourceFromSession(): void {
|
private restoreStateFromSession(): void {
|
||||||
const raw = sessionStorage.getItem(this.SESSION_KEY);
|
const raw = sessionStorage.getItem(this.SESSION_KEY);
|
||||||
if (!raw) return;
|
if (!raw) return;
|
||||||
|
|
||||||
@@ -751,6 +992,7 @@ export class KeywordsSearchComponent {
|
|||||||
coarseKeywordEntries,
|
coarseKeywordEntries,
|
||||||
fineKeywordEntries,
|
fineKeywordEntries,
|
||||||
manualKeywordEntries,
|
manualKeywordEntries,
|
||||||
|
selectedKeywords,
|
||||||
} = JSON.parse(raw);
|
} = JSON.parse(raw);
|
||||||
|
|
||||||
this.extractionSource.set(source as InputMode);
|
this.extractionSource.set(source as InputMode);
|
||||||
@@ -760,12 +1002,13 @@ export class KeywordsSearchComponent {
|
|||||||
this.coarseKeywordEntries.set(coarseKeywordEntries ?? []);
|
this.coarseKeywordEntries.set(coarseKeywordEntries ?? []);
|
||||||
this.fineKeywordEntries.set(fineKeywordEntries ?? []);
|
this.fineKeywordEntries.set(fineKeywordEntries ?? []);
|
||||||
this.manualKeywordEntries.set(manualKeywordEntries ?? []);
|
this.manualKeywordEntries.set(manualKeywordEntries ?? []);
|
||||||
|
this.selectedKeywords.set(selectedKeywords ?? []);
|
||||||
} catch {
|
} catch {
|
||||||
sessionStorage.removeItem(this.SESSION_KEY);
|
sessionStorage.removeItem(this.SESSION_KEY);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private clearSourceFromSession(): void {
|
private clearStateFromSession(): void {
|
||||||
sessionStorage.removeItem(this.SESSION_KEY);
|
sessionStorage.removeItem(this.SESSION_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
<div class="result-layout">
|
||||||
|
<mat-card class="results-card">
|
||||||
|
<mat-card-content class="results-placeholder">
|
||||||
|
<mat-icon>groups</mat-icon>
|
||||||
|
<h2>Newsliste</h2>
|
||||||
|
<p>
|
||||||
|
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||||
|
</p>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="weights-card">
|
||||||
|
<mat-card-content>
|
||||||
|
<app-weights-sliders
|
||||||
|
[options]="weightOptions"
|
||||||
|
[initialWeights]="defaultWeights"
|
||||||
|
title="News-Gewichtung"
|
||||||
|
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||||
|
resetLabel="Ausgewogen"
|
||||||
|
applyLabel="Neu gewichten"
|
||||||
|
normalizedTitle="Normalisiert"
|
||||||
|
queryParamPrefix="newsW_"
|
||||||
|
[persistInQueryParams]="true"
|
||||||
|
[showApplyButton]="true"
|
||||||
|
[showResetButton]="true"
|
||||||
|
[showNormalizedPreview]="true"
|
||||||
|
(weightsChange)="onWeightsChange($event)"
|
||||||
|
(applyWeights)="onApplyWeights($event)" />
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
/* ============================================================
|
||||||
|
RESULT LAYOUT
|
||||||
|
============================================================ */
|
||||||
|
.result-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||||
|
grid-template-areas: 'summary results';
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-summary-card {
|
||||||
|
grid-area: summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
.results-card {
|
||||||
|
grid-area: results;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-summary-card,
|
||||||
|
.results-card {
|
||||||
|
background: var(--sg-surface, #ffffff);
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||||
|
box-shadow: none;
|
||||||
|
|
||||||
|
.mat-mdc-card-content {
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
import { Component, inject, signal } from '@angular/core';
|
||||||
|
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
|
||||||
|
import {
|
||||||
|
WeightMap,
|
||||||
|
WeightSliderOption,
|
||||||
|
WeightsSlidersComponent,
|
||||||
|
WeightsSlidersValue,
|
||||||
|
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||||
|
|
||||||
|
import { SearchResultsStateService } from '../search-results-state.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-news-results',
|
||||||
|
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||||
|
templateUrl: './news-results.component.html',
|
||||||
|
styleUrl: './news-results.component.scss',
|
||||||
|
})
|
||||||
|
export class KeywordsToNewsResultsComponent {
|
||||||
|
// injects the state set by the parent route — no duplicate parsing here
|
||||||
|
private readonly state = inject(SearchResultsStateService);
|
||||||
|
|
||||||
|
readonly defaultWeights: WeightMap = {
|
||||||
|
param1: 0.33,
|
||||||
|
param2: 0.33,
|
||||||
|
param3: 0.34,
|
||||||
|
};
|
||||||
|
|
||||||
|
readonly weightOptions: WeightSliderOption[] = [
|
||||||
|
{
|
||||||
|
key: 'param1',
|
||||||
|
label: 'Parameter 1',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 1.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam1',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'param2',
|
||||||
|
label: 'Parameter 2',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 2.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam2',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'param3',
|
||||||
|
label: 'Parameter 3',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 3.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam3',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||||
|
raw: this.defaultWeights,
|
||||||
|
normalized: {
|
||||||
|
param1: 0.33,
|
||||||
|
param2: 0.33,
|
||||||
|
param3: 0.34,
|
||||||
|
},
|
||||||
|
rawSum: 2.5,
|
||||||
|
normalizedSum: 1,
|
||||||
|
valid: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
|
||||||
|
|
||||||
|
private hasLoadedInitial = false;
|
||||||
|
constructor() {
|
||||||
|
console.log('check', this.state.payload());
|
||||||
|
}
|
||||||
|
onWeightsChange(value: WeightsSlidersValue): void {
|
||||||
|
this.currentWeights.set(value);
|
||||||
|
|
||||||
|
// fires once with the query-param-aware initial state — use it to load
|
||||||
|
if (!this.hasLoadedInitial) {
|
||||||
|
this.hasLoadedInitial = true;
|
||||||
|
this.loadprojects();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onApplyWeights(value: WeightsSlidersValue): void {
|
||||||
|
this.currentWeights.set(value);
|
||||||
|
this.loadprojects();
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadprojects(): void {
|
||||||
|
const weights = this.currentWeights();
|
||||||
|
|
||||||
|
const requestPayload = {
|
||||||
|
manualKeywords: this.state.manualKeywords(),
|
||||||
|
extractedKeywords: this.state.extractedKeywords(),
|
||||||
|
keywords: this.state.keywords(),
|
||||||
|
softSearch: this.state.softSearch(),
|
||||||
|
weights: {
|
||||||
|
raw: weights.raw,
|
||||||
|
normalized: weights.normalized,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(requestPayload);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TODO:
|
||||||
|
* this.projectsService.searchprojects(requestPayload).subscribe({
|
||||||
|
* next: results => this.projects.set(results),
|
||||||
|
* error: error => console.error(error),
|
||||||
|
* });
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
<div class="result-layout">
|
||||||
|
<mat-card class="results-card">
|
||||||
|
<mat-card-content class="results-placeholder">
|
||||||
|
<mat-icon>groups</mat-icon>
|
||||||
|
<h2>Patentenliste</h2>
|
||||||
|
<p>
|
||||||
|
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||||
|
</p>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="weights-card">
|
||||||
|
<mat-card-content>
|
||||||
|
<app-weights-sliders
|
||||||
|
[options]="weightOptions"
|
||||||
|
[initialWeights]="defaultWeights"
|
||||||
|
title="Patenten-Gewichtung"
|
||||||
|
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||||
|
resetLabel="Ausgewogen"
|
||||||
|
applyLabel="Neu gewichten"
|
||||||
|
normalizedTitle="Normalisiert"
|
||||||
|
queryParamPrefix="patentW_"
|
||||||
|
[persistInQueryParams]="true"
|
||||||
|
[showApplyButton]="true"
|
||||||
|
[showResetButton]="true"
|
||||||
|
[showNormalizedPreview]="true"
|
||||||
|
(weightsChange)="onWeightsChange($event)"
|
||||||
|
(applyWeights)="onApplyWeights($event)" />
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
/* ============================================================
|
||||||
|
RESULT LAYOUT
|
||||||
|
============================================================ */
|
||||||
|
.result-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||||
|
grid-template-areas: 'summary results';
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-summary-card {
|
||||||
|
grid-area: summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
.results-card {
|
||||||
|
grid-area: results;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-summary-card,
|
||||||
|
.results-card {
|
||||||
|
background: var(--sg-surface, #ffffff);
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||||
|
box-shadow: none;
|
||||||
|
|
||||||
|
.mat-mdc-card-content {
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
+112
@@ -0,0 +1,112 @@
|
|||||||
|
import { Component, inject, signal } from '@angular/core';
|
||||||
|
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
|
||||||
|
import {
|
||||||
|
WeightMap,
|
||||||
|
WeightSliderOption,
|
||||||
|
WeightsSlidersComponent,
|
||||||
|
WeightsSlidersValue,
|
||||||
|
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||||
|
import { SearchResultsStateService } from '../search-results-state.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-patents-results',
|
||||||
|
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||||
|
templateUrl: './patents-results.component.html',
|
||||||
|
styleUrl: './patents-results.component.scss',
|
||||||
|
})
|
||||||
|
export class KeywordsToPatentsResultsComponent {
|
||||||
|
// injects the state set by the parent route — no duplicate parsing here
|
||||||
|
private readonly state = inject(SearchResultsStateService);
|
||||||
|
|
||||||
|
readonly defaultWeights: WeightMap = {
|
||||||
|
param1: 0.33,
|
||||||
|
param2: 0.33,
|
||||||
|
param3: 0.34,
|
||||||
|
};
|
||||||
|
|
||||||
|
readonly weightOptions: WeightSliderOption[] = [
|
||||||
|
{
|
||||||
|
key: 'param1',
|
||||||
|
label: 'Parameter 1',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 1.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam1',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'param2',
|
||||||
|
label: 'Parameter 2',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 2.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam2',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'param3',
|
||||||
|
label: 'Parameter 3',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 3.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam3',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||||
|
raw: this.defaultWeights,
|
||||||
|
normalized: {
|
||||||
|
param1: 0.33,
|
||||||
|
param2: 0.33,
|
||||||
|
param3: 0.34,
|
||||||
|
},
|
||||||
|
rawSum: 2.5,
|
||||||
|
normalizedSum: 1,
|
||||||
|
valid: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
|
||||||
|
|
||||||
|
private hasLoadedInitial = false;
|
||||||
|
|
||||||
|
onWeightsChange(value: WeightsSlidersValue): void {
|
||||||
|
this.currentWeights.set(value);
|
||||||
|
|
||||||
|
// fires once with the query-param-aware initial state — use it to load
|
||||||
|
if (!this.hasLoadedInitial) {
|
||||||
|
this.hasLoadedInitial = true;
|
||||||
|
this.loadprojects();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onApplyWeights(value: WeightsSlidersValue): void {
|
||||||
|
this.currentWeights.set(value);
|
||||||
|
this.loadprojects();
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadprojects(): void {
|
||||||
|
const weights = this.currentWeights();
|
||||||
|
|
||||||
|
const requestPayload = {
|
||||||
|
manualKeywords: this.state.manualKeywords(),
|
||||||
|
extractedKeywords: this.state.extractedKeywords(),
|
||||||
|
keywords: this.state.keywords(),
|
||||||
|
softSearch: this.state.softSearch(),
|
||||||
|
weights: {
|
||||||
|
raw: weights.raw,
|
||||||
|
normalized: weights.normalized,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(requestPayload);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TODO:
|
||||||
|
* this.projectsService.searchprojects(requestPayload).subscribe({
|
||||||
|
* next: results => this.projects.set(results),
|
||||||
|
* error: error => console.error(error),
|
||||||
|
* });
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
<div class="result-layout">
|
||||||
|
<mat-card class="results-card">
|
||||||
|
<mat-card-content class="results-placeholder">
|
||||||
|
<mat-icon>groups</mat-icon>
|
||||||
|
<h2>Personenliste</h2>
|
||||||
|
<p>
|
||||||
|
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||||
|
</p>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="weights-card">
|
||||||
|
<mat-card-content>
|
||||||
|
<app-weights-sliders
|
||||||
|
[options]="weightOptions"
|
||||||
|
[initialWeights]="defaultWeights"
|
||||||
|
title="Personen-Gewichtung"
|
||||||
|
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||||
|
resetLabel="Ausgewogen"
|
||||||
|
applyLabel="Neu gewichten"
|
||||||
|
normalizedTitle="Normalisiert"
|
||||||
|
queryParamPrefix="personW_"
|
||||||
|
[persistInQueryParams]="true"
|
||||||
|
[showApplyButton]="true"
|
||||||
|
[showResetButton]="true"
|
||||||
|
[showNormalizedPreview]="true"
|
||||||
|
(weightsChange)="onWeightsChange($event)"
|
||||||
|
(applyWeights)="onApplyWeights($event)" />
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
/* ============================================================
|
||||||
|
RESULT LAYOUT
|
||||||
|
============================================================ */
|
||||||
|
.result-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||||
|
grid-template-areas: 'summary results';
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-summary-card {
|
||||||
|
grid-area: summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
.results-card {
|
||||||
|
grid-area: results;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-summary-card,
|
||||||
|
.results-card {
|
||||||
|
background: var(--sg-surface, #ffffff);
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||||
|
box-shadow: none;
|
||||||
|
|
||||||
|
.mat-mdc-card-content {
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
+135
@@ -0,0 +1,135 @@
|
|||||||
|
import { Component, inject, signal } from '@angular/core';
|
||||||
|
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
|
||||||
|
import {
|
||||||
|
WeightMap,
|
||||||
|
WeightSliderOption,
|
||||||
|
WeightsSlidersComponent,
|
||||||
|
WeightsSlidersValue,
|
||||||
|
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||||
|
|
||||||
|
import { SearchResultsStateService } from '../search-results-state.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-persons-results',
|
||||||
|
standalone: true,
|
||||||
|
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||||
|
templateUrl: './persons-results.component.html',
|
||||||
|
styleUrl: './persons-results.component.scss',
|
||||||
|
})
|
||||||
|
export class KeywordsToPersonsResultsComponent {
|
||||||
|
// injects the state set by the parent route — no duplicate parsing here
|
||||||
|
private readonly state = inject(SearchResultsStateService);
|
||||||
|
|
||||||
|
readonly defaultWeights: WeightMap = {
|
||||||
|
publications: 0.5,
|
||||||
|
citations: 0.5,
|
||||||
|
patents: 0.5,
|
||||||
|
projects: 0.5,
|
||||||
|
mediaVisibility: 0.5,
|
||||||
|
};
|
||||||
|
|
||||||
|
readonly weightOptions: WeightSliderOption[] = [
|
||||||
|
{
|
||||||
|
key: 'publications',
|
||||||
|
label: 'Publikationen',
|
||||||
|
icon: 'article',
|
||||||
|
description:
|
||||||
|
'Gewichtet die Anzahl und Relevanz wissenschaftlicher Arbeiten.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wPublications',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'citations',
|
||||||
|
label: 'Zitationen',
|
||||||
|
icon: 'format_quote',
|
||||||
|
description: 'Gewichtet wissenschaftlichen Einfluss über Zitationen.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wCitations',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'patents',
|
||||||
|
label: 'Patente',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Innovations- und Transferleistung.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wPatents',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'projects',
|
||||||
|
label: 'Projekte',
|
||||||
|
icon: 'account_tree',
|
||||||
|
description: 'Gewichtet Beteiligung an relevanten Forschungsprojekten.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wProjects',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'mediaVisibility',
|
||||||
|
label: 'Medien-Sichtbarkeit',
|
||||||
|
icon: 'visibility',
|
||||||
|
description: 'Gewichtet öffentliche und mediale Sichtbarkeit.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wMedia',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||||
|
raw: this.defaultWeights,
|
||||||
|
normalized: {
|
||||||
|
publications: 0.2,
|
||||||
|
citations: 0.2,
|
||||||
|
patents: 0.2,
|
||||||
|
projects: 0.2,
|
||||||
|
mediaVisibility: 0.2,
|
||||||
|
},
|
||||||
|
rawSum: 2.5,
|
||||||
|
normalizedSum: 1,
|
||||||
|
valid: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly persons = signal<unknown[]>([]); // placeholder until the results service lands
|
||||||
|
|
||||||
|
private hasLoadedInitial = false;
|
||||||
|
|
||||||
|
onWeightsChange(value: WeightsSlidersValue): void {
|
||||||
|
this.currentWeights.set(value);
|
||||||
|
|
||||||
|
// fires once with the query-param-aware initial state — use it to load
|
||||||
|
if (!this.hasLoadedInitial) {
|
||||||
|
this.hasLoadedInitial = true;
|
||||||
|
this.loadPersons();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onApplyWeights(value: WeightsSlidersValue): void {
|
||||||
|
this.currentWeights.set(value);
|
||||||
|
this.loadPersons();
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadPersons(): void {
|
||||||
|
const weights = this.currentWeights();
|
||||||
|
|
||||||
|
const requestPayload = {
|
||||||
|
manualKeywords: this.state.manualKeywords(),
|
||||||
|
extractedKeywords: this.state.extractedKeywords(),
|
||||||
|
keywords: this.state.keywords(),
|
||||||
|
softSearch: this.state.softSearch(),
|
||||||
|
weights: {
|
||||||
|
raw: weights.raw,
|
||||||
|
normalized: weights.normalized,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(requestPayload);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TODO:
|
||||||
|
* this.personsService.searchPersons(requestPayload).subscribe({
|
||||||
|
* next: results => this.persons.set(results),
|
||||||
|
* error: error => console.error(error),
|
||||||
|
* });
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
<div class="result-layout">
|
||||||
|
<mat-card class="results-card">
|
||||||
|
<mat-card-content class="results-placeholder">
|
||||||
|
<mat-icon>groups</mat-icon>
|
||||||
|
<h2>Projectsliste</h2>
|
||||||
|
<p>
|
||||||
|
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
||||||
|
</p>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<mat-card class="weights-card">
|
||||||
|
<mat-card-content>
|
||||||
|
<app-weights-sliders
|
||||||
|
[options]="weightOptions"
|
||||||
|
[initialWeights]="defaultWeights"
|
||||||
|
title="Projects-Gewichtung"
|
||||||
|
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
||||||
|
resetLabel="Ausgewogen"
|
||||||
|
applyLabel="Neu gewichten"
|
||||||
|
normalizedTitle="Normalisiert"
|
||||||
|
queryParamPrefix="projectW_"
|
||||||
|
[persistInQueryParams]="true"
|
||||||
|
[showApplyButton]="true"
|
||||||
|
[showResetButton]="true"
|
||||||
|
[showNormalizedPreview]="true"
|
||||||
|
(weightsChange)="onWeightsChange($event)"
|
||||||
|
(applyWeights)="onApplyWeights($event)" />
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
/* ============================================================
|
||||||
|
RESULT LAYOUT
|
||||||
|
============================================================ */
|
||||||
|
.result-layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(300px, 420px) 1fr;
|
||||||
|
grid-template-areas: 'summary results';
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-summary-card {
|
||||||
|
grid-area: summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
.results-card {
|
||||||
|
grid-area: results;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-summary-card,
|
||||||
|
.results-card {
|
||||||
|
background: var(--sg-surface, #ffffff);
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||||
|
box-shadow: none;
|
||||||
|
|
||||||
|
.mat-mdc-card-content {
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
+111
@@ -0,0 +1,111 @@
|
|||||||
|
import { Component, inject, signal } from '@angular/core';
|
||||||
|
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
|
||||||
|
import {
|
||||||
|
WeightMap,
|
||||||
|
WeightSliderOption,
|
||||||
|
WeightsSlidersComponent,
|
||||||
|
WeightsSlidersValue,
|
||||||
|
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
||||||
|
import { SearchResultsStateService } from '../search-results-state.service';
|
||||||
|
@Component({
|
||||||
|
selector: 'app-projects-results',
|
||||||
|
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
||||||
|
templateUrl: './projects-results.component.html',
|
||||||
|
styleUrl: './projects-results.component.scss',
|
||||||
|
})
|
||||||
|
export class KeywordsToProjectsResultsComponent {
|
||||||
|
// injects the state set by the parent route — no duplicate parsing here
|
||||||
|
private readonly state = inject(SearchResultsStateService);
|
||||||
|
|
||||||
|
readonly defaultWeights: WeightMap = {
|
||||||
|
param1: 0.33,
|
||||||
|
param2: 0.33,
|
||||||
|
param3: 0.34,
|
||||||
|
};
|
||||||
|
|
||||||
|
readonly weightOptions: WeightSliderOption[] = [
|
||||||
|
{
|
||||||
|
key: 'param1',
|
||||||
|
label: 'Parameter 1',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 1.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam1',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'param2',
|
||||||
|
label: 'Parameter 2',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 2.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam2',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'param3',
|
||||||
|
label: 'Parameter 3',
|
||||||
|
icon: 'workspace_premium',
|
||||||
|
description: 'Gewichtet Parameter 3.',
|
||||||
|
defaultValue: 0.5,
|
||||||
|
queryParamName: 'wParam3',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
readonly currentWeights = signal<WeightsSlidersValue>({
|
||||||
|
raw: this.defaultWeights,
|
||||||
|
normalized: {
|
||||||
|
param1: 0.33,
|
||||||
|
param2: 0.33,
|
||||||
|
param3: 0.34,
|
||||||
|
},
|
||||||
|
rawSum: 2.5,
|
||||||
|
normalizedSum: 1,
|
||||||
|
valid: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
|
||||||
|
|
||||||
|
private hasLoadedInitial = false;
|
||||||
|
|
||||||
|
onWeightsChange(value: WeightsSlidersValue): void {
|
||||||
|
this.currentWeights.set(value);
|
||||||
|
|
||||||
|
// fires once with the query-param-aware initial state — use it to load
|
||||||
|
if (!this.hasLoadedInitial) {
|
||||||
|
this.hasLoadedInitial = true;
|
||||||
|
this.loadprojects();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onApplyWeights(value: WeightsSlidersValue): void {
|
||||||
|
this.currentWeights.set(value);
|
||||||
|
this.loadprojects();
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadprojects(): void {
|
||||||
|
const weights = this.currentWeights();
|
||||||
|
|
||||||
|
const requestPayload = {
|
||||||
|
manualKeywords: this.state.manualKeywords(),
|
||||||
|
extractedKeywords: this.state.extractedKeywords(),
|
||||||
|
keywords: this.state.keywords(),
|
||||||
|
softSearch: this.state.softSearch(),
|
||||||
|
weights: {
|
||||||
|
raw: weights.raw,
|
||||||
|
normalized: weights.normalized,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(requestPayload);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TODO:
|
||||||
|
* this.projectsService.searchprojects(requestPayload).subscribe({
|
||||||
|
* next: results => this.projects.set(results),
|
||||||
|
* error: error => console.error(error),
|
||||||
|
* });
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { Injectable, computed, signal } from '@angular/core';
|
||||||
|
import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic';
|
||||||
|
|
||||||
|
export interface SearchResultsPayload {
|
||||||
|
extractedKeywords: KeywordEntryWithTopic[];
|
||||||
|
manualKeywords: KeywordEntryWithTopic[];
|
||||||
|
keywords: string[];
|
||||||
|
options: {
|
||||||
|
softSearch: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provided at the parent route (KeywordsSearchResultsComponent) so it's
|
||||||
|
* created once when entering /search-results and destroyed when leaving it.
|
||||||
|
* Child routes (persons/projects/patents) inject it read-only to build
|
||||||
|
* their own search requests without re-deriving the keyword state.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class SearchResultsStateService {
|
||||||
|
private readonly _payload = signal<SearchResultsPayload | null>(null);
|
||||||
|
|
||||||
|
readonly payload = this._payload.asReadonly();
|
||||||
|
|
||||||
|
readonly hasValidSearch = computed(() => {
|
||||||
|
const payload = this._payload();
|
||||||
|
return !!payload && payload.keywords.length > 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly keywords = computed(() => this._payload()?.keywords ?? []);
|
||||||
|
readonly softSearch = computed(
|
||||||
|
() => this._payload()?.options.softSearch ?? false,
|
||||||
|
);
|
||||||
|
readonly extractedKeywords = computed(
|
||||||
|
() => this._payload()?.extractedKeywords ?? [],
|
||||||
|
);
|
||||||
|
readonly manualKeywords = computed(
|
||||||
|
() => this._payload()?.manualKeywords ?? [],
|
||||||
|
);
|
||||||
|
|
||||||
|
setPayload(payload: SearchResultsPayload): void {
|
||||||
|
this._payload.set(payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
<div class="search-results-page">
|
||||||
|
<div class="search-results-header">
|
||||||
|
<button mat-stroked-button color="primary" (click)="goBackToSearch()">
|
||||||
|
<mat-icon>arrow_back</mat-icon>
|
||||||
|
Keywords anpassen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
@if (state.hasValidSearch()) {
|
||||||
|
<mat-card class="summary-card">
|
||||||
|
<mat-card-content>
|
||||||
|
<div class="summary-header">
|
||||||
|
<div>
|
||||||
|
<span class="summary-label">Suchprofil</span>
|
||||||
|
<span class="summary-count"
|
||||||
|
>{{ selectedKeywordCount() }} Keywords</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<span class="mode-badge">
|
||||||
|
<mat-icon>account_tree</mat-icon>
|
||||||
|
{{ state.softSearch() ? 'Topic Mapping' : 'Keyword Matching' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="keyword-stack">
|
||||||
|
@for (entry of selectedKeywordEntries(); track getEntryTrack(entry)) {
|
||||||
|
<app-topic-chip
|
||||||
|
[label]="getChipLabel(entry)"
|
||||||
|
[count]="getChipCount(entry)"
|
||||||
|
[description]="getChipDescription(entry)"
|
||||||
|
[subfieldName]="getChipSubfieldName(entry)"
|
||||||
|
[fieldName]="getChipFieldName(entry)"
|
||||||
|
[domainName]="getChipDomainName(entry)"
|
||||||
|
[color]="getTopicColor(entry.topic_mapping?.topic)"
|
||||||
|
[active]="true"
|
||||||
|
countIcon="article"
|
||||||
|
descriptionTooltipTarget="button" />
|
||||||
|
}
|
||||||
|
@for (keyword of missingKeywordLabels(); track keyword) {
|
||||||
|
<app-topic-chip
|
||||||
|
[label]="keyword"
|
||||||
|
[active]="true"
|
||||||
|
countIcon="article" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
|
||||||
|
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
|
||||||
|
@for (route of childRoutes; track route.path) {
|
||||||
|
<a
|
||||||
|
mat-tab-link
|
||||||
|
[routerLink]="route.path"
|
||||||
|
routerLinkActive
|
||||||
|
#rla="routerLinkActive"
|
||||||
|
[active]="rla.isActive"
|
||||||
|
[queryParams]="{
|
||||||
|
keywords: state.payload()?.keywords?.join(','),
|
||||||
|
softSearch: state.payload()?.options?.softSearch,
|
||||||
|
}">
|
||||||
|
<mat-icon>{{ route.icon }}</mat-icon>
|
||||||
|
{{ route.label }}
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<mat-tab-nav-panel #resultTabPanel>
|
||||||
|
<router-outlet />
|
||||||
|
</mat-tab-nav-panel>
|
||||||
|
} @else {
|
||||||
|
<mat-card class="empty-card">
|
||||||
|
<mat-card-content class="empty-state">
|
||||||
|
<mat-icon>manage_search</mat-icon>
|
||||||
|
<h2>Keine Suchdaten</h2>
|
||||||
|
<p>Starte eine neue Suche, um Ergebnisse zu sehen.</p>
|
||||||
|
<button mat-flat-button color="primary" (click)="goBackToSearch()">
|
||||||
|
Zur Suche
|
||||||
|
</button>
|
||||||
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
/* ============================================================
|
||||||
|
DESIGN TOKENS
|
||||||
|
============================================================ */
|
||||||
|
$phone: 599px;
|
||||||
|
$tablet: 900px;
|
||||||
|
$touch-target: 44px;
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
SEARCH RESULTS PAGE (parent shell)
|
||||||
|
============================================================ */
|
||||||
|
.search-results-page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.75rem;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: clamp(1.2rem, 2vw, 1.6rem);
|
||||||
|
font-weight: 650;
|
||||||
|
color: var(--sg-text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin: 0.2rem 0 0;
|
||||||
|
color: var(--sg-text-secondary);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
KEYWORD SUMMARY CARD
|
||||||
|
============================================================ */
|
||||||
|
.summary-card {
|
||||||
|
background: var(--sg-surface, #ffffff);
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||||
|
box-shadow: none;
|
||||||
|
|
||||||
|
.mat-mdc-card-content {
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.summary-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.summary-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.03em;
|
||||||
|
color: var(--sg-text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.summary-count {
|
||||||
|
display: block;
|
||||||
|
margin-top: 0.15rem;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-weight: 650;
|
||||||
|
color: var(--sg-text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mode-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
background: var(--sg-background-muted, #f4f5f7);
|
||||||
|
color: var(--sg-text-secondary);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
font-size: 16px;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.keyword-stack {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.6rem;
|
||||||
|
|
||||||
|
::ng-deep app-topic-chip .topic-chip__count {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
CHILD ROUTE NAV
|
||||||
|
============================================================ */
|
||||||
|
.result-nav {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.25rem;
|
||||||
|
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-nav__link {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
padding: 0.5rem 0.85rem;
|
||||||
|
border-radius: 6px 6px 0 0;
|
||||||
|
color: var(--sg-text-secondary);
|
||||||
|
text-decoration: none;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 500;
|
||||||
|
border-bottom: 2px solid transparent;
|
||||||
|
transition:
|
||||||
|
color 0.15s ease,
|
||||||
|
border-color 0.15s ease;
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
font-size: 18px;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
color: var(--sg-text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
&--active {
|
||||||
|
color: var(--sg-text-primary);
|
||||||
|
border-bottom-color: var(--sg-primary, currentColor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
EMPTY STATE
|
||||||
|
============================================================ */
|
||||||
|
.empty-card {
|
||||||
|
background: var(--sg-surface, #ffffff);
|
||||||
|
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
min-height: 240px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--sg-text-secondary);
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
font-size: 48px;
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
opacity: 0.65;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--sg-text-primary);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin: 0;
|
||||||
|
max-width: 480px;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
min-height: $touch-target;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
PHONE
|
||||||
|
============================================================ */
|
||||||
|
@media (max-width: $phone) {
|
||||||
|
.search-results-page {
|
||||||
|
padding: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.summary-header {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mode-badge {
|
||||||
|
width: 100%;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-nav {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
import { Component, computed, inject } from '@angular/core';
|
||||||
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
import {
|
||||||
|
ActivatedRoute,
|
||||||
|
Router,
|
||||||
|
RouterLink,
|
||||||
|
RouterLinkActive,
|
||||||
|
RouterOutlet,
|
||||||
|
} from '@angular/router';
|
||||||
|
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
|
||||||
|
import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic';
|
||||||
|
import { Topic } from '../../../api/model/topic';
|
||||||
|
import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
|
||||||
|
import {
|
||||||
|
topicHierarchyColor,
|
||||||
|
TopicHierarchyColorInput,
|
||||||
|
} from '../../../resolvers/utils/topic-colors';
|
||||||
|
import { MatTabsModule } from '@angular/material/tabs';
|
||||||
|
import {
|
||||||
|
SearchResultsPayload,
|
||||||
|
SearchResultsStateService,
|
||||||
|
} from './search-results-state.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-keywords-search-results',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
RouterLink,
|
||||||
|
RouterLinkActive,
|
||||||
|
RouterOutlet,
|
||||||
|
MatButtonModule,
|
||||||
|
MatCardModule,
|
||||||
|
MatIconModule,
|
||||||
|
TopicChipComponent,
|
||||||
|
MatTabsModule,
|
||||||
|
],
|
||||||
|
providers: [SearchResultsStateService],
|
||||||
|
templateUrl: './search-results.component.html',
|
||||||
|
styleUrl: './search-results.component.scss',
|
||||||
|
})
|
||||||
|
export class KeywordsSearchResultsComponent {
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
|
||||||
|
protected readonly state = inject(SearchResultsStateService);
|
||||||
|
|
||||||
|
// Must match KeywordsSearchComponent.SEARCH_RESULTS_HANDOFF_KEY exactly —
|
||||||
|
// that's where search() writes the enriched entries before navigating.
|
||||||
|
private readonly HANDOFF_KEY = 'search-results-handoff';
|
||||||
|
|
||||||
|
protected readonly childRoutes = [
|
||||||
|
{ path: 'persons', label: 'Personen', icon: 'groups' },
|
||||||
|
{ path: 'projects', label: 'Projekte', icon: 'work' },
|
||||||
|
{ path: 'patents', label: 'Patente', icon: 'workspace_premium' },
|
||||||
|
{ path: 'works', label: 'Publikationen', icon: 'article' },
|
||||||
|
{ path: 'news', label: 'Nachrichten', icon: 'newspaper' },
|
||||||
|
];
|
||||||
|
|
||||||
|
readonly selectedKeywordCount = computed(() => this.state.keywords().length);
|
||||||
|
|
||||||
|
readonly selectedKeywordEntries = computed(() => {
|
||||||
|
const payload = this.state.payload();
|
||||||
|
if (!payload) return [];
|
||||||
|
|
||||||
|
const allEntries = [
|
||||||
|
...(payload.extractedKeywords ?? []),
|
||||||
|
...(payload.manualKeywords ?? []),
|
||||||
|
];
|
||||||
|
|
||||||
|
const entryByKeyword = new Map<string, KeywordEntryWithTopic>();
|
||||||
|
|
||||||
|
for (const entry of allEntries) {
|
||||||
|
entryByKeyword.set(
|
||||||
|
this.normalizeKeyword(this.getKeywordLabel(entry)),
|
||||||
|
entry,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: KeywordEntryWithTopic[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
for (const keyword of payload.keywords) {
|
||||||
|
const normalized = this.normalizeKeyword(keyword);
|
||||||
|
const entry = entryByKeyword.get(normalized);
|
||||||
|
|
||||||
|
if (!entry || seen.has(normalized)) continue;
|
||||||
|
|
||||||
|
seen.add(normalized);
|
||||||
|
result.push(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly missingKeywordLabels = computed(() => {
|
||||||
|
const payload = this.state.payload();
|
||||||
|
if (!payload) return [];
|
||||||
|
|
||||||
|
const entryKeywordSet = new Set(
|
||||||
|
this.selectedKeywordEntries().map((entry) =>
|
||||||
|
this.normalizeKeyword(this.getKeywordLabel(entry)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return payload.keywords.filter(
|
||||||
|
(keyword) => !entryKeywordSet.has(this.normalizeKeyword(keyword)),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
// Query params are authoritative (URL survives reload, deep links,
|
||||||
|
// browser back/forward). sessionStorage is a best-effort cache for the
|
||||||
|
// heavier, topic-enriched entries — only trusted if its keyword set
|
||||||
|
// still matches what's in the URL right now, so a stale cache from a
|
||||||
|
// previous search never gets silently applied to a new one.
|
||||||
|
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe((params) => {
|
||||||
|
const keywords = this.parseKeywordList(params.get('keywords'));
|
||||||
|
const softSearch = params.get('softSearch') === 'on';
|
||||||
|
|
||||||
|
const cached = this.readHandoffCache();
|
||||||
|
const cacheMatches =
|
||||||
|
cached && this.sameKeywordSet(cached.keywords, keywords);
|
||||||
|
|
||||||
|
this.state.setPayload({
|
||||||
|
keywords,
|
||||||
|
options: { softSearch },
|
||||||
|
extractedKeywords: cacheMatches ? cached!.extractedKeywords : [],
|
||||||
|
manualKeywords: cacheMatches ? cached!.manualKeywords : [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
goBackToSearch(): void {
|
||||||
|
void this.router.navigate(['/keywords']);
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipLabel(keyword: KeywordEntryWithTopic): string {
|
||||||
|
return keyword.llm_keyword?.keyword ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipDescription(item: KeywordEntryWithTopic): string | null {
|
||||||
|
return this.getTopic(item)?.description ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipSubfieldName(item: KeywordEntryWithTopic): string | null {
|
||||||
|
return this.getTopic(item)?.subfield?.display_name ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipFieldName(item: KeywordEntryWithTopic): string | null {
|
||||||
|
return this.getTopic(item)?.field?.display_name ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipDomainName(item: KeywordEntryWithTopic): string | null {
|
||||||
|
return this.getTopic(item)?.domain?.display_name ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChipCount(item: KeywordEntryWithTopic): number | null {
|
||||||
|
return this.getTopic(item)?.works_count ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getTopicColor(topic: Topic | undefined | null): string {
|
||||||
|
const topicInput: TopicHierarchyColorInput = {
|
||||||
|
id: topic?.id ?? null,
|
||||||
|
name: topic?.display_name ?? null,
|
||||||
|
field_id: topic?.field?.id ?? null,
|
||||||
|
field_name: topic?.field?.display_name ?? null,
|
||||||
|
domain_id: topic?.domain?.id ?? null,
|
||||||
|
domain_name: topic?.domain?.display_name ?? null,
|
||||||
|
};
|
||||||
|
|
||||||
|
return topicHierarchyColor(topicInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
getEntryTrack(entry: KeywordEntryWithTopic): string {
|
||||||
|
return this.getKeywordLabel(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
private readHandoffCache(): SearchResultsPayload | null {
|
||||||
|
const raw = sessionStorage.getItem(this.HANDOFF_KEY);
|
||||||
|
if (!raw) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
return this.parsePayload(JSON.parse(raw));
|
||||||
|
} catch {
|
||||||
|
sessionStorage.removeItem(this.HANDOFF_KEY);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parsePayload(value: unknown): SearchResultsPayload | null {
|
||||||
|
if (!value || typeof value !== 'object') return null;
|
||||||
|
|
||||||
|
const maybePayload = value as Partial<SearchResultsPayload>;
|
||||||
|
|
||||||
|
if (!Array.isArray(maybePayload.keywords)) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
extractedKeywords: maybePayload.extractedKeywords ?? [],
|
||||||
|
manualKeywords: maybePayload.manualKeywords ?? [],
|
||||||
|
keywords: maybePayload.keywords ?? [],
|
||||||
|
options: {
|
||||||
|
softSearch: maybePayload.options?.softSearch ?? false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private sameKeywordSet(a: string[], b: string[]): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
const setA = new Set(a.map((k) => this.normalizeKeyword(k)));
|
||||||
|
return b.every((k) => setA.has(this.normalizeKeyword(k)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseKeywordList(raw: string | null): string[] {
|
||||||
|
if (!raw) return [];
|
||||||
|
return raw
|
||||||
|
.split(',')
|
||||||
|
.map((v) => v.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getKeywordLabel(item: KeywordEntryWithTopic): string {
|
||||||
|
return item.llm_keyword.keyword;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getTopic(item: KeywordEntryWithTopic): Topic | null {
|
||||||
|
return item.topic_mapping?.topic ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeKeyword(value: string): string {
|
||||||
|
return value.trim().toLowerCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user