Compare commits

...
Author SHA1 Message Date
farajollahi 92e32cd79e Merge branch 'dev' into dfg-projects-analyse
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 20:59:36 +02:00
farajollahi acad12bf27 remove dfg projects analyse
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-12 20:32:01 +02:00
farajollahi 3fa6f1dd6e Merge pull request 'fix dfg projects analyse' (#210) from dfg-projects-analyse into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #210
2026-07-12 20:20:07 +02:00
farajollahi f20be8aa63 fix dfg projects analyse
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-07-12 18:32:04 +02:00
genja 0f3388d290 Merge pull request 'feature/keywords-analysis' (#209) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #209
2026-07-12 16:32:28 +02:00
genja 2e855dcf7b removed commented sections, cleaned log outputs
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 16:30:44 +02:00
genja 680d2924ee Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keyword-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 16:25:12 +02:00
genja ace2a6bba3 added tooltips, snackbar messages 2026-07-12 16:23:19 +02:00
genja 6dfec1cfd4 updated keywords extraction logic for accepting pdfs 2026-07-12 16:22:43 +02:00
farajollahi 4568669d53 Merge pull request 'bookmark-Authors' (#208) from bookmark-Authors into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #208
2026-07-12 13:42:42 +02:00
genja e5cf17620a fixed layout for fileupload, added snackbars on errors 2026-07-09 23:29:06 +02:00
genja ea3ddabac0 file upload integration fixes 2026-07-09 23:28:40 +02:00
genja 233a2d2fca file upload component added (version 1) 2026-07-09 11:37:12 +02:00
genja b12e254cae added file upload component to keywords extraction UI 2026-07-09 11:36:30 +02:00
genja 40610c94c5 regenerated services 2026-07-09 11:34:56 +02:00
genja 2b1aa8d9e3 added file upload backend logic + content extraction from pdf files 2026-07-09 11:34:43 +02:00
20 changed files with 1340 additions and 323 deletions
+2 -1
View File
@@ -18,7 +18,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
"websockets==12.0" \
"partial-json-parser==0.2.1.1.post7" \
"sqlmodel~=0.0.33" \
"argon2-cffi~=25.1.0"
"argon2-cffi~=25.1.0" \
"pypdf==6.14.2"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
+1
View File
@@ -10,6 +10,7 @@ dependencies = [
"fastapi~=0.115.0",
"httpx~=0.27.0",
"openai~=2.41.0",
"pypdf==6.14.2",
"pydantic~=2.7.1",
"pydantic-settings~=2.2.1",
"pyjwt~=2.8.0",
+12 -14
View File
@@ -599,7 +599,7 @@ async def _top_project_authors(
return []
counts: dict[str, int] = {}
names: dict[str, str] = {}
for bucket in await _top_bund_project_author_buckets(aliases):
for bucket in await _top_dfg_project_author_buckets(aliases):
key = str(bucket.get("key", "")).strip()
if key:
normalized_key = key.casefold()
@@ -635,20 +635,20 @@ async def _top_project_authors(
]
async def _top_bund_project_author_buckets(
async def _top_dfg_project_author_buckets(
aliases: list[str],
) -> list[dict[str, Any]]:
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
index=ESIndex.PROJECTS_DFG_ALL,
body={
"size": 0,
"query": _alias_match_query("Zuwendungsempfänger", aliases),
"query": _dfg_institution_query(aliases),
"aggs": {
"people": {
"terms": {
"script": {
"lang": "painless",
"source": _bund_persons_script(),
"source": _dfg_involved_persons_script(),
},
"size": 10000,
}
@@ -662,17 +662,15 @@ async def _top_bund_project_author_buckets(
)
def _bund_persons_script() -> str:
def _dfg_involved_persons_script() -> str:
return (
"def names = new HashSet(); "
"if (params['_source'].containsKey('Arb') && params['_source']['Arb'] != null) { "
" for (entry in params['_source']['Arb'].entrySet()) { "
" def value = entry.getValue(); "
" if (value instanceof String && value.length() > 0) { "
" if (value.contains(';')) { "
" for (name in value.splitOnToken(';')) { names.add(name.trim()); } "
" } else { names.add(value.trim()); } "
" } "
"def value = params['_source'].containsKey('Beteiligte Personen') "
" ? params['_source']['Beteiligte Personen'] : null; "
"if (value instanceof String && value.length() > 0) { "
" for (name in value.splitOnToken(';')) { "
" def trimmed = name.trim(); "
" if (trimmed.length() > 0) { names.add(trimmed); } "
" } "
"} "
"return new ArrayList(names);"
+63 -13
View File
@@ -98,7 +98,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
@pytest.mark.anyio
async def test_top_authors_maps_works_and_bund_project_aggregations():
async def test_top_authors_maps_works_and_dfg_project_aggregations():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -131,7 +131,7 @@ async def test_top_authors_maps_works_and_bund_project_aggregations():
}
}
}
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
@@ -184,21 +184,21 @@ async def test_top_authors_maps_works_and_bund_project_aggregations():
in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1}
]
assert len(project_calls) == 1
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_BUND_V1
assert project_calls[0].kwargs["body"]["query"]["bool"]["should"][0]["match"] == {
"Zuwendungsempfänger": {
"query": "Example Org",
"operator": "and",
}
}
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_DFG_ALL
assert project_calls[0].kwargs["body"]["query"]["bool"][
"minimum_should_match"
] == 1
assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][
"people"
]["terms"]["script"]["source"]
@pytest.mark.anyio
async def test_top_authors_keeps_bund_project_authors_without_openalex_match():
async def test_top_authors_keeps_dfg_project_authors_without_openalex_match():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
@@ -228,11 +228,11 @@ async def test_top_authors_keeps_bund_project_authors_without_openalex_match():
@pytest.mark.anyio
async def test_top_authors_returns_top_ten_bund_project_people_by_project_count():
async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
@@ -262,6 +262,56 @@ async def test_top_authors_returns_top_ten_bund_project_people_by_project_count(
assert len(result.projects) == 10
@pytest.mark.anyio
async def test_top_authors_combines_dfg_involved_people_case_insensitively():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
"works_count": 1,
"counts_by_year": [],
}
}
]
}
}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
"buckets": [
{"key": "Ada Example", "doc_count": 2},
{"key": "ada example", "doc_count": 3},
{"key": "DFG Person", "doc_count": 4},
]
}
}
}
return {"aggregations": {"authors": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert [author.model_dump() for author in result.projects] == [
{"id": "A1", "name": "Ada Example", "count": 5},
{"id": None, "name": "DFG Person", "count": 4},
]
@pytest.mark.anyio
async def test_top_authors_returns_partial_response_when_one_source_fails():
async def search(**kwargs):
@@ -0,0 +1,58 @@
# inse/keywords/file_extraction.py
import base64
import logging
import httpx
from bs4 import BeautifulSoup
# import fitz
import io
from pypdf import PdfReader
from pypdf.errors import PdfReadError
logger = logging.getLogger(__name__)
def extract_text_from_upload(filename: str, content_base64: str, mime_type: str) -> str:
try:
raw = base64.b64decode(content_base64)
except Exception:
logger.warning("Failed to decode base64 for %s", filename)
return f"[{filename}: could not decode upload]"
if mime_type == "application/pdf" or filename.lower().endswith(".pdf"):
return _extract_pdf_text(filename, raw)
try:
return raw.decode("utf-8", errors="replace")
except Exception:
logger.warning("Failed to decode %s as text", filename)
return f"[{filename}: unsupported or undecodable content]"
def _extract_pdf_text(filename: str, raw: bytes) -> str:
try:
reader = PdfReader(io.BytesIO(raw), strict=False) # non-strict: tolerate minor spec violations
except Exception as e:
logger.warning("Failed to open PDF %s: %s", filename, e)
return f"[{filename}: PDF could not be opened (corrupted or invalid)]"
if reader.is_encrypted:
try:
# Attempt to decrypt with an empty password (common for "owner-locked"
# PDFs that don't require one to read content)
reader.decrypt("")
except Exception as e:
logger.warning("Encrypted PDF %s could not be decrypted: %s", filename, e)
return f"[{filename}: PDF is encrypted and could not be read]"
parts = []
for page_num, page in enumerate(reader.pages):
try:
parts.append(page.extract_text() or "")
except PdfReadError as e:
logger.warning("Failed to extract page %d of %s: %s", page_num, filename, e)
parts.append(f"[Page {page_num + 1} could not be extracted]")
except Exception as e:
logger.warning("Unexpected error extracting page %d of %s: %s", page_num, filename, e)
parts.append(f"[Page {page_num + 1} could not be extracted]")
return "\n".join(parts)
+256 -123
View File
@@ -23,7 +23,9 @@ from inse.keywords.model import (
KeywordEntry,
KeywordEntryWithTopic,
KeywordsWsEvent,
FileUpload,
)
from inse.keywords.extract_text import extract_text_from_upload
from inse.topics.logic import vector_search_topics_batch
logger = logging.getLogger(__name__)
EventCallback = Callable[[dict], Awaitable[None]]
@@ -64,7 +66,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
"""
start_time = time.time()
if mode == "url":
text = await _get_text_content(query)
text = await get_text_from_url(query)
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
else:
@@ -97,67 +99,18 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time)
async def _get_text_content(url: str) -> str:
"""
Fetches the HTML content from the given URL using httpx and extracts visible text.
"""
try:
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/91.0.4472.124 Safari/537.36"
)
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.get(url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for element in soup(["script", "style"]):
element.decompose()
text = soup.get_text(separator=" ", strip=True)
text = " ".join(text.split())
return text
except httpx.HTTPError as e:
logger.error(f"HTTP error for {url}: {e}")
except Exception as e:
logger.error(f"Error processing {url}: {e}")
async def extract_keywords_stream_enriched(
query: str,
mode: str,
limit: int,
emit: EventCallback,
files: List[FileUpload] | None = None,
) -> ExtractedKeywordsResponse:
start_time = time.time()
timeout_seconds = 120
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)
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"
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")
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
enrichment_tasks: List[asyncio.Task] = []
@@ -183,78 +136,224 @@ async def extract_keywords_stream_enriched(
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
await emit_full_results()
async def on_chunk(event: Dict[str, Any]) -> None:
if event["type"] != "llm_chunk":
await emit(event)
return
def make_on_chunk(base_offset: Dict[str, int]):
"""
Builds an on_chunk callback for a single streaming LLM call.
`base_offset` records how many items each level already had in the
shared `confirmed` list *before* this call started, so growth from
this call's own (independent) partial JSON can be tracked correctly
even though `confirmed` keeps accumulating across multiple calls
(one per file).
"""
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 []
# How many items belonging to *this* call have already been
# appended to the shared `confirmed` list.
local_have = len(confirmed[level]) - base_offset[level]
start_idx = len(confirmed[level])
while local_have < len(current):
raw_item = current[local_have]
try:
validated_item = KeywordEntry.model_validate(raw_item)
except ValidationError:
break
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
local_have += 1
grew = True
for idx in range(start_idx, len(confirmed[level])):
keyword_text = confirmed[level][idx].llm_keyword.keyword
await emit(
KeywordsWsEvent(
type="status",
step="enriching",
message=f"Extracting topic for keyword '{keyword_text}'",
).model_dump()
)
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
enrichment_tasks.append(task)
if grew:
await emit_full_results()
return on_chunk
async def run_llm_extraction(text: str, system_prompt: str, label: str | None = None) -> None:
"""
Runs a single independent streaming LLM extraction call over `text`
and folds its results into the shared `confirmed` structure. Used
once for url/text mode, and once *per file* for file mode.
"""
base_offset = {level: len(confirmed[level]) for level in LEVELS}
on_chunk = make_on_chunk(base_offset)
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)
user_prompt = "\nNow analyze the following text.\n"
if limit:
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
user_prompt += f"\nInput:\n{text}"
suffix = f" for {label}" if label else ""
try:
partial = partial_json_parser.loads(event.get("_full_content", ""))
except Exception:
return
if not isinstance(partial, dict):
return
keywords_raw = 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.0,
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{suffix}").model_dump())
raise RuntimeError(f"LLM streaming call timed out{suffix}")
except asyncio.CancelledError:
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
raise
grew = False
if not keywords_raw:
# 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=f"LLM call failed or returned no content{suffix}").model_dump())
raise RuntimeError(f"LLM streaming call returned empty content{suffix}")
for level in LEVELS:
current = partial.get(level) or []
start_idx = len(confirmed[level])
try:
json.loads(keywords_raw)
except json.JSONDecodeError as e:
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response{suffix}: {e}").model_dump())
raise RuntimeError(f"LLM response is not valid JSON{suffix}")
while len(confirmed[level]) < len(current):
raw_item = current[len(confirmed[level])]
try:
validated_item = KeywordEntry.model_validate(raw_item)
except ValidationError:
break
# ---------- Gather input text & run extraction(s) ----------
source_content = ""
try:
if mode == "url":
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
text = await get_text_from_url(query)
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}")
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
grew = True
source_content = text
await run_llm_extraction(text, KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT)
elif mode == "files":
provided_files = files or []
total_files = len(provided_files)
await emit(
KeywordsWsEvent(
type="status",
step="extracting_files",
message=f"Extrahiere Inhalt aus {total_files} Datei(en)",
).model_dump()
)
file_texts: List[str] = []
failed_files: List[str] = []
for i, f in enumerate(provided_files, start=1):
text = await asyncio.to_thread(
extract_text_from_upload, f.filename, f.content_base64, f.mime_type
)
if not text or not text.strip():
await emit(
KeywordsWsEvent(
type="status",
step="content_extracted",
message=f"Kein Text in '{f.filename}' gefunden, überspringe",
).model_dump()
)
failed_files.append(f.filename)
continue
for idx in range(start_idx, len(confirmed[level])):
keyword_text = confirmed[level][idx].llm_keyword.keyword
await emit(
KeywordsWsEvent(
type="status",
step="enriching",
message=f"Extracting topic for keyword '{keyword_text}'",
step="content_extracted",
message=f"'{f.filename}': {len(text)} Zeichen extrahiert ({i}/{total_files})",
).model_dump()
)
await emit(
KeywordsWsEvent(
type="status",
step="calling_llm",
message=f"Extrahiere Keywords aus '{f.filename}' ({i}/{total_files})",
).model_dump()
)
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
enrichment_tasks.append(task)
if grew:
await emit_full_results()
try:
# Each file gets its own, independent LLM call so
# keywords from one file can't dilute or get mixed up
# with the content of another. Results from every call
# still accumulate into the same shared `confirmed`
# structure, so they keep streaming to the client
# progressively as before.
await run_llm_extraction(
text,
KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT,
label=f"file '{f.filename}'",
)
file_texts.append(f"# {f.filename}\n\n{text}")
except asyncio.CancelledError:
raise
except Exception as e:
# Isolate failures: one broken/unparseable file shouldn't
# abort keyword extraction for the rest of the batch.
logger.error(f"Keyword extraction failed for file '{f.filename}': {e}")
failed_files.append(f.filename)
continue
full_content_holder = {"value": ""}
if not file_texts:
await emit(KeywordsWsEvent(type="error", message="Kein Text konnte aus den Dateien extrahiert werden").model_dump())
raise RuntimeError("Failed to extract text from uploaded files")
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)
if failed_files:
await emit(
KeywordsWsEvent(
type="status",
step="content_extracted",
message=f"{len(failed_files)} Datei(en) konnten nicht verarbeitet werden: {', '.join(failed_files)}",
).model_dump()
)
# ---------- Call the LLM ----------
keywords = ""
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.0,
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
source_content = "\n\n---\n\n".join(file_texts)
else:
text = query
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
source_content = text
await run_llm_extraction(text, KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT)
finally:
if enrichment_tasks:
@@ -264,22 +363,8 @@ async def extract_keywords_stream_enriched(
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())
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")
await emit_full_results()
try:
@@ -294,8 +379,56 @@ async def extract_keywords_stream_enriched(
results=final_validated,
source=mode,
source_url=query if mode == "url" else None,
source_content=text,
source_content=source_content,
duration=elapsed_time,
)
return result
return result
async def get_text_from_url(url: str) -> str:
"""
Fetches the HTML content from the given URL using httpx and extracts visible text.
"""
try:
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/91.0.4472.124 Safari/537.36"
)
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.get(url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for element in soup(["script", "style"]):
element.decompose()
text = soup.get_text(separator=" ", strip=True)
text = " ".join(text.split())
return text
except httpx.HTTPError as e:
logger.error(f"HTTP error for {url}: {e}")
except Exception as e:
logger.error(f"Error processing {url}: {e}")
async def _get_files_text(files: List[FileUpload]) -> str:
"""
Extracts and joins text from uploaded files. Runs blocking PDF parsing
in a thread so it doesn't stall the event loop.
NOTE: no longer used by extract_keywords_stream_enriched(), which now
extracts and processes each file independently so it can run a
separate LLM call per file. Kept here in case other callers still rely
on a single combined text blob.
"""
parts = []
for f in files:
text = await asyncio.to_thread(
extract_text_from_upload, f.filename, f.content_base64, f.mime_type
)
parts.append(text)
return "\n\n---\n\n".join(parts)
+11
View File
@@ -8,10 +8,21 @@ from typing import List, Literal
from pydantic import BaseModel, Field
from inse.topics.model import KeywordTopicMatch
class FileUpload(BaseModel):
filename: str = Field(description="The name of the uploaded file.")
content_base64: str = Field(description="The base64-encoded content of the uploaded file.")
mime_type: str = Field(description="The MIME type of the uploaded file, e.g., 'application/pdf', 'image/png', etc.")
class KeywordsRequest(BaseModel):
query: str = Field(description="The input text from which to extract keywords.")
files: list[FileUpload] | None = None
mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
limit: int = Field(default=None, description="The maximum number of keywords to extract.")
# class KeywordsRequest(BaseModel):
# query: str = Field(description="The input text from which to extract keywords.")
# mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
# limit: int = Field(default=None, description="The maximum number of keywords to extract.")
class KeywordEntry(BaseModel):
keyword: str = Field(description="The extracted keyword.")
+12 -6
View File
@@ -31,9 +31,11 @@ async def extract_keywords_ws(websocket: WebSocket):
disconnected = asyncio.Event()
extraction_task: asyncio.Task | None = None
def _is_socket_open() -> bool:
return not disconnected.is_set() and websocket.application_state.name != "DISCONNECTED"
async def emit(event: dict):
if disconnected.is_set():
if not _is_socket_open():
return
try:
await websocket.send_json(event)
@@ -41,7 +43,7 @@ async def extract_keywords_ws(websocket: WebSocket):
disconnected.set()
async def safe_send(payload: dict):
if disconnected.is_set():
if not _is_socket_open():
return
try:
await websocket.send_json(payload)
@@ -51,12 +53,12 @@ async def extract_keywords_ws(websocket: WebSocket):
try:
raw = await websocket.receive_json()
request = KeywordsRequest(**raw)
extraction_task = asyncio.create_task(
logic.extract_keywords_stream_enriched(
query=request.query,
mode=request.mode,
limit=request.limit,
files=request.files,
emit=emit,
)
)
@@ -71,7 +73,6 @@ async def extract_keywords_ws(websocket: WebSocket):
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()
@@ -89,8 +90,11 @@ async def extract_keywords_ws(websocket: WebSocket):
except (asyncio.CancelledError, Exception):
pass
if websocket.application_state.name != "DISCONNECTED":
await websocket.close()
if _is_socket_open():
try:
await websocket.close()
except RuntimeError:
logger.debug("WebSocket already closed, skipping close()")
@router.post(
"/keywords/extract",
@@ -107,3 +111,5 @@ async def extract_keywords(
):
return await logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit)
+11
View File
@@ -799,6 +799,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/2b/4f/e04a8067c7c96c364cef7ef73906504e2f40d690811c021e1a1901473a19/PyJWT-2.8.0-py3-none-any.whl", hash = "sha256:59127c392cc44c2da5bb3192169a91f429924e17aff6534d70fdc02ab3e04320", size = 22591, upload-time = "2023-07-18T20:02:21.561Z" },
]
[[package]]
name = "pypdf"
version = "6.14.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/03/72/7dfd5ff1c9c37de97a731701f51af091325f123d9d4270361c9c69e4431f/pypdf-6.14.2.tar.gz", hash = "sha256:7873f502fe4385e79539b21d872392dc0c4e3714327c15881cbc7fbfd1f95b25", size = 6491182, upload-time = "2026-06-23T14:18:30.859Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/49/e6/136aa8993a2ae7214e0b0ef2edaa0d2e08d1d4e4982635b08a835ff31ec8/pypdf-6.14.2-py3-none-any.whl", hash = "sha256:3f07891af76dc002657e04993ab9b4de81de29f9013b9761d0b7968bff12e946", size = 349514, upload-time = "2026-06-23T14:18:28.867Z" },
]
[[package]]
name = "pytest"
version = "8.1.2"
@@ -1137,6 +1146,7 @@ dependencies = [
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyjwt" },
{ name = "pypdf" },
{ name = "pytest" },
{ name = "python-multipart" },
{ name = "pyyaml" },
@@ -1158,6 +1168,7 @@ requires-dist = [
{ name = "pydantic", specifier = "~=2.7.1" },
{ name = "pydantic-settings", specifier = "~=2.2.1" },
{ name = "pyjwt", specifier = "~=2.8.0" },
{ name = "pypdf", specifier = "==6.14.2" },
{ name = "pytest", specifier = "~=8.1.0" },
{ name = "python-multipart", specifier = "~=0.0.19" },
{ name = "pyyaml", specifier = "~=6.0.1" },
@@ -81,6 +81,7 @@ model/euProjectData.ts
model/extractedKeywords.ts
model/extractedKeywordsLLM.ts
model/extractedKeywordsResponse.ts
model/fileUpload.ts
model/filterInformation.ts
model/filterProperties.ts
model/fp7EurosciVoc.ts
+26
View File
@@ -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 FileUpload {
/**
* The name of the uploaded file.
*/
filename: string;
/**
* The base64-encoded content of the uploaded file.
*/
content_base64: string;
/**
* The MIME type of the uploaded file, e.g., \'application/pdf\', \'image/png\', etc.
*/
mime_type: string;
}
+16 -16
View File
@@ -1,26 +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.
*/
import { FileUpload } from './fileUpload';
export interface KeywordsRequest {
/**
* The input text from which to extract keywords.
*/
query: string;
/**
* The mode of keyword extraction, e.g., \'url\', \'text\', or \'keywords\'.
*/
mode: string;
/**
* The maximum number of keywords to extract.
*/
limit?: number;
export interface KeywordsRequest {
/**
* The input text from which to extract keywords.
*/
query: string;
files?: Array<FileUpload> | null;
/**
* The mode of keyword extraction, e.g., \'url\', \'text\', or \'keywords\'.
*/
mode: string;
/**
* The maximum number of keywords to extract.
*/
limit?: number;
}
@@ -174,7 +174,7 @@
<header class="top-authors-header">
<div>
<h2>Top 10 Personen aller Zeiten</h2>
<p>Nach Anzahl der Works und Projekte Ihrer Organisation.</p>
<p>Nach Anzahl der Works, Patente und News Ihrer Organisation.</p>
</div>
<div class="top-authors-period-toggle" aria-label="Works-Zeitraum">
<button
@@ -105,11 +105,6 @@ export class DashboardComponent implements OnInit {
icon: 'menu_book',
entries: this.topAuthors?.works ?? [],
},
{
title: 'Projekte',
icon: 'work',
entries: this.topAuthors?.projects ?? [],
},
{
title: 'Patente',
icon: 'description',
@@ -19,6 +19,7 @@
mat-flat-button
type="button"
class="extract-btn"
[disabled]="!form.controls.urlInput.value"
[color]="isExtracting() ? 'warn' : 'primary'"
(click)="onExtractKeywordsClick()">
<mat-icon>
@@ -43,6 +44,7 @@
<button
mat-flat-button
type="button"
[disabled]="!form.controls.textInput.value"
[color]="isExtracting() ? 'warn' : 'primary'"
class="extract-btn"
(click)="onExtractKeywordsClick()">
@@ -54,6 +56,32 @@
</div>
</div>
</mat-tab>
<mat-tab label="Datei">
<div class="tab-content">
<app-file-upload
[requiredFileType]="'text/plain,application/pdf'"
[maxFileSize]="5 * 1024 * 1024"
[maxFiles]="3"
[uploadedFiles]="uploadedFiles()"
(filesChange)="onFilesSelected($event)">
</app-file-upload>
<div class="actions">
<button
mat-flat-button
type="button"
[color]="isExtracting() ? 'warn' : 'primary'"
[disabled]="uploadedFiles().length === 0"
class="extract-btn"
(click)="onExtractKeywordsClick()">
<mat-icon>
{{ isExtracting() ? 'close' : 'troubleshoot' }}
</mat-icon>
{{ isExtracting() ? 'Abbrechen' : 'Keywords extrahieren' }}
</button>
<!-- Add this inside your form or section -->
</div>
</div>
</mat-tab>
</mat-tab-group>
<!-- Extraction Table -->
<mat-card
@@ -110,37 +138,40 @@
</button>
</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()) {
<div class="toolbar-group toolbar-group--view">
<mat-button-toggle-group
[value]="keywordView()"
(change)="onViewToggleChange($event.value)"
aria-label="Keyword Ansicht wählen">
<mat-button-toggle
[disabled]="isExtracting()"
value="topic"
matTooltip="Topic Mapping">
<mat-icon>account_tree</mat-icon>
<span>Topic Mapping</span>
value="llm"
matTooltip="Extrahierte Keywords">
<mat-icon>text_fields</mat-icon>
<span>Extrahierte Keywords</span>
</mat-button-toggle>
}
</mat-button-toggle-group>
@if (topicMappingSearch()) {
<mat-button-toggle
[disabled]="isExtracting()"
value="topic"
matTooltip="Die Abbildung der extrahierten Keywords auf die bekannten Themenbereiche">
<mat-icon>account_tree</mat-icon>
<span>Topic Mapping</span>
</mat-button-toggle>
}
</mat-button-toggle-group>
</div>
<div class="toolbar-divider"></div>
<div class="toolbar-group toolbar-group--view">
<mat-slide-toggle
(change)="onToggleTopicMappingSearch($event)"
labelPosition="before"
[checked]="topicMappingSearch()"
class="mapping-toggle">
Topic Mapping
</mat-slide-toggle>
<div class="toggle-container">
<mat-slide-toggle
(change)="onToggleTopicMappingSearch($event)"
[checked]="topicMappingSearch()"
matTooltip="Wenn aktiviert, werden die extrahierten Keywords auf bekannte Themenbereiche abgebildet, was die Suchergebnisse verbessert.">
Topic Mapping
</mat-slide-toggle>
</div>
</div>
</div>
@@ -243,36 +274,48 @@
<div class="table-body">
<div class="table-col broad-col">
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: broadKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
@if (isExtracting() && broadKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<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>
@if (isExtracting() && coarseKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<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>
@if (isExtracting() && fineKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: fineKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
<div class="table-col own-col">
@@ -289,14 +332,18 @@
<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>
@if (isExtracting() && broadKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: broadKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
</mat-tab>
@@ -306,14 +353,18 @@
<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>
@if (isExtracting() && coarseKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: coarseKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
</mat-tab>
@@ -323,14 +374,18 @@
<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>
@if (isExtracting() && fineKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: fineKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
</mat-tab>
@@ -345,30 +400,27 @@
</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()) {
<!-- @if (isExtracting() && !keywordsExist()) {
<app-loading
text="{{ statusMessage() }}"
icon="manage_search"
[size]="200"
[diameter]="200" />
} -->
<!-- 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>
@if (isExtracting() && keywordsExist()) {
@if (isExtracting()) {
<div class="status-message">{{ statusMessage() }}</div>
}
</div>
@@ -19,10 +19,12 @@ $touch-target: 44px;
.tab-content {
display: flex;
flex-direction: column;
margin-top: 0.5rem;
gap: 0.5rem;
align-items: center;
align-items: top;
app-file-upload {
width: 100%;
}
}
.full-width {
@@ -87,7 +89,6 @@ $touch-target: 44px;
gap: auto;
::ng-deep .mdc-switch {
position: relative;
width: 100%;
}
::ng-deep .mdc-form-field {
@@ -573,7 +574,7 @@ mat-button-toggle-group {
SOURCE EXPANSION PANEL
============================================================ */
.source-expansion {
margin: 0.75rem 0;
margin: 0.5rem 1rem;
background: var(--sg-background-muted, #f5f5f5);
border-radius: 4px;
//border-left: 4px solid var(--sg-primary, #1976d2);
@@ -1,4 +1,4 @@
import { Component, computed, signal, inject } from '@angular/core';
import { Component, computed, signal, inject, effect } from '@angular/core';
import { BreakpointObserver } from '@angular/cdk/layout';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
@@ -32,6 +32,12 @@ 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 { FileUpload } from '../../api/model/fileUpload';
import { MatSnackBar } from '@angular/material/snack-bar';
import {
FileUploadComponent,
FileUploadItem,
} from '../../shared/ui/file-upload/file-upload.component';
import {
MatButtonToggleModule,
MatButtonToggleGroup,
@@ -51,8 +57,12 @@ import { PatentsService } from '../../api/api/patents.service';
import { KeywordsPatentsComponent } from './keywords-patents/keywords-patents.component';
import { DomSanitizer } from '@angular/platform-browser';
import { SearchResultsPayload } from './search-results/search-results-state.service';
import { KeywordPatentMatch, KeywordPatentSearchItem, KeywordsService } from '../../api';
type InputMode = 'url' | 'text';
import {
KeywordPatentMatch,
KeywordPatentSearchItem,
KeywordsService,
} from '../../api';
type InputMode = 'url' | 'text' | 'file';
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
type KeywordView = 'llm' | 'topic';
type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom';
@@ -82,6 +92,7 @@ type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom';
LoadingComponent,
MatSlideToggleModule,
MatSliderModule,
FileUploadComponent,
],
templateUrl: './keywords-search.component.html',
styleUrl: './keywords-search.component.scss',
@@ -91,24 +102,23 @@ export class KeywordsSearchComponent {
private readonly sanitizer = inject(DomSanitizer);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly _snackBar = inject(MatSnackBar);
private readonly destroyRef = inject(DestroyRef);
private readonly websocketService = inject(KeywordWebSocketService);
private readonly topicsService = inject(TopicsService);
private readonly patentsService = inject(PatentsService);
private readonly breakpointObserver = inject(BreakpointObserver);
private readonly keywordsService = inject(KeywordsService);
readonly form = this.formBuilder.nonNullable.group({
selectedInputType: 'url' as InputMode,
urlInput: '',
textInput: '',
fileInput: '',
});
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)')
@@ -139,6 +149,7 @@ export class KeywordsSearchComponent {
readonly patentsLoaded = signal(false);
readonly topicMappingSearch = signal<boolean>(false);
readonly uploadedFiles = signal<FileUploadItem[]>([]);
readonly keywordsExist = computed(
() =>
this.broadKeywords().length > 0 ||
@@ -159,43 +170,58 @@ export class KeywordsSearchComponent {
let highlightedContent = content;
// replace the keyword with highlighted spans
const normalizeText = (text: string): string => {
return text
.trim()
.toLowerCase()
.replace(/[\u2010-\u2015\u2026—–]/g, '-')
.replace(/[\u2018\u2019\u201b\u201c\u201d\u201f]/g, "'")
.replace(/[\s\n\r\t]+/g, ' ')
.replace(/[^a-zA-Z0-9\s\-]/g, '');
};
// Normalize keyword for matching
const normalizeKeyword = (keyword: string): string => {
return keyword
.trim()
.toLowerCase()
.replace(/[\s\-]+/g, '')
.replace(/[^a-zA-Z0-9]/g, '');
};
for (const keyword of selectedKeywords) {
const normalizedKeyword = this.normalizeKeyword(keyword);
const normalizedKeyword = normalizeKeyword(keyword);
// Find the first keyword entry that matches this normalized keyword
const entry = this.allKeywordEntries().find(
(e) =>
this.normalizeKeyword(this.getKeywordLabel(e)) === normalizedKeyword,
);
const entry = this.allKeywordEntries().find((e) => {
const label = this.getKeywordLabel(e);
return normalizeKeyword(label) === 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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
if (!entry) continue;
// 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 topic = this.getTopic(entry);
if (!topic) continue;
const escapedRegexKeyword = keyword.replace(
/[.*+?^${}()|[\]\\]/g,
'\\$&',
);
const regex = new RegExp(escapedRegexKeyword, 'g');
const color = this.getTopicColor(topic);
highlightedContent = highlightedContent.replace(regex, replacement);
}
}
const escapedKeyword = keyword
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
const escapedRegexKeyword = keyword
.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
.replace(/\s+/g, '\\s*');
const regex = new RegExp(escapedRegexKeyword, 'gi');
const replacement = `<span style="text-decoration: underline; background-color: color-mix(in srgb, ${color} 27%, #ffffff); font-weight: bold;" title="Keyword: ${escapedKeyword}">${escapedKeyword}</span>`;
highlightedContent = highlightedContent.replace(regex, replacement);
}
console.log(
'Highlighted content:',
this.sanitizer.bypassSecurityTrustHtml(highlightedContent),
);
return this.sanitizer.bypassSecurityTrustHtml(highlightedContent);
});
@@ -211,6 +237,7 @@ export class KeywordsSearchComponent {
readonly progress = signal(0);
readonly statusMessage = signal('');
readonly errorMessage = signal('');
readonly keywordView = signal<KeywordView>('llm');
readonly subfieldLegendVisible = signal(true);
readonly subfieldLegendExpanded = signal(false);
@@ -254,6 +281,14 @@ export class KeywordsSearchComponent {
.getMessages()
.subscribe((event: WsEvent) => this.handleWsEvent(event));
effect(() => {
const message = this.errorMessage();
if (message) {
this._snackBar.open(message, 'Schließen', {
duration: 5000,
});
}
});
// this.destroyRef.onDestroy(() => {
// this.websocketService.close();
// const isReload = this.router.lastSuccessfulNavigation === null;
@@ -293,11 +328,15 @@ export class KeywordsSearchComponent {
this.statusMessage.set('Fertig!');
this.websocketService.close();
this.isExtracting.set(false);
if (!this.keywordsExist()) {
this.errorMessage.set('Keine Keywords extrahiert');
}
}
private handleErrorEvent(event: WsEvent): void {
this.progress.set(0);
this.statusMessage.set('Fehler: ' + event.message);
this.errorMessage.set(event.message || 'Unbekannter Fehler');
//this.statusMessage.set('Fehler: ' + event.message);
this.broadKeywordEntries.set([]);
this.coarseKeywordEntries.set([]);
this.fineKeywordEntries.set([]);
@@ -372,14 +411,49 @@ export class KeywordsSearchComponent {
// --- Tabs ---------------------------------------------------------------
selectedTabIndex(): number {
return this.form.controls.selectedInputType.value === 'text' ? 1 : 0;
if (this.form.controls.selectedInputType.value === 'url') return 0;
if (this.form.controls.selectedInputType.value === 'text') return 1;
return 2;
}
onTabChange(index: number): void {
const nextMode: InputMode = index === 1 ? 'text' : 'url';
let nextMode: InputMode;
if (index === 0) {
nextMode = 'url';
} else if (index === 1) {
nextMode = 'text';
} else {
nextMode = 'file';
}
this.form.controls.selectedInputType.setValue(nextMode);
}
// fileupload
onFilesSelected(files: FileUploadItem[]): void {
this.uploadedFiles.set(files);
}
// Helper: Send files to WebSocket for server-side extraction
private sendFilesToWebSocket(files: FileUpload[]) {
const keywordsRequest: KeywordsRequest = {
query: '',
files,
mode: 'files',
limit: undefined,
};
this.statusMessage.set('Files uploaded. Extracting keywords...');
this.websocketService
.sendRequest(keywordsRequest)
.then(() => {
this.statusMessage.set('Extracting keywords...');
})
.catch((err) => {
console.error('WebSocket error: OPA', err);
this.errorMessage.set('Failed to send content');
this.isExtracting.set(false);
});
}
// --- Keyword selection & manual entry ------------------------------------
private keywordExists(keyword: string): boolean {
@@ -396,7 +470,7 @@ export class KeywordsSearchComponent {
if (!normalizedKeyword) return;
if (this.keywordExists(normalizedKeyword)) {
this.statusMessage.set(`"${normalizedKeyword}" ist bereits vorhanden.`);
this.errorMessage.set(`"${normalizedKeyword}" ist bereits vorhanden.`);
return;
}
@@ -427,7 +501,7 @@ export class KeywordsSearchComponent {
error: (err) => {
console.error('vectorSearchTopics failed', err);
this.loadingNewKeyword.set(false);
this.statusMessage.set(
this.errorMessage.set(
`Fehler beim Hinzufügen von "${normalizedKeyword}".`,
);
},
@@ -555,10 +629,72 @@ export class KeywordsSearchComponent {
}
onExtractKeywordsClick(): void {
this.clearKeywords();
if (this.isExtracting()) {
this.cancelKeywordExtraction();
return;
}
const mode = this.form.controls.selectedInputType.value;
if (mode === 'file') {
const files = this.uploadedFiles();
if (!files || files.length === 0) {
this.errorMessage.set('Bitte Datei hochladen.');
return;
}
this.isExtracting.set(true);
this.progress.set(0);
this.statusMessage.set('Dateien werden verarbeitet...');
const totalFiles = files.length;
let processedFiles = 0;
const fileUploads: FileUpload[] = new Array(totalFiles);
files.forEach((fileItem, index) => {
const file = fileItem.file;
const reader = new FileReader();
reader.onload = (e) => {
const dataUrl = e.target?.result as string;
const base64 = dataUrl.split(',')[1] ?? '';
fileUploads[index] = {
filename: file.name,
content_base64: base64,
mime_type: file.type || 'application/octet-stream',
};
processedFiles++;
if (processedFiles === totalFiles) {
this.sendFilesToWebSocket(fileUploads);
}
};
reader.onerror = () => {
console.error('Error reading file:', file.name);
fileUploads[index] = {
filename: file.name,
content_base64: '',
mime_type: file.type || 'application/octet-stream',
};
processedFiles++;
if (processedFiles === totalFiles) {
this.sendFilesToWebSocket(fileUploads);
}
};
reader.readAsDataURL(file);
});
return;
}
// For URL and text, fall back to original behavior
void this.extractKeywords();
}
@@ -615,7 +751,7 @@ export class KeywordsSearchComponent {
} catch (error) {
console.error('WebSocket send error:', error);
this.isExtracting.set(false);
this.statusMessage.set('Fehler beim Senden der Anfrage');
this.errorMessage.set('Fehler beim Senden der Anfrage');
}
}
@@ -623,7 +759,7 @@ export class KeywordsSearchComponent {
this.websocketService.close();
this.isExtracting.set(false);
this.progress.set(0);
this.statusMessage.set('Extraktion abgebrochen');
this.errorMessage.set('Extraktion abgebrochen');
}
search(): void {
@@ -864,7 +1000,6 @@ export class KeywordsSearchComponent {
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
const softSearch = queryParams.get('softSearch') === 'true';
this.isRestoringState = true;
this.form.patchValue(
{
selectedInputType: mode,
@@ -889,12 +1024,6 @@ export class KeywordsSearchComponent {
// enrich only newly added keywords that have no topic yet
this.enrichManualKeywordsWithTopics(manual);
// User intent (the current selection): the URL is always authoritative
// here, deliberately overriding whatever the session cache had. This
// is what makes a deep link like ?selected=foo&manual=bar from another
// page reliably preselect keywords, instead of getting merged with (or
// hidden behind) leftover state from a previous visit in the same tab.
// clean up the selection to only include keywords that actually exist in
const manualKeywordSet = new Set(
this.getKeywordLabels(this.manualKeywords()).map((k) =>
@@ -1048,7 +1177,10 @@ export class KeywordsSearchComponent {
}
private parseMode(mode: string | null): InputMode {
return mode === 'text' ? 'text' : 'url';
if (mode === 'url') return 'url';
if (mode === 'text') return 'text';
if (mode === 'file') return 'file';
return 'url';
}
private parseKeywordList(rawValue: string | null): string[] {
@@ -0,0 +1,84 @@
<div
#uploadContainer
class="file-upload-container"
[class.compact]="files.length > 0">
<!-- Drop Zone (shrinks when files are present) -->
<div class="drop-zone-wrapper">
<div
#dropZone
class="drop-zone"
[class.drag-over]="isDragging"
(click)="fileInput.click()">
<mat-icon class="upload-icon">attach_file</mat-icon>
<p class="drop-text">Drag & Drop Dateien hier oder klicken</p>
<small class="file-info">
Unterstützt: {{ requiredFileType }} (Max:
{{ maxFileSize / 1024 / 1024 }}MB, {{ maxFiles }} Dateien)
</small>
</div>
<!-- File Strip (compact row, appears above the drop zone) -->
@if (files.length > 0) {
<mat-divider></mat-divider>
<div class="file-strip">
@for (file of files; track file.id) {
<div class="file-chip" [matTooltip]="file.file.name">
<div class="chip-thumb">
@if (file.file.type.startsWith('image/')) {
<img [src]="file.previewUrl" alt="Preview" />
} @else {
<mat-icon>{{ getIcon(file.file.type) }}</mat-icon>
}
<div class="chip-overlay">
<button
type="button"
class="chip-btn"
(click)="downloadFile(file.id)"
matTooltip="Download">
<mat-icon>download</mat-icon>
</button>
<button
type="button"
class="chip-btn"
(click)="cancelUpload(file.id)"
matTooltip="Cancel">
<mat-icon>cancel</mat-icon>
</button>
<button
type="button"
class="chip-btn"
(click)="removeFile(file.id)"
matTooltip="Remove">
<mat-icon>close</mat-icon>
</button>
</div>
</div>
@if (file.progress > 0 && file.progress < 100) {
<div class="chip-progress">
<div
class="chip-progress-fill"
[style.width.%]="file.progress"></div>
</div>
}
<div class="chip-name">{{ file.file.name }}</div>
</div>
}
</div>
}
</div>
<!-- Hidden File Input -->
<input
#fileInput
type="file"
[accept]="
typeof requiredFileType === 'string'
? requiredFileType
: requiredFileType.join(',')
"
multiple
(change)="onFileChange($event)"
style="display: none" />
</div>
@@ -0,0 +1,223 @@
.file-upload-container {
margin: 0 auto;
display: flex;
width: 100%;
flex-direction: column;
gap: 12px;
position: relative;
.drop-zone-wrapper {
border: 2px dashed #ccc;
border-radius: 12px;
background-color: #f9f9f9;
height: 100%;
}
.drop-zone {
max-width: 100%;
flex: 1;
min-height: 0;
padding: 40px 20px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.upload-icon {
font-size: 48px;
height: 48px;
width: 48px;
color: #1976d2;
margin-bottom: 12px;
transition: all 0.3s ease;
}
.drop-text {
font-size: 16px;
color: #555;
margin-bottom: 8px;
transition: all 0.3s ease;
}
.file-info {
font-size: 12px;
color: #888;
}
&.drag-over {
border-color: #1976d2;
background-color: #e3f2fd;
}
}
&.compact .drop-zone {
padding: 16px 20px;
.upload-icon {
font-size: 28px;
height: 28px;
width: 28px;
margin-bottom: 6px;
}
.drop-text {
font-size: 13px;
margin-bottom: 4px;
}
.file-info {
font-size: 11px;
}
}
// Compact horizontal file strip
.file-strip {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(90px, 2fr));
align-items: center;
justify-content: center;
overflow-x: auto;
overflow-y: hidden;
padding: 2px 2px 8px;
&::-webkit-scrollbar {
height: 6px;
}
&::-webkit-scrollbar-thumb {
background: #ccc;
border-radius: 3px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
}
// Individual compact file chip
.file-chip {
flex: 0 0 auto;
width: 90px;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
.chip-thumb {
position: relative;
width: 60px;
height: 60px;
border-radius: 10px;
overflow: hidden;
background-color: #eef1f4;
border: 1px solid #e0e0e0;
display: flex;
align-items: center;
justify-content: center;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
mat-icon {
font-size: 28px;
height: 28px;
width: 28px;
color: #1976d2;
}
.chip-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
gap: 2px;
background: rgba(0, 0, 0, 0.55);
opacity: 0;
transition: opacity 0.2s ease;
.chip-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: none;
background: transparent;
color: #fff;
cursor: pointer;
border-radius: 4px;
&:hover {
background: rgba(255, 255, 255, 0.2);
}
mat-icon {
font-size: 15px;
height: 15px;
width: 15px;
color: #fff;
}
}
}
&:hover .chip-overlay,
&:focus-within .chip-overlay {
opacity: 1;
}
}
.chip-progress {
width: 100%;
height: 3px;
border-radius: 2px;
background-color: #e0e0e0;
overflow: hidden;
.chip-progress-fill {
height: 100%;
background-color: #1976d2;
transition: width 0.2s ease;
}
}
.chip-name {
width: 100%;
font-size: 11px;
line-height: 1.3;
color: #333;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
/* Responsive */
@media (max-width: 600px) {
.file-upload-container {
gap: 10px;
height: 280px;
}
.drop-zone {
padding: 24px 16px;
}
.file-chip {
width: 64px;
.chip-thumb {
width: 50px;
height: 50px;
}
}
}
@@ -0,0 +1,234 @@
import {
Component,
Input,
Output,
EventEmitter,
ViewChild,
ElementRef,
OnDestroy,
OnInit,
inject,
effect,
} from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatDividerModule } from '@angular/material/divider';
export interface FileUploadItem {
file: File;
id: string;
previewUrl?: string;
progress: number;
error?: string;
}
@Component({
selector: 'app-file-upload',
imports: [MatIconModule, MatTooltipModule, MatDividerModule],
templateUrl: 'file-upload.component.html',
styleUrls: ['file-upload.component.scss'],
})
export class FileUploadComponent implements OnInit, OnDestroy {
private snackBar = inject(MatSnackBar);
private http = inject(HttpClient);
@Input() uploadUrl: string = '';
@Input() uploadedFiles: FileUploadItem[] = [];
@Input() requiredFileType: string | string[] = 'application/pdf';
@Input() maxFileSize: number = 10 * 1024 * 1024; // 10MB
@Input() maxFiles: number = 5;
@Output() filesChange = new EventEmitter<FileUploadItem[]>();
@Output() filesSelected = new EventEmitter<FileUploadItem[]>();
@Output() uploadProgressChange = new EventEmitter<{
id: string;
progress: number;
}>();
@ViewChild('fileInput', { static: true })
fileInput!: ElementRef<HTMLInputElement>;
@ViewChild('dropZone', { static: true })
dropZone!: ElementRef<HTMLDivElement>;
@ViewChild('uploadContainer', { static: true })
uploadContainer!: ElementRef<HTMLDivElement>;
files: FileUploadItem[] = [];
private uploadSub: Subscription = new Subscription();
isDragging = false;
private dragCounter = 0;
ngOnInit() {
this.files = [...this.uploadedFiles]; // bind the input files to the internal state
this.setupDragAndDrop();
}
ngOnDestroy() {
this.uploadSub.unsubscribe();
}
private setupDragAndDrop() {
const zone = this.uploadContainer.nativeElement;
zone.addEventListener('dragenter', (e) => {
e.preventDefault();
this.dragCounter++;
this.isDragging = this.dragCounter > 0;
});
zone.addEventListener('dragover', (e) => {
e.preventDefault();
});
zone.addEventListener('dragleave', (e) => {
e.preventDefault();
this.dragCounter--;
this.isDragging = this.dragCounter > 0;
});
zone.addEventListener('drop', (e) => {
e.preventDefault();
this.dragCounter = 0;
this.isDragging = false;
const files = e.dataTransfer?.files;
if (files) {
this.handleFiles(files);
}
});
}
onFileChange(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files) {
this.handleFiles(input.files);
}
}
private handleFiles(fileList: FileList) {
const validFiles: File[] = [];
const newFiles: FileUploadItem[] = [];
Array.from(fileList).forEach((file) => {
if (!this.isValidFile(file)) return;
validFiles.push(file);
});
console.log('Valid files:', validFiles);
if (validFiles.length === 0) return;
const remainingSlots = this.maxFiles - this.files.length;
const filesToAdd = validFiles.slice(0, remainingSlots);
filesToAdd.forEach((file) => {
newFiles.push({
file,
id: this.generateId(),
progress: 0,
previewUrl: this.getPreviewUrl(file),
});
});
this.files = [...this.files, ...newFiles];
this.emitFilesChange();
this.filesSelected.emit(this.files);
}
private isValidFile(file: File): boolean {
const type = file.type;
const size = file.size;
const allowedTypes = Array.isArray(this.requiredFileType)
? this.requiredFileType
: this.requiredFileType.split(',');
const isValidType = allowedTypes.some((t) => {
if (t.includes('/')) return type.startsWith(t);
if (t === 'image') return type.startsWith('image/');
if (t === 'pdf') return type === 'application/pdf';
if (t === 'text') return type.startsWith('text/');
return false;
});
if (!isValidType) {
this.showError(`Dateityp nicht erlaubt: ${file.name}`);
return false;
}
if (size > this.maxFileSize) {
this.showError(
`File zu groß: ${file.name} (${(size / 1024 / 1024).toFixed(2)}MB)`,
);
return false;
}
if (this.files.length + 1 > this.maxFiles) {
this.showError(
`Maximal ${this.maxFiles} Dateien erlaubt. Datei ${file.name} wurde nicht hinzugefügt.`,
);
return false;
}
return true;
}
private getPreviewUrl(file: File): string | undefined {
if (file.type.startsWith('image/')) {
return URL.createObjectURL(file);
}
return undefined;
}
private generateId(): string {
return Math.random().toString(36).substr(2, 9);
}
getIcon(fileType: string): string {
if (fileType.startsWith('image/')) return 'image';
if (fileType === 'application/pdf') return 'picture_as_pdf';
if (fileType.startsWith('text/')) return 'description';
return 'insert_drive_file';
}
cancelUpload(id: string) {
const file = this.files.find((f) => f.id === id);
if (file) {
this.files = this.files.filter((f) => f.id !== id);
this.emitFilesChange();
this.showError('Upload cancelled');
}
}
removeFile(id: string) {
this.files = this.files.filter((f) => f.id !== id);
this.emitFilesChange();
}
downloadFile(id: string) {
const file = this.files.find((f) => f.id === id);
if (file) {
const url = URL.createObjectURL(file.file);
const a = document.createElement('a');
a.href = url;
a.download = file.file.name;
a.click();
URL.revokeObjectURL(url);
}
}
private emitFilesChange() {
this.filesChange.emit(this.files);
}
private reset() {
this.uploadSub.unsubscribe();
this.uploadSub = new Subscription();
}
private showError(message: string) {
this.snackBar.open(message, 'OK', { duration: 3000 });
}
}