Metadata-Version: 2.4
Name: das-setup-helper
Version: 1.0.0
Summary: Public helper to setup crawlers and manage acquisitions in WIHP (EUROSTAT)
Author: estat-wihp
License-Expression: EUPL-1.2
Keywords: eurostat,wihp,web-intelligence-hub,wikipedia,crawler
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: boto3<2,>=1.42
Requires-Dist: requests<3,>=2.33
Requires-Dist: pyjwt<3,>=2.11
Requires-Dist: pyyaml<7,>=6.0
Requires-Dist: python-dotenv<2,>=1.1
Requires-Dist: pandas<4,>=3.0
Requires-Dist: aws-secretsmanager-caching<2,>=1.1
Provides-Extra: dev
Requires-Dist: isort<7,>=6.0; extra == "dev"
Requires-Dist: black<27,>=26.1; extra == "dev"
Requires-Dist: pytest<10,>=9.0; extra == "dev"
Requires-Dist: pytest-cov<8,>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio<2,>=1.2; extra == "dev"
Requires-Dist: pre-commit<5,>=4.5; extra == "dev"
Dynamic: license-file

# DAS Setup Helper

A Python command-line tool to set up crawlers, manage acquisitions and extract
structured data in the **Web Intelligence Hub Platform (WIHP)** operated for
Eurostat.

It chains four pipelines that turn a list of Wikipedia pages of multinational
enterprises (MNEs) into a semicolon-separated CSV file of company attributes:

| Command | What it does |
|---|---|
| `das-setup-crawler` | Validates the input CSV, creates or updates the WIHP sources and creates a crawler. |
| `das-create-acq` | Starts the WIHP acquisitions of the crawlers that were set up. |
| `das-stop-acq` | Stops running acquisitions that have no URL left to discover. |
| `das-extract-data` | Converts the crawled Wikipedia content into CSV files. |

```text
 input CSV            WIHP                         storage (local or S3)
 (mne_name;url)
     |
     v
 das-setup-crawler -> sources + crawler created -> ready_for_crawling/<crawler>/ (audit files)
     |
     v
 das-create-acq    -> acquisitions started      -> ready_to_export/<crawler>/
     |
     v   (WIHP crawls and writes the pages under staging/)
 das-stop-acq      -> finished acquisitions stopped
     |
     v
 das-extract-data  -> staging/**/content/*.json -> processed/**/*.csv
                                                -> done/<crawler>/
```

Run the commands in this order: **setup-crawler, create-acq, stop-acq, extract-data**.

---

## Requirements

- Python >= 3.12
- Access to a WIHP environment (API URL, token endpoint, API key and group).
- A storage location: a local folder, or an AWS S3 bucket.

## Installation

```bash
pip install das-setup-helper
```

