diff --git a/service/scripts/eu-project-calls/README.md b/service/scripts/eu-project-calls/README.md new file mode 100644 index 00000000..1569ed4b --- /dev/null +++ b/service/scripts/eu-project-calls/README.md @@ -0,0 +1,132 @@ +# EU Project Calls Fetcher + +Fetches Horizon Europe funding opportunities from the European Commission Funding & Tenders API and uploads them into Elasticsearch. + +## Install + +```bash +pip install requests elasticsearch +``` + +## Step 1: Fetch Calls + +Execute: + +```bash +python fetch_calls.py +``` + +Output: + +```text +eu_tenders_raw.json +``` + +### Query Filters + +Only calls matching the following criteria are fetched: + +* Status: + + * Forthcoming + * Open for Submission +* Type of Grant Call: + + * Direct calls for proposals (issued by the EU) +* Programme: + + * Horizon Europe (2021–2027) +* Programme Part: + + * Global Challenges and European Industrial Competitiveness + +The filter corresponds to the url: https://ec.europa.eu/info/funding-tenders/opportunities/portal/screen/opportunities/calls-for-proposals?order=DESC&pageNumber=1&pageSize=50&sortBy=startDate&isExactMatch=true&type=1&status=31094502,31094501&programmePart=43108557,43118846,43118971,43120193,43120821,43121563,43108541&frameworkProgramme=43108390 + +## Step 2: Upload to Elasticsearch + +The uploader reads the connection from the environment (the background job +runner injects `ELASTICSEARCH_INSE_URL` and `ELASTICSEARCH_INSE_API_KEY`). +Override the target index with `EU_PROJECT_CALLS_INDEX`. + +Execute: + +```bash +python upload_calls.py +``` + +Use `--fresh` to delete all existing documents in the target index, then refill +it from the fetched calls. The index and its mapping must already exist: + +```bash +python upload_calls.py --fresh +``` + +Input: + +```text +eu_tenders_raw.json +``` + +Output: + +```text +Elasticsearch index +``` + +Default index: + +```text +eu_project_calls +``` + +Documents are keyed by the call identifier, so re-runs overwrite instead of +duplicating. + +Upload log: + +```text +eu_upload_log.json +``` + +## Indexed Fields + +```text +id +title +link +state +programm +call +work_programm_part +description +type_of_action +type_of_mga +open_date +deadline_date +deadline_model +full_title +agr_number +acronym +keywords +``` + +## Run as a Background Job + +The image at `service/scripts/jobs-image/eu-project-calls` fetches and uploads in +one run: + +```bash +docker build -f service/scripts/jobs-image/eu-project-calls/Dockerfile \ + -t docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest . +docker push docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest +``` + +Then create a job in the Jobs UI with that image. The runner injects the +Elasticsearch credentials for registry images. Set the job's **Command** to +`--fresh` to clear and refill the existing index on every run; leave it empty to +upsert into the existing index. The index and its mapping must already exist. + +## Data Source + +European Commission Funding & Tenders Portal Search API +https://api.tech.ec.europa.eu/search-api/ diff --git a/service/scripts/eu-project-calls/fetch_calls.py b/service/scripts/eu-project-calls/fetch_calls.py new file mode 100644 index 00000000..19b23d66 --- /dev/null +++ b/service/scripts/eu-project-calls/fetch_calls.py @@ -0,0 +1,83 @@ +import json +import os +import requests +import time + +# === CONFIG === +PAGE_SIZE = 50 +OUTPUT_FILE = os.getenv("EU_PROJECT_CALLS_INPUT_FILE", "eu_tenders_raw.json") + +url = "https://api.tech.ec.europa.eu/search-api/prod/rest/search" + +sort_data = {"order": "DESC", "field": "startDate"} +query_data = { + "bool": { + "must": [ + {"terms": {"type": ["1"]}}, + {"terms": {"status": ["31094502", "31094501"]}}, + {"terms": {"DATASOURCE": ["SEDIA"]}}, + {"terms": {"frameworkProgramme": ["43108390"]}}, + {"terms": {"programmeDivision": ["43108557", "43118846", "43118971", "43120193", "43120821", "43121563", "43108541"]}}, + {"terms": {"language": ["en"]}}, + ] + } +} +headers = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36", + "Accept": "application/json, text/plain, */*", + "Cache-Control": "No-Cache", + "X-Requested-With": "XMLHttpRequest", + "Origin": "https://ec.europa.eu", + "Referer": "https://ec.europa.eu/", +} + +# === FETCH === +all_results = [] +page = 1 +fetch_failed = False + +while True: + params = { + "apiKey": "SEDIA", + "text": "***", + "pageSize": PAGE_SIZE, + "pageNumber": page + } + files = { + "sort": ("blob", json.dumps(sort_data), "application/json"), + "query": ("blob", json.dumps(query_data), "application/json"), + "languages": ("blob", json.dumps(["en"]), "application/json"), + } + + try: + response = requests.post(url, params=params, files=files, headers=headers, timeout=30) + response.raise_for_status() + data = response.json() + except Exception as e: + print(f"Error on page {page}: {e}") + fetch_failed = True + break + + results = data.get("results", []) + total = data.get("totalResults", 0) + + all_results.extend(results) + print(f"Page {page}: got {len(results)} results — total so far: {len(all_results)}/{total}") + + if len(all_results) >= total or len(results) < PAGE_SIZE: + break + + page += 1 + time.sleep(0.5) + +print(f"\nDone. Total fetched: {len(all_results)}") + +# === SAVE === +with open(OUTPUT_FILE, "w", encoding="utf-8") as f: + json.dump(all_results, f, ensure_ascii=False, indent=2) + +print(f"Saved to {OUTPUT_FILE}") + +# Fail the job (and skip the upload) instead of reporting a partial fetch as success. +if fetch_failed: + raise SystemExit(1) \ No newline at end of file diff --git a/service/scripts/eu-project-calls/upload_calls.py b/service/scripts/eu-project-calls/upload_calls.py new file mode 100644 index 00000000..9dc8d6ae --- /dev/null +++ b/service/scripts/eu-project-calls/upload_calls.py @@ -0,0 +1,155 @@ +import argparse +import json +import os +import traceback +from datetime import datetime + +from elasticsearch import Elasticsearch + +# config — the background job runner injects ELASTICSEARCH_INSE_* for registry images. +ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200") +ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY") + +es = Elasticsearch( + ES_URL, + api_key=ES_API_KEY or None, + request_timeout=60, + max_retries=5, + retry_on_timeout=True, +) + +index_name = os.getenv("EU_PROJECT_CALLS_INDEX", "eu_project_calls") +INPUT_FILE = os.getenv("EU_PROJECT_CALLS_INPUT_FILE", "eu_tenders_raw.json") +LOG_FILE = os.getenv("EU_PROJECT_CALLS_LOG_FILE", "eu_upload_log.json") + +# helpers +def get(metadata, field): + val = metadata.get(field) + if isinstance(val, list): + return val[0] if val else "" + return val or "" + +def get_state(metadata): + val = metadata.get("status") + if isinstance(val, list): + if val[0]== "31094502": + return "open for submission" + if val[0] == "31094501": + return "forthcoming" + if val[0] == "31094503": + return "closed" + return val or "" +def parse_date(date_str): + if not date_str: + return None + try: + return datetime.strptime(date_str[:10], "%Y-%m-%d").strftime("%d.%m.%Y") + except Exception: + return None + +def map_result(result): + m = result.get("metadata", {}) + return { + "id": get(m, "identifier"), + "title": get(m, "title"), + "link": result.get("url") or get(m, "url"), + "state": get_state(m), + "programm": get(m, "frameworkProgramme"), + "call": get(m, "callIdentifier"), + "work_programm_part": get(m, "programmeDivision"), + "description": get(m, "descriptionByte"), + "type_of_action": get(m, "typesOfAction"), + "type_of_mga": get(m, "typeOfMGAs"), + "open_date": parse_date(get(m, "startDate")), + "deadline_date": parse_date(get(m, "deadlineDate")), + "deadline_model": get(m, "deadlineModel"), + "full_title": get(m, "callTitle"), + "agr_number": get(m, "callccm2Id"), + "acronym": get(m, "projectAcronym"), + "funding": "", + "participation_time": "", + "topic": "", + "agr_number": get(m, "ccm2Id"), + "keywords": m.get("keywords",[]) + } + +# elastic setup +def clear_index(): + # The index and its mapping are managed outside this script; --fresh only + # removes the documents so the index can be refilled. + es.delete_by_query( + index=index_name, + body={"query": {"match_all": {}}}, + conflicts="proceed", + refresh=True, + ) + print(f"Cleared all documents from INDEX {index_name} (--fresh)...") + +# logs +def load_log(): + if os.path.exists(LOG_FILE): + with open(LOG_FILE, 'r', encoding='utf-8') as f: + return json.load(f) + log = {"done": [], "failed": []} + with open(LOG_FILE, 'w', encoding='utf-8') as f: + json.dump(log, f) + return log + +def save_log(log): + with open(LOG_FILE, 'w', encoding='utf-8') as f: + json.dump(log, f, indent=2) + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Upload EU project calls to Elasticsearch.") + parser.add_argument( + "--fresh", + action="store_true", + help="Delete the target index first, then recreate and refill it.", + ) + args = parser.parse_args() + + print("Starting upload...") + + if args.fresh: + clear_index() + + with open(INPUT_FILE, 'r', encoding='utf-8') as f: + raw_results = json.load(f) + + log = load_log() + if args.fresh: + log = {"done": [], "failed": []} + done_set = set(log["done"]) + + total = len(raw_results) + uploaded = 0 + failed = 0 + + for i, result in enumerate(raw_results): + try: + doc = map_result(result) + identifier = doc["id"] + if not identifier: + raise ValueError("missing call identifier") + + # Keyed on the call identifier so scheduled re-runs overwrite + # instead of duplicating every document. + es.index(index=index_name, id=identifier, body=doc) + log["done"].append(identifier) + done_set.add(identifier) + uploaded += 1 + print(f" [{i+1}/{total}] ✓ {identifier}") + + except Exception as e: + identifier = result.get("metadata", {}).get("identifier", ["unknown"])[0] + print(f" [{i+1}/{total}] ✗ Failed {identifier}: {e}") + traceback.print_exc() + log["failed"].append(identifier) + failed += 1 + + # save log every 10 items + if i % 10 == 0: + save_log(log) + + save_log(log) + print(f"\nDone. Uploaded: {uploaded} | Failed: {failed}") \ No newline at end of file diff --git a/service/scripts/jobs-image/README.md b/service/scripts/jobs-image/README.md index d0c7a4e0..c3a130f6 100644 --- a/service/scripts/jobs-image/README.md +++ b/service/scripts/jobs-image/README.md @@ -83,6 +83,7 @@ differ only by their `command`. | News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend | | News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | | UDE OrgMiner Verified Persons | `jobs/orgminer-verified-persons-ude` | `upload_orgminer_verified_persons_ude.py --progress-file /state/orgminer_verified_persons_ude_progress.json` | Writes `orgminer_verified_persons_ude`; image-scoped NES creds; persistent checkpoint | +| EU Project Calls | `jobs/eu-project-calls` | `fetch_calls.py && upload_calls.py` | Horizon Europe calls; writes `eu_project_calls`; `--fresh` clears+refills index | | Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows | Each image is its own repository under the `jobs/` path namespace, prefixed diff --git a/service/scripts/jobs-image/eu-project-calls/Dockerfile b/service/scripts/jobs-image/eu-project-calls/Dockerfile new file mode 100644 index 00000000..cfa32abc --- /dev/null +++ b/service/scripts/jobs-image/eu-project-calls/Dockerfile @@ -0,0 +1,25 @@ +# EU project calls fetcher + uploader (Horizon Europe -> eu_project_calls). +# Build from the repo root: +# docker build -f service/scripts/jobs-image/eu-project-calls/Dockerfile \ +# -t docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest . +# +# Fetches the EC Funding & Tenders API, then uploads to Elasticsearch. The +# runner injects ELASTICSEARCH_INSE_URL/API_KEY for registry images. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 + +COPY service/scripts/jobs-image/eu-project-calls/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Only the scripts: the local raw JSON (15 MB) and upload log stay out of the image. +COPY service/scripts/eu-project-calls/fetch_calls.py \ + service/scripts/eu-project-calls/upload_calls.py \ + ./service/scripts/eu-project-calls/ +WORKDIR /app/service/scripts/eu-project-calls + +# One run fetches all calls, then uploads them (keyed by call id, so re-runs +# overwrite instead of duplicating). The job's command field is appended here +# and forwarded to the uploader, e.g. --fresh to rebuild the index from scratch. +ENTRYPOINT ["sh", "-c", "python fetch_calls.py && exec python upload_calls.py \"$@\"", "--"] diff --git a/service/scripts/jobs-image/eu-project-calls/requirements.txt b/service/scripts/jobs-image/eu-project-calls/requirements.txt new file mode 100644 index 00000000..7e2d2957 --- /dev/null +++ b/service/scripts/jobs-image/eu-project-calls/requirements.txt @@ -0,0 +1,2 @@ +requests~=2.32 +elasticsearch>=7.17,<8