Files
smartguide/service/scripts/projects/bund/gpc.data.py
T
kallweit 82d2c508b8
LocationBasedServices/smartguide/pipeline/head This commit looks good
feat(jobs): add per-job dockerfiles and requirements and unify logging format
2026-07-23 22:59:06 +02:00

244 lines
9.0 KiB
Python

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.alert import Alert
from random import randint
import time
import pandas as pd
import json
from datetime import datetime
import sys
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())
# 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)
search_field = driver.find_element(By.ID,"suche_schnellSuche")
if search_field.is_displayed():
# The element is visible, safe to interact
search_field.send_keys("*")
start_search_btn = driver.find_element(By.XPATH,'/html/body/div[1]/div/div/form[1]/div/fieldset/table/tbody/tr[1]/td[2]/input')
start_search_btn.click()
WebDriverWait(driver, 30).until(
EC.element_to_be_clickable((By.XPATH,'//*[@id="unterNavigation"]/ul/li[4]/div/a'))
)
#Click the Export button to trigger data export
export_button = driver.find_element(By.XPATH,'//*[@id="unterNavigation"]/ul/li[4]/div/a')
export_button.click()
# Wait for the prompt to appear
time.sleep(2)
# Switch to the alert and Clicks the "OK" button
Alert(driver).accept()
logger.info("downloading data")
else:
# The element is likely a honeypot, do not interact
logger.info("Honeypot detected, skipping interaction")
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
def upload_data(df, index_name):
logger.info("Uploading data...")
docs = []
for _, row in df.iterrows():
doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest()
source = {key: _clean(val) for key, val in row.to_dict().items()}
source["new"] = True
docs.append((doc_id, source))
data_rate = 200
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}'.")
def wait_for_file_complete(download_path,file_name):
while True:
file_path = os.path.join(download_path, file_name)
if os.path.exists(file_path) and not any(
fname.endswith(".part") or fname.endswith(".crdownload")
for fname in os.listdir(download_path)
):
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)
else:
time.sleep(1)
def format_data(df):
logger.info("Formatting data...")
df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True)
def clean_format(text):
if isinstance(text, str):
if text.startswith('="') and text.endswith('"'):
return text[2:-1]
return text
df.columns = [clean_format(col) for col in df.columns]
df = df.applymap(clean_format)
df["FKZ"] = df["FKZ"].str.replace(' /','/')
json_path = os.path.join(os.path.abspath(os.getcwd()), 'extendingColumns.json')
with open(json_path, 'r', encoding='utf-8') as f:
columnsObj = json.load(f)
for column_name, content in columnsObj.items():
alias_map = content['aliases']
df[content['column_alias']] = df[column_name].map(alias_map)
df['Publikationsdatum'] = df['Laufzeit von'].str.split('.').str[2]
df['unix_timestamp'] = int(time.time())
df['datum'] = datetime.now().strftime("%d.%m.%Y")
df['new'] = True
if len(df['Laufzeit von']) and len(df['Laufzeit bis']):
df['Laufzeit'] = "von " + df['Laufzeit von'] + " bis " + df['Laufzeit bis']
config_path = os.path.join(os.path.abspath(os.getcwd()), 'data_config.json')
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
df.rename(columns=config,inplace=True)
df = df.where(pd.notnull(df), "")
df['Fördersumme'] = pd.to_numeric(
df['Fördersumme'].astype(str)
.str.replace('.', '', regex=False)
.str.replace(',', '.', regex=False),
errors='coerce'
)
return df
def setup_chrome_driver(download_path):
options = Options()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_experimental_option("prefs", {
"download.default_directory": download_path,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True,
})
chrome_bin = os.getenv("CHROME_BIN")
if chrome_bin:
options.binary_location = chrome_bin
chromedriver_path = os.getenv("CHROMEDRIVER_PATH", "/usr/bin/chromedriver")
service = Service(executable_path=chromedriver_path)
driver = webdriver.Chrome(service=service, options=options)
return driver
# main - entry point
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Crawl the bund foerderportal project export and upload it to Elasticsearch."
)
parser.add_argument(
"--skip-upload",
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()
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)
link_to_crawl= "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=searchreset"
crawl_data(link_to_crawl,driver)
wait_for_file_complete(download_path, "Suchliste.csv")
driver.close()
file = pd.read_csv(file_path,encoding = "latin1",sep=";")
df = pd.DataFrame(file)
df_formatted = format_data(df)
if args.max_rows:
df_formatted = df_formatted.head(args.max_rows)
if args.skip_upload:
logger.info(f"Skipping upload (--skip-upload): Elasticsearch was not contacted. "
f"Formatted {len(df_formatted)} rows.")
else:
upload_data(df_formatted, INDEX_NAME)
os.remove(file_path)