or, with [uv](https://docs.astral.sh/uv/):

```bash
uv add das-setup-helper
```

The four commands listed above are then available in your environment
(`uv run das-setup-crawler`, ...).

---

## Configuration

All settings are read from environment variables. Export them in your shell
(recommended), for example from a file you load with `set -a; source env.sh; set +a`.
A `.env` file is also read, but it is looked up by `python-dotenv` starting from
the folder where the package is installed and walking up the parent folders (not
from the current working directory). It is found, for example, when it sits next
to the `.venv` folder of a `uv` project.

Variables already present in the environment are never overwritten by `.env`.
Never commit these files: they contain credentials.

### Variables

| Variable | Required | Description |
|---|---|---|
| `STORAGE_BACKEND` | no | `local` (default) or `s3`. |
| `WIHP_API_URL` | yes | WIHP API base URL. |
| `WIHP_TOKEN_URL` | yes | WIHP OAuth token endpoint. |
| `WIHP_API_KEY` | yes | WIHP API key. |
| `WIHP_GROUP` | yes | WIHP group the sources belong to (for example `/MNE`). |
| `CRAWLER_BASE_NAME` | yes | Prefix of the crawler name; the timestamp is appended (`<base>__YYYY_MM_DD__HH_MM_SS`). |
| `SOURCE_NAME` | yes | Label used in the WIHP source names (for example `WIKIPEDIA`). |
| `S3_AWS_WIHP_CONFIG_DIRECTORY` | yes | Folder holding the input CSV. |
| `S3_AWS_WIHP_INPUT_SOURCES_TO_CREATE` | yes | Input CSV path, relative to the config folder. |
| `S3_AWS_WHIP_READY_FOR_CRAWLING_DIRECTORY` | yes | Folder where each new crawler workspace is created. |
| `S3_AWS_WHIP_READY_TO_EXPORT_DIRECTORY` | yes | Folder where workspaces wait for the extraction. |
| `S3_AWS_WHIP_DONE_DIRECTORY` | yes | Folder where finished workspaces are archived. |
| `S3_AWS_STAGING_DIRECTORY` | no | Root of the crawled content written by WIHP (default `staging`). |
| `S3_AWS_PROCESSED_DIRECTORY` | no | Root of the CSV files produced by the extraction (default `processed`). |
| `S3_AWS_WIHP_CREATED_CRAWLER_INFO` | yes | File name of the crawler description (`created_crawler.json`). |
| `S3_AWS_CREATED_ACQUISITION_INFO` | yes | File name of the acquisition description (`created_acquisition.json`). |
| `S3_AWS_WIHP_VALIDATED_SOURCES_TO_CREATE` | yes | File name of the validated sources (`validated_sources_to_create.csv`). |
| `S3_AWS_WIHP_UPDATED_SOURCES` | no | File name of the report of updated WIHP sources (`updated_sources.csv`). |
| `S3_AWS_WIHP_DUPLICATED_URLS` | yes | File name of the rejected duplicated URLs. |
| `S3_AWS_WIHP_NULL_MNE_NAMES` | yes | File name of the rejected rows without URL. |
| `S3_AWS_WHIP_NON_ENGLISH_URLS` | yes | File name of the rejected non-English URLs. |
| `S3_AWS_WIHP_LONG_MNE_NAMES` | yes | File name of the rejected overlong names. |
| `OVERWRITE_EXISTING` | no | `false` (default) skips existing CSV files, `true` regenerates them. |
| `S3_AWS_ACCESS_KEY_ID`, `S3_AWS_SECRET_ACCESS_KEY`, `S3_AWS_REGION_NAME`, `S3_AWS_BUCKET_NAME` | `s3` only | Bucket and credentials. The default AWS credential chain (IAM role, AWS CLI profile) is tried first. |
| `USE_SECRET_MANAGER`, `AWS_SECRET_MANAGER_NAME` | no | When `true`, settings are loaded from this AWS Secrets Manager secret. |

The spelling `WHIP` in some names is historical and must be kept as is.

The `STORAGE_BACKEND=local` and `s3` modes behave identically: path variables are
folders on disk in `local` mode and object-key prefixes in `s3` mode.

### Example layout

The folder names are entirely driven by the variables above. A typical layout is:

```text
<root>/
├── config/
│   └── sources_to_extract/mnes_sources_to_create.csv   # input
├── ready_for_crawling/<crawler>/                      # after das-setup-crawler
├── ready_to_export/<crawler>/                         # after das-create-acq
├── done/<crawler>/                                    # after das-extract-data
├── staging/<...>/<acquisition id>/content/...json     # written by WIHP
└── processed/<...>/content/...csv                     # written by das-extract-data
```

### Using AWS Secrets Manager

Set `USE_SECRET_MANAGER=true`, `AWS_SECRET_MANAGER_NAME=<secret>` and
`STORAGE_BACKEND=s3`. The secret is a JSON object whose keys are the variable
names above, except `STORAGE_BACKEND`, `USE_SECRET_MANAGER` and
`AWS_SECRET_MANAGER_NAME`, which must be set in the environment. Values missing
from the secret fall back to the environment. The
IAM role needs `secretsmanager:GetSecretValue` on the secret.

---

## Input file

`das-setup-crawler` reads `<S3_AWS_WIHP_CONFIG_DIRECTORY>/<S3_AWS_WIHP_INPUT_SOURCES_TO_CREATE>`,
a semicolon-separated CSV with exactly these headers:

```csv
mne_name;wikipedia_url
Airbus;https://en.wikipedia.org/wiki/Airbus
Decathlon;https://en.wikipedia.org/wiki/Decathlon_(retailer)
```

Rows are rejected, and listed in an audit file, when:

| Rule | Audit file (variable) |
|---|---|
| `wikipedia_url` is empty (the file lists the `mne_name` values of these rows) | `S3_AWS_WIHP_NULL_MNE_NAMES` |
| `wikipedia_url` does not contain `en.wikipedia.org` | `S3_AWS_WHIP_NON_ENGLISH_URLS` |
| `mne_name` is longer than 83 characters | `S3_AWS_WIHP_LONG_MNE_NAMES` |
| the URL already appeared in an earlier row | `S3_AWS_WIHP_DUPLICATED_URLS` |

If no valid row remains, or the file does not exist, the command ends with the
message "No sources to create" and nothing is created.

### URL encoding

An URL can be written with encoded characters (`Decathlon_%28retailer%29`) or
with plain ones (`Decathlon_(retailer)`): both designate the same page. The tool
normalizes them to the readable form `Decathlon_(retailer)`, which is the form
stored in WIHP. Characters that cannot appear raw in a path (spaces, `#`, `?`,
`%`, non-ASCII characters) stay percent-encoded. Rows whose URLs only differ by
their encoding are reported as duplicates.

---

## Running the pipelines

Export your configuration (see above), then run the commands in order.

### 1. `das-setup-crawler`

Reads and validates the input CSV, then creates one crawler named
`<CRAWLER_BASE_NAME>__<timestamp>`. For every valid row it looks for the WIHP
source (by URL, then by name) and creates it or updates it, and attaches it to
the crawler. It finally writes the workspace `ready_for_crawling/<crawler>/`:

| File | Content |
|---|---|
| `created_crawler.json` | Crawler name, id and timestamp. |
| `validated_sources_to_create.csv` | The rows that passed validation. Used later to fill `GEG_NAME`. |
| `updated_sources.csv` | Only when existing WIHP sources were modified: previous and new name/URL, action, date. |
| rejected-row files | Duplicated URLs, rows without URL, non-English URLs, overlong names (JSON lists, whatever their extension). Only written when not empty. |
| the input CSV | Moved here as an archive once the crawler is created. |

A WIHP source is named `<MNE NAME>_<SOURCE_NAME>_<LANGUAGE>_<GROUP>`
(for example `AIRBUS_WIKIPEDIA_EN_MNE`). Requests to WIHP are retried three times.

### 2. `das-create-acq`

Starts an acquisition for each crawler found in `ready_for_crawling/`, which
begins about five minutes later. It saves `created_acquisition.json` in each
crawler workspace and then moves the whole `ready_for_crawling` folder to
`ready_to_export`.

### 3. `das-stop-acq`

Looks at all `RUNNING` acquisitions and stops those that have no URL left in the
`DISCOVERED` state. It reads and writes nothing in the storage.

### 4. `das-extract-data`

Only the acquisitions described in `ready_to_export/*/created_acquisition.json`
are processed. For each of them, every `content/*.json` file found under the
staging folder is converted to a CSV file with the same relative path under the
processed folder, and a `_metadata/manifest.json` records the status
(`PROCESSED`, `SKIPPED` or `FAILED`) of every file.

```bash
das-extract-data            # skip files whose CSV already exists
das-extract-data --force    # regenerate every CSV (same as OVERWRITE_EXISTING=true)
```

- A file that cannot be processed is marked `FAILED`; the others are still processed.
- The command exits with code `1` when at least one file failed.
- When at least one file was found and none failed, the **whole** `ready_to_export` folder is moved to `done`. When no file is found (for example the crawl has not written anything yet), nothing is moved and a warning is logged.
- The command needs the same environment as the other ones, including the WIHP settings.

---

## Output

One CSV file per crawled content file, separated by `;`, with one row per
Wikipedia page. The columns come from `output_columns_mapping.json` and are
always present, in the same order:

| Columns | Meaning |
|---|---|
| `STRUCTURE`, `STRUCTURE_ID`, `ACTION`, `SOURCE` | Constant values (`dataflow`, `ESTAT:EGR_WIHMNE_Q(1.0)`, `R`, `WIKIPEDIA`). |
| `GEG_NAME` | Name of the enterprise taken from your input CSV, matched on the page URL whatever its encoding. Empty when no input row matches. |
| `SOURCE_URL`, `RETRIEVAL_DATE` | URL of the crawled page and crawl date (`YYYY-MM-DD`). |
| `GEG_GDC_COUNTRY`, `GEG_GDC_COUNTRY_CODE`, `GEG_ADDRESS`, `GEG_ISIN`, `GEG_WEB` | Country (and code), address, ISIN and website read from the Wikipedia infobox. `GEG_WEB` only comes from the infobox `website` field. |
| `GEG_INCOME`, `GEG_T_ASSET`, `GEG_T_REVENUE`, `GEG_TURNOV`, `GEG_PERS_EMPL` | Net income, total assets, revenue, turnover and number of employees, as integers. |
| `<metric>_CITE_WEB`, `_CUR_CODE`, `_RYEAR` | Source reference, ISO currency code and reference year of the metric. |
| `<metric>_EUR` | Amount converted to euro with Eurostat exchange rates: year-end rate for total assets, annual average for the other amounts. Empty when the currency, the year or the rate is missing. |
| other identifiers, `OBS_STATUS_*`, `COMMENT_OBS` | Reserved columns, currently always empty. |

### Customizing the extraction

The extraction rules are JSON files shipped with the package (columns kept,
units, currencies, countries, output mapping...). To change one without editing
the installed package, set an environment variable named after the file in
upper case, with the JSON content as value, for example
`COUNTRIES_CODES_MAPPING='{"France": "FR"}'`. The supported names are
`ADDITIONAL_COLUMNS_AND_VALUES`, `CHARACTERS_TO_REMOVE`, `COUNTRIES_CODES_MAPPING`,
`COUNTRIES_COLUMNS`, `CURRENCIES`, `CURRENCY_COLUMNS`, `EXCHANGE_RATES_LOOKUP`,
`INDIAN_UNIT_MAPPING`, `ISIN_CHARACTERS_TO_REMOVE`, `NEGATIVE_SIGN_KEYWORDS`,
`NUMERIC_COLUMNS`, `OUTPUT_COLUMNS_MAPPING`, `UNIT_MAPPING`,
`UPPERCASE_OUTPUT_COLUMNS`, `WEBSITE_COLUMNS`,
`WIKIPEDIA_SELECTED_EXTRACTED_COLUMNS` and `YEAR_COLUMNS_MAPPING`.
An override replaces the whole file; an invalid JSON value is ignored with a
warning.

---

## Re-processing and recovery

| Situation | What to do |
|---|---|
| Some files failed | Read `_metadata/manifest.json` and the logs, fix the cause, run `das-extract-data` again: files already converted are skipped and the workspace is moved to `done` once nothing fails. |
| Regenerate the CSV files after a rule change | Run `das-extract-data --force`. |
| The workspace is already in `done` | The extraction only looks at `ready_to_export`. Move `done/<crawler>` back to `ready_to_export/<crawler>`, then run `das-extract-data --force`. |
| `das-extract-data` finds nothing | Check that `created_acquisition.json` exists under `ready_to_export/<crawler>/` and that the acquisition id appears in the staging path. |
| `GEG_NAME` is empty | The page URL does not match any row of `validated_sources_to_create.csv`, or that file is missing from the workspace. The log names the URL. |
| `_EUR` columns are empty | The currency, the year or the exchange rate of that currency and year is missing. |
| "No sources to create" | The input CSV is missing at the configured path, or all rows were rejected (see the audit files). |

---

## Logs

Each module writes a dated log file (`<module>_YYYY_MM_DD.log`) in a `logs`
folder **inside the installed package** (`das_setup_helper/logs/`) and to the
console. The file of a given day is overwritten at each run, so keep the console
output if you need a history. The body of token responses is not logged.

---

## Versioning

The package follows [PEP 440](https://peps.python.org/pep-0440/) versions
(`X.Y.Z`). Pre-releases (`X.Y.Z.devN`, `X.Y.Z.rcN`) are published for validation
only; install the latest final release in production. Command names, environment
variable names and output file formats are considered public interfaces:
removals are announced as deprecations in a release before they happen.

## License

This project is distributed under the European Union Public Licence v1.2
(EUPL-1.2). The licence text is shipped with the package (`LICENSE` file) and
available on the European Commission website:
https://commission.europa.eu/about/departments-and-executive-agencies/digital-services/open-source-strategy-history/european-union-public-licence_en
