diff --git a/service/src/main/inse/keywords/logic.py b/service/src/main/inse/keywords/logic.py index a24c2a46..964c5364 100644 --- a/service/src/main/inse/keywords/logic.py +++ b/service/src/main/inse/keywords/logic.py @@ -414,21 +414,3 @@ async def get_text_from_url(url: str) -> str: 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) \ No newline at end of file diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index b0d9629c..b8fa3d17 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -111,7 +111,7 @@ app.include_router(bookmarks_router) app.add_middleware( ETagCacheMiddleware, - ttl=300, # 5 minutes expiration time + ttl=120, # 2 minutes expiration time ) app.add_middleware( CORSMiddleware, diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py index e9d605c0..3f36e483 100644 --- a/service/src/main/inse/middleware/etag_cache.py +++ b/service/src/main/inse/middleware/etag_cache.py @@ -1,79 +1,161 @@ -# middleware/etag_cache.py -import hashlib -import json -import time - -from starlette.middleware.base import BaseHTTPMiddleware -from starlette.requests import Request -from starlette.responses import Response - - -class ETagCacheMiddleware(BaseHTTPMiddleware): - def __init__(self, app, ttl: int = 60): - super().__init__(app) - self.ttl = ttl # timeout in seconds - self.cache: dict[str, dict] = {} # key → {body, etag, expires} - - def _cache_key(self, request: Request) -> str: - # Include query params and relevant headers in the key - return f"{request.url.path}?{request.url.query}" - - def _content_type(self, response: Response) -> str | None: - return response.headers.get("content-type") - - async def dispatch(self, request: Request, call_next): - if request.method != "GET": - return await call_next(request) - - if request.url.path.startswith( - ("/api/auth", "/api/accounts", "/api/bookmarks") - ): - return await call_next(request) - - if request.headers.get("authorization"): - return await call_next(request) - - key = self._cache_key(request) - entry = self.cache.get(key) - client_etag = request.headers.get("if-none-match") - - # Cache hit + not expired - if entry and time.time() < entry["expires"]: - if client_etag == entry["etag"]: - headers = {"ETag": entry["etag"]} - if entry.get("content_type"): - headers["Content-Type"] = entry["content_type"] - return Response(status_code=304, headers=headers) - - # Client has stale ETag - return fresh cached body - headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} - if entry.get("content_type"): - headers["Content-Type"] = entry["content_type"] - return Response( - content=entry["body"], - status_code=entry.get("status_code", 200), - headers=headers, - ) - - # Cache miss or expired → hit the actual route - response = await call_next(request) - body = b"".join([chunk async for chunk in response.body_iterator]) - etag = f'"{hashlib.md5(body).hexdigest()}"' - content_type = self._content_type(response) - - if response.status_code < 400: - self.cache[key] = { - "body": body, - "etag": etag, - "expires": time.time() + self.ttl, - "status_code": response.status_code, - "content_type": content_type, - } - headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"} - if content_type: - headers["Content-Type"] = content_type - return Response( - content=body, - status_code=response.status_code, - headers=headers, - ) +# middleware/etag_cache.py + +import hashlib +import time +from collections import OrderedDict + +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import Response + +# Paths excluded from caching entirely (everything concerning auth/identity/mutations) +EXCLUDED_PATHS = ( + "/api/auth/v2", + "/api/accounts", + "/api/bookmarks", + "/api/organizations", +) + +# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/ +# trigger side effects), even if it "usually" returns 200. +EXCLUDED_POST_PATHS = ( + # "/api/notes/mark-read", +) + +# Don't buffer/hash large POST bodies (e.g. uploads) just to compute a cache key. +MAX_CACHEABLE_BODY_SIZE = 64 * 1024 # 64 KB + + +class ETagCacheMiddleware(BaseHTTPMiddleware): + def __init__(self, app, ttl: int = 60, maxsize: int = 5000): + super().__init__(app) + self.ttl = ttl + self.maxsize = maxsize + # Insertion-ordered so we can evict the oldest entry in O(1) when over capacity. + self.cache: "OrderedDict[str, dict]" = OrderedDict() + + def _get(self, key: str) -> dict | None: + entry = self.cache.get(key) + if entry is None: + return None + if time.time() >= entry["expires"]: + del self.cache[key] + return None + return entry + + def _set(self, key: str, value: dict) -> None: + # Refreshing an existing key should count as "newest" for + # eviction purposes, so drop it first if present. + if key in self.cache: + del self.cache[key] + + # Clear a few expired entries so the cache + # doesn't fill up with dead weight between accesses. + now = time.time() + expired_keys = [] + for k, v in self.cache.items(): + if len(expired_keys) >= 50: + break + if v["expires"] <= now: + expired_keys.append(k) + for k in expired_keys: + del self.cache[k] + + # Hard cap: evict oldest-inserted entries until there's room. + while len(self.cache) >= self.maxsize: + self.cache.popitem(last=False) + + self.cache[key] = value + + def _user_id(self, request: Request) -> str | None: + auth_header = request.headers.get("authorization") + if not auth_header: + return None + return hashlib.sha256(auth_header.encode()).hexdigest()[:16] + + def _cache_key(self, request: Request, body: bytes = b"") -> str: + user_id = self._user_id(request) + base = f"{request.method}:{request.url.path}?{request.url.query}" + if body: + base += f":{hashlib.sha256(body).hexdigest()[:16]}" + if user_id: + return f"{user_id}:{base}" + return base + + def _content_type(self, response: Response) -> str | None: + return response.headers.get("content-type") + + def _is_cacheable_request(self, request: Request) -> bool: + if request.url.path.startswith(EXCLUDED_PATHS): + return False + if request.method == "GET": + return True + if request.method == "POST": + return not request.url.path.startswith(EXCLUDED_POST_PATHS) + return False + + async def dispatch(self, request: Request, call_next): + if not self._is_cacheable_request(request): + return await call_next(request) + + body_bytes = b"" + if request.method == "POST": + content_length = request.headers.get("content-length") + if content_length and int(content_length) > MAX_CACHEABLE_BODY_SIZE: + # Too large to safely cache/key on — bypass entirely. + return await call_next(request) + + # Starlette caches the body internally after this read, so + # downstream handlers (call_next) can still read it normally. + body_bytes = await request.body() + if len(body_bytes) > MAX_CACHEABLE_BODY_SIZE: + return await call_next(request) + + key = self._cache_key(request, body_bytes) + entry = self._get(key) + client_etag = request.headers.get("if-none-match") + + # Cache hit + not expired + if entry: + if client_etag == entry["etag"]: + headers = {"ETag": entry["etag"]} + if entry.get("content_type"): + headers["Content-Type"] = entry["content_type"] + return Response(status_code=304, headers=headers) + + headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"} + if entry.get("content_type"): + headers["Content-Type"] = entry["content_type"] + return Response( + content=entry["body"], + status_code=entry["status_code"], + headers=headers, + ) + + # Cache miss or expired → hit the actual route + response = await call_next(request) + body = b"".join([chunk async for chunk in response.body_iterator]) + etag = f'"{hashlib.md5(body).hexdigest()}"' + content_type = self._content_type(response) + + # Only cache clean, non-mutating-looking successes. 201/202/204 etc. + if response.status_code == 200: + self._set( + key, + { + "body": body, + "etag": etag, + "status_code": response.status_code, + "content_type": content_type, + "expires": time.time() + self.ttl, + }, + ) + + headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"} + if content_type: + headers["Content-Type"] = content_type + return Response( + content=body, + status_code=response.status_code, + headers=headers, + ) \ No newline at end of file diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index ac68827c..3de176be 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -150,29 +150,16 @@ text_fields Extrahierte Keywords - @if (topicMappingSearch()) { - - account_tree - Topic Mapping - - } + + account_tree + Ähnliche Themen +
- -
-
- - Topic Mapping - -
-
diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index b67b9017..c20ecd09 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -147,7 +147,6 @@ export class KeywordsSearchComponent { readonly loadingPatents = signal(false); readonly patentsError = signal(false); readonly patentsLoaded = signal(false); - readonly topicMappingSearch = signal(false); readonly uploadedFiles = signal([]); readonly keywordsExist = computed( @@ -765,13 +764,14 @@ export class KeywordsSearchComponent { search(): void { this.showVisualization.set(false); this.showPatents.set(false); - + const fuzzySearch = + this.route.snapshot.queryParamMap.get('fuzzy') === 'true'; const payload: SearchResultsPayload = { extractedKeywords: this.getSelectedExtractedKeywordEntries(), manualKeywords: this.getSelectedManualKeywordEntries(), keywords: this.selectedKeywords(), options: { - softSearch: this.topicMappingSearch(), + fuzzy: fuzzySearch, }, }; @@ -790,7 +790,7 @@ export class KeywordsSearchComponent { this.router.navigate(['keywords/search-results'], { queryParams: { keywords: this.serializeKeywords(payload.keywords), - softSearch: payload.options.softSearch ? true : false, + fuzzy: fuzzySearch, }, }); } @@ -864,10 +864,6 @@ export class KeywordsSearchComponent { } this.updateQueryParams(); } - onToggleTopicMappingSearch(event: any): void { - this.topicMappingSearch.set(event.checked); - this.updateQueryParams(); - } onSubfieldLegendVisibleChange(visible: boolean): void { this.subfieldLegendVisible.set(visible); this.updateQueryParams(); @@ -998,7 +994,6 @@ export class KeywordsSearchComponent { const view = queryParams.get('view') ?? 'llm'; const legend = queryParams.get('legend') ?? 'on'; const legendExpanded = queryParams.get('legendExpanded') ?? 'off'; - const softSearch = queryParams.get('softSearch') === 'true'; this.isRestoringState = true; this.form.patchValue( { @@ -1012,7 +1007,6 @@ export class KeywordsSearchComponent { this.subfieldLegendVisible.set(legend === 'on'); this.subfieldLegendExpanded.set(legendExpanded === 'on'); this.extractionSource.set(source as InputMode); - this.topicMappingSearch.set(softSearch); this.restoreStateFromSession(); const merged = this.uniqueKeywordEntries([ @@ -1074,7 +1068,6 @@ export class KeywordsSearchComponent { view: this.keywordView(), legend: this.subfieldLegendVisible() ? 'on' : 'off', legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off', - softSearch: this.topicMappingSearch() ? true : false, broad: this.serializeKeywords( this.getKeywordLabels(this.broadKeywords()), ), diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts index e7096249..6c904810 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts @@ -95,7 +95,7 @@ export class KeywordsToNewsResultsComponent { manualKeywords: this.state.manualKeywords(), extractedKeywords: this.state.extractedKeywords(), keywords: this.state.keywords(), - softSearch: this.state.softSearch(), + fuzzy: this.state.fuzzySearch(), weights: { raw: weights.raw, normalized: weights.normalized, diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts index 659c9064..5a26983b 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.ts @@ -92,7 +92,7 @@ export class KeywordsToPatentsResultsComponent { manualKeywords: this.state.manualKeywords(), extractedKeywords: this.state.extractedKeywords(), keywords: this.state.keywords(), - softSearch: this.state.softSearch(), + fuzzy: this.state.fuzzySearch(), weights: { raw: weights.raw, normalized: weights.normalized, diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts index 533c28e7..3f4e2b98 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts @@ -115,7 +115,7 @@ export class KeywordsToPersonsResultsComponent { manualKeywords: this.state.manualKeywords(), extractedKeywords: this.state.extractedKeywords(), keywords: this.state.keywords(), - softSearch: this.state.softSearch(), + fuzzy: this.state.fuzzySearch(), weights: { raw: weights.raw, normalized: weights.normalized, diff --git a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts index d09d09db..61c4e797 100644 --- a/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/projects-results/projects-results.component.ts @@ -91,7 +91,7 @@ export class KeywordsToProjectsResultsComponent { manualKeywords: this.state.manualKeywords(), extractedKeywords: this.state.extractedKeywords(), keywords: this.state.keywords(), - softSearch: this.state.softSearch(), + fuzzy: this.state.fuzzySearch(), weights: { raw: weights.raw, normalized: weights.normalized, diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index b5b91234..b1ba2a44 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -6,7 +6,7 @@ export interface SearchResultsPayload { manualKeywords: KeywordEntryWithTopic[]; keywords: string[]; options: { - softSearch: boolean; + fuzzy: boolean; }; } @@ -28,8 +28,8 @@ export class SearchResultsStateService { }); readonly keywords = computed(() => this._payload()?.keywords ?? []); - readonly softSearch = computed( - () => this._payload()?.options.softSearch ?? false, + readonly fuzzySearch = computed( + () => this._payload()?.options.fuzzy ?? false, ); readonly extractedKeywords = computed( () => this._payload()?.extractedKeywords ?? [], diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html index d1ce9543..8a06a069 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.html @@ -10,14 +10,23 @@
- Suchprofil + + {{ + state.fuzzySearch() ? 'Topic Mapping' : 'Keyword Matching' + }} {{ selectedKeywordCount() }} Keywords
- account_tree - {{ state.softSearch() ? 'Topic Mapping' : 'Keyword Matching' }} + + Fuzzy Search +
@@ -55,7 +64,7 @@ [active]="rla.isActive" [queryParams]="{ keywords: state.payload()?.keywords?.join(','), - softSearch: state.payload()?.options?.softSearch, + fuzzy: state.payload()?.options?.fuzzy, }"> {{ route.icon }} {{ route.label }} diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts index e425de4c..e04fef8d 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results.component.ts @@ -1,4 +1,4 @@ -import { Component, computed, inject } from '@angular/core'; +import { Component, computed, inject, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, @@ -11,7 +11,7 @@ import { import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; - +import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic'; import { Topic } from '../../../api/model/topic'; import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; @@ -37,6 +37,7 @@ import { MatIconModule, TopicChipComponent, MatTabsModule, + MatSlideToggleModule, ], providers: [SearchResultsStateService], templateUrl: './search-results.component.html', @@ -61,7 +62,7 @@ export class KeywordsSearchResultsComponent { ]; readonly selectedKeywordCount = computed(() => this.state.keywords().length); - + readonly fuzzySearch = signal(false); readonly selectedKeywordEntries = computed(() => { const payload = this.state.payload(); if (!payload) return []; @@ -119,7 +120,7 @@ export class KeywordsSearchResultsComponent { // previous search never gets silently applied to a new one. this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe((params) => { const keywords = this.parseKeywordList(params.get('keywords')); - const softSearch = params.get('softSearch') === 'on'; + const fuzzySearch = params.get('fuzzy') === 'true'; const cached = this.readHandoffCache(); const cacheMatches = @@ -127,19 +128,30 @@ export class KeywordsSearchResultsComponent { this.state.setPayload({ keywords, - options: { softSearch }, + options: { fuzzy: fuzzySearch }, extractedKeywords: cacheMatches ? cached!.extractedKeywords : [], manualKeywords: cacheMatches ? cached!.manualKeywords : [], }); + + this.fuzzySearch.set(fuzzySearch); }); } goBackToSearch(): void { - void this.router.navigate(['/keywords']); + void this.router.navigate(['/keywords'], { + queryParamsHandling: 'merge', + }); } getChipLabel(keyword: KeywordEntryWithTopic): string { - return keyword.llm_keyword?.keyword ?? ''; + if (!this.fuzzySearch()) { + return keyword.llm_keyword?.keyword ?? ''; + } + return ( + keyword.topic_mapping?.topic?.display_name ?? + keyword.llm_keyword?.keyword ?? + '' + ); } getChipDescription(item: KeywordEntryWithTopic): string | null { @@ -203,7 +215,7 @@ export class KeywordsSearchResultsComponent { manualKeywords: maybePayload.manualKeywords ?? [], keywords: maybePayload.keywords ?? [], options: { - softSearch: maybePayload.options?.softSearch ?? false, + fuzzy: maybePayload.options?.fuzzy ?? false, }, }; } @@ -233,4 +245,15 @@ export class KeywordsSearchResultsComponent { private normalizeKeyword(value: string): string { return value.trim().toLowerCase(); } + onToggleFuzzySearch(event: any): void { + this.fuzzySearch.set(event.checked); + this.router.navigate([], { + relativeTo: this.route, + queryParams: { + fuzzy: this.fuzzySearch(), + }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } } diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts index be981674..44a918fb 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.ts @@ -91,7 +91,7 @@ export class KeywordsToWorksResultsComponent { manualKeywords: this.state.manualKeywords(), extractedKeywords: this.state.extractedKeywords(), keywords: this.state.keywords(), - softSearch: this.state.softSearch(), + fuzzy: this.state.fuzzySearch(), weights: { raw: weights.raw, normalized: weights.normalized,