feature/keywords-analysis #190

Merged
genja merged 16 commits from feature/keywords-analysis into dev 2026-07-05 20:12:27 +02:00
12 changed files with 1466 additions and 960 deletions
+18 -7
View File
@@ -2,7 +2,7 @@ from openai import OpenAI, APIConnectionError
from openai import AsyncOpenAI
from .. import config
from typing import Optional, Dict, Any
import asyncio
def call(
system_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(
system_prompt: str,
user_prompt: str,
emit, # EventCallback
emit,
model: str = None,
json_schema=None,
schema_name=None,
@@ -98,15 +98,26 @@ async def call_stream(
stream=True,
)
async for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
full_content += delta
await emit({"type": "llm_chunk", "content": delta})
try:
async for chunk in stream:
delta = chunk.choices[0].delta.content
if 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:
print(f"Connection error: {e}")
return ""
except asyncio.CancelledError:
# Real cancellation (e.g. asyncio.wait_for timeout, or task.cancel()
# from the router)
raise
except Exception as e:
import traceback
print(f"LLM streaming failed: {type(e).__name__}: {e}")
+24 -167
View File
@@ -126,141 +126,6 @@ async def _get_text_content(url: str) -> str:
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(
query: str,
@@ -275,13 +140,17 @@ async def extract_keywords_stream_enriched(
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())
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
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.\n"
if limit:
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
@@ -290,15 +159,10 @@ async def extract_keywords_stream_enriched(
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
# Holds enriched keyword wrappers for each level
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
# Track background enrichment tasks
enrichment_tasks: List[asyncio.Task] = []
async def emit_full_results() -> None:
"""Attempt to build and emit the full enriched keyword model."""
try:
validated = _build_enriched_snapshot(confirmed)
except ValidationError:
@@ -306,29 +170,19 @@ async def extract_keywords_stream_enriched(
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
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:
topic = await vector_search_topics_batch(
keywords=[item.keyword],
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
# Emit the full updated set after each enrichment so the frontend sees progress.
await emit_full_results()
except asyncio.CancelledError:
# If the whole request is cancelled, we can just re-raise
raise
except Exception as e:
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
await emit_full_results()
# ---------- on_chunk: parses LLM stream and appends new keywords ----------
async def on_chunk(event: Dict[str, Any]) -> None:
if event["type"] != "llm_chunk":
await emit(event)
@@ -338,7 +192,6 @@ async def extract_keywords_stream_enriched(
partial = partial_json_parser.loads(event.get("_full_content", ""))
except Exception:
return
if not isinstance(partial, dict):
return
@@ -346,19 +199,18 @@ async def extract_keywords_stream_enriched(
for level in LEVELS:
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):
raw_item = current[len(confirmed[level])]
try:
validated_item = KeywordEntry.model_validate(raw_item)
except ValidationError:
break # item not complete yet
break
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
grew = True
# Launch openalex topic mapping
for idx in range(start_idx, len(confirmed[level])):
keyword_text = confirmed[level][idx].llm_keyword.keyword
await emit(
@@ -374,7 +226,6 @@ async def extract_keywords_stream_enriched(
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:
@@ -384,6 +235,7 @@ async def extract_keywords_stream_enriched(
await on_chunk(event)
# ---------- Call the LLM ----------
keywords = ""
try:
keywords = await asyncio.wait_for(
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())
raise RuntimeError("LLM streaming call timed out")
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())
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 ----------
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())
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()
# Build final response
try:
final_validated = _build_enriched_snapshot(confirmed)
except ValidationError:
+319 -171
View File
@@ -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
## 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
* Healthcare
@@ -50,15 +155,15 @@ class KeywordsPrompt(StrEnum):
* Materials Science
* 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
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
* Drug Discovery
@@ -73,9 +178,9 @@ class KeywordsPrompt(StrEnum):
## 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
* CRISPR-Cas9
@@ -114,21 +219,56 @@ class KeywordsPrompt(StrEnum):
# 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.
* Avoid complete sentences.
* Avoid duplicates across levels whenever possible.
* Do not invent technologies not supported by the text.
* 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.
* If fewer valid keywords exist, return fewer.
---
# 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
@@ -136,269 +276,277 @@ class KeywordsPrompt(StrEnum):
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.
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
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:
{"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.
"""
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
* Headers and footers
* Cookie notices
* Marketing language
* Contact information
* Repeated sections
* Calls to action
* Legal disclaimers
* Product pages
* Blog articles
* News articles
* Landing pages
* Navigation menus
* Headers and footers
* Cookie notices
* Marketing language
* Contact information
* Repeated sections
* Calls to action
* Legal disclaimers
* Product pages
* Blog articles
* News articles
* 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
* Cookie banners
* Legal notices
* Copyright text
* Generic marketing statements
* Contact information
* Login/signup content
* Careers pages unless they contain relevant technical information
* Repeated website boilerplate
* Navigation elements
* Cookie banners
* Legal notices
* Copyright text
* Generic marketing statements
* Contact information
* Login/signup content
* Careers pages unless they contain relevant technical information
* 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
* Company Page
* Research Article
* Scientific Blog Post
* News Article
* Technical Documentation
* White Paper
* Industry Report
* Other
1. Extract ONLY keywords, entities, concepts, technologies, methods, products, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the webpage text.
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
* Scientific literature discovery
* Patent scouting
* Technology scouting
* Innovation monitoring
Allowed:
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
* Healthcare
* Manufacturing
* Energy Storage
* Biotechnology
* Robotics
# Step 1: Determine Page Type
---
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
* CRISPR-Cas9
* OPC UA
* Retrieval-Augmented Generation
* YOLOv8
* Lithium Iron Phosphate
Do NOT replace webpage terminology with your own preferred terminology.
---
---
# 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
* 0.90 = major topic
* 0.80 = highly relevant
* 0.70 = supporting concept
* 0.60 = secondary concept
Only use this level when such broad concepts are explicitly present.
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.
---
---
# Example 3 — News Article
## coarse_grained
## 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 = """
+49 -60
View File
@@ -8,10 +8,13 @@ import asyncio
from typing import Annotated
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
from uvicorn.protocols.utils import ClientDisconnected
from . import logic
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
import logging
logger = logging.getLogger(__name__)
router = APIRouter(
prefix="/api/inse-service",
@@ -19,26 +22,35 @@ router = APIRouter(
responses={404: {"description": "Not found"}},
)
@router.websocket("/keywords/extract/ws")
async def extract_keywords_ws(websocket: WebSocket):
print("WebSocket connection established for keyword extraction.")
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:
raw = await websocket.receive_json()
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
request = KeywordsRequest(**raw)
extraction_task = asyncio.create_task(
logic.extract_keywords_stream_enriched(
@@ -48,60 +60,37 @@ async def extract_keywords_ws(websocket: WebSocket):
emit=emit,
)
)
disconnect_task = asyncio.create_task(watch_disconnect())
done, pending = await asyncio.wait(
{extraction_task, disconnect_task},
return_when=asyncio.FIRST_COMPLETED,
)
result = await extraction_task
if disconnect_task in done:
disconnected.set()
await safe_send({
"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()
try:
await extraction_task
except asyncio.CancelledError:
except (asyncio.CancelledError, Exception):
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":
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(
"/keywords/extract",
@@ -39,6 +39,7 @@ class Topic(BaseModel):
keywords: Optional[List[StrictStr]] = Field(default=None, description="Keywords representing the content of papers in the topic.")
subfield: Optional[TopicSubfield] = None
var_field: Optional[TopicField] = Field(default=None, alias="field")
field: Optional[TopicField] = Field(default=None)
domain: Optional[TopicDomain] = None
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this topic.")
cited_by_count: Optional[StrictInt] = None
@@ -16,6 +16,7 @@
<button
mat-flat-button
type="button"
class="extract-btn"
[color]="isExtracting() ? 'warn' : 'primary'"
(click)="onExtractKeywordsClick()">
<mat-icon>
@@ -42,9 +43,12 @@
<button
mat-flat-button
type="button"
color="primary"
[color]="isExtracting() ? 'warn' : 'primary'"
class="extract-btn"
(click)="onExtractKeywordsClick()">
<mat-icon>troubleshoot</mat-icon>
<mat-icon>
{{ isExtracting() ? 'close' : 'troubleshoot' }}
</mat-icon>
{{ isExtracting() ? 'Abbrechen' : 'Keywords extrahieren' }}
</button>
</div>
@@ -52,182 +56,346 @@
</mat-tab>
</mat-tab-group>
@if (isExtracting()) {
<div class="progress-container">
<mat-progress-bar
mode="determinate"
[value]="progress()"
color="primary">
</mat-progress-bar>
<div class="status-message">{{ statusMessage() }}</div>
</div>
}
<!-- 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
mat-stroked-button
color="primary"
size="small"
(click)="deselectAllExtracted()">
<mat-icon>select_all</mat-icon> Alle extrahierten Keywords
abwählen
</button>
} @else {
<button
mat-stroked-button
color="primary"
size="small"
[disabled]="isExtracting()"
(click)="selectAllExtracted()">
<mat-icon>select_all</mat-icon> Alle extrahierten Keywords
auswählen
</button>
@if (keywordsExist()) {
<div class="extraction-grid">
<mat-card class="keyword-card extracted-card">
<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>
}
<button
mat-stroked-button
color="warn"
size="small"
[disabled]="isExtracting()"
(click)="clearExtractedKeywords()">
<mat-icon>delete_outline</mat-icon> Lösche alle extrahierten
Keywords
</button>
</div>
}
@if (isExtracting()) {
<div class="progress-container">
<mat-progress-bar
mode="determinate"
[value]="progress()"
color="primary">
</mat-progress-bar>
<div class="status-message">{{ statusMessage() }}</div>
</div>
} @else if (
!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>
<!-- Manual input is ALWAYS available, independent of extraction state -->
<div class="toolbar-wrapper">
@if (!isExtracting()) {
<div class="toolbar-controls thick-border">
<div class="toolbar-group toolbar-group--view">
@if (areAllSelected()) {
<button
mat-stroked-button
color="primary"
(click)="deselectAll()">
<mat-icon>select_all</mat-icon>
<span>Alle abwählen</span>
</button>
} @else {
<button
mat-stroked-button
color="primary"
[disabled]="isExtracting()"
(click)="selectAll()"
matTooltip="Alle extrahierten Keywords auswählen">
<mat-icon>select_all</mat-icon>
<span>Alle auswählen</span>
</button>
}
</div>
<div class="toolbar-divider"></div>
<!-- Search Button -->
<div class="search-container">
<button
mat-flat-button
color="primary"
[disabled]="isSearchDisabled()"
(click)="search()">
<mat-icon>search</mat-icon>
Suchen
</button>
</div>
<mat-button-toggle-group
[value]="keywordView()"
(change)="onViewToggleChange($event.value)"
aria-label="Keyword Ansicht wählen">
<mat-button-toggle
value="llm"
matTooltip="Extrahierte Keywords">
<mat-icon>text_fields</mat-icon>
<span>Extrahierte Keywords</span>
</mat-button-toggle>
<mat-button-toggle
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>
<div class="toolbar-group toolbar-group--view">
<button
mat-stroked-button
color="warn"
[disabled]="isExtracting()"
(click)="clearKeywords()"
matTooltip="Alle extrahierten Keywords löschen">
<mat-icon>delete_outline</mat-icon>
<span>Alle löschen</span>
</button>
</div>
</div>
} @else {
<!-- Empty placeholder keeps grid column 1 occupied so
the autocomplete below stays fixed in column 2 -->
<div
class="toolbar-controls toolbar-controls--placeholder"></div>
}
<div class="spacer toolbar-controls manual-input-controls">
<app-topic-autocomplete
label="z. B. Knowledge Graphs"
placeholder="Thema suchen oder eintippen..."
(topicSelected)="addKeywordFromInput($event)" />
</div>
</div>
</div>
<!-- ===== Reusable chip stack templates ===== -->
<ng-template
#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">{{ sourceContent() }}</div>
</mat-expansion-panel>
}
</mat-card-content>
</mat-card>
</div>
<!-- Search Button -->
<div class="search-container">
<button
mat-flat-button
color="primary"
class="search-btn"
[disabled]="isSearchDisabled()"
(click)="search()">
<mat-icon>search</mat-icon>
Analyse starten
</button>
</div>
}
</div>
</div>
@@ -1,30 +1,192 @@
/* ============================================================
DESIGN TOKENS / LOCAL VARIABLES
============================================================ */
$phone: 599px;
$tablet: 900px;
$touch-target: 44px;
/* ============================================================
BASE LAYOUT — container becomes the responsive anchor
============================================================ */
.content {
container-type: inline-size;
container-name: keyword-tool;
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 1rem;
gap: clamp(0.5rem, 1.5vw, 0.75rem);
padding: clamp(0.5rem, 2vw, 1rem);
}
.tab-content {
padding: 0.5rem 0;
display: grid;
grid-template-columns: 5fr 1fr;
display: flex;
flex-direction: column;
margin-top: 0.5rem;
gap: 0.5rem;
align-items: center;
}
.full-width {
width: 100%;
}
.extract-btn {
white-space: nowrap;
min-width: 240px;
min-height: $touch-target;
}
.actions {
display: flex;
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%;
margin: 0;
}
}
.toolbar-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 0.75rem;
flex-wrap: nowrap; /* fixed: was invalid "no-wrap" */
padding: 0.5rem 0.75rem;
background: var(--sg-background-muted, #f4f5f7);
}
.toolbar-wrapper {
display: grid;
grid-template-columns: 3fr 1.3fr;
border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08));
}
.toolbar-controls--placeholder {
/* invisible spacer, preserves grid column width/position */
visibility: hidden;
pointer-events: none;
}
.manual-input-controls {
min-width: 0;
}
@container keyword-tool (max-width: #{$tablet}) {
.toolbar-wrapper {
grid-template-columns: 1fr;
border-left: none;
}
.toolbar-controls--placeholder {
display: none; /* no need for a spacer once stacked */
}
}
.toolbar-group {
display: flex;
align-items: center;
gap: 0.6rem;
}
.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 {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
border: 0;
}
.keyword-card {
@@ -40,137 +202,38 @@
}
}
/* === Table-like keyword grid === */
/* ============================================================
DESKTOP TABLE-LIKE KEYWORD GRID
============================================================ */
.keyword-table {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin: 0.5rem 0;
}
.table-head {
border-top: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
padding-top: 0.5rem;
display: grid;
grid-template-columns: repeat(3, 1fr) 1.3fr;
grid-template-rows: auto;
column-gap: 1rem;
border-bottom: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
padding-bottom: 0.5rem;
background: var(--sg-background-muted, #f4f5f7);
}
.head-cell {
min-width: 0;
text-align: center; /* Center header text */
}
.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 */
text-align: center;
}
.sub-cell {
font-weight: 500;
color: var(--sg-text-secondary);
font-size: 1rem;
font-size: clamp(0.8rem, 1.2vw, 1rem);
text-transform: uppercase;
letter-spacing: 0.05em;
align-self: end;
grid-row: 2;
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;
}
}
}
text-align: center;
}
.table-body {
@@ -179,10 +242,9 @@
column-gap: 1rem;
row-gap: 0.4rem;
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.08));
}
/* Add vertical separators between columns */
.table-col {
display: flex;
flex-direction: column;
@@ -194,17 +256,94 @@
&:last-child {
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%;
margin-top: 0.5rem;
opacity: 0.4;
}
}
.thick-border {
border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)) !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 {
font-size: 1rem;
padding: 0.2rem 0.6rem;
@@ -215,11 +354,9 @@
animation: popIn 0.2s ease-in-out;
cursor: default;
// Add removable indicator and hover effect
&.mat-mdc-chip-option {
.mat-mdc-chip-action {
padding: 0 4px;
.mat-mdc-chip-action-label {
padding: 0 4px;
display: flex;
@@ -227,8 +364,6 @@
gap: 4px;
}
}
// Show remove button on hover for removable chips
&:hover {
::ng-deep .mat-mdc-chip-remove {
opacity: 1;
@@ -236,7 +371,6 @@
}
}
// Style for removable chips
::ng-deep .mat-mdc-chip-remove {
opacity: 0;
transition: opacity 0.2s ease;
@@ -262,12 +396,9 @@
}
}
::ng-deep .mat-mdc-chip-option.compact-chip {
.mat-mdc-chip-action-label {
padding: 0 4px;
}
.mat-mdc-chip-action {
padding: 0 4px;
@container keyword-tool (max-width: #{$tablet}) {
.compact-chip {
width: 100%;
}
}
@@ -283,80 +414,95 @@
}
}
.select-all-container {
/* ============================================================
SEARCH BUTTON (sticky on mobile — improves conversion/UX)
============================================================ */
.search-container {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
justify-content: flex-end;
justify-content: center;
margin-top: 0.5rem;
}
button {
font-size: 0.75rem;
padding: 0 12px;
line-height: 30px;
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
.search-btn {
min-width: 240px;
align-self: center;
min-height: $touch-target;
}
@media (max-width: $phone) {
.search-container {
position: sticky;
bottom: 0;
z-index: 5;
background: var(--sg-background);
padding: 0.75rem 0.5rem;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
}
.search-btn {
width: 100%;
}
}
.search-container {
display: flex;
justify-content: flex-end;
margin-top: 0.5rem;
}
/* ============================================================
TABS (URL / Text) — stretch on smaller containers
============================================================ */
@container keyword-tool (max-width: #{$tablet}) {
.content ::ng-deep .mat-mdc-tab-labels {
justify-content: stretch;
}
/* Responsive: stack columns on small screens */
@media (max-width: 768px) {
.table-head,
.table-body {
.content ::ng-deep .mat-mdc-tab {
flex: 1;
}
.tab-content {
display: grid;
grid-template-columns: 1fr;
}
.extracted-header {
grid-column: 1;
grid-row: 1;
.extract-btn {
width: 100%;
justify-content: center;
}
.own-header {
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;
}
.search-btn {
width: 100%;
}
}
/* 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 {
margin: 0.75rem 0;
background: var(--sg-background-muted, #f5f5f5);
@@ -406,30 +552,27 @@
background: rgba(0, 0, 0, 0.03);
}
}
/* ============================================================
PROGRESS BAR
============================================================ */
.progress-container {
margin-top: 1rem;
padding: 0.5rem 0;
// Make the progress bar container relative for the shimmer overlay
mat-progress-bar {
position: relative;
overflow: hidden; // keeps the shimmer inside the bar
overflow: hidden;
// --- 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
background-color: #2196f3;
}
// --- 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
inset: 0;
pointer-events: none;
background: linear-gradient(
105deg,
transparent 0%,
@@ -457,3 +600,21 @@
transform: translateX(100%);
}
}
/* ============================================================
ACCESSIBILITY
============================================================ */
@media (prefers-reduced-motion: reduce) {
.compact-chip,
.progress-container mat-progress-bar::after {
animation: none !important;
transition: none !important;
}
}
button:focus-visible,
.mat-button-toggle:focus-visible,
::ng-deep .mat-mdc-tab:focus-visible {
outline: 2px solid var(--sg-primary, #1976d2);
outline-offset: 2px;
}
@@ -1,15 +1,9 @@
import {
Component,
computed,
signal,
Signal,
WritableSignal,
} from '@angular/core';
import { Component, computed, signal, inject } from '@angular/core';
import { BreakpointObserver } from '@angular/cdk/layout';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
@@ -28,10 +22,30 @@ import { TopicsService } from '../../api/api/topics.service';
import { KeywordsTopicsRequest } from '../../api/model/keywordsTopicsRequest';
import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic';
import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.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 { map } from 'rxjs/operators';
import { toSignal } from '@angular/core/rxjs-interop';
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';
type InputMode = 'url' | 'text';
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
type KeywordView = 'llm' | 'topic';
@Component({
selector: 'app-keywords-search',
imports: [
@@ -41,12 +55,18 @@ type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
MatInputModule,
MatButtonModule,
MatIconModule,
MatChipsModule,
MatDividerModule,
MatCardModule,
MatExpansionModule,
MatProgressBarModule,
TopicAutocompleteComponent,
TopicChipComponent,
TopicLegendComponent,
MatButtonToggleModule,
MatButtonToggleGroup,
MatTooltipModule,
A11yModule,
NgTemplateOutlet,
],
templateUrl: './keywords-search.component.html',
styleUrl: './keywords-search.component.scss',
@@ -59,7 +79,15 @@ export class KeywordsSearchComponent {
});
private readonly SESSION_KEY = 'keywords-search-source';
// 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;
// the *Keywords() computed signals below just project the label out of them.
private readonly broadKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
@@ -67,55 +95,22 @@ export class KeywordsSearchComponent {
private readonly fineKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
private readonly manualKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
readonly broadKeywords = computed(() =>
this.broadKeywordEntries().map((item) => this.getKeywordLabel(item)),
);
readonly coarseKeywords = computed(() =>
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 broadKeywords = computed(() => this.broadKeywordEntries());
readonly coarseKeywords = computed(() => this.coarseKeywordEntries());
readonly fineKeywords = computed(() => this.fineKeywordEntries());
readonly manualKeywords = computed(() => this.manualKeywordEntries());
readonly selectedKeywords = signal<string[]>([]);
readonly isExtracting = signal(false);
readonly loadingNewKeyword = signal(false);
readonly extractionSource = signal<InputMode | null>(null);
// Single place mapping a category name to its label signal and its
// 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(
readonly keywordsExist = computed(
() =>
this.broadKeywords().length > 0 ||
this.coarseKeywords().length > 0 ||
this.fineKeywords().length > 0,
this.fineKeywords().length > 0 ||
this.manualKeywords().length > 0,
);
readonly sourceContent = signal<string>('');
@@ -133,6 +128,23 @@ export class KeywordsSearchComponent {
readonly progress = signal(0);
readonly statusMessage = signal('');
readonly keywordView = signal<KeywordView>('llm');
readonly subfieldLegendVisible = signal(true);
readonly subfieldLegendExpanded = signal(false);
get topicLegendGroups(): TopicLegendGroup[] {
const topics = [
...this.broadKeywordEntries(),
...this.coarseKeywordEntries(),
...this.fineKeywordEntries(),
...this.manualKeywordEntries(),
]
.map((entry) => entry.topic_mapping?.topic)
.filter((topic): topic is Topic => Boolean(topic))
.map((topic) => this.toTopicLegendTopic(topic));
return buildTopicLegendGroups(topics);
}
constructor(
private readonly formBuilder: FormBuilder,
@@ -220,9 +232,12 @@ export class KeywordsSearchComponent {
this.fineKeywordEntries.set([]);
this.websocketService.close();
this.isExtracting.set(false);
this.loadingNewKeyword.set(false);
// Keep manual, but remove selected that are not in manual
this.selectedKeywords.set(
this.selectedKeywords().filter((k) => this.manualKeywords().includes(k)),
this.selectedKeywords().filter((k) =>
this.getKeywordLabels(this.manualKeywords()).includes(k),
),
);
this.updateQueryParams();
}
@@ -295,16 +310,14 @@ export class KeywordsSearchComponent {
private keywordExists(keyword: string): boolean {
const normalized = this.normalizeKeyword(keyword);
return [
...this.broadKeywords(),
...this.coarseKeywords(),
...this.fineKeywords(),
...this.manualKeywords(),
...this.getKeywordLabels(this.broadKeywords()),
...this.getKeywordLabels(this.coarseKeywords()),
...this.getKeywordLabels(this.fineKeywords()),
...this.getKeywordLabels(this.manualKeywords()),
].some((k) => this.normalizeKeyword(k) === normalized);
}
// Add manually from Keywords tab
addKeywordFromInput(keyword: string): void {
const normalizedKeyword = keyword.trim();
addKeywordFromInput(keyword: Topic): void {
const normalizedKeyword = keyword.display_name?.trim() ?? '';
if (!normalizedKeyword) return;
if (this.keywordExists(normalizedKeyword)) {
@@ -312,35 +325,54 @@ export class KeywordsSearchComponent {
return;
}
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.loadingNewKeyword.set(true);
const updated = this.uniqueKeywordEntries([
...this.manualKeywordEntries(),
newEntry,
]);
if (keyword.id === null) {
console.log('Adding new keyword without topic:', normalizedKeyword);
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.selectedKeywords.set([
...this.selectedKeywords(),
normalizedKeyword,
]);
// Explicit enrichment trigger for new keywords
this.enrichManualKeywordsWithTopics([normalizedKeyword]);
this.updateQueryParams();
},
});
this.manualKeywordEntries.set(
this.uniqueKeywordEntries([
...this.manualKeywordEntries(),
newEntry,
]),
);
this.selectedKeywords.set([
...this.selectedKeywords(),
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 {
@@ -350,50 +382,72 @@ export class KeywordsSearchComponent {
this.updateQueryParams();
}
onCategoryChange(
category: KeywordCategory,
event: MatChipListboxChange,
): void {
const newSelection = (event.value as string[]) || [];
const otherCategories = (
Object.keys(this.categoryKeywordsMap) as KeywordCategory[]
).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));
toggleKeywordSelection(keyword: KeywordEntryWithTopic): void {
const label = this.getKeywordLabel(keyword);
const nextSelection = this.selectedKeywords().includes(label)
? this.selectedKeywords().filter((value) => value !== label)
: [...this.selectedKeywords(), label];
this.selectedKeywords.set(this.uniqueKeywords(nextSelection));
this.updateQueryParams();
}
selectAllExtracted(): void {
const all = [
...this.selectedManualKeywords(),
...this.broadKeywords(),
...this.coarseKeywords(),
...this.fineKeywords(),
];
this.selectedKeywords.set(this.uniqueKeywords(all));
this.updateQueryParams();
isKeywordSelected(keyword: KeywordEntryWithTopic): boolean {
const normalized = this.normalizeKeyword(this.getKeywordLabel(keyword));
return this.selectedKeywords().some(
(value) => this.normalizeKeyword(value) === normalized,
);
}
deselectAllExtracted(): void {
removeManualKeyword(keyword: KeywordEntryWithTopic): void {
const label = this.getKeywordLabel(keyword);
this.manualKeywordEntries.set(
this.filterKeywordEntries(this.manualKeywordEntries(), label),
);
this.selectedKeywords.set(
this.uniqueKeywords(this.selectedManualKeywords()),
this.selectedKeywords().filter((value) => value !== label),
);
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.coarseKeywordEntries.set([]);
this.fineKeywordEntries.set([]);
this.manualKeywordEntries.set([]);
this.sourceContent.set('');
this.sourceUrl.set(null);
// 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().filter((k) => manualSet.has(k)),
);
@@ -407,11 +461,12 @@ export class KeywordsSearchComponent {
this.updateQueryParams();
}
areAllExtractedSelected(): boolean {
areAllSelected(): boolean {
const allExtracted = [
...this.broadKeywords(),
...this.coarseKeywords(),
...this.fineKeywords(),
...this.getKeywordLabels(this.broadKeywords()),
...this.getKeywordLabels(this.coarseKeywords()),
...this.getKeywordLabels(this.fineKeywords()),
...this.getKeywordLabels(this.manualKeywords()),
];
return allExtracted.every((k) => this.selectedKeywords().includes(k));
}
@@ -432,16 +487,6 @@ export class KeywordsSearchComponent {
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 {
if (result === undefined || !result.results) return;
@@ -454,10 +499,10 @@ export class KeywordsSearchComponent {
// Keep only selected keywords that still exist in any category (including manual)
const allExtracted = [
...this.broadKeywords(),
...this.coarseKeywords(),
...this.fineKeywords(),
...this.manualKeywords(),
...this.getKeywordLabels(this.broadKeywords()),
...this.getKeywordLabels(this.coarseKeywords()),
...this.getKeywordLabels(this.fineKeywords()),
...this.getKeywordLabels(this.manualKeywords()),
];
this.selectedKeywords.set(
this.selectedKeywords().filter((k) => allExtracted.includes(k)),
@@ -469,7 +514,7 @@ export class KeywordsSearchComponent {
}
async extractKeywords(): Promise<void> {
this.clearExtractedKeywords();
this.clearKeywords();
const query = this.getCurrentExtractionQuery();
if (!query) return;
@@ -516,17 +561,11 @@ export class KeywordsSearchComponent {
// --- Helpers --------------------------------------------------------------
private selectedInCategory(category: KeywordCategory): Signal<string[]> {
return computed(() =>
this.selectedKeywords().filter((k) =>
this.categoryKeywordsMap[category]().includes(k),
),
);
}
private applyExtractedKeywords(keywords: ExtractedKeywords): void {
const seenKeywords = new Set(
this.manualKeywords().map((keyword) => this.normalizeKeyword(keyword)),
this.getKeywordLabels(this.manualKeywords()).map((keyword) =>
this.normalizeKeyword(keyword),
),
);
this.broadKeywordEntries.set(
this.uniqueKeywordEntries(keywords.broad_keywords, seenKeywords),
@@ -537,6 +576,7 @@ export class KeywordsSearchComponent {
this.fineKeywordEntries.set(
this.uniqueKeywordEntries(keywords.fine_grained, seenKeywords),
);
this.selectAll();
}
private getSelectedExtractedKeywordEntries(): KeywordEntryWithTopic[] {
@@ -572,8 +612,93 @@ export class KeywordsSearchComponent {
);
}
onViewToggleChange(value: KeywordView): void {
if (this.keywordView() !== value) {
this.keywordView.set(value);
}
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 {
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(
@@ -621,6 +746,9 @@ export class KeywordsSearchComponent {
const manual = this.parseKeywordList(queryParams.get('manual'));
const selected = this.parseKeywordList(queryParams.get('selected'));
const source = queryParams.get('source') ?? '';
const view = queryParams.get('view') ?? 'llm';
const legend = queryParams.get('legend') ?? 'on';
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
this.isRestoringState = true;
@@ -628,7 +756,9 @@ export class KeywordsSearchComponent {
{ selectedInputType: mode, urlInput, textInput },
{ 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.restoreSourceFromSession();
@@ -649,16 +779,24 @@ export class KeywordsSearchComponent {
// clean up the selection to only include keywords that actually exist in
const manualKeywordSet = new Set(
this.manualKeywords().map((k) => this.normalizeKeyword(k)),
this.getKeywordLabels(this.manualKeywords()).map((k) =>
this.normalizeKeyword(k),
),
);
const broadKeywordSet = new Set(
this.broadKeywords().map((k) => this.normalizeKeyword(k)),
this.getKeywordLabels(this.broadKeywords()).map((k) =>
this.normalizeKeyword(k),
),
);
const coarseKeywordSet = new Set(
this.coarseKeywords().map((k) => this.normalizeKeyword(k)),
this.getKeywordLabels(this.coarseKeywords()).map((k) =>
this.normalizeKeyword(k),
),
);
const fineKeywordSet = new Set(
this.fineKeywords().map((k) => this.normalizeKeyword(k)),
this.getKeywordLabels(this.fineKeywords()).map((k) =>
this.normalizeKeyword(k),
),
);
const validSelected = selected.filter(
(k) =>
@@ -684,10 +822,19 @@ export class KeywordsSearchComponent {
mode: this.form.controls.selectedInputType.value,
url: this.toNullableParam(this.form.controls.urlInput.value),
text: this.toNullableParam(this.form.controls.textInput.value),
broad: this.serializeKeywords(this.broadKeywords()),
coarse: this.serializeKeywords(this.coarseKeywords()),
fine: this.serializeKeywords(this.fineKeywords()),
manual: this.serializeKeywords(this.manualKeywords()),
view: this.keywordView(),
legend: this.subfieldLegendVisible() ? 'on' : 'off',
legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off',
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()),
};
@@ -806,7 +953,6 @@ export class KeywordsSearchComponent {
seenKeywords.add(normalized);
uniqueValues.push(value.trim());
}
return uniqueValues;
}
@@ -23,7 +23,6 @@ import {
import { TopicsService } from '../../api/api/topics.service';
import { TopicHierarchyComponent } from '../topic-hierarchy/topic-hierarchy.component';
import { PersonCardComponent } from '../person-card/person-card.component';
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import { SharedStateService } from '../../shared/services/shared-state.service';
import { PaginationService } from '../../shared/services/pagination.service';
@@ -57,7 +56,6 @@ import { SkTextDirective } from '../../custom-directives/sk-text.directive';
MatRadioModule,
TopicHierarchyComponent,
PersonCardComponent,
TopicChipComponent,
SkTextDirective,
MatAutocompleteModule,
],
@@ -9,6 +9,7 @@
(click)="$event.preventDefault()"
(keydown.enter)="submitCurrentValue(); $event.preventDefault()"
(keydown.tab)="onKeydownTab($any($event))" />
<mat-hint>Füge ein Keyword hinzu</mat-hint>
@if (searchControl.value.trim()) {
<button
@@ -22,7 +23,7 @@
</button>
}
@if (searchControl.value) {
<!-- @if (searchControl.value) {
<button
mat-icon-button
matSuffix
@@ -31,7 +32,7 @@
(click)="clear()">
<mat-icon>close</mat-icon>
</button>
}
} -->
<mat-autocomplete
#auto="matAutocomplete"
@@ -44,7 +45,9 @@
}
@for (topic of topics(); track topic) {
<mat-option [value]="topic">{{ topic }}</mat-option>
<mat-option [value]="topic.display_name">{{
topic.display_name
}}</mat-option>
}
@if (
@@ -12,5 +12,4 @@ mat-form-field {
.topic-field {
width: 100%;
min-width: 320px;
}
@@ -19,6 +19,7 @@ import {
of,
switchMap,
} from 'rxjs';
import { Topic } from '../../../api';
@Component({
selector: 'app-topic-autocomplete',
@@ -42,10 +43,10 @@ export class TopicAutocompleteComponent {
readonly minCharacters = input(2);
readonly limit = input(12);
readonly topicSelected = output<string>();
readonly topicSelected = output<Topic>();
readonly searchControl = new FormControl('', { nonNullable: true });
readonly topics = signal<string[]>([]);
readonly topics = signal<Topic[]>([]);
readonly loading = signal(false);
constructor(
@@ -60,12 +61,12 @@ export class TopicAutocompleteComponent {
const normalizedQuery = query.trim();
if (normalizedQuery.length < this.minCharacters()) {
this.loading.set(false);
return of([] as string[]);
return of([]);
}
this.loading.set(true);
return this.topicsService
.autocompleteTopics(
.listTopics(
normalizedQuery,
undefined,
undefined,
@@ -73,21 +74,19 @@ export class TopicAutocompleteComponent {
this.limit(),
)
.pipe(
map((response) =>
Array.from(
new Set(
(response.results ?? [])
.map((topic) => topic.display_name?.trim() ?? '')
.filter((topic) => !!topic),
),
),
),
map(({ results }) => {
const seen = new Map<string, Topic>();
for (const topic of results ?? []) {
if (topic?.id != null) seen.set(String(topic.id), topic);
}
return Array.from(seen.values());
}),
catchError((error) => {
console.error(
'Error fetching topic autocomplete options:',
error,
);
return of([] as string[]);
return of([] as Topic[]);
}),
finalize(() => this.loading.set(false)),
);
@@ -101,19 +100,45 @@ export class TopicAutocompleteComponent {
selectTopic(topic: string): void {
this.searchControl.setValue('', { emitEvent: false });
const selectedTopic = this.getTopicByDisplayName(topic);
this.topics.set([]);
this.topicSelected.emit(topic);
if (selectedTopic) {
this.topicSelected.emit(selectedTopic);
} else {
const newTopic: Topic = {
display_name: topic,
id: null,
};
this.topicSelected.emit(newTopic);
}
}
onKeydownTab(event: KeyboardEvent): void {
event.preventDefault();
this.searchControl.setValue(this.topics()[0], { emitEvent: false });
const first = this.topics()[0];
if (!first) return;
this.searchControl.setValue(first.display_name ?? '', { emitEvent: false });
}
getTopicByDisplayName(displayName: string): Topic | undefined {
const normalized = displayName.trim().toLowerCase();
return this.topics().find(
(topic) => topic.display_name?.trim().toLowerCase() === normalized,
);
}
submitCurrentValue(): void {
const topic = this.searchControl.value.trim();
if (!topic) return;
this.searchControl.setValue('', { emitEvent: false });
this.topics.set([]);
this.topicSelected.emit(topic);
const selectedTopic = this.getTopicByDisplayName(topic);
if (selectedTopic) {
this.topicSelected.emit(selectedTopic);
} else {
const newTopic: Topic = {
display_name: topic,
id: null,
};
this.topicSelected.emit(newTopic);
}
}
clear(): void {