feature/keywords-analysis #214

Merged
genja merged 7 commits from feature/keywords-analysis into dev 2026-07-13 15:43:39 +02:00
13 changed files with 225 additions and 149 deletions
-18
View File
@@ -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)
+1 -1
View File
@@ -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,
+161 -79
View File
@@ -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,
)
@@ -150,29 +150,16 @@
<mat-icon>text_fields</mat-icon>
<span>Extrahierte Keywords</span>
</mat-button-toggle>
@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
[disabled]="isExtracting()"
value="topic"
matTooltip="Die Abbildung der extrahierten Keywords auf die bekannten Themenbereiche">
<mat-icon>account_tree</mat-icon>
<span>Ähnliche Themen</span>
</mat-button-toggle>
</mat-button-toggle-group>
</div>
<div class="toolbar-divider"></div>
<div class="toolbar-group toolbar-group--view">
<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>
<div class="spacer toolbar-controls manual-input-controls">
@@ -147,7 +147,6 @@ export class KeywordsSearchComponent {
readonly loadingPatents = signal(false);
readonly patentsError = signal(false);
readonly patentsLoaded = signal(false);
readonly topicMappingSearch = signal<boolean>(false);
readonly uploadedFiles = signal<FileUploadItem[]>([]);
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()),
),
@@ -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,
@@ -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,
@@ -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,
@@ -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,
@@ -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 ?? [],
@@ -10,14 +10,23 @@
<mat-card-content>
<div class="summary-header">
<div>
<span class="summary-label">Suchprofil</span>
<span class="summary-label">
{{
state.fuzzySearch() ? 'Topic Mapping' : 'Keyword Matching'
}}</span
>
<span class="summary-count"
>{{ selectedKeywordCount() }} Keywords</span
>
</div>
<span class="mode-badge">
<mat-icon>account_tree</mat-icon>
{{ state.softSearch() ? 'Topic Mapping' : 'Keyword Matching' }}
<mat-slide-toggle
labelPosition="before"
(change)="onToggleFuzzySearch($event)"
[checked]="fuzzySearch()"
matTooltip="Wenn aktiviert, werden die extrahierten Keywords auf bekannte Themenbereiche abgebildet, was die Suchergebnisse vermehrt">
Fuzzy Search
</mat-slide-toggle>
</span>
</div>
@@ -55,7 +64,7 @@
[active]="rla.isActive"
[queryParams]="{
keywords: state.payload()?.keywords?.join(','),
softSearch: state.payload()?.options?.softSearch,
fuzzy: state.payload()?.options?.fuzzy,
}">
<mat-icon>{{ route.icon }}</mat-icon>
{{ route.label }}
@@ -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<boolean>(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,
});
}
}
@@ -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,