From 82d2c508b80babaa13f06960c9322859979221b8 Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Thu, 23 Jul 2026 22:59:06 +0200 Subject: [PATCH] feat(jobs): add per-job dockerfiles and requirements and unify logging format --- background-jobs/README.md | 2 +- background-jobs/app/elastic/client.py | 14 + background-jobs/app/sync.py | 59 ++-- service/scripts/demo/demo.py | 10 +- service/scripts/jobs-image/README.md | 65 +++++ .../scripts/jobs-image/bund-crawl/Dockerfile | 28 ++ .../jobs-image/bund-crawl/requirements.txt | 3 + service/scripts/jobs-image/demo-a/Dockerfile | 10 + service/scripts/jobs-image/demo-b/Dockerfile | 10 + service/scripts/jobs-image/demo-c/Dockerfile | 10 + .../scripts/jobs-image/news-crawl/Dockerfile | 21 ++ .../jobs-image/news-crawl/requirements.txt | 3 + .../jobs-image/news-keywords/Dockerfile | 21 ++ .../jobs-image/news-keywords/requirements.txt | 3 + .../scripts/jobs-image/news-topics/Dockerfile | 24 ++ .../jobs-image/news-topics/requirements.txt | 2 + .../jobs-image/project-topics/Dockerfile | 25 ++ .../project-topics/requirements.txt | 2 + service/scripts/news/ude/run_pipeline.py | 23 +- service/scripts/news/ude/upload_aktuell.py | 254 +++--------------- service/scripts/projects/bund/gpc.data.py | 196 ++++++-------- .../preprocessing.component.html | 204 ++++++++++++++ 22 files changed, 613 insertions(+), 376 deletions(-) create mode 100644 service/scripts/jobs-image/README.md create mode 100644 service/scripts/jobs-image/bund-crawl/Dockerfile create mode 100644 service/scripts/jobs-image/bund-crawl/requirements.txt create mode 100644 service/scripts/jobs-image/demo-a/Dockerfile create mode 100644 service/scripts/jobs-image/demo-b/Dockerfile create mode 100644 service/scripts/jobs-image/demo-c/Dockerfile create mode 100644 service/scripts/jobs-image/news-crawl/Dockerfile create mode 100644 service/scripts/jobs-image/news-crawl/requirements.txt create mode 100644 service/scripts/jobs-image/news-keywords/Dockerfile create mode 100644 service/scripts/jobs-image/news-keywords/requirements.txt create mode 100644 service/scripts/jobs-image/news-topics/Dockerfile create mode 100644 service/scripts/jobs-image/news-topics/requirements.txt create mode 100644 service/scripts/jobs-image/project-topics/Dockerfile create mode 100644 service/scripts/jobs-image/project-topics/requirements.txt create mode 100644 webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html diff --git a/background-jobs/README.md b/background-jobs/README.md index e1bb7396..000e414c 100644 --- a/background-jobs/README.md +++ b/background-jobs/README.md @@ -49,7 +49,7 @@ docker push docker.nes.uni-due.de/inse/background-jobs:latest Lokal testen ohne Pull: ```bash -export INSE_BACKGROUND_JOBS_PULL_BEFORE_RUN=false +export BACKGROUND_JOBS_PULL_BEFORE_RUN=false ``` ## Scheduling diff --git a/background-jobs/app/elastic/client.py b/background-jobs/app/elastic/client.py index a3c06382..1ef0c6dc 100644 --- a/background-jobs/app/elastic/client.py +++ b/background-jobs/app/elastic/client.py @@ -57,6 +57,20 @@ def add_entry(index: str, entry: dict): return created_id +def index_entry(index: str, document_id: str, entry: dict): + + encoded_document_id = quote(document_id, safe="") + endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}" + + document_body = { + "news_id": entry["news_id"], + "relevant": int(entry["relevant"]), + "authors": entry["authors"], + "keywords": entry.get("keywords", []), + } + + return _send_es_request("PUT", endpoint, payload=document_body) + def update_entry(index: str, document_id: str, partial_doc: dict): encoded_document_id = quote(document_id, safe="") diff --git a/background-jobs/app/sync.py b/background-jobs/app/sync.py index c0cf185e..7c1fed29 100644 --- a/background-jobs/app/sync.py +++ b/background-jobs/app/sync.py @@ -3,13 +3,17 @@ import llm.client as llm_client import json import argparse import time +import logging import threading from concurrent.futures import ThreadPoolExecutor, as_completed +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) + POSTPROC_INDEX = "aktuell_postproc" def print_pretty_json(data): - print(json.dumps(data, indent=2)) + logger.info(json.dumps(data, indent=2)) def sync_single_news(news_id, max_retries=3): attempt = 0 @@ -29,11 +33,11 @@ def sync_single_news(news_id, max_retries=3): return True except Exception as error: attempt += 1 - print(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})") + logger.warning(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})") if attempt < max_retries: time.sleep(1) else: - print(f"Error: {news_id} - {error}") + logger.error(f"Error: {news_id} - {error}") return False def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retries=3): @@ -48,13 +52,16 @@ def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retr if not keywords: # Empty article or unparseable LLM answer: writing an empty list # would look like a success and block a later retry. - print(f"Skipped {news_id}: no keywords extracted.") + logger.info(f"Skipped {news_id}: no keywords extracted.") return False if target_index == POSTPROC_INDEX: es_client.update_entry(POSTPROC_INDEX, doc_id, {"keywords": keywords}) else: - es_client.add_entry( + # Key the target doc on news_id so re-runs update it in place + # instead of piling up a new document each time. + es_client.index_entry( target_index, + news_id, { "news_id": news_id, "relevant": source.get("relevant", 0), @@ -65,11 +72,11 @@ def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retr return True except Exception as error: attempt += 1 - print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})") + logger.warning(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})") if attempt < max_retries: time.sleep(1) else: - print(f"Error: {news_id} - {error}") + logger.error(f"Error: {news_id} - {error}") return False def main(): @@ -136,7 +143,7 @@ def main(): if args.reset_keywords: result = es_client.remove_field_all("aktuell_postproc", "keywords") - print(f"Removed 'keywords' from {result.get('updated', 0)} entries.") + logger.info(f"Removed 'keywords' from {result.get('updated', 0)} entries.") if args.sync_delta: start_time = time.time() @@ -147,7 +154,7 @@ def main(): target_ids = set(entry["_source"]["news_id"] for entry in postproc_ids_raw) missing_ids = source_ids - target_ids - print(f"Number of missing IDs: {len(missing_ids)}") + logger.info(f"Number of missing IDs: {len(missing_ids)}") missing_ids = list(missing_ids) total = len(missing_ids) @@ -164,11 +171,11 @@ def main(): processed += 1 if was_successful: succeeded += 1 - print(f"Sync: {processed} / {total}") + logger.info(f"Sync: {processed} / {total}") end_time = time.time() - print(f"Sync DONE: {succeeded} entries synced.") - print(f"Time taken: {end_time - start_time} seconds.") + logger.info(f"Sync DONE: {succeeded} entries synced.") + logger.info(f"Time taken: {end_time - start_time} seconds.") if args.update_keywords: start_time = time.time() @@ -178,20 +185,20 @@ def main(): if args.target_index == POSTPROC_INDEX: pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")] - print(f"Number of entries without keywords: {len(pending)}") + logger.info(f"Number of entries without keywords: {len(pending)}") else: # Writing elsewhere never marks the postproc entries, so the "missing # keywords" filter would select the same entries on every run. Pick # entries that already have keywords instead: those are known to come # from articles with actual content, unlike the empty archive stubs. pending = [entry for entry in postproc_entries if entry["_source"].get("keywords")] - print(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.") + logger.info(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.") if args.limit is not None: pending = pending[:args.limit] total = len(pending) - print(f"Processing {total} entries.") + logger.info(f"Processing {total} entries.") processed = 0 succeeded = 0 @@ -208,15 +215,15 @@ def main(): processed += 1 if was_successful: succeeded += 1 - print(f"Update keywords: {processed} / {total}") + logger.info(f"Update keywords: {processed} / {total}") end_time = time.time() - print(f"Update keywords DONE: {succeeded} entries updated.") - print(f"Time taken: {end_time - start_time} seconds.") + logger.info(f"Update keywords DONE: {succeeded} entries updated.") + logger.info(f"Time taken: {end_time - start_time} seconds.") if args.stats: aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"]) - print(f"Total entries in 'aktuell': {len(aktuell_entries)}") + logger.info(f"Total entries in 'aktuell': {len(aktuell_entries)}") postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"]) total_entries = len(postproc_entries) @@ -227,13 +234,13 @@ def main(): news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords")) news_without_keywords = total_entries - news_with_keywords - print(f"Total entries in 'aktuell_postproc': {total_entries}") - print(f"Relevant entries: {relevant_count}") - print(f"Irrelevant entries: {irrelevant_count}") - print(f"Entries with extracted names: {news_with_extracted_names}") - print(f"Entries without extracted names: {news_without_extracted_names}") - print(f"Entries with keywords: {news_with_keywords}") - print(f"Entries without keywords: {news_without_keywords}") + logger.info(f"Total entries in 'aktuell_postproc': {total_entries}") + logger.info(f"Relevant entries: {relevant_count}") + logger.info(f"Irrelevant entries: {irrelevant_count}") + logger.info(f"Entries with extracted names: {news_with_extracted_names}") + logger.info(f"Entries without extracted names: {news_without_extracted_names}") + logger.info(f"Entries with keywords: {news_with_keywords}") + logger.info(f"Entries without keywords: {news_without_keywords}") if __name__ == "__main__": main() diff --git a/service/scripts/demo/demo.py b/service/scripts/demo/demo.py index a89e6dd0..5e505495 100644 --- a/service/scripts/demo/demo.py +++ b/service/scripts/demo/demo.py @@ -1,15 +1,19 @@ import sys import time +import logging + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) def main() -> None: seconds = int(sys.argv[1]) if len(sys.argv) > 1 else 20 - print(f"Demo job started, running for {seconds} seconds.", flush=True) + logger.info(f"Demo job started, running for {seconds} seconds.") for elapsed in range(1, seconds + 1): time.sleep(1) if elapsed % 5 == 0: - print(f"Progress: {elapsed}/{seconds} seconds.", flush=True) - print("Demo job finished successfully.", flush=True) + logger.info(f"Progress: {elapsed}/{seconds} seconds.") + logger.info("Demo job finished successfully.") if __name__ == "__main__": diff --git a/service/scripts/jobs-image/README.md b/service/scripts/jobs-image/README.md new file mode 100644 index 00000000..9135c57c --- /dev/null +++ b/service/scripts/jobs-image/README.md @@ -0,0 +1,65 @@ +# Per-Job Images + +One distinct Docker image per background job. Each image installs only its own +dependencies and bakes the job's command as its `ENTRYPOINT`, so a job runs with +no `command` override in the database — the job definition just points `image` at +the matching tag. + +This is deliberately different from the single shared-image model described in +[background-jobs/README.md](../../../background-jobs/README.md): here every job is +self-contained, at the cost of maintaining one Dockerfile per job. + +## Images + +| Job (DB name) | Image | Entrypoint | Notes | +| -------------------------- | --------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| News-Crawler | `jobs/news-crawl` | `run_pipeline.py` | scrapy<2.13, Twisted<24.7; uploads to `NEWS_UPLOAD_INDEX` | +| Bund-Crawler | `jobs/bund-crawl` | `gpc.data.py --max-rows 200` | headless Chrome; uploads to `BUND_UPLOAD_INDEX`; capped, full export is ~300k rows | +| Projekt-Themen-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend | +| News-Themen-Mapping | `jobs/news-topics` | `map_news_topics --output-index docker-job_test` | bundles both topic_mapper pkgs; needs host backend | +| News-Schlagwort-Extraktion | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | +| Demo-Job A / B / C | `jobs/demo-a/b/c` | `demo.py 20 / 25 / 30` | no dependencies | + +Each job is its own repository under the `jobs/` path namespace, prefixed +`docker.nes.uni-due.de/inse/` (e.g. `docker.nes.uni-due.de/inse/jobs/news-crawl:latest`). + +The entrypoints carry no run limits: anything set in the job's `command` field is +appended to the entrypoint, so limits (`--max-items`, `--max-docs`, `--limit`) are +passed per run from the UI. The one exception is the Bund-Crawler, which keeps a +`--max-rows` cap in the image because its full export is ~300k rows. + +## Build + +From the repo root (the build context must be the repo root so the Dockerfiles +can copy `service/scripts/…` and `background-jobs/app/`): + +```bash +docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \ + -t docker.nes.uni-due.de/inse/jobs/news-crawl:latest . +docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest +``` + +Each job's Dockerfile header lists its own build command. + +## Running locally without pushing + +The backend tries to pull each image before a run. If the image isn't in the +registry, the pull fails softly and the local copy is used — so building locally +is enough for local runs. To skip the pull attempt entirely: + +```bash +export BACKGROUND_JOBS_PULL_BEFORE_RUN=false +``` + +## Env vars + +Because every tag lives under the `docker.nes.uni-due.de` registry host, the +backend treats these as registry images and injects the INSE Elasticsearch / LLM +credentials automatically (plus any per-job `env`). + +No image writes to a production index by default: the crawlers upload into the +index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to +`docker-job_test` in their Dockerfile), and the mappers and the keyword +extraction write to `docker-job_test` via `--output-index` / `--target-index`. +To not contact Elasticsearch at all, pass `--skip-upload` (crawlers) or +`--dry-run` (mappers) through the job's command field. diff --git a/service/scripts/jobs-image/bund-crawl/Dockerfile b/service/scripts/jobs-image/bund-crawl/Dockerfile new file mode 100644 index 00000000..dcbebcbb --- /dev/null +++ b/service/scripts/jobs-image/bund-crawl/Dockerfile @@ -0,0 +1,28 @@ +# Bund-Crawler (foerderportal export via headless Chrome). Build from the repo root: +# docker build -f service/scripts/jobs-image/bund-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/bund-crawl:latest . +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 +# Upload the crawled projects into the shared test index (gpc.data.py reads +# ELASTICSEARCH_INSE_* creds + BUND_UPLOAD_INDEX from the env). +ENV BUND_UPLOAD_INDEX=docker-job_test + +# Headless Chrome for the Selenium crawler. +RUN apt-get update \ + && apt-get install -y --no-install-recommends chromium chromium-driver \ + && rm -rf /var/lib/apt/lists/* +ENV CHROME_BIN=/usr/bin/chromium \ + CHROMEDRIVER_PATH=/usr/bin/chromedriver + +COPY service/scripts/jobs-image/bund-crawl/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/scripts/projects/bund/ ./service/scripts/projects/bund/ + +WORKDIR /app/service/scripts/projects/bund + +# Capped on purpose: the full export is ~300k rows, so an uncapped run would +# write that entire volume into BUND_UPLOAD_INDEX. Raise or drop the cap by +# passing --max-rows N through the job's command field. +ENTRYPOINT ["python", "gpc.data.py", "--max-rows", "200"] diff --git a/service/scripts/jobs-image/bund-crawl/requirements.txt b/service/scripts/jobs-image/bund-crawl/requirements.txt new file mode 100644 index 00000000..f660d056 --- /dev/null +++ b/service/scripts/jobs-image/bund-crawl/requirements.txt @@ -0,0 +1,3 @@ +selenium~=4.20 +pandas~=2.2 +requests~=2.32 diff --git a/service/scripts/jobs-image/demo-a/Dockerfile b/service/scripts/jobs-image/demo-a/Dockerfile new file mode 100644 index 00000000..34fa453b --- /dev/null +++ b/service/scripts/jobs-image/demo-a/Dockerfile @@ -0,0 +1,10 @@ +# Demo-Job A. Build from the repo root: +# docker build -f service/scripts/jobs-image/demo-a/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-a:latest . +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/demo/demo.py ./demo.py + +ENTRYPOINT ["python", "demo.py", "20"] diff --git a/service/scripts/jobs-image/demo-b/Dockerfile b/service/scripts/jobs-image/demo-b/Dockerfile new file mode 100644 index 00000000..7533c877 --- /dev/null +++ b/service/scripts/jobs-image/demo-b/Dockerfile @@ -0,0 +1,10 @@ +# Demo-Job B. Build from the repo root: +# docker build -f service/scripts/jobs-image/demo-b/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-b:latest . +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/demo/demo.py ./demo.py + +ENTRYPOINT ["python", "demo.py", "25"] diff --git a/service/scripts/jobs-image/demo-c/Dockerfile b/service/scripts/jobs-image/demo-c/Dockerfile new file mode 100644 index 00000000..60896d34 --- /dev/null +++ b/service/scripts/jobs-image/demo-c/Dockerfile @@ -0,0 +1,10 @@ +# Demo-Job C. Build from the repo root: +# docker build -f service/scripts/jobs-image/demo-c/Dockerfile -t docker.nes.uni-due.de/inse/jobs/demo-c:latest . +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/demo/demo.py ./demo.py + +ENTRYPOINT ["python", "demo.py", "30"] diff --git a/service/scripts/jobs-image/news-crawl/Dockerfile b/service/scripts/jobs-image/news-crawl/Dockerfile new file mode 100644 index 00000000..86101794 --- /dev/null +++ b/service/scripts/jobs-image/news-crawl/Dockerfile @@ -0,0 +1,21 @@ +# News-Crawler (UDE 'aktuell'). Build from the repo root: +# docker build -f service/scripts/jobs-image/news-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-crawl:latest . +# +# scrapy<2.13 + Twisted<24.7 are load-bearing: the spiders use the removed +# start_requests() hook, and newer versions silently crawl 0 items. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 +# Upload the crawled articles into the shared test index (see upload_aktuell.py, +# which reads ELASTICSEARCH_INSE_* creds + NEWS_UPLOAD_INDEX from the env). +ENV NEWS_UPLOAD_INDEX=docker-job_test + +COPY service/scripts/jobs-image/news-crawl/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/scripts/news/ude/ ./service/scripts/news/ude/ + +# Uncapped: crawls every article and uploads to NEWS_UPLOAD_INDEX. Limit a run by +# passing --max-items N through the job's command field. +ENTRYPOINT ["python", "service/scripts/news/ude/run_pipeline.py"] diff --git a/service/scripts/jobs-image/news-crawl/requirements.txt b/service/scripts/jobs-image/news-crawl/requirements.txt new file mode 100644 index 00000000..394c2a2d --- /dev/null +++ b/service/scripts/jobs-image/news-crawl/requirements.txt @@ -0,0 +1,3 @@ +scrapy>=2.11,<2.13 +Twisted>=22.10,<24.7 +requests~=2.32 diff --git a/service/scripts/jobs-image/news-keywords/Dockerfile b/service/scripts/jobs-image/news-keywords/Dockerfile new file mode 100644 index 00000000..e8059947 --- /dev/null +++ b/service/scripts/jobs-image/news-keywords/Dockerfile @@ -0,0 +1,21 @@ +# News keyword extraction (LLM keyword extraction into docker-job_test). +# Build from the repo root: +# docker build -f service/scripts/jobs-image/news-keywords/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-keywords:latest . +# +# Needs Elasticsearch + LLM creds (injected as env vars by the backend for +# registry images). Calls the LLM once per entry. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/jobs-image/news-keywords/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY background-jobs/app/ ./ + +# Writes into docker-job_test, leaving production aktuell_postproc untouched. +# A non-postproc target re-extracts entries that already have keywords (real +# content) and updates them in place, keyed on news_id (re-runs overwrite, no +# duplicates). Cap a run by appending --limit N via the job's command field. +ENTRYPOINT ["python", "sync.py", "--update-keywords", "--target-index", "docker-job_test"] diff --git a/service/scripts/jobs-image/news-keywords/requirements.txt b/service/scripts/jobs-image/news-keywords/requirements.txt new file mode 100644 index 00000000..d5f8a74c --- /dev/null +++ b/service/scripts/jobs-image/news-keywords/requirements.txt @@ -0,0 +1,3 @@ +requests~=2.32 +openai~=2.41 +python-dotenv~=1.0 diff --git a/service/scripts/jobs-image/news-topics/Dockerfile b/service/scripts/jobs-image/news-topics/Dockerfile new file mode 100644 index 00000000..0c14852e --- /dev/null +++ b/service/scripts/jobs-image/news-topics/Dockerfile @@ -0,0 +1,24 @@ +# News-Topic-Mapping (news keywords -> OpenAlex topics). Build from the repo root: +# docker build -f service/scripts/jobs-image/news-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-topics:latest . +# +# map_news_topics imports map_project_topics as its "base", so both topic_mapper +# packages must be present. Needs a reachable backend and Elasticsearch creds +# (injected as env vars by the backend for registry images). +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/jobs-image/news-topics/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/ +COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ + +# Writes topic mappings into docker-job_test. Only maps (article, keyword) pairs +# not already present in the output index; pass --overwrite to re-map all. +# Uncapped: limit a run by passing --max-docs N through the job's command field. +# host.docker.internal reaches the host backend for vector search. +ENTRYPOINT ["python", "-m", "service.scripts.news.topic_mapper.map_news_topics", \ + "--output-index", "docker-job_test", \ + "--api-base-url", "http://host.docker.internal:8000"] diff --git a/service/scripts/jobs-image/news-topics/requirements.txt b/service/scripts/jobs-image/news-topics/requirements.txt new file mode 100644 index 00000000..7507eb03 --- /dev/null +++ b/service/scripts/jobs-image/news-topics/requirements.txt @@ -0,0 +1,2 @@ +httpx>=0.27 +python-dotenv>=1.0 diff --git a/service/scripts/jobs-image/project-topics/Dockerfile b/service/scripts/jobs-image/project-topics/Dockerfile new file mode 100644 index 00000000..f8a46a05 --- /dev/null +++ b/service/scripts/jobs-image/project-topics/Dockerfile @@ -0,0 +1,25 @@ +# Projekt-Topic-Mapping (bund keywords -> OpenAlex topics). Build from the repo root: +# docker build -f service/scripts/jobs-image/project-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/project-topics:latest . +# +# Needs a reachable backend (vector search) and Elasticsearch creds. The creds +# arrive as env vars injected by the backend for registry images. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/jobs-image/project-topics/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ + +# Writes topic mappings into docker-job_test. Only maps (project, keyword) pairs +# not already present in the output index, so an interrupted run can be resumed. +# There is no overwrite flag: to re-map all, point --output-index at a fresh index. +# Uncapped: limit a run by passing --max-docs N through the job's command field. +# host.docker.internal reaches the host backend for vector search. +ENTRYPOINT ["python", "-m", "service.scripts.projects.topic_mapper.map_project_topics", \ + "--source-index", "projects_bund_v1", \ + "--text-field", "Leistungsplansystematik_fullname", \ + "--output-index", "docker-job_test", \ + "--api-base-url", "http://host.docker.internal:8000"] diff --git a/service/scripts/jobs-image/project-topics/requirements.txt b/service/scripts/jobs-image/project-topics/requirements.txt new file mode 100644 index 00000000..7507eb03 --- /dev/null +++ b/service/scripts/jobs-image/project-topics/requirements.txt @@ -0,0 +1,2 @@ +httpx>=0.27 +python-dotenv>=1.0 diff --git a/service/scripts/news/ude/run_pipeline.py b/service/scripts/news/ude/run_pipeline.py index 75f9e4b6..5f54229c 100644 --- a/service/scripts/news/ude/run_pipeline.py +++ b/service/scripts/news/ude/run_pipeline.py @@ -4,6 +4,11 @@ import os import shutil import time import argparse +import logging + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) + def run_command(command, cwd=None): """Run a shell command and exit if it fails.""" @@ -13,8 +18,8 @@ def run_command(command, cwd=None): #capture_output=True, #supresses output from subprocess text=True) if result.returncode != 0: - print(f"Command failed: {command}") - print("Error output:\n", result.stderr) + logger.error(f"Command failed: {command}") + logger.error(f"Error output:\n{result.stderr}") sys.exit(result.returncode) if __name__ == "__main__": @@ -50,25 +55,25 @@ if __name__ == "__main__": limit = f" -s CLOSESPIDER_ITEMCOUNT={args.max_items}" if args.max_items else "" - print("Running Scrapy link crawler...") + logger.info("Running Scrapy link crawler...") run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"{limit}", cwd=crawler_dir) - print("Running Scrapy meta crawler...") + logger.info("Running Scrapy meta crawler...") run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"{limit}", cwd=crawler_dir) if args.skip_upload: - print("Skipping upload (--skip-upload): Elasticsearch was not contacted.") + logger.info("Skipping upload (--skip-upload): Elasticsearch was not contacted.") else: - print("Running upload script") + logger.info("Running upload script") run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir) end_time = time.time() runtime_seconds = end_time - start_time runtime_hours = runtime_seconds / 3600 - print(f"Runtime: {runtime_hours:.2f} hours") + logger.info(f"Runtime: {runtime_hours:.2f} hours") if args.skip_upload: - print("Finished crawling UDE news articles (no upload).") + logger.info("Finished crawling UDE news articles (no upload).") else: - print("Finished crawling and uploading UDE news articles.") + logger.info("Finished crawling and uploading UDE news articles.") diff --git a/service/scripts/news/ude/upload_aktuell.py b/service/scripts/news/ude/upload_aktuell.py index 72a9654e..c97bcb3e 100644 --- a/service/scripts/news/ude/upload_aktuell.py +++ b/service/scripts/news/ude/upload_aktuell.py @@ -1,231 +1,39 @@ -from elasticsearch import Elasticsearch import sys import os import json -from datetime import datetime import time +import logging +from urllib.parse import quote -# elasticsearch-connection should be adjusted -# uni-server -es = Elasticsearch() +import requests -index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) +# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so +# the elasticsearch client's ping/product-check would 403. We talk to the index +# endpoint directly over HTTP with the ApiKey header, like the other jobs do. +ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/") +ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY") +# Default is a test index — you lack rights to push to the production index; +# contact the ES admin for that. Override via NEWS_UPLOAD_INDEX. +# The target index is never created here: an index that doesn't exist yet gets +# ES dynamic mapping, without the searchabilityAnalyzer the search relies on. +# Create it with the proper mapping before pointing a run at a new index. +INDEX_NAME = os.getenv("NEWS_UPLOAD_INDEX", "aktuell-test") -# checks if elastic is up and creates the index if not already done -def check_elastic(): - if not es.ping(): - sys.exit("No connection to Elasticsearch") +_session = requests.Session() +_session.headers.update({"Content-Type": "application/json"}) +if ES_API_KEY: + _session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"}) - if not es.indices.exists(index=index_name): - settings = { - "analysis": { - "analyzer": { - "searchabilityAnalyzer": { - "type": "custom", - "tokenizer": "standard", - "filter": [ - "lowercase", - "asciifolding" - ] - } - } - } - } - mappings = { - "properties": { - "subtitle": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "maintitle": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "author": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "date": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "date_year": { - "type": "long", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "date_full": { - "type": "long", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "intro_content": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "main_content": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "further_content": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "redaktion": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "full_content": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "tags": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - }, - "tags_nested": { - "type": "nested", - "properties": { - "tag": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 250 - } - } - } - } - }, - #"links": { - # "type": "text", - # "analyzer": "searchabilityAnalyzer", - # "search_analyzer": "searchabilityAnalyzer", - # "fields": { - # "keyword": { - # "type": "keyword", - # "ignore_above": 256 - # } - # } - #}, - "links_nested": { - "type": "nested", - "properties": { - "url": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 250 - } - } - }, - "text": { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 250 - } - } - } - } - }, - } - } - es.indices.create(index=index_name, mappings=mappings, settings=settings) def upload(path): - with open(path, "r", encoding='utf-8') as json_file: - + with open(path, "r", encoding="utf-8") as json_file: try: json_loaded = json.load(json_file) + uploaded = 0 for news in json_loaded: time.sleep(10 / 1000) id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "") @@ -241,7 +49,7 @@ def upload(path): for p in range(len(tags)): tags_nested.append({"tag": tags[p]}) - dict = { + document = { "subtitle": news["subtitle"], "maintitle": news["maintitle"], "tags": news["tags"], @@ -255,21 +63,25 @@ def upload(path): "tags_nested": tags_nested, "date_year": news["date_year"], "date_full": news["date_full"], - #"links": news["links"], "links_nested": links_nested, "url": news["url"] } - es.index(index=index_name, id=id, document=dict) + response = _session.put( + f"{ES_URL}/{INDEX_NAME}/_doc/{quote(id, safe='')}", + json=document, + ) + response.raise_for_status() + uploaded += 1 + + logger.info(f"Uploaded {uploaded} news articles to '{INDEX_NAME}'.") except Exception as e: - print("--- Failed to upload news.") - print(e) + logger.error(f"Failed to upload news: {e}") + # main - entry point if __name__ == '__main__': - check_elastic() - if len(sys.argv) != 2: sys.exit("No path given.") upload(sys.argv[1]) diff --git a/service/scripts/projects/bund/gpc.data.py b/service/scripts/projects/bund/gpc.data.py index 4cba5952..2d538982 100644 --- a/service/scripts/projects/bund/gpc.data.py +++ b/service/scripts/projects/bund/gpc.data.py @@ -12,15 +12,34 @@ import pandas as pd import json from datetime import datetime import sys -from elasticsearch import Elasticsearch, helpers -from elasticsearch.helpers import bulk,BulkIndexError import os +import math +import requests import hashlib import argparse +import logging + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) download_path=os.path.abspath(os.getcwd()) -es = Elasticsearch() + +# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so +# the elasticsearch client's ping/product-check would 403. We POST to _bulk +# directly over HTTP with the ApiKey header, like the other jobs do. +ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/") +ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY") +# Default is a test index — you lack rights to push to the production index; +# contact the ES admin for that. Override via BUND_UPLOAD_INDEX. +# The target index is never created here: an index that doesn't exist yet gets +# ES dynamic mapping, without the searchabilityAnalyzer the search relies on. +# Create it with the proper mapping before pointing a run at a new index. +INDEX_NAME = os.getenv("BUND_UPLOAD_INDEX", "projects_bund_test") + +_session = requests.Session() +if ES_API_KEY: + _session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"}) def crawl_data(link,driver): driver.get(link) @@ -42,123 +61,61 @@ def crawl_data(link,driver): time.sleep(2) # Switch to the alert and Clicks the "OK" button Alert(driver).accept() - print("downloading data") + logger.info("downloading data") else: # The element is likely a honeypot, do not interact - print("Honeypot detected, skipping interaction") + logger.info("Honeypot detected, skipping interaction") -def check_elastic_online(): - if not es.ping(): - sys.exit("No connection to Elasticsearch") - else : - print("Elasticsearch connection established") -def check_elastic_index(df, index_name): - - if not es.indices.exists(index=index_name): - print(index_name + " index wasn't found. Creating a new one..") - settings = { - "analysis": { - "analyzer": { - "searchabilityAnalyzer": { - "type": "custom", - "tokenizer": "standard", - "filter": [ - "lowercase", - "asciifolding" - ] - } - } - } - } - mappings = {} - properties = {} +def _clean(value): + # pandas/numpy scalars -> native python; NaN -> None (ES rejects NaN in JSON). + if hasattr(value, "item"): + value = value.item() + if isinstance(value, float) and math.isnan(value): + return None + return value - for key in list(df.columns): - if key in ("funding_start", "funding_end", "datum"): - properties[key] = { - "type": "date", - "format": "dd.MM.yyyy" - } - elif key == "Publikationsdatum": - properties[key] = { - "type": "date", - "format": "yyyy" - } - elif key == "unix_timestamp": - properties[key] = { - "type": "long" - } - elif key == "Fördersumme": - properties[key] = { - "type": "float" - } - elif key == "new": - properties[key] = { - "type": "boolean" - } - else: - properties[key] = { - "type": "text", - "analyzer": "searchabilityAnalyzer", - "search_analyzer": "searchabilityAnalyzer", - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 - } - } - } - - mappings["properties"] = properties - es.indices.create(index=index_name, mappings=mappings, settings=settings) - es.indices.refresh(index=index_name) - print("The new index '"+index_name+"' has been created") - else: - print(index_name + " already exists. Uploading data...") +def upload_data(df, index_name): + logger.info("Uploading data...") -def upload_data(df,index_name): - def fill_docs_to_upload(row): + docs = [] + for _, row in df.iterrows(): doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest() - doc = { - "_op_type": "update", # Update existing documents - "_index": index_name, - "_id": doc_id, - "doc": { - "new":False - }, - "upsert":{ - **row.to_dict(), - "new":True - } - } + source = {key: _clean(val) for key, val in row.to_dict().items()} + source["new"] = True + docs.append((doc_id, source)) - docs_to_upload.append(doc) - print("Uploading data...") - - try: - check_elastic_index(df, index_name) - except Exception as e: - print("Error while creating index") - print(e) - - docs_to_upload = [] - df.apply(fill_docs_to_upload,axis=1) - def bulk_docs(docs,data_rate): - response_sum = 0 - for i in range(0, len(docs), data_rate): - try: - response = helpers.bulk(es,docs[i:i + data_rate]) - response_sum = response_sum + response[0] - except BulkIndexError as e: - print(f"{len(e.errors)} document(s) failed to index.") - for error in e.errors: - print("Error details:", error) - print ("Upload is completed. "+ str(response_sum) +" documents have been uploaded." ) data_rate = 200 - bulk_docs(docs_to_upload,data_rate) + uploaded = 0 + for i in range(0, len(docs), data_rate): + batch = docs[i:i + data_rate] + lines = [] + for doc_id, source in batch: + # update + upsert: flag an existing project as not-new, or create an + # unseen one from the row (with new=True). + lines.append(json.dumps({"update": {"_index": index_name, "_id": doc_id}})) + lines.append(json.dumps({"doc": {"new": False}, "upsert": source}, default=str)) + payload = ("\n".join(lines) + "\n").encode("utf-8") + response = _session.post( + f"{ES_URL}/_bulk", + data=payload, + headers={"Content-Type": "application/x-ndjson"}, + ) + response.raise_for_status() + result = response.json() + if result.get("errors"): + failed = [item for item in result["items"] + if next(iter(item.values())).get("status", 200) >= 300] + logger.error(f"{len(failed)} document(s) failed to index.") + for item in failed[:5]: + logger.error(f"Error details: {item}") + uploaded += len(batch) - len(failed) + else: + uploaded += len(batch) + + logger.info(f"Upload is completed. {uploaded} documents have been uploaded to '{index_name}'.") @@ -171,7 +128,7 @@ def wait_for_file_complete(download_path,file_name): fname.endswith(".part") or fname.endswith(".crdownload") for fname in os.listdir(download_path) ): - print(f"Download complete: {file_name}") + logger.info(f"Download complete: {file_name}") return True if any(fname.endswith((".part", ".crdownload")) for fname in os.listdir(download_path)): time.sleep(1) @@ -181,7 +138,7 @@ def wait_for_file_complete(download_path,file_name): def format_data(df): - print("Formattind data...") + logger.info("Formatting data...") df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True) def clean_format(text): if isinstance(text, str): @@ -253,9 +210,15 @@ if __name__ == '__main__': action="store_true", help="Only crawl and format the export; never connect to Elasticsearch", ) + parser.add_argument( + "--max-rows", + type=int, + default=None, + help="Keep at most this many rows of the formatted export (e.g. for a smoke test).", + ) args = parser.parse_args() - print("Starting") + logger.info("Starting") file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv') if not os.path.exists(file_path): driver = setup_chrome_driver(download_path) @@ -269,12 +232,13 @@ if __name__ == '__main__': df = pd.DataFrame(file) df_formatted = format_data(df) - index_name = "projects_bund_test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index + if args.max_rows: + df_formatted = df_formatted.head(args.max_rows) + if args.skip_upload: - print(f"Skipping upload (--skip-upload): Elasticsearch was not contacted. " + logger.info(f"Skipping upload (--skip-upload): Elasticsearch was not contacted. " f"Formatted {len(df_formatted)} rows.") else: - check_elastic_online() - upload_data(df_formatted,index_name) + upload_data(df_formatted, INDEX_NAME) os.remove(file_path) \ No newline at end of file diff --git a/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html b/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html new file mode 100644 index 00000000..b13eb6f3 --- /dev/null +++ b/webapp/src/app/modules/preprocessing-mock-backup/preprocessing.component.html @@ -0,0 +1,204 @@ +
+ + + + +
+ + +
+ {{ containerStatus().name }} +
+ {{ containerStatus().image }} + {{ + containerStatus().imageDigest + }} + @switch (containerStatus().state) { + @case ('running') { + Läuft{{ + containerStatus().uptime + ? ' · seit ' + containerStatus().uptime + : '' + }} + } + @case ('stopped') { + Gestoppt + } + @case ('restarting') { + Wird neu gestartet … + } + } + @if (containerStatus().updateAvailable) { + + upgrade + Neue Version verfügbar + + } +
+
+
+ +
+ @if (containerStatus().updateAvailable) { + + } + @if (containerStatus().state === 'running') { + + + } @else { + + } +
+
+
+ + + + + + +
+ + +
+ {{ row.name }} + {{ row.description }} + {{ row.targetIndex }} +
+
+ + +
+ {{ formatSchedule(row.schedule) }} + +
+
+ + + @switch (row.status) { + @case ('running') { + + + Läuft + + } + @case ('success') { + + check_circle + Erfolgreich + + } + @case ('failed') { + + error + Fehlgeschlagen + + } + @default { + + schedule + Bereit + + } + } + + + + @if (row.lastRun) { +
+ {{ row.lastRun.startedAt | date: 'dd.MM.yyyy HH:mm' }} + {{ row.lastRun.message }} +
+ } @else { + Noch nicht ausgeführt + } +
+ + +
+ + +
+