hash
stringlengths 40
40
| authorName
stringclasses 42
values | authorEmail
stringclasses 41
values | date
timestamp[ms]date 2021-07-26 09:52:55
2025-07-18 10:19:56
| subject
stringlengths 11
116
| diff
stringlengths 0
987k
|
---|---|---|---|---|---|
5df82c77180cc10eeaf6b5e7f3cc7c1b2fc9d091
|
Quentin Lhoest
| 2023-09-05T17:33:35 |
Set maximum allowed arrow data for /rows to avoid OOM (#1773)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index a1355113..8cd9272a 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -145,0 +146,3 @@ duckDBIndex:
+rowsIndex:
+ maxArrowDataInMemory: "300_000_000"
+
diff --git a/chart/templates/services/rows/_container.tpl b/chart/templates/services/rows/_container.tpl
index 94881190..64e8181d 100644
--- a/chart/templates/services/rows/_container.tpl
+++ b/chart/templates/services/rows/_container.tpl
@@ -31,0 +32,2 @@
+ - name: ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY
+ value: {{ .Values.rowsIndex.maxArrowDataInMemory | quote }}
diff --git a/chart/templates/worker/_container.tpl b/chart/templates/worker/_container.tpl
index 93c31fa5..0b54a59b 100644
--- a/chart/templates/worker/_container.tpl
+++ b/chart/templates/worker/_container.tpl
@@ -27,0 +28,2 @@
+ - name: ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY
+ value: {{ .Values.rowsIndex.maxArrowDataInMemory | quote }}
diff --git a/chart/values.yaml b/chart/values.yaml
index 999620b5..fae7b7d3 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -275,0 +276,4 @@ duckDBIndex:
+rowsIndex:
+ # Maximum number of bytes to load in memory from parquet row groups to avoid OOM
+ maxArrowDataInMemory: "300_000_000"
+
diff --git a/libs/libcommon/src/libcommon/config.py b/libs/libcommon/src/libcommon/config.py
index 35f76992..ad081d13 100644
--- a/libs/libcommon/src/libcommon/config.py
+++ b/libs/libcommon/src/libcommon/config.py
@@ -111,0 +112,18 @@ class ParquetMetadataConfig:
+ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY = 300_000_000
+
+
+@dataclass(frozen=True)
+class RowsIndexConfig:
+ max_arrow_data_in_memory: int = ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY
+
+ @classmethod
+ def from_env(cls) -> "RowsIndexConfig":
+ env = Env(expand_vars=True)
+ with env.prefixed("ROWS_INDEX_"):
+ return cls(
+ max_arrow_data_in_memory=env.int(
+ name="MAX_ARROW_DATA_IN_MEMORY", default=ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY
+ ),
+ )
+
+
diff --git a/libs/libcommon/src/libcommon/parquet_utils.py b/libs/libcommon/src/libcommon/parquet_utils.py
index 10651bf0..56dc43bb 100644
--- a/libs/libcommon/src/libcommon/parquet_utils.py
+++ b/libs/libcommon/src/libcommon/parquet_utils.py
@@ -5,2 +5,2 @@ from dataclasses import dataclass, field
-from functools import lru_cache, partial
-from typing import Callable, List, Literal, Optional, TypedDict, Union
+from functools import lru_cache
+from typing import List, Literal, Optional, TypedDict, Union
@@ -12,0 +13 @@ from datasets.features.features import FeatureType
+from datasets.utils.py_utils import size_str
@@ -34,0 +36,4 @@ class FileSystemError(Exception):
+class TooBigRows(Exception):
+ pass
+
+
@@ -45,0 +51,12 @@ class ParquetFileMetadataItem(TypedDict):
+@dataclass
+class RowGroupReader:
+ parquet_file: pq.ParquetFile
+ group_id: int
+
+ def read(self, columns: List[str]) -> pa.Table:
+ return self.parquet_file.read_row_group(i=self.group_id, columns=columns)
+
+ def read_size(self) -> int:
+ return self.parquet_file.metadata.row_group(self.group_id).total_byte_size # type: ignore
+
+
@@ -56,0 +74 @@ class ParquetIndexWithMetadata:
+ max_arrow_data_in_memory: int
@@ -78,0 +97,3 @@ class ParquetIndexWithMetadata:
+
+ Raises:
+ TooBigRows: if the arrow data from the parquet row groups is bigger than max_arrow_data_in_memory
@@ -128,2 +149,2 @@ class ParquetIndexWithMetadata:
- row_group_readers: List[Callable[[], pa.Table]] = [
- partial(parquet_file.read_row_group, i=group_id, columns=self.supported_columns)
+ row_group_readers = [
+ RowGroupReader(parquet_file=parquet_file, group_id=group_id)
@@ -141,0 +163,12 @@ class ParquetIndexWithMetadata:
+ with StepProfiler(
+ method="parquet_index_with_metadata.row_groups_size_check", step="check if the rows can fit in memory"
+ ):
+ row_groups_size = sum(
+ [row_group_readers[i].read_size() for i in range(first_row_group_id, last_row_group_id + 1)]
+ )
+ if row_groups_size > self.max_arrow_data_in_memory:
+ raise TooBigRows(
+ "Rows from parquet row groups are too big to be read:"
+ f" {size_str(row_groups_size)} (max={size_str(self.max_arrow_data_in_memory)})"
+ )
+
@@ -144 +177,4 @@ class ParquetIndexWithMetadata:
- [row_group_readers[i]() for i in range(first_row_group_id, last_row_group_id + 1)]
+ [
+ row_group_readers[i].read(self.supported_columns)
+ for i in range(first_row_group_id, last_row_group_id + 1)
+ ]
@@ -155,0 +192 @@ class ParquetIndexWithMetadata:
+ max_arrow_data_in_memory: int,
@@ -197,0 +235 @@ class ParquetIndexWithMetadata:
+ max_arrow_data_in_memory=max_arrow_data_in_memory,
@@ -210,0 +249 @@ class RowsIndex:
+ max_arrow_data_in_memory: int,
@@ -221,0 +261 @@ class RowsIndex:
+ max_arrow_data_in_memory=max_arrow_data_in_memory,
@@ -228,0 +269 @@ class RowsIndex:
+ max_arrow_data_in_memory: int,
@@ -262,0 +304 @@ class RowsIndex:
+ max_arrow_data_in_memory=max_arrow_data_in_memory,
@@ -293,0 +336 @@ class Indexer:
+ max_arrow_data_in_memory: int,
@@ -301,0 +345 @@ class Indexer:
+ self.max_arrow_data_in_memory = max_arrow_data_in_memory
@@ -324,0 +369 @@ class Indexer:
+ max_arrow_data_in_memory=self.max_arrow_data_in_memory,
diff --git a/services/rows/src/rows/app.py b/services/rows/src/rows/app.py
index 4bf9d410..22a9fcfc 100644
--- a/services/rows/src/rows/app.py
+++ b/services/rows/src/rows/app.py
@@ -79,0 +80 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
+ max_arrow_data_in_memory=app_config.rows_index.max_arrow_data_in_memory,
diff --git a/services/rows/src/rows/config.py b/services/rows/src/rows/config.py
index 722f4b93..3dc6dd1c 100644
--- a/services/rows/src/rows/config.py
+++ b/services/rows/src/rows/config.py
@@ -14,0 +15 @@ from libcommon.config import (
+ RowsIndexConfig,
@@ -25,0 +27 @@ class AppConfig:
+ rows_index: RowsIndexConfig = field(default_factory=RowsIndexConfig)
@@ -40,0 +43 @@ class AppConfig:
+ rows_index=RowsIndexConfig.from_env(),
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index 05fd330b..0eb54ea4 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -90,0 +91 @@ def create_rows_endpoint(
+ max_arrow_data_in_memory: int,
@@ -108,0 +110 @@ def create_rows_endpoint(
+ max_arrow_data_in_memory=max_arrow_data_in_memory,
diff --git a/services/rows/tests/routes/test_rows.py b/services/rows/tests/routes/test_rows.py
index 666c2355..9bb628f7 100644
--- a/services/rows/tests/routes/test_rows.py
+++ b/services/rows/tests/routes/test_rows.py
@@ -18 +18,6 @@ from fsspec.implementations.http import HTTPFileSystem
-from libcommon.parquet_utils import Indexer, ParquetIndexWithMetadata, RowsIndex
+from libcommon.parquet_utils import (
+ Indexer,
+ ParquetIndexWithMetadata,
+ RowsIndex,
+ TooBigRows,
+)
@@ -254,0 +260 @@ def indexer(
+ max_arrow_data_in_memory=9999999999,
@@ -269,0 +276,21 @@ def rows_index_with_parquet_metadata(
[email protected]
+def rows_index_with_too_big_rows(
+ app_config: AppConfig,
+ processing_graph: ProcessingGraph,
+ parquet_metadata_directory: StrPath,
+ ds_sharded: Dataset,
+ ds_sharded_fs: AbstractFileSystem,
+ dataset_sharded_with_config_parquet_metadata: dict[str, Any],
+) -> Generator[RowsIndex, None, None]:
+ indexer = Indexer(
+ processing_graph=processing_graph,
+ hf_token=app_config.common.hf_token,
+ parquet_metadata_directory=parquet_metadata_directory,
+ httpfs=HTTPFileSystem(),
+ max_arrow_data_in_memory=1,
+ )
+ with ds_sharded_fs.open("default/train/0003.parquet") as f:
+ with patch("libcommon.parquet_utils.HTTPFile", return_value=f):
+ yield indexer.get_rows_index("ds_sharded", "default", "train")
+
+
@@ -322,0 +350,5 @@ def test_rows_index_query_with_parquet_metadata(
+def test_rows_index_query_with_too_big_rows(rows_index_with_too_big_rows: RowsIndex, ds_sharded: Dataset) -> None:
+ with pytest.raises(TooBigRows):
+ rows_index_with_too_big_rows.query(offset=0, length=3)
+
+
diff --git a/services/worker/src/worker/config.py b/services/worker/src/worker/config.py
index 3f11ca6a..58a9ba3f 100644
--- a/services/worker/src/worker/config.py
+++ b/services/worker/src/worker/config.py
@@ -15,0 +16 @@ from libcommon.config import (
+ RowsIndexConfig,
@@ -335,0 +337 @@ class AppConfig:
+ rows_index: RowsIndexConfig = field(default_factory=RowsIndexConfig)
@@ -360,0 +363 @@ class AppConfig:
+ rows_index=RowsIndexConfig.from_env(),
diff --git a/services/worker/src/worker/job_runners/split/first_rows_from_parquet.py b/services/worker/src/worker/job_runners/split/first_rows_from_parquet.py
index 03509c67..af6bf483 100644
--- a/services/worker/src/worker/job_runners/split/first_rows_from_parquet.py
+++ b/services/worker/src/worker/job_runners/split/first_rows_from_parquet.py
@@ -18 +18 @@ from libcommon.exceptions import (
-from libcommon.parquet_utils import Indexer
+from libcommon.parquet_utils import Indexer, TooBigRows
@@ -106 +106,4 @@ def compute_first_rows_response(
- pa_table = rows_index.query(offset=0, length=rows_max_number)
+ try:
+ pa_table = rows_index.query(offset=0, length=rows_max_number)
+ except TooBigRows as err:
+ raise TooBigContentError(str(err))
@@ -194,0 +198 @@ class SplitFirstRowsFromParquetJobRunner(SplitJobRunner):
+ max_arrow_data_in_memory=app_config.rows_index.max_arrow_data_in_memory,
diff --git a/services/worker/tests/job_runners/config/test_parquet_metadata.py b/services/worker/tests/job_runners/config/test_parquet_metadata.py
index 74f3aa7b..052ab58b 100644
--- a/services/worker/tests/job_runners/config/test_parquet_metadata.py
+++ b/services/worker/tests/job_runners/config/test_parquet_metadata.py
@@ -320,0 +321 @@ def test_ParquetIndexWithMetadata_query(
+ max_arrow_data_in_memory=999999999,
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index d21e2509..d68435d4 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -104,0 +105 @@ services:
+ ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY: ${ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY-300_000_000}
@@ -195,0 +197 @@ services:
+ ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY: ${ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY-300_000_000}
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index 43e71762..70797710 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -106,0 +107 @@ services:
+ ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY: ${ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY-300_000_000}
@@ -201,0 +203 @@ services:
+ ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY: ${ROWS_INDEX_MAX_ARROW_DATA_IN_MEMORY-300_000_000}
|
|
fb0903b4274b5edca8e98459b4a322fe78d917d3
|
Steven Liu
| 2023-09-05T15:51:37 |
[docs] ClickHouse integration (#1720)
|
diff --git a/docs/source/_toctree.yml b/docs/source/_toctree.yml
index bd3bb312..3bc16679 100644
--- a/docs/source/_toctree.yml
+++ b/docs/source/_toctree.yml
@@ -28,0 +29,2 @@
+ - local: clickhouse
+ title: ClickHouse
diff --git a/docs/source/clickhouse.md b/docs/source/clickhouse.md
new file mode 100644
index 00000000..f4266bdb
--- /dev/null
+++ b/docs/source/clickhouse.md
@@ -0,0 +1,143 @@
+# ClickHouse
+
+[ClickHouse](https://clickhouse.com/docs/en/intro) is a fast and efficient column-oriented database for analytical workloads, making it easy to analyze Hub-hosted datasets with SQL. To get started quickly, use [`clickhouse-local`](https://clickhouse.com/docs/en/operations/utilities/clickhouse-local) to run SQL queries from the command line and avoid the need to fully install ClickHouse.
+
+<Tip>
+
+Check this [blog](https://clickhouse.com/blog/query-analyze-hugging-face-datasets-with-clickhouse) for more details about how to analyze datasets on the Hub with ClickHouse.
+
+</Tip>
+
+To start, download and install `clickhouse-local`:
+
+```bash
+curl https://clickhouse.com/ | sh
+```
+
+For this example, you'll analyze the [maharshipandya/spotify-tracks-dataset](https://huggingface.co/datasets/maharshipandya/spotify-tracks-dataset) which contains information about Spotify tracks. Datasets on the Hub are stored as Parquet files and you can access it with the [`/parquet`](parquet) endpoint:
+
+```py
+import requests
+
+r = requests.get("https://datasets-server.huggingface.co/parquet?dataset=maharshipandya/spotify-tracks-dataset")
+j = r.json()
+url = [f['url'] for f in j['parquet_files']]
+url
+['https://huggingface.co/datasets/maharshipandya/spotify-tracks-dataset/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet']
+```
+
+## Aggregate functions
+
+Now you can begin to analyze the dataset. Use the `-q` argument to specify the query to execute, and the [`url`](https://clickhouse.com/docs/en/sql-reference/table-functions/url) function to create a table from the data in the Parquet file.
+
+You should set `enable_url_encoding` to 0 to ensure the escape characters in the URL are preserved as intended, and `max_https_get_redirects` to 1 to redirect to the path of the Parquet file.
+
+Let's start by identifying the most popular artists:
+
+```bash
+./clickhouse local -q "
+ SELECT count() AS c, artists
+ FROM url('https://huggingface.co/datasets/maharshipandya/spotify-tracks-dataset/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet')
+ GROUP BY artists
+ ORDER BY c
+ DESC LIMIT 5
+ SETTINGS enable_url_encoding=0, max_http_get_redirects=1"
+
+┌───c─┬─artists─────────┐
+│ 279 │ The Beatles │
+│ 271 │ George Jones │
+│ 236 │ Stevie Wonder │
+│ 224 │ Linkin Park │
+│ 222 │ Ella Fitzgerald │
+└─────┴─────────────────┘
+```
+
+ClickHouse also provides functions for visualizing your queries. For example, you can use the [`bar`](https://clickhouse.com/docs/en/sql-reference/functions/other-functions#bar) function to create a bar chart of the danceability of songs:
+
+```bash
+./clickhouse local -q "
+ SELECT
+ round(danceability, 1) AS danceability,
+ bar(count(), 0, max(count()) OVER ()) AS dist
+ FROM url('https://huggingface.co/datasets/maharshipandya/spotify-tracks-dataset/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet')
+ GROUP BY danceability
+ ORDER BY danceability ASC
+ SETTINGS enable_url_encoding=0, max_http_get_redirects=1"
+
+┌─danceability─┬─dist─────────────────────────────────────────────────────────────────────────────────┐
+│ 0 │ ▍ │
+│ 0.1 │ ████▎ │
+│ 0.2 │ █████████████▍ │
+│ 0.3 │ ████████████████████████ │
+│ 0.4 │ ████████████████████████████████████████████▋ │
+│ 0.5 │ ████████████████████████████████████████████████████████████████████▊ │
+│ 0.6 │ ████████████████████████████████████████████████████████████████████████████████ │
+│ 0.7 │ ██████████████████████████████████████████████████████████████████████ │
+│ 0.8 │ ██████████████████████████████████████████ │
+│ 0.9 │ ██████████▋ │
+│ 1 │ ▌ │
+└──────────────┴──────────────────────────────────────────────────────────────────────────────────────┘
+```
+
+To get a deeper understanding about a dataset, ClickHouse provides statistical analysis functions for determining how your data is correlated, calculating statistical hypothesis tests, and more. Take a look at ClickHouse's [List of Aggregate Functions](https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference) for a complete list of available aggregate functions.
+
+## User-defined function (UDFs)
+
+A user-defined function (UDF) allows you to reuse custom logic. Many Hub datasets are often sharded into more than one Parquet file, so it can be easier and more efficient to create a UDF to list and query all the Parquet files of a given dataset from just the dataset name.
+
+For this example, you'll need to run `clickhouse-local` in console mode so the UDF persists between queries:
+
+```bash
+./clickhouse local
+```
+
+Remember to set `enable_url_encoding` to 0 and `max_https_get_redirects` to 1 to redirect to the path of the Parquet files:
+
+```bash
+SET max_http_get_redirects = 1, enable_url_encoding = 0
+```
+
+Let's create a function to return a list of Parquet files from the [`blog_authorship_corpus`](https://huggingface.co/datasets/blog_authorship_corpus):
+
+```bash
+CREATE OR REPLACE FUNCTION hugging_paths AS dataset -> (
+ SELECT arrayMap(x -> (x.1), JSONExtract(json, 'parquet_files', 'Array(Tuple(url String))'))
+ FROM url('https://datasets-server.huggingface.co/parquet?dataset=' || dataset, 'JSONAsString')
+);
+
+SELECT hugging_paths('blog_authorship_corpus') AS paths
+
+['https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0000.parquet','https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0001.parquet','https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/validation/0000.parquet']
+```
+
+You can make this even easier by creating another function that calls `hugging_paths` and outputs all the files based on the dataset name:
+
+```bash
+CREATE OR REPLACE FUNCTION hf AS dataset -> (
+ WITH hugging_paths(dataset) as urls
+ SELECT multiIf(length(urls) = 0, '', length(urls) = 1, urls[1], 'https://huggingface.co/datasets/{' || arrayStringConcat(arrayMap(x -> replaceRegexpOne(replaceOne(x, 'https://huggingface.co/datasets/', ''), '\\.parquet$', ''), urls), ',') || '}.parquet')
+);
+
+SELECT hf('blog_authorship_corpus') AS pattern
+
+['https://huggingface.co/datasets/{blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00000-of-00002,blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00001-of-00002,blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-validation}.parquet']
+```
+
+Now use the `hf` function to query any dataset by passing the dataset name:
+
+```bash
+SELECT horoscope, count(*), AVG(LENGTH(text)) AS avg_blog_length
+FROM url(hf('blog_authorship_corpus'))
+GROUP BY horoscope
+ORDER BY avg_blog_length
+DESC LIMIT(5)
+
+┌─────────────┬───────┬────────────────────┐
+│ Aquarius │ 51747 │ 1132.487873693161 │
+├─────────────┼───────┼────────────────────┤
+│ Cancer │ 66944 │ 1111.613109464627 │
+│ Libra │ 63994 │ 1060.3968184517298 │
+│ Sagittarius │ 52753 │ 1055.7120732470191 │
+│ Capricorn │ 52207 │ 1055.4147719654452 │
+└─────────────┴───────┴────────────────────┘
+```
\ No newline at end of file
diff --git a/docs/source/parquet_process.mdx b/docs/source/parquet_process.mdx
index 1ace2523..5a3c8203 100644
--- a/docs/source/parquet_process.mdx
+++ b/docs/source/parquet_process.mdx
@@ -7 +7,2 @@ Datasets Server automatically converts and publishes public datasets less than 5
-- [DuckDB](https://duckdb.org/docs/), a high-performance SQL database for analytical queries
\ No newline at end of file
+- [DuckDB](https://duckdb.org/docs/), a high-performance SQL database for analytical queries
+- [ClickHouse](https://clickhouse.com/docs/en/intro), a column-oriented database management system for online analytical processing
\ No newline at end of file
|
|
5be07b08061f4044c74e54c28bdf4ddba9f51888
|
Sylvain Lesage
| 2023-09-05T15:45:48 |
Add endpoint /hub-cache (#1739)
|
diff --git a/.github/workflows/_e2e_tests.yml b/.github/workflows/_e2e_tests.yml
index 94be4ede..ae2b3c01 100644
--- a/.github/workflows/_e2e_tests.yml
+++ b/.github/workflows/_e2e_tests.yml
@@ -48,0 +49,2 @@ jobs:
+ # hub-cache
+ HUB_CACHE_NUM_RESULTS_PER_PAGE: "2"
@@ -89,0 +92,2 @@ jobs:
+ # hub-cache
+ HUB_CACHE_NUM_RESULTS_PER_PAGE: "2"
diff --git a/chart/templates/services/api/_container.tpl b/chart/templates/services/api/_container.tpl
index 2288c02a..2e7d6153 100644
--- a/chart/templates/services/api/_container.tpl
+++ b/chart/templates/services/api/_container.tpl
@@ -22,0 +23,5 @@
+ # /hub-cache
+ - name: HUB_CACHE_BASE_URL
+ value: "https://{{ include "datasetsServer.ingress.hostname" . }}"
+ - name: HUB_CACHE_NUM_RESULTS_PER_PAGE
+ value: {{ .Values.api.hubCacheNumResultsPerPage | quote }}
diff --git a/chart/values.yaml b/chart/values.yaml
index 06febdd1..999620b5 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -466,0 +467,2 @@ api:
+ # the number of results per page. Defaults to `1_000`.
+ hubCacheNumResultsPerPage: "1_000"
diff --git a/docs/source/openapi.json b/docs/source/openapi.json
index 6314d09b..35fda1d1 100644
--- a/docs/source/openapi.json
+++ b/docs/source/openapi.json
@@ -30,0 +31,8 @@
+ "Access-Control-Allow-Origin": {
+ "description": "Indicates whether the response can be shared with requesting code from the given origin.",
+ "schema": {
+ "type": "string"
+ },
+ "example": "*",
+ "required": true
+ },
@@ -48,2 +56,2 @@
- "Access-Control-Allow-Origin": {
- "description": "Indicates whether the response can be shared with requesting code from the given origin.",
+ "Link": {
+ "description": "A link for the next page of results. See https://docs.github.com/en/rest/guides/using-pagination-in-the-rest-api#using-link-headers. Only 'rel=\"next\"' is used. If not present, there is no next page.",
@@ -53,2 +61,5 @@
- "example": "*",
- "required": true
+ "example": {
+ "summary": "Link to the next page.",
+ "value": "<https://datasets-server.huggingface.co/hub-cache?cursor=64f7278d81223b123ba9d68b>; rel=\"next\""
+ },
+ "required": false
@@ -138,0 +150,9 @@
+ "X-Error-Code-500-hub-cache": {
+ "description": "A string that identifies the underlying error for 500 on /hub-cache. It's marked as required: false because the header can be missing on text-plain response.",
+ "schema": {
+ "oneOf": [
+ { "$ref": "#/components/schemas/X-Error-Code-UnexpectedError" }
+ ]
+ },
+ "required": false
+ },
@@ -1211,0 +1232,24 @@
+ "HubCacheResponse": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["dataset", "preview", "viewer", "partial", "num_rows"],
+ "properties": {
+ "dataset": {
+ "type": "string"
+ },
+ "preview": {
+ "type": "boolean"
+ },
+ "viewer": {
+ "type": "boolean"
+ },
+ "partial": {
+ "type": "boolean"
+ },
+ "num_rows": {
+ "type": "integer"
+ }
+ }
+ }
+ },
@@ -5259,0 +5304,89 @@
+ },
+ "/hub-cache": {
+ "get": {
+ "summary": "[Internal] Datasets info for the Hub",
+ "description": "A list of dataset infos. It's an internal endpoint meant to be cached by the Hub's backend. The response is paginated, use the Link header to get the next page.",
+ "operationId": "listDatasetsInfoForHubCache",
+ "parameters": [],
+ "responses": {
+ "200": {
+ "description": "The datasets info.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "Link": {
+ "$ref": "#/components/headers/Link"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HubCacheResponse"
+ },
+ "examples": {
+ "an example of the response format (only kept the first two values for brevity)": {
+ "summary": "list of datasets info",
+ "description": "Try with https://datasets-server.huggingface.co/hub-cache",
+ "value": [
+ {
+ "preview": true,
+ "viewer": true,
+ "partial": false,
+ "num_rows": 4,
+ "dataset": "__DUMMY_DATASETS_SERVER_USER__/repo_csv_data-16939190414468"
+ },
+ {
+ "preview": true,
+ "viewer": true,
+ "partial": false,
+ "num_rows": 4,
+ "dataset": "__DUMMY_DATASETS_SERVER_USER__/repo_csv_data-16939190442968"
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "The server crashed.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-500-hub-cache"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
diff --git a/e2e/Makefile b/e2e/Makefile
index 42598aaa..fd7eeab3 100644
--- a/e2e/Makefile
+++ b/e2e/Makefile
@@ -26,0 +27 @@ export WORKER_SLEEP_SECONDS := 1
+export HUB_CACHE_NUM_RESULTS_PER_PAGE := 2
diff --git a/e2e/tests/test_16_statistics.py b/e2e/tests/test_14_statistics.py
similarity index 100%
rename from e2e/tests/test_16_statistics.py
rename to e2e/tests/test_14_statistics.py
diff --git a/e2e/tests/test_15_is_valid.py b/e2e/tests/test_18_is_valid.py
similarity index 100%
rename from e2e/tests/test_15_is_valid.py
rename to e2e/tests/test_18_is_valid.py
diff --git a/e2e/tests/test_19_hub_cache.py b/e2e/tests/test_19_hub_cache.py
new file mode 100644
index 00000000..46a227f6
--- /dev/null
+++ b/e2e/tests/test_19_hub_cache.py
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2022 The HuggingFace Authors.
+
+import os
+
+from .fixtures.hub import DatasetRepos
+from .utils import get
+
+
+def test_hub_cache_after_datasets_processed(hf_dataset_repos_csv_data: DatasetRepos) -> None:
+ # this test ensures that the datasets processed successfully are present in /hub-cache
+ link = None
+ iteration = 0
+ keep_iterating = True
+ while keep_iterating and iteration < 10:
+ if link is None:
+ response = get(relative_url="/hub-cache")
+ else:
+ response = get(url=link, relative_url="")
+ assert response.status_code == 200
+ body = response.json()
+
+ keep_iterating = "Link" in response.headers
+ link = response.headers["Link"].split(";")[0][1:-1] if keep_iterating else None
+ iteration += 1
+
+ print(f"{body=}")
+ print(f"{response.headers=}")
+ print(f"{link=}")
+
+ assert all(item["viewer"] and item["num_rows"] > 0 for item in body)
+
+ NUM_DATASETS = 4
+ NUM_RESULTS_PER_PAGE = int(os.environ.get("HUB_CACHE_NUM_RESULTS_PER_PAGE", 1_000))
+ assert iteration >= NUM_DATASETS // NUM_RESULTS_PER_PAGE
diff --git a/e2e/tests/test_14_valid.py b/e2e/tests/test_19_valid.py
similarity index 100%
rename from e2e/tests/test_14_valid.py
rename to e2e/tests/test_19_valid.py
diff --git a/libs/libapi/src/libapi/utils.py b/libs/libapi/src/libapi/utils.py
index 158f51d7..be9634bf 100644
--- a/libs/libapi/src/libapi/utils.py
+++ b/libs/libapi/src/libapi/utils.py
@@ -9 +9 @@ from itertools import islice
-from typing import Any, Callable, Coroutine, List, Optional
+from typing import Any, Callable, Coroutine, Dict, List, Optional
@@ -51,0 +52 @@ def get_json_response(
+ headers: Optional[Dict[str, str]] = None,
@@ -53 +54,3 @@ def get_json_response(
- headers = {"Cache-Control": f"max-age={max_age}" if max_age > 0 else "no-store"}
+ if not headers:
+ headers = {}
+ headers["Cache-Control"] = f"max-age={max_age}" if max_age > 0 else "no-store"
@@ -68,2 +71,4 @@ EXPOSED_HEADERS = [
-def get_json_ok_response(content: Any, max_age: int = 0, revision: Optional[str] = None) -> Response:
- return get_json_response(content=content, max_age=max_age, revision=revision)
+def get_json_ok_response(
+ content: Any, max_age: int = 0, revision: Optional[str] = None, headers: Optional[Dict[str, str]] = None
+) -> Response:
+ return get_json_response(content=content, max_age=max_age, revision=revision, headers=headers)
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index 45f1292b..1117d823 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -116,0 +117 @@ class CachedResponseDocument(Document):
+ ("kind", "http_status", "_id"),
@@ -575,0 +577,43 @@ def has_any_successful_response(
+class ContentsPage(TypedDict):
+ contents: List[Dict[str, Any]]
+ cursor: Optional[str]
+
+
+def get_contents_page(kind: str, limit: int, cursor: Optional[str] = None) -> ContentsPage:
+ """
+ Get a list of contents of the cache entries for a specific kind, along with the next cursor.
+ Only the successful responses are returned.
+
+ The server returns results after the given cursor (the last object id).
+
+ Args:
+ kind (str): the kind of the cache entries
+ limit (strictly positive `int`):
+ The maximum number of results.
+ cursor (`str`):
+ A string representing the last object (id). An empty string means to start from the beginning.
+ Returns:
+ [`PageByUpdatedAt`]: A dict with the list of contents and the next cursor. The next cursor is
+ an empty string if there are no more items to be fetched. Note that the contents always contain the
+ dataset field.
+ Raises the following errors:
+ - [`~simple_cache.InvalidCursor`]
+ If the cursor is invalid.
+ - [`~simple_cache.InvalidLimit`]
+ If the limit is an invalid number.
+ """
+ if not cursor:
+ queryset = CachedResponseDocument.objects(kind=kind, http_status=HTTPStatus.OK)
+ else:
+ try:
+ queryset = CachedResponseDocument.objects(kind=kind, http_status=HTTPStatus.OK, id__gt=ObjectId(cursor))
+ except InvalidId as err:
+ raise InvalidCursor("Invalid cursor.") from err
+ if limit <= 0:
+ raise InvalidLimit("Invalid limit.")
+ objects = queryset.order_by("+id").only("content", "dataset").limit(limit)
+ length = objects.count(with_limit_and_skip=True)
+ new_cursor = str(objects[length - 1].id) if length >= limit else None
+ return ContentsPage(contents=[{**o.content, "dataset": o.dataset} for o in objects], cursor=new_cursor)
+
+
diff --git a/libs/libcommon/tests/test_simple_cache.py b/libs/libcommon/tests/test_simple_cache.py
index 64688b4d..69dbc7be 100644
--- a/libs/libcommon/tests/test_simple_cache.py
+++ b/libs/libcommon/tests/test_simple_cache.py
@@ -27,0 +28 @@ from libcommon.simple_cache import (
+ get_contents_page,
@@ -349,0 +351,68 @@ def test_has_any_successful_response_only_invalid_responses() -> None:
+def test_get_contents_page() -> None:
+ kind = "test_kind"
+
+ assert get_contents_page(kind=kind, limit=2) == {"contents": [], "cursor": None}
+
+ dataset_a = "test_dataset_a"
+ content_a = {"key": "a"}
+ expected_content_a = {"key": "a", "dataset": dataset_a}
+ upsert_response(
+ kind=kind,
+ dataset=dataset_a,
+ content=content_a,
+ http_status=HTTPStatus.OK,
+ )
+
+ content_b = {"key": "b"}
+ upsert_response(
+ kind=kind,
+ dataset="test_dataset_b",
+ content=content_b,
+ http_status=HTTPStatus.INTERNAL_SERVER_ERROR,
+ )
+
+ dataset_c = "test_dataset_c"
+ content_c = {"key": "c"}
+ expected_content_c = {"key": "c", "dataset": dataset_c}
+ upsert_response(
+ kind=kind,
+ dataset=dataset_c,
+ content=content_c,
+ http_status=HTTPStatus.OK,
+ )
+
+ content_d = {"key": "d"}
+ upsert_response(
+ kind="another_kind",
+ dataset="test_dataset_d",
+ content=content_d,
+ http_status=HTTPStatus.OK,
+ )
+
+ dataset_e = "test_dataset_e"
+ content_e = {"key": "e"}
+ expected_content_e = {"key": "e", "dataset": dataset_e}
+ upsert_response(
+ kind=kind,
+ dataset=dataset_e,
+ content=content_e,
+ http_status=HTTPStatus.OK,
+ )
+
+ response = get_contents_page(kind=kind, limit=2)
+ assert response["contents"] == [expected_content_a, expected_content_c]
+ assert response["cursor"] is not None
+ next_cursor = response["cursor"]
+
+ response = get_contents_page(kind=kind, limit=2, cursor=next_cursor)
+ assert response["contents"] == [expected_content_e]
+ assert response["cursor"] is None
+
+ with pytest.raises(InvalidCursor):
+ get_cache_reports(kind=kind, cursor="not an objectid", limit=2)
+ with pytest.raises(InvalidLimit):
+ get_cache_reports(kind=kind, cursor=next_cursor, limit=-1)
+ with pytest.raises(InvalidLimit):
+ get_cache_reports(kind=kind, cursor=next_cursor, limit=0)
+
+
diff --git a/services/api/README.md b/services/api/README.md
index 5cf8431a..55a960fe 100644
--- a/services/api/README.md
+++ b/services/api/README.md
@@ -16,0 +17,9 @@ See [../../libs/libcommon/README.md](../../libs/libcommon/README.md) for more in
+## /hub-cache endpoint
+
+The `/hub-cache` endpoint is used to cache the datasets' metadata from the Hugging Face Hub.
+
+Set environment variables to configure the application (`HUB_CACHE_` prefix):
+
+- `HUB_CACHE_BASE_URL`: the base URL of the Datasets Server. Defaults to `https://datasets-server.huggingface.co`.
+- `HUB_CACHE_NUM_RESULTS_PER_PAGE`: the number of results per page. Defaults to `1_000`.
+
@@ -21,8 +30,8 @@ See https://huggingface.co/docs/datasets-server
-- /healthcheck: ensure the app is running
-- /valid: give the list of the valid datasets
-- /is-valid: tell if a dataset is valid
-- /webhook: add, update or remove a dataset
-- /splits: list the [splits](https://huggingface.co/docs/datasets/splits.html) names for a dataset
-- /first-rows: extract the first [rows](https://huggingface.co/docs/datasets/splits.html) for a dataset split
-- /parquet: list the parquet files auto-converted for a dataset
-- /metrics: return a list of metrics in the Prometheus format
+- /healthcheck: Ensure the app is running
+- /metrics: Return a list of metrics in the Prometheus format
+- /webhook: Add, update or remove a dataset
+- /valid: Give the list of the [valid](https://huggingface.co/docs/datasets-server/valid) datasets
+- /is-valid: Tell if a dataset is [valid](https://huggingface.co/docs/datasets-server/valid)
+- /splits: List the [splits](https://huggingface.co/docs/datasets-server/splits) names for a dataset
+- /first-rows: Extract the [first rows](https://huggingface.co/docs/datasets-server/first_rows) for a dataset split
+- /parquet: List the [parquet files](https://huggingface.co/docs/datasets-server/parquet) auto-converted for a dataset
diff --git a/services/api/src/api/app.py b/services/api/src/api/app.py
index dadbe2cd..b8190115 100644
--- a/services/api/src/api/app.py
+++ b/services/api/src/api/app.py
@@ -21,0 +22 @@ from api.routes.endpoint import EndpointsDefinition, create_endpoint
+from api.routes.hub_cache import create_hub_cache_endpoint
@@ -65,0 +67 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
+ HUB_CACHE_ENDPOINT = "/hub-cache"
@@ -85,0 +88,10 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
+ Route(
+ HUB_CACHE_ENDPOINT,
+ endpoint=create_hub_cache_endpoint(
+ endpoint_url=f"{app_config.hub_cache.base_url}{HUB_CACHE_ENDPOINT}",
+ cache_kind=app_config.hub_cache.cache_kind,
+ num_results_per_page=app_config.hub_cache.num_results_per_page,
+ max_age_long=app_config.api.max_age_long,
+ max_age_short=app_config.api.max_age_short,
+ ),
+ ),
diff --git a/services/api/src/api/config.py b/services/api/src/api/config.py
index 3521e8d1..cfdf7f6e 100644
--- a/services/api/src/api/config.py
+++ b/services/api/src/api/config.py
@@ -6,0 +7 @@ from typing import List, Mapping
+from environs import Env
@@ -16,0 +18,21 @@ from libcommon.processing_graph import InputType
+HUB_CACHE_BASE_URL = "https://datasets-server.huggingface.co"
+HUB_CACHE_CACHE_KIND = "dataset-hub-cache"
+HUB_CACHE_NUM_RESULTS_PER_PAGE = 1_000
+
+
+@dataclass(frozen=True)
+class HubCacheConfig:
+ base_url: str = HUB_CACHE_BASE_URL
+ cache_kind: str = HUB_CACHE_CACHE_KIND
+ num_results_per_page: int = HUB_CACHE_NUM_RESULTS_PER_PAGE
+
+ @classmethod
+ def from_env(cls) -> "HubCacheConfig":
+ env = Env(expand_vars=True)
+ with env.prefixed("HUB_CACHE_"):
+ return cls(
+ base_url=env.str(name="BASE_URL", default=HUB_CACHE_BASE_URL),
+ cache_kind=HUB_CACHE_CACHE_KIND, # don't allow changing the cache kind
+ num_results_per_page=env.int(name="NUM_RESULTS_PER_PAGE", default=HUB_CACHE_NUM_RESULTS_PER_PAGE),
+ )
+
@@ -25,0 +48 @@ class AppConfig:
+ hub_cache: HubCacheConfig = field(default_factory=HubCacheConfig)
@@ -36,0 +60 @@ class AppConfig:
+ hub_cache=HubCacheConfig.from_env(),
diff --git a/services/api/src/api/routes/hub_cache.py b/services/api/src/api/routes/hub_cache.py
new file mode 100644
index 00000000..88f066c8
--- /dev/null
+++ b/services/api/src/api/routes/hub_cache.py
@@ -0,0 +1,38 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2022 The HuggingFace Authors.
+
+import logging
+
+from libapi.exceptions import UnexpectedApiError
+from libapi.utils import Endpoint, get_json_api_error_response, get_json_ok_response
+from libcommon.prometheus import StepProfiler
+from libcommon.simple_cache import get_contents_page
+from starlette.requests import Request
+from starlette.responses import Response
+
+
+def create_hub_cache_endpoint(
+ endpoint_url: str,
+ cache_kind: str,
+ num_results_per_page: int,
+ max_age_long: int = 0,
+ max_age_short: int = 0,
+) -> Endpoint:
+ # this endpoint is used by the frontend to know which datasets support the dataset viewer
+ # and to give their size (number of rows)
+ async def hub_cache_endpoint(request: Request) -> Response:
+ with StepProfiler(method="hub_cache_endpoint", step="all"):
+ logging.info("/hub-cache")
+ try:
+ cursor = request.query_params.get("cursor")
+
+ # TODO: add auth to only allow the Hub to call this endpoint?
+ result = get_contents_page(kind=cache_kind, limit=num_results_per_page, cursor=cursor)
+ next_cursor = result["cursor"]
+ rel_next = 'rel="next"'
+ headers = {"Link": f"<{endpoint_url}?cursor={next_cursor}>; {rel_next}"} if next_cursor else None
+ return get_json_ok_response(result["contents"], max_age=max_age_long, headers=headers)
+ except Exception as e:
+ return get_json_api_error_response(UnexpectedApiError("Unexpected error.", e), max_age=max_age_short)
+
+ return hub_cache_endpoint
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index 23af5ce9..d21e2509 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -73,0 +74,3 @@ services:
+ # hub-cache
+ HUB_CACHE_BASE_URL: http://localhost:${PORT_REVERSE_PROXY-8000}
+ HUB_CACHE_NUM_RESULTS_PER_PAGE: ${HUB_CACHE_NUM_RESULTS_PER_PAGE-1000}
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index 92ba68c5..43e71762 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -75,0 +76,3 @@ services:
+ # hub-cache
+ HUB_CACHE_BASE_URL: http://localhost:${PORT_REVERSE_PROXY-8000}
+ HUB_CACHE_NUM_RESULTS_PER_PAGE: ${HUB_CACHE_NUM_RESULTS_PER_PAGE-1000}
|
|
6f2572b5767ca18307a14e888002f29d31f21589
|
Quentin Lhoest
| 2023-09-05T10:30:19 |
less rows workers and less uvicorn workers (#1770)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 044ee460..a1355113 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -310 +310,2 @@ rows:
- uvicornNumWorkers: "9"
+ # but we only set to 2 to avoid OOM
+ uvicornNumWorkers: "2"
@@ -313 +314 @@ rows:
- replicas: 20
+ replicas: 12
|
|
405109dd7e083c2c1efc84b46b058661c5dafa94
|
Quentin Lhoest
| 2023-09-05T10:20:46 |
reduce other workers (#1769)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 4d628397..044ee460 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -344 +344 @@ workers:
- workerDifficultyMax: 100
+ workerDifficultyMax: 70
|
|
f44ee2aa76c8ba8dc9862152bcc7f7b4479889fb
|
Quentin Lhoest
| 2023-09-05T09:52:10 |
more rows (#1768)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 7552e6a9..4d628397 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -313 +313 @@ rows:
- replicas: 12
+ replicas: 20
@@ -331 +331 @@ search:
- replicas: 12
+ replicas: 4
|
|
53475cb1c7833e7b83a7e10de300c7eccea82e16
|
Sylvain Lesage
| 2023-09-04T21:33:41 |
feat: 🎸 add resources (#1765)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 919550ce..7552e6a9 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -279 +279 @@ admin:
- memory: "1Gi"
+ memory: "8Gi"
@@ -350 +350 @@ workers:
- replicas: 20
+ replicas: 60
@@ -366 +366 @@ workers:
- replicas: 8
+ replicas: 16
|
|
75ade8572c3578ba4b6b4bc1ff361c3c0509a0eb
|
Andrea Francis Soria Jimenez
| 2023-09-04T18:51:33 |
Queue metrics every 2 minutes (#1764)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 6f59cd66..919550ce 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -198,2 +198,2 @@ queueMetricsCollector:
- schedule: "0 */2 * * *"
- # every two hours
+ schedule: "*/2 * * * *"
+ # every two minutes
|
|
f199ce70c9cd1e91ff592f0383ed2ffa440ec096
|
Sylvain Lesage
| 2023-09-04T18:23:23 |
feat: 🎸 reduce the number of workers (/4) (#1763)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index f132dad6..6f59cd66 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -350 +350 @@ workers:
- replicas: 80
+ replicas: 20
@@ -366 +366 @@ workers:
- replicas: 32
+ replicas: 8
|
|
c5149d08a9bbe28b5a8051b19e10c02bdddd1f60
|
Sylvain Lesage
| 2023-09-04T16:44:23 |
feat: 🎸 reduce the max ram (#1762)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 6933adb4..f132dad6 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -350 +350 @@ workers:
- replicas: 64
+ replicas: 80
@@ -354 +354 @@ workers:
- memory: "16Gi"
+ memory: "14Gi"
@@ -357 +357 @@ workers:
- memory: "16Gi"
+ memory: "14Gi"
|
|
61d2e2533b6e54caaf2c624ffb1c33ffb059267e
|
Sylvain Lesage
| 2023-09-04T16:38:47 |
fix: 🐛 upgrade gitpython (#1761)
|
diff --git a/e2e/poetry.lock b/e2e/poetry.lock
index f7db8814..78d8b6a5 100644
--- a/e2e/poetry.lock
+++ b/e2e/poetry.lock
@@ -420 +420 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -426,2 +426,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/jobs/cache_maintenance/poetry.lock b/jobs/cache_maintenance/poetry.lock
index b051b2e9..500572f1 100644
--- a/jobs/cache_maintenance/poetry.lock
+++ b/jobs/cache_maintenance/poetry.lock
@@ -877 +877 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -883,2 +883,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/jobs/mongodb_migration/poetry.lock b/jobs/mongodb_migration/poetry.lock
index b051b2e9..500572f1 100644
--- a/jobs/mongodb_migration/poetry.lock
+++ b/jobs/mongodb_migration/poetry.lock
@@ -877 +877 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -883,2 +883,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/libs/libapi/poetry.lock b/libs/libapi/poetry.lock
index ce06d623..e7d88482 100644
--- a/libs/libapi/poetry.lock
+++ b/libs/libapi/poetry.lock
@@ -953 +953 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -959,2 +959,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/libs/libcommon/poetry.lock b/libs/libcommon/poetry.lock
index 1eb12b3c..f4f05459 100644
--- a/libs/libcommon/poetry.lock
+++ b/libs/libcommon/poetry.lock
@@ -877 +877 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -883,2 +883,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/services/admin/poetry.lock b/services/admin/poetry.lock
index 51b6bd12..860c650f 100644
--- a/services/admin/poetry.lock
+++ b/services/admin/poetry.lock
@@ -877 +877 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -883,2 +883,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/services/api/poetry.lock b/services/api/poetry.lock
index 65f6d085..5d11a355 100644
--- a/services/api/poetry.lock
+++ b/services/api/poetry.lock
@@ -923 +923 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -929,2 +929,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/services/rows/poetry.lock b/services/rows/poetry.lock
index e31f4e56..d5db5b28 100644
--- a/services/rows/poetry.lock
+++ b/services/rows/poetry.lock
@@ -934 +934 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -940,2 +940,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/services/search/poetry.lock b/services/search/poetry.lock
index 0dcd6e7d..f493dd49 100644
--- a/services/search/poetry.lock
+++ b/services/search/poetry.lock
@@ -983 +983 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -989,2 +989,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
diff --git a/services/worker/poetry.lock b/services/worker/poetry.lock
index 8e9c72b5..3b08f903 100644
--- a/services/worker/poetry.lock
+++ b/services/worker/poetry.lock
@@ -1325 +1325 @@ name = "gitpython"
-version = "3.1.32"
+version = "3.1.34"
@@ -1331,2 +1331,2 @@ files = [
- {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
- {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
+ {file = "GitPython-3.1.34-py3-none-any.whl", hash = "sha256:5d3802b98a3bae1c2b8ae0e1ff2e4aa16bcdf02c145da34d092324f599f01395"},
+ {file = "GitPython-3.1.34.tar.gz", hash = "sha256:85f7d365d1f6bf677ae51039c1ef67ca59091c7ebd5a3509aa399d4eda02d6dd"},
|
|
56cc59bf49678916804449753fb499cdaad6d65d
|
Quentin Lhoest
| 2023-09-04T16:31:45 |
More memory for workers (#1759)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 31c92569..6933adb4 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -350 +350 @@ workers:
- replicas: 100
+ replicas: 64
@@ -354 +354 @@ workers:
- memory: "8Gi"
+ memory: "16Gi"
@@ -357 +357 @@ workers:
- memory: "8Gi"
+ memory: "16Gi"
@@ -366 +366 @@ workers:
- replicas: 50
+ replicas: 32
|
|
0430d6d12a25da7b4ca4a05fde73dd8fff0e2d44
|
Sylvain Lesage
| 2023-09-04T16:29:51 |
feat: 🎸 increase resources for admin service (#1760)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 2511bf9f..31c92569 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -245 +245 @@ ingress:
- - "datasets-server.huggingface.co"
+ - "datasets-server.huggingface.co"
@@ -273 +273 @@ admin:
- replicas: 1
+ replicas: 2
@@ -279 +279 @@ admin:
- memory: "512Mi"
+ memory: "1Gi"
@@ -282 +282 @@ admin:
- memory: "4Gi"
+ memory: "8Gi"
@@ -343,2 +343 @@ workers:
- -
- deployName: "all"
+ - deployName: "all"
@@ -360,2 +359 @@ workers:
- -
- deployName: "light"
+ - deployName: "light"
|
|
6befc0b5928effd2a1df108ce9df41ab18cf965e
|
Sylvain Lesage
| 2023-09-04T14:09:54 |
ci: 🎡 upgrade github action (#1757)
|
diff --git a/.github/workflows/_e2e_tests.yml b/.github/workflows/_e2e_tests.yml
index 7819cfeb..94be4ede 100644
--- a/.github/workflows/_e2e_tests.yml
+++ b/.github/workflows/_e2e_tests.yml
@@ -22 +22 @@ jobs:
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
diff --git a/.github/workflows/_quality-python.yml b/.github/workflows/_quality-python.yml
index c00daf88..cfb711d7 100644
--- a/.github/workflows/_quality-python.yml
+++ b/.github/workflows/_quality-python.yml
@@ -24 +24 @@ jobs:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
diff --git a/.github/workflows/_unit-tests-python.yml b/.github/workflows/_unit-tests-python.yml
index 3bbe3156..58638bd8 100644
--- a/.github/workflows/_unit-tests-python.yml
+++ b/.github/workflows/_unit-tests-python.yml
@@ -25 +25 @@ jobs:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml
index 698c6f38..17d5e4fc 100644
--- a/.github/workflows/cd.yml
+++ b/.github/workflows/cd.yml
@@ -43 +43 @@ jobs:
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
@@ -78 +78 @@ jobs:
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
@@ -99 +99 @@ jobs:
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
diff --git a/.github/workflows/chart-pr.yml b/.github/workflows/chart-pr.yml
index 3946060d..5827a8b5 100644
--- a/.github/workflows/chart-pr.yml
+++ b/.github/workflows/chart-pr.yml
@@ -15 +15 @@ jobs:
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
@@ -33 +33 @@ jobs:
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
diff --git a/.github/workflows/openapi-spec.yml b/.github/workflows/openapi-spec.yml
index 4161aab7..5e5cb570 100644
--- a/.github/workflows/openapi-spec.yml
+++ b/.github/workflows/openapi-spec.yml
@@ -31 +31 @@ jobs:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
diff --git a/.github/workflows/publish-helm.yml b/.github/workflows/publish-helm.yml
index 0c176e80..82100ebc 100644
--- a/.github/workflows/publish-helm.yml
+++ b/.github/workflows/publish-helm.yml
@@ -17 +17 @@ jobs:
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index 9586e941..bd7c684d 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -18 +18 @@ jobs:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
|
|
823aa9171eb47b01c53b9518fba060f5f2bb9e3d
|
Quentin Lhoest
| 2023-09-04T13:32:06 |
Add blockedDatasets variable (#1751)
|
diff --git a/chart/templates/_env/_envWorker.tpl b/chart/templates/_env/_envWorker.tpl
index d5401ff7..087b2647 100644
--- a/chart/templates/_env/_envWorker.tpl
+++ b/chart/templates/_env/_envWorker.tpl
@@ -4,0 +5,2 @@
+- name: WORKER_BLOCKED_DATASETS
+ value: {{ .Values.worker.blockedDatasets | quote}}
diff --git a/chart/values.yaml b/chart/values.yaml
index 066ca07c..06febdd1 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -160,0 +161,2 @@ worker:
+ # comma-separated list of blocked datasets (e.g. if not supported by the Hub). No jobs will be processed for those datasets.
+ blockedDatasets: "alexandrainst/nota"
diff --git a/services/worker/src/worker/config.py b/services/worker/src/worker/config.py
index 660bfb2f..3f11ca6a 100644
--- a/services/worker/src/worker/config.py
+++ b/services/worker/src/worker/config.py
@@ -17,0 +18 @@ from libcommon.config import (
+WORKER_BLOCKED_DATASETS: List[str] = []
@@ -38,0 +40 @@ class WorkerConfig:
+ blocked_datasets: List[str] = field(default_factory=WORKER_BLOCKED_DATASETS.copy)
@@ -60,0 +63 @@ class WorkerConfig:
+ blocked_datasets=env.list(name="BLOCKED_DATASETS", default=WORKER_BLOCKED_DATASETS.copy()),
diff --git a/services/worker/src/worker/job_manager.py b/services/worker/src/worker/job_manager.py
index 5a5a4f63..af44aaa5 100644
--- a/services/worker/src/worker/job_manager.py
+++ b/services/worker/src/worker/job_manager.py
@@ -149,0 +150,8 @@ class JobManager:
+ if self.job_info["params"]["dataset"] in self.worker_config.blocked_datasets:
+ self.debug(f"the dataset={self.job_params['dataset']} is blocked, don't update the cache")
+ return {
+ "job_info": self.job_info,
+ "job_runner_version": self.job_runner.get_job_runner_version(),
+ "is_success": False,
+ "output": None,
+ }
|
|
6f7b726c7bcc500c5d6547ae59139fe04420a5cd
|
Quentin Lhoest
| 2023-09-04T12:54:57 |
Index partial parquet (#1750)
|
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index a391ef1e..df453c43 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -248 +248,5 @@ def create_search_endpoint(
- repo_file_location = f"{config}/{split}/{file_name}"
+ # For directories like "partial-train" for the file
+ # at "en/partial-train/0000.parquet" in the C4 dataset.
+ # Note that "-" is forbidden for split names so it doesn't create directory names collisions.
+ split_directory = content["url"].rsplit("/", 2)[1]
+ repo_file_location = f"{config}/{split_directory}/{file_name}"
diff --git a/services/worker/src/worker/job_runners/split/descriptive_statistics.py b/services/worker/src/worker/job_runners/split/descriptive_statistics.py
index ceb9c9ac..0b4383f8 100644
--- a/services/worker/src/worker/job_runners/split/descriptive_statistics.py
+++ b/services/worker/src/worker/job_runners/split/descriptive_statistics.py
@@ -346 +345,0 @@ def compute_descriptive_statistics_response(
- parquet_filenames = [parquet_file["filename"] for parquet_file in split_parquet_files]
@@ -351 +350,4 @@ def compute_descriptive_statistics_response(
- for parquet_filename in parquet_filenames:
+ for parquet_file in split_parquet_files:
+ # For directories like "partial-train" for the file at "en/partial-train/0000.parquet" in the C4 dataset.
+ # Note that "-" is forbidden for split names so it doesn't create directory names collisions.
+ split_directory = parquet_file["url"].rsplit("/", 2)[1]
@@ -356 +358 @@ def compute_descriptive_statistics_response(
- filename=f"{config}/{split}/{parquet_filename}",
+ filename=f"{config}/{split_directory}/{parquet_file['filename']}",
diff --git a/services/worker/src/worker/job_runners/split/duckdb_index.py b/services/worker/src/worker/job_runners/split/duckdb_index.py
index b037b8ec..41b38426 100644
--- a/services/worker/src/worker/job_runners/split/duckdb_index.py
+++ b/services/worker/src/worker/job_runners/split/duckdb_index.py
@@ -128,0 +129,4 @@ def compute_index_rows(
+ # For directories like "partial-train" for the file at "en/partial-train/0000.parquet" in the C4 dataset.
+ # Note that "-" is forbidden for split names so it doesn't create directory names collisions.
+ split_directory = split_parquet_files[0]["url"].rsplit("/", 2)[1]
+
@@ -169 +173 @@ def compute_index_rows(
- filename=f"{config}/{split}/{parquet_file}",
+ filename=f"{config}/{split_directory}/{parquet_file}",
@@ -176 +180 @@ def compute_index_rows(
- all_split_parquets = f"{duckdb_index_file_directory}/{config}/{split}/*.parquet"
+ all_split_parquets = f"{duckdb_index_file_directory}/{config}/{split_directory}/*.parquet"
@@ -190 +194 @@ def compute_index_rows(
- index_file_location = f"{config}/{split}/{DUCKDB_DEFAULT_INDEX_FILENAME}"
+ index_file_location = f"{config}/{split_directory}/{DUCKDB_DEFAULT_INDEX_FILENAME}"
diff --git a/services/worker/tests/fixtures/hub.py b/services/worker/tests/fixtures/hub.py
index a37ac73f..84598f98 100644
--- a/services/worker/tests/fixtures/hub.py
+++ b/services/worker/tests/fixtures/hub.py
@@ -859,0 +860,13 @@ def hub_responses_duckdb_index(hub_public_duckdb_index: str) -> HubDatasetTest:
[email protected]
+def hub_responses_partial_duckdb_index(hub_public_duckdb_index: str) -> HubDatasetTest:
+ return {
+ "name": hub_public_duckdb_index,
+ "config_names_response": create_config_names_response(hub_public_duckdb_index),
+ "splits_response": create_splits_response(hub_public_duckdb_index),
+ "first_rows_response": create_first_rows_response(hub_public_duckdb_index, TEXT_cols, TEXT_rows),
+ "parquet_and_info_response": create_parquet_and_info_response(
+ dataset=hub_public_duckdb_index, data_type="csv", partial=True
+ ),
+ }
+
+
diff --git a/services/worker/tests/job_runners/split/test_duckdb_index.py b/services/worker/tests/job_runners/split/test_duckdb_index.py
index 3f0cfef8..a3e16bf6 100644
--- a/services/worker/tests/job_runners/split/test_duckdb_index.py
+++ b/services/worker/tests/job_runners/split/test_duckdb_index.py
@@ -137,0 +138 @@ def get_parquet_job_runner(
+ ("partial_duckdb_index", None, None),
@@ -156,0 +158 @@ def test_compute(
+ "partial_duckdb_index": hub_responses_duckdb_index,
@@ -163,0 +166 @@ def test_compute(
+ partial = hub_dataset_name.startswith("partial_")
@@ -186,0 +190,10 @@ def test_compute(
+ app_config = (
+ app_config
+ if not partial
+ else replace(
+ app_config,
+ parquet_and_info=replace(
+ app_config.parquet_and_info, max_dataset_size=1, max_row_group_byte_size_for_copy=1
+ ),
+ )
+ )
@@ -191,0 +205,2 @@ def test_compute(
+ assert config_parquet["partial"] is partial
+
@@ -217 +232,5 @@ def test_compute(
- assert url is not None
+ assert isinstance(url, str)
+ if partial:
+ assert url.rsplit("/", 2)[1] == "partial-" + split
+ else:
+ assert url.rsplit("/", 2)[1] == split
|
|
9e0d3c4a0ce901d71043d8b50141bb7515c8a6b8
|
Andrea Francis Soria Jimenez
| 2023-09-04T12:52:26 |
fix: Error response in rows when cache is failed (#1747)
|
diff --git a/libs/libapi/src/libapi/utils.py b/libs/libapi/src/libapi/utils.py
index e39833b6..158f51d7 100644
--- a/libs/libapi/src/libapi/utils.py
+++ b/libs/libapi/src/libapi/utils.py
@@ -17,0 +18,5 @@ from libcommon.rows_utils import transform_rows
+from libcommon.simple_cache import (
+ CACHED_RESPONSE_NOT_FOUND,
+ CacheEntry,
+ get_best_response,
+)
@@ -139,0 +145,37 @@ def try_backfill_dataset_then_raise(
+def get_cache_entry_from_steps(
+ processing_steps: List[ProcessingStep],
+ dataset: str,
+ config: Optional[str],
+ split: Optional[str],
+ processing_graph: ProcessingGraph,
+ cache_max_days: int,
+ hf_endpoint: str,
+ hf_token: Optional[str] = None,
+ hf_timeout_seconds: Optional[float] = None,
+) -> CacheEntry:
+ """Gets the cache from the first successful step in the processing steps list.
+ If no successful result is found, it will return the last one even if it's an error,
+ Checks if job is still in progress by each processing step in case of no entry found.
+ Raises:
+ - [`~utils.ResponseNotFoundError`]
+ if no result is found.
+ - [`~utils.ResponseNotReadyError`]
+ if the response is not ready yet.
+
+ Returns: the cached record
+ """
+ kinds = [processing_step.cache_kind for processing_step in processing_steps]
+ best_response = get_best_response(kinds=kinds, dataset=dataset, config=config, split=split)
+ if "error_code" in best_response.response and best_response.response["error_code"] == CACHED_RESPONSE_NOT_FOUND:
+ try_backfill_dataset_then_raise(
+ processing_steps=processing_steps,
+ processing_graph=processing_graph,
+ dataset=dataset,
+ hf_endpoint=hf_endpoint,
+ hf_timeout_seconds=hf_timeout_seconds,
+ hf_token=hf_token,
+ cache_max_days=cache_max_days,
+ )
+ return best_response.response
+
+
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index 59cb63ae..45f1292b 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -359,0 +360,20 @@ class CacheEntryWithDetails(CacheEntry):
+class CachedArtifactNotFoundError(Exception):
+ kind: str
+ dataset: str
+ config: Optional[str]
+ split: Optional[str]
+
+ def __init__(
+ self,
+ kind: str,
+ dataset: str,
+ config: Optional[str],
+ split: Optional[str],
+ ):
+ super().__init__("The cache entry has not been found.")
+ self.kind = kind
+ self.dataset = dataset
+ self.config = config
+ self.split = split
+
+
@@ -526,0 +547,2 @@ def get_previous_step_or_raise(
+ if "error_code" in best_response.response and best_response.response["error_code"] == CACHED_RESPONSE_NOT_FOUND:
+ raise CachedArtifactNotFoundError(kind=best_response.kind, dataset=dataset, config=config, split=split)
diff --git a/services/api/src/api/routes/endpoint.py b/services/api/src/api/routes/endpoint.py
index 75e023f6..70552866 100644
--- a/services/api/src/api/routes/endpoint.py
+++ b/services/api/src/api/routes/endpoint.py
@@ -17,0 +18 @@ from libapi.utils import (
+ get_cache_entry_from_steps,
@@ -21 +21,0 @@ from libapi.utils import (
- try_backfill_dataset_then_raise,
@@ -25,5 +24,0 @@ from libcommon.prometheus import StepProfiler
-from libcommon.simple_cache import (
- CACHED_RESPONSE_NOT_FOUND,
- CacheEntry,
- get_best_response,
-)
@@ -60,37 +54,0 @@ class EndpointsDefinition:
-def get_cache_entry_from_steps(
- processing_steps: List[ProcessingStep],
- dataset: str,
- config: Optional[str],
- split: Optional[str],
- processing_graph: ProcessingGraph,
- cache_max_days: int,
- hf_endpoint: str,
- hf_token: Optional[str] = None,
- hf_timeout_seconds: Optional[float] = None,
-) -> CacheEntry:
- """Gets the cache from the first successful step in the processing steps list.
- If no successful result is found, it will return the last one even if it's an error,
- Checks if job is still in progress by each processing step in case of no entry found.
- Raises:
- - [`~utils.ResponseNotFoundError`]
- if no result is found.
- - [`~utils.ResponseNotReadyError`]
- if the response is not ready yet.
-
- Returns: the cached record
- """
- kinds = [processing_step.cache_kind for processing_step in processing_steps]
- best_response = get_best_response(kinds=kinds, dataset=dataset, config=config, split=split)
- if "error_code" in best_response.response and best_response.response["error_code"] == CACHED_RESPONSE_NOT_FOUND:
- try_backfill_dataset_then_raise(
- processing_steps=processing_steps,
- processing_graph=processing_graph,
- dataset=dataset,
- hf_endpoint=hf_endpoint,
- hf_timeout_seconds=hf_timeout_seconds,
- hf_token=hf_token,
- cache_max_days=cache_max_days,
- )
- return best_response.response
-
-
diff --git a/services/api/tests/routes/test_endpoint.py b/services/api/tests/routes/test_endpoint.py
index 2e1335c1..de54a72c 100644
--- a/services/api/tests/routes/test_endpoint.py
+++ b/services/api/tests/routes/test_endpoint.py
@@ -7,0 +8 @@ from libapi.exceptions import ResponseNotReadyError
+from libapi.utils import get_cache_entry_from_steps
@@ -15 +16 @@ from api.config import AppConfig, EndpointConfig
-from api.routes.endpoint import EndpointsDefinition, get_cache_entry_from_steps
+from api.routes.endpoint import EndpointsDefinition
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index da447a97..05fd330b 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -22,0 +23 @@ from libapi.utils import (
+ get_json_error_response,
@@ -30 +31 @@ from libcommon.prometheus import StepProfiler
-from libcommon.simple_cache import CachedArtifactError
+from libcommon.simple_cache import CachedArtifactError, CachedArtifactNotFoundError
@@ -152 +153 @@ def create_rows_endpoint(
- except CachedArtifactError:
+ except CachedArtifactNotFoundError:
@@ -213,0 +215,11 @@ def create_rows_endpoint(
+ except CachedArtifactError as e:
+ content = e.cache_entry_with_details["content"]
+ http_status = e.cache_entry_with_details["http_status"]
+ error_code = e.cache_entry_with_details["error_code"]
+ return get_json_error_response(
+ content=content,
+ status_code=http_status,
+ max_age=max_age_short,
+ error_code=error_code,
+ revision=revision,
+ )
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index a97a8802..a391ef1e 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -28,0 +29 @@ from libapi.utils import (
+ get_cache_entry_from_steps,
@@ -33 +33,0 @@ from libapi.utils import (
- try_backfill_dataset_then_raise,
@@ -35 +35 @@ from libapi.utils import (
-from libcommon.processing_graph import ProcessingGraph, ProcessingStep
+from libcommon.processing_graph import ProcessingGraph
@@ -37,5 +36,0 @@ from libcommon.prometheus import StepProfiler
-from libcommon.simple_cache import (
- CACHED_RESPONSE_NOT_FOUND,
- CacheEntry,
- get_best_response,
-)
@@ -119,36 +113,0 @@ def full_text_search(index_file_location: str, query: str, offset: int, length:
-def get_cache_entry_from_steps(
- processing_steps: List[ProcessingStep],
- dataset: str,
- config: Optional[str],
- split: Optional[str],
- processing_graph: ProcessingGraph,
- cache_max_days: int,
- hf_endpoint: str,
- hf_token: Optional[str] = None,
- hf_timeout_seconds: Optional[float] = None,
-) -> CacheEntry:
- """Gets the cache from the first successful step in the processing steps list.
- If no successful result is found, it will return the last one even if it's an error,
- Checks if job is still in progress by each processing step in case of no entry found.
- Raises:
- - [`~utils.ResponseNotFoundError`]
- if no result is found.
- - [`~utils.ResponseNotReadyError`]
- if the response is not ready yet.
- Returns: the cached record
- """
- kinds = [processing_step.cache_kind for processing_step in processing_steps]
- best_response = get_best_response(kinds=kinds, dataset=dataset, config=config, split=split)
- if "error_code" in best_response.response and best_response.response["error_code"] == CACHED_RESPONSE_NOT_FOUND:
- try_backfill_dataset_then_raise(
- processing_steps=processing_steps,
- processing_graph=processing_graph,
- dataset=dataset,
- hf_endpoint=hf_endpoint,
- hf_timeout_seconds=hf_timeout_seconds,
- hf_token=hf_token,
- cache_max_days=cache_max_days,
- )
- return best_response.response
-
-
diff --git a/services/worker/tests/job_runners/config/test_info.py b/services/worker/tests/job_runners/config/test_info.py
index 2b9b1983..9ebcb196 100644
--- a/services/worker/tests/job_runners/config/test_info.py
+++ b/services/worker/tests/job_runners/config/test_info.py
@@ -11 +11,5 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import (
+ CachedArtifactError,
+ CachedArtifactNotFoundError,
+ upsert_response,
+)
@@ -237 +241 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/config/test_opt_in_out_urls_count.py b/services/worker/tests/job_runners/config/test_opt_in_out_urls_count.py
index 8a06c6fb..cf2295ed 100644
--- a/services/worker/tests/job_runners/config/test_opt_in_out_urls_count.py
+++ b/services/worker/tests/job_runners/config/test_opt_in_out_urls_count.py
@@ -10 +10 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import CachedArtifactNotFoundError, upsert_response
@@ -180 +180 @@ def get_job_runner(
- "previos_step_error",
+ "previous_step_error",
@@ -252 +252 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/config/test_parquet.py b/services/worker/tests/job_runners/config/test_parquet.py
index a4f9b9ae..6c3f63ed 100644
--- a/services/worker/tests/job_runners/config/test_parquet.py
+++ b/services/worker/tests/job_runners/config/test_parquet.py
@@ -12 +12,5 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import (
+ CachedArtifactError,
+ CachedArtifactNotFoundError,
+ upsert_response,
+)
@@ -276 +280 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/config/test_parquet_and_info.py b/services/worker/tests/job_runners/config/test_parquet_and_info.py
index f3dbd42b..30c51d92 100644
--- a/services/worker/tests/job_runners/config/test_parquet_and_info.py
+++ b/services/worker/tests/job_runners/config/test_parquet_and_info.py
@@ -37 +37 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import CachedArtifactNotFoundError, upsert_response
@@ -535,6 +534,0 @@ def test_compute_splits_response_simple_csv_error(
[email protected](
- "name,error_code,cause",
- [
- ("public", "CachedResponseNotFound", None), # no cache for dataset-config-names -> CachedResponseNotFound
- ],
-)
@@ -544,3 +537,0 @@ def test_compute_splits_response_simple_csv_error_2(
- name: str,
- error_code: str,
- cause: str,
@@ -553 +544 @@ def test_compute_splits_response_simple_csv_error_2(
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/config/test_size.py b/services/worker/tests/job_runners/config/test_size.py
index 33692159..f842ca5b 100644
--- a/services/worker/tests/job_runners/config/test_size.py
+++ b/services/worker/tests/job_runners/config/test_size.py
@@ -11 +11,5 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import (
+ CachedArtifactError,
+ CachedArtifactNotFoundError,
+ upsert_response,
+)
@@ -213 +217 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/config/test_split_names_from_info.py b/services/worker/tests/job_runners/config/test_split_names_from_info.py
index 5a06b413..7701921f 100644
--- a/services/worker/tests/job_runners/config/test_split_names_from_info.py
+++ b/services/worker/tests/job_runners/config/test_split_names_from_info.py
@@ -11 +11,5 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import (
+ CachedArtifactError,
+ CachedArtifactNotFoundError,
+ upsert_response,
+)
@@ -144 +148 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/dataset/test_info.py b/services/worker/tests/job_runners/dataset/test_info.py
index 385b5fbc..eddc780d 100644
--- a/services/worker/tests/job_runners/dataset/test_info.py
+++ b/services/worker/tests/job_runners/dataset/test_info.py
@@ -11 +11,5 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import (
+ CachedArtifactError,
+ CachedArtifactNotFoundError,
+ upsert_response,
+)
@@ -242 +246 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/dataset/test_opt_in_out_urls_count.py b/services/worker/tests/job_runners/dataset/test_opt_in_out_urls_count.py
index 71d37579..427beea4 100644
--- a/services/worker/tests/job_runners/dataset/test_opt_in_out_urls_count.py
+++ b/services/worker/tests/job_runners/dataset/test_opt_in_out_urls_count.py
@@ -10 +10 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import CachedArtifactNotFoundError, upsert_response
@@ -224 +224 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/dataset/test_parquet.py b/services/worker/tests/job_runners/dataset/test_parquet.py
index 15286174..23c07899 100644
--- a/services/worker/tests/job_runners/dataset/test_parquet.py
+++ b/services/worker/tests/job_runners/dataset/test_parquet.py
@@ -11 +11,5 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import (
+ CachedArtifactError,
+ CachedArtifactNotFoundError,
+ upsert_response,
+)
@@ -198 +202 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/dataset/test_size.py b/services/worker/tests/job_runners/dataset/test_size.py
index 3d2e38d7..a3e88dca 100644
--- a/services/worker/tests/job_runners/dataset/test_size.py
+++ b/services/worker/tests/job_runners/dataset/test_size.py
@@ -11 +11,5 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import (
+ CachedArtifactError,
+ CachedArtifactNotFoundError,
+ upsert_response,
+)
@@ -296 +300 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/dataset/test_split_names.py b/services/worker/tests/job_runners/dataset/test_split_names.py
index 6832f6e9..c24a2b68 100644
--- a/services/worker/tests/job_runners/dataset/test_split_names.py
+++ b/services/worker/tests/job_runners/dataset/test_split_names.py
@@ -11 +11 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import CachedArtifactNotFoundError, upsert_response
@@ -270 +270 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/split/test_first_rows_from_streaming.py b/services/worker/tests/job_runners/split/test_first_rows_from_streaming.py
index 1cb702a2..2312659d 100644
--- a/services/worker/tests/job_runners/split/test_first_rows_from_streaming.py
+++ b/services/worker/tests/job_runners/split/test_first_rows_from_streaming.py
@@ -109 +109 @@ def test_compute(app_config: AppConfig, get_job_runner: GetJobRunner, hub_public
- ("does_not_exist_config", False, "CachedArtifactError", None),
+ ("does_not_exist_config", False, "CachedArtifactNotFoundError", None),
diff --git a/services/worker/tests/job_runners/split/test_image_url_columns.py b/services/worker/tests/job_runners/split/test_image_url_columns.py
index e1d82708..7870722c 100644
--- a/services/worker/tests/job_runners/split/test_image_url_columns.py
+++ b/services/worker/tests/job_runners/split/test_image_url_columns.py
@@ -214 +214 @@ def test_compute(
- ("doesnotexist", {}, HTTPStatus.OK, "CachedArtifactError"),
+ ("doesnotexist", {}, HTTPStatus.OK, "CachedArtifactNotFoundError"),
diff --git a/services/worker/tests/job_runners/split/test_opt_in_out_urls_count.py b/services/worker/tests/job_runners/split/test_opt_in_out_urls_count.py
index 399b4d8a..62b9c91a 100644
--- a/services/worker/tests/job_runners/split/test_opt_in_out_urls_count.py
+++ b/services/worker/tests/job_runners/split/test_opt_in_out_urls_count.py
@@ -10 +10 @@ from libcommon.resources import CacheMongoResource, QueueMongoResource
-from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.simple_cache import CachedArtifactNotFoundError, upsert_response
@@ -160 +160 @@ def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> No
- with pytest.raises(CachedArtifactError):
+ with pytest.raises(CachedArtifactNotFoundError):
diff --git a/services/worker/tests/job_runners/split/test_opt_in_out_urls_scan_from_streaming.py b/services/worker/tests/job_runners/split/test_opt_in_out_urls_scan_from_streaming.py
index 49463062..25dfacd0 100644
--- a/services/worker/tests/job_runners/split/test_opt_in_out_urls_scan_from_streaming.py
+++ b/services/worker/tests/job_runners/split/test_opt_in_out_urls_scan_from_streaming.py
@@ -215 +215 @@ def test_compute(
- ("doesnotexist", 10, {}, HTTPStatus.OK, "CachedArtifactError"),
+ ("doesnotexist", 10, {}, HTTPStatus.OK, "CachedArtifactNotFoundError"),
|
|
2c5dc44d2469db88babebde777c590f78c4fcbea
|
Polina Kazakova
| 2023-09-01T12:53:08 |
improve error messages in statistics worker (#1745)
|
diff --git a/services/worker/src/worker/job_runners/split/descriptive_statistics.py b/services/worker/src/worker/job_runners/split/descriptive_statistics.py
index 01de5099..ceb9c9ac 100644
--- a/services/worker/src/worker/job_runners/split/descriptive_statistics.py
+++ b/services/worker/src/worker/job_runners/split/descriptive_statistics.py
@@ -103,0 +104 @@ def generate_bins(
+ column_name: str,
@@ -116 +117 @@ def generate_bins(
- f"Incorrect number of bins generated, expected {n_bins}, got {len(bin_edges)}."
+ f"Incorrect number of bins generated for {column_name=}, expected {n_bins}, got {len(bin_edges)}."
@@ -123 +124 @@ def generate_bins(
- f"Incorrect number of bins generated, expected {n_bins}, got {len(bin_edges)}."
+ f"Incorrect number of bins generated for {column_name=}, expected {n_bins}, got {len(bin_edges)}."
@@ -126 +127 @@ def generate_bins(
- raise ValueError(f"Incorrect column type {column_type}. ")
+ raise ValueError(f"Incorrect column type of {column_name=}: {column_type}. ")
@@ -143 +144,3 @@ def compute_histogram(
- bins_df = generate_bins(min_value=min_value, max_value=max_value, column_type=column_type, n_bins=n_bins)
+ bins_df = generate_bins(
+ min_value=min_value, max_value=max_value, column_name=column_name, column_type=column_type, n_bins=n_bins
+ )
@@ -150 +153 @@ def compute_histogram(
- logging.debug(f"Compute histogram for {column_name}")
+ logging.debug(f"Compute histogram for {column_name=}")
@@ -155,2 +158,2 @@ def compute_histogram(
- "Got unexpected result during histogram computation: returned more bins than requested. "
- f"{n_bins=} {hist_query_result=}. "
+ f"Got unexpected result during histogram computation for {column_name=}: returned more bins than"
+ f" requested. {n_bins=} {hist_query_result=}. "
@@ -164,2 +167,2 @@ def compute_histogram(
- "Got unexpected result during histogram computation: histogram sum and number of non-null samples don't"
- f" match. histogram sum={sum(hist)}, {n_samples=}"
+ f"Got unexpected result during histogram computation for {column_name=}: "
+ f" histogram sum and number of non-null samples don't match, histogram sum={sum(hist)}, {n_samples=}"
@@ -180 +183 @@ def compute_numerical_statistics(
- logging.debug(f"Compute min, max, mean, median, std and proportion of null values for {column_name}")
+ logging.debug(f"Compute min, max, mean, median, std and proportion of null values for {column_name=}")
@@ -206 +209 @@ def compute_numerical_statistics(
- raise ValueError(f"Incorrect column type {column_type}")
+ raise ValueError(f"Incorrect column type of {column_name=}: {column_type}")
@@ -233 +235,0 @@ def compute_categorical_statistics(
- logging.debug(f"Statistics for {column_name} computed")
@@ -240,0 +243,2 @@ def compute_categorical_statistics(
+ logging.debug(f"Statistics for {column_name=} computed")
+
@@ -388 +392 @@ def compute_descriptive_statistics_response(
- logging.debug(f"Compute statistics for ClassLabel feature {feature_name}")
+ logging.debug(f"Compute statistics for ClassLabel feature '{feature_name}'")
diff --git a/services/worker/tests/job_runners/split/test_descriptive_statistics.py b/services/worker/tests/job_runners/split/test_descriptive_statistics.py
index a47a3ad7..361c894c 100644
--- a/services/worker/tests/job_runners/split/test_descriptive_statistics.py
+++ b/services/worker/tests/job_runners/split/test_descriptive_statistics.py
@@ -125 +125,3 @@ def get_parquet_and_info_job_runner(
-def count_expected_statistics_for_numerical_column(column: pd.Series, dtype: ColumnType) -> dict: # type: ignore
+def count_expected_statistics_for_numerical_column(
+ column: pd.Series, column_name: str, dtype: ColumnType # type: ignore
+) -> dict: # type: ignore
@@ -139 +141,2 @@ def count_expected_statistics_for_numerical_column(column: pd.Series, dtype: Col
- bins = generate_bins(minimum, maximum, dtype, 10) # TODO: N BINS
+ # TODO: n_bins is hardcoded here but should be fetched from the app_config.descriptive_statistics_config
+ bins = generate_bins(minimum, maximum, column_name=column_name, column_type=dtype, n_bins=10)
@@ -197 +200,3 @@ def descriptive_statistics_expected(datasets: Mapping[str, Dataset]) -> dict: #
- column_stats = count_expected_statistics_for_numerical_column(df[column_name], dtype=column_type)
+ column_stats = count_expected_statistics_for_numerical_column(
+ df[column_name], column_name=column_name, dtype=column_type
+ )
|
|
560d72910c103c68e1838573bb360459e4a2b857
|
Quentin Lhoest
| 2023-09-01T10:24:24 |
Support audio in rows and search (#1743)
|
diff --git a/libs/libcommon/src/libcommon/rows_utils.py b/libs/libcommon/src/libcommon/rows_utils.py
index af05f1a7..8031e329 100644
--- a/libs/libcommon/src/libcommon/rows_utils.py
+++ b/libs/libcommon/src/libcommon/rows_utils.py
@@ -4 +4,2 @@
-from typing import List, Optional
+from functools import partial
+from typing import List, Optional, Tuple
@@ -6,0 +8 @@ from datasets import Features
+from tqdm.contrib.concurrent import thread_map
@@ -12,0 +15,28 @@ from libcommon.viewer_utils.features import get_cell_value
+def _transform_row(
+ row_idx_and_row: Tuple[int, Row],
+ dataset: str,
+ config: str,
+ split: str,
+ features: Features,
+ assets_base_url: str,
+ assets_directory: StrPath,
+ offset: int,
+ row_idx_column: Optional[str],
+) -> Row:
+ row_idx, row = row_idx_and_row
+ return {
+ featureName: get_cell_value(
+ dataset=dataset,
+ config=config,
+ split=split,
+ row_idx=offset + row_idx if row_idx_column is None else row[row_idx_column],
+ cell=row[featureName] if featureName in row else None,
+ featureName=featureName,
+ fieldType=fieldType,
+ assets_base_url=assets_base_url,
+ assets_directory=assets_directory,
+ )
+ for (featureName, fieldType) in features.items()
+ }
+
+
@@ -24,17 +54,18 @@ def transform_rows(
- return [
- {
- featureName: get_cell_value(
- dataset=dataset,
- config=config,
- split=split,
- row_idx=offset + row_idx if row_idx_column is None else row[row_idx_column],
- cell=row[featureName] if featureName in row else None,
- featureName=featureName,
- fieldType=fieldType,
- assets_base_url=cached_assets_base_url,
- assets_directory=cached_assets_directory,
- )
- for (featureName, fieldType) in features.items()
- }
- for row_idx, row in enumerate(rows)
- ]
+ fn = partial(
+ _transform_row,
+ dataset=dataset,
+ config=config,
+ split=split,
+ features=features,
+ assets_base_url=cached_assets_base_url,
+ assets_directory=cached_assets_directory,
+ offset=offset,
+ row_idx_column=row_idx_column,
+ )
+ if "Audio(" in str(features):
+ # use multithreading to parallelize audio files processing
+ # (we use pydub which might spawn one ffmpeg process per conversion, which releases the GIL)
+ desc = f"transform_rows(audio) for {dataset}"
+ return thread_map(fn, enumerate(rows), desc=desc, total=len(rows)) # type: ignore
+ else:
+ return [fn((row_idx, row)) for row_idx, row in enumerate(rows)]
diff --git a/libs/libcommon/src/libcommon/viewer_utils/asset.py b/libs/libcommon/src/libcommon/viewer_utils/asset.py
index 55dbf532..366e6341 100644
--- a/libs/libcommon/src/libcommon/viewer_utils/asset.py
+++ b/libs/libcommon/src/libcommon/viewer_utils/asset.py
@@ -10,2 +9,0 @@ from typing import Generator, List, Tuple, TypedDict
-import soundfile # type:ignore
-from numpy import ndarray
@@ -106 +104 @@ class AudioSource(TypedDict):
-def create_audio_files(
+def create_audio_file(
@@ -112,2 +110 @@ def create_audio_files(
- array: ndarray, # type: ignore
- sampling_rate: int,
+ audio_file_path: str,
@@ -115 +112 @@ def create_audio_files(
- filename_base: str,
+ filename: str,
@@ -119,2 +115,0 @@ def create_audio_files(
- wav_filename = f"{filename_base}.wav"
- mp3_filename = f"{filename_base}.mp3"
@@ -130,7 +125,5 @@ def create_audio_files(
- wav_file_path = dir_path / wav_filename
- mp3_file_path = dir_path / mp3_filename
- if overwrite or not wav_file_path.exists():
- soundfile.write(wav_file_path, array, sampling_rate)
- if overwrite or not mp3_file_path.exists():
- segment = AudioSegment.from_wav(wav_file_path)
- segment.export(mp3_file_path, format="mp3")
+ file_path = dir_path / filename
+ if overwrite or not file_path.exists():
+ # might spawn a process to convert the audio file using ffmpeg
+ segment: AudioSegment = AudioSegment.from_file(audio_file_path)
+ segment.export(file_path, format="mp3")
@@ -138,2 +131 @@ def create_audio_files(
- {"src": f"{assets_base_url}/{url_dir_path}/{mp3_filename}", "type": "audio/mpeg"},
- {"src": f"{assets_base_url}/{url_dir_path}/{wav_filename}", "type": "audio/wav"},
+ {"src": f"{assets_base_url}/{url_dir_path}/{filename}", "type": "audio/mpeg"},
diff --git a/libs/libcommon/src/libcommon/viewer_utils/features.py b/libs/libcommon/src/libcommon/viewer_utils/features.py
index 6a0dfe6a..a6929410 100644
--- a/libs/libcommon/src/libcommon/viewer_utils/features.py
+++ b/libs/libcommon/src/libcommon/viewer_utils/features.py
@@ -4,0 +5 @@ import json
+import os
@@ -5,0 +7 @@ from io import BytesIO
+from tempfile import NamedTemporaryFile
@@ -8,0 +11,2 @@ from zlib import adler32
+import numpy as np
+import soundfile # type: ignore
@@ -24 +27,0 @@ from datasets.features.features import FeatureType, _visit
-from numpy import ndarray
@@ -29 +32 @@ from libcommon.utils import FeatureItem
-from libcommon.viewer_utils.asset import create_audio_files, create_image_file
+from libcommon.viewer_utils.asset import create_audio_file, create_image_file
@@ -64,0 +68,7 @@ def image(
+ elif (
+ isinstance(value, dict)
+ and "path" in value
+ and isinstance(value["path"], str)
+ and os.path.exists(value["path"])
+ ):
+ value = PILImage.open(value["path"])
@@ -107,6 +117 @@ def audio(
- if isinstance(value, dict) and value.get("bytes"):
- value = Audio().decode_example(value)
- try:
- array = value["array"]
- sampling_rate = value["sampling_rate"]
- except Exception as e:
+ if not isinstance(value, dict):
@@ -114 +119 @@ def audio(
- "audio cell must contain 'array' and 'sampling_rate' fields, "
+ "Audio cell must be an encoded dict of an audio sample, "
@@ -116,19 +121,35 @@ def audio(
- ) from e
- if type(array) != ndarray:
- raise TypeError("'array' field must be a numpy.ndarray")
- if type(sampling_rate) != int:
- raise TypeError("'sampling_rate' field must be an integer")
- # this function can raise, we don't catch it
- return create_audio_files(
- dataset=dataset,
- config=config,
- split=split,
- row_idx=row_idx,
- column=featureName,
- array=array,
- sampling_rate=sampling_rate,
- assets_base_url=assets_base_url,
- filename_base=append_hash_suffix("audio", json_path),
- assets_directory=assets_directory,
- overwrite=overwrite,
- )
+ )
+ if "path" in value and isinstance(value["path"], str):
+ tmp_file_suffix = os.path.splitext(value["path"])[1]
+ else:
+ tmp_file_suffix = None
+ with NamedTemporaryFile("wb", suffix=tmp_file_suffix) as tmp_audio_file:
+ if "bytes" in value and isinstance(value["bytes"], bytes):
+ with open(tmp_audio_file.name, "wb") as f:
+ f.write(value["bytes"])
+ audio_file_path = tmp_audio_file.name
+ elif "path" in value and isinstance(value["path"], str) and os.path.exists(value["path"]):
+ audio_file_path = value["path"]
+ elif (
+ "array" in value
+ and isinstance(value["array"], np.ndarray)
+ and "sampling_rate" in value
+ and isinstance(value["sampling_rate"], int)
+ ):
+ soundfile.write(tmp_audio_file.name, value["array"], value["sampling_rate"], format="wav")
+ audio_file_path = tmp_audio_file.name
+ else:
+ raise ValueError(f"An audio sample should have one of 'path' or 'bytes' but both are None in {value}.")
+ # this function can raise, we don't catch it
+ return create_audio_file(
+ dataset=dataset,
+ config=config,
+ split=split,
+ row_idx=row_idx,
+ column=featureName,
+ audio_file_path=audio_file_path,
+ assets_base_url=assets_base_url,
+ filename=f"{append_hash_suffix('audio', json_path)}.mp3",
+ assets_directory=assets_directory,
+ overwrite=overwrite,
+ )
diff --git a/libs/libcommon/tests/viewer_utils/test_features.py b/libs/libcommon/tests/viewer_utils/test_features.py
index 50f62a9b..b28c4b49 100644
--- a/libs/libcommon/tests/viewer_utils/test_features.py
+++ b/libs/libcommon/tests/viewer_utils/test_features.py
@@ -138,5 +138 @@ def test_value(
- },
- {
- "src": "http://localhost/assets/dataset/--/config/split/7/col/audio.wav",
- "type": "audio/wav",
- },
+ }
@@ -191,4 +186,0 @@ def test_value(
- {
- "src": "http://localhost/assets/dataset/--/config/split/7/col/audio-1d100e9.wav",
- "type": "audio/wav",
- },
@@ -201,4 +192,0 @@ def test_value(
- {
- "src": "http://localhost/assets/dataset/--/config/split/7/col/audio-1d300ea.wav",
- "type": "audio/wav",
- },
@@ -233,4 +220,0 @@ def test_value(
- {
- "src": "http://localhost/assets/dataset/--/config/split/7/col/audio-1d100e9.wav",
- "type": "audio/wav",
- },
@@ -243,4 +226,0 @@ def test_value(
- {
- "src": "http://localhost/assets/dataset/--/config/split/7/col/audio-1d300ea.wav",
- "type": "audio/wav",
- },
@@ -274,4 +253,0 @@ def test_value(
- {
- "src": "http://localhost/assets/dataset/--/config/split/7/col/audio-18360330.wav",
- "type": "audio/wav",
- },
@@ -284,4 +259,0 @@ def test_value(
- {
- "src": "http://localhost/assets/dataset/--/config/split/7/col/audio-18380331.wav",
- "type": "audio/wav",
- },
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index be4310a9..a97a8802 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -16 +16 @@ import pyarrow as pa
-from datasets import Audio, Features, Value
+from datasets import Features, Value
@@ -56 +56 @@ MAX_ROWS = 100
-UNSUPPORTED_FEATURES = [Value("binary"), Audio()]
+UNSUPPORTED_FEATURES = [Value("binary")]
diff --git a/services/worker/tests/fixtures/hub.py b/services/worker/tests/fixtures/hub.py
index 35037c8f..a37ac73f 100644
--- a/services/worker/tests/fixtures/hub.py
+++ b/services/worker/tests/fixtures/hub.py
@@ -570,4 +569,0 @@ def get_AUDIO_rows(dataset: str) -> Any:
- {
- "src": f"http://localhost/assets/{dataset}/--/{config}/{split}/0/col/audio.wav",
- "type": "audio/wav",
- },
|
|
92d6676e91df92e643b76dd86971667bbdabf520
|
Quentin Lhoest
| 2023-08-31T22:57:01 |
Search for nested data (#1735)
|
diff --git a/services/worker/src/worker/job_runners/split/duckdb_index.py b/services/worker/src/worker/job_runners/split/duckdb_index.py
index 33061ae4..b037b8ec 100644
--- a/services/worker/src/worker/job_runners/split/duckdb_index.py
+++ b/services/worker/src/worker/job_runners/split/duckdb_index.py
@@ -3,0 +4 @@
+import copy
@@ -9,0 +11 @@ import duckdb
+from datasets.features.features import Features, FeatureType, Value, _visit
@@ -65,0 +68,16 @@ class DuckdbIndexWithFeatures(SplitHubFile):
+def get_indexable_columns(features: Features) -> List[str]:
+ indexable_columns: List[str] = []
+ for column, feature in features.items():
+ indexable = False
+
+ def check_indexable(feature: FeatureType) -> None:
+ nonlocal indexable
+ if isinstance(feature, Value) and feature.dtype == "string":
+ indexable = True
+
+ _visit(feature, check_indexable)
+ if indexable:
+ indexable_columns.append(column)
+ return indexable_columns
+
+
@@ -115,10 +133,6 @@ def compute_index_rows(
- # look for string columns
- string_columns = [
- column
- for column, feature in features.items()
- if "dtype" in feature
- and "_type" in feature
- and feature["dtype"] == STRING_FEATURE_DTYPE
- and feature["_type"] == VALUE_FEATURE_TYPE
- ]
- if not string_columns:
+ # look for indexable columns (= possibly nested columns containing string data)
+ # copy the features is needed but will be fixed with https://github.com/huggingface/datasets/pull/6189
+ indexable_columns = ",".join(
+ '"' + column + '"' for column in get_indexable_columns(Features.from_dict(copy.deepcopy(features)))
+ )
+ if not indexable_columns:
@@ -169 +183 @@ def compute_index_rows(
- create_index_sql = CREATE_INDEX_COMMAND.format(columns=column_names)
+ create_index_sql = CREATE_INDEX_COMMAND.format(columns=indexable_columns)
diff --git a/services/worker/tests/job_runners/split/test_duckdb_index.py b/services/worker/tests/job_runners/split/test_duckdb_index.py
index 925346d4..3f0cfef8 100644
--- a/services/worker/tests/job_runners/split/test_duckdb_index.py
+++ b/services/worker/tests/job_runners/split/test_duckdb_index.py
@@ -7 +7 @@ from http import HTTPStatus
-from typing import Callable, Optional
+from typing import Callable, List, Optional
@@ -9 +8,0 @@ from typing import Callable, Optional
-import datasets
@@ -10,0 +10 @@ import duckdb
+import pandas as pd
@@ -12,0 +13 @@ import requests
+from datasets import Features, Image, Sequence, Value
@@ -21 +22,7 @@ from worker.job_runners.config.parquet_and_info import ConfigParquetAndInfoJobRu
-from worker.job_runners.split.duckdb_index import SplitDuckDbIndexJobRunner
+from worker.job_runners.split.duckdb_index import (
+ CREATE_INDEX_COMMAND,
+ CREATE_SEQUENCE_COMMAND,
+ CREATE_TABLE_COMMAND,
+ SplitDuckDbIndexJobRunner,
+ get_indexable_columns,
+)
@@ -212 +219 @@ def test_compute(
- assert datasets.Features.from_dict(features) is not None
+ assert Features.from_dict(features) is not None
@@ -251,0 +259,57 @@ def test_compute(
+
+
[email protected](
+ "features, expected",
+ [
+ (Features({"col_1": Value("string"), "col_2": Value("int64")}), ["col_1"]),
+ (
+ Features(
+ {
+ "nested_1": [Value("string")],
+ "nested_2": Sequence(Value("string")),
+ "nested_3": Sequence({"foo": Value("string")}),
+ "nested_4": {"foo": Value("string"), "bar": Value("int64")},
+ "nested_int": [Value("int64")],
+ }
+ ),
+ ["nested_1", "nested_2", "nested_3", "nested_4"],
+ ),
+ (Features({"col_1": Image()}), []),
+ ],
+)
+def test_get_indexable_columns(features: Features, expected: List[str]) -> None:
+ indexable_columns = get_indexable_columns(features)
+ assert indexable_columns == expected
+
+
+DATA = """Hello there !
+General Kenobi.
+You are a bold one.
+Kill him !
+...
+Back away ! I will deal with this Jedi slime myself"""
+
+
+FTS_COMMAND = (
+ "SELECT * EXCLUDE (__hf_fts_score) FROM (SELECT *, fts_main_data.match_bm25(__hf_index_id, ?) AS __hf_fts_score"
+ " FROM data) A WHERE __hf_fts_score IS NOT NULL ORDER BY __hf_index_id;"
+)
+
+
[email protected](
+ "df, query, expected_ids",
+ [
+ (pd.DataFrame([{"line": line} for line in DATA.split("\n")]), "bold", [2]),
+ (pd.DataFrame([{"nested": [line]} for line in DATA.split("\n")]), "bold", [2]),
+ (pd.DataFrame([{"nested": {"foo": line}} for line in DATA.split("\n")]), "bold", [2]),
+ (pd.DataFrame([{"nested": [{"foo": line}]} for line in DATA.split("\n")]), "bold", [2]),
+ (pd.DataFrame([{"nested": [{"foo": line, "bar": 0}]} for line in DATA.split("\n")]), "bold", [2]),
+ ],
+)
+def test_index_command(df: pd.DataFrame, query: str, expected_ids: List[int]) -> None:
+ columns = ",".join('"' + str(column) + '"' for column in df.columns)
+ duckdb.sql(CREATE_SEQUENCE_COMMAND)
+ duckdb.sql(CREATE_TABLE_COMMAND.format(columns=columns) + " df;")
+ duckdb.sql(CREATE_INDEX_COMMAND.format(columns=columns))
+ result = duckdb.execute(FTS_COMMAND, parameters=[query]).df()
+ assert list(result.__hf_index_id) == expected_ids
|
|
fdba2ab8a460977a4a57b9de393ec7bec7bc1f9e
|
Quentin Lhoest
| 2023-08-31T10:18:19 |
ignore vuln (#1746)
|
diff --git a/.github/workflows/_quality-python.yml b/.github/workflows/_quality-python.yml
index 74f10fca..c00daf88 100644
--- a/.github/workflows/_quality-python.yml
+++ b/.github/workflows/_quality-python.yml
@@ -52 +52 @@ jobs:
- run: bash -c "poetry run pip-audit --ignore-vuln GHSA-wfm5-v35h-vwf4 -r <(poetry export -f requirements.txt --with dev | sed '/^kenlm @/d' | sed '/^torch @/d' | sed '/^libapi @/d' | sed '/^libcommon @/d' | sed '/^trec-car-tools @/d' | sed 's/^huggingface-hub @ git.*/huggingface-hub==0.15.1 ; python_full_version == \"3.9.15\" --hash=sha256:05b0fb0abbf1f625dfee864648ac3049fe225ac4371c7bafaca0c2d3a2f83445 --hash=sha256:a61b7d1a7769fe10119e730277c72ab99d95c48d86a3d6da3e9f3d0f632a4081/')"
+ run: bash -c "poetry run pip-audit --ignore-vuln GHSA-wfm5-v35h-vwf4 --ignore-vuln GHSA-cwvm-v4w8-q58c -r <(poetry export -f requirements.txt --with dev | sed '/^kenlm @/d' | sed '/^torch @/d' | sed '/^libapi @/d' | sed '/^libcommon @/d' | sed '/^trec-car-tools @/d' | sed 's/^huggingface-hub @ git.*/huggingface-hub==0.15.1 ; python_full_version == \"3.9.15\" --hash=sha256:05b0fb0abbf1f625dfee864648ac3049fe225ac4371c7bafaca0c2d3a2f83445 --hash=sha256:a61b7d1a7769fe10119e730277c72ab99d95c48d86a3d6da3e9f3d0f632a4081/')"
diff --git a/tools/Python.mk b/tools/Python.mk
index e45fc11f..dfefec45 100644
--- a/tools/Python.mk
+++ b/tools/Python.mk
@@ -31 +31 @@ pip-audit:
- bash -c "poetry run pip-audit --ignore-vuln GHSA-wfm5-v35h-vwf4 -r <(poetry export -f requirements.txt --with dev | sed '/^kenlm @/d' |sed '/^torch @/d' | sed '/^libapi @/d' | sed '/^libcommon @/d' | sed '/^trec-car-tools @/d')"
+ bash -c "poetry run pip-audit --ignore-vuln GHSA-wfm5-v35h-vwf4 --ignore-vuln GHSA-cwvm-v4w8-q58c -r <(poetry export -f requirements.txt --with dev | sed '/^kenlm @/d' |sed '/^torch @/d' | sed '/^libapi @/d' | sed '/^libcommon @/d' | sed '/^trec-car-tools @/d')"
|
|
fed4257b88b0491af32a60889b1cb83d6c10e9f2
|
Quentin Lhoest
| 2023-08-31T10:03:39 |
ignore gitpython vuln (#1744)
|
diff --git a/.github/workflows/_quality-python.yml b/.github/workflows/_quality-python.yml
index 39c3fb2b..74f10fca 100644
--- a/.github/workflows/_quality-python.yml
+++ b/.github/workflows/_quality-python.yml
@@ -52 +52 @@ jobs:
- run: bash -c "poetry run pip-audit -r <(poetry export -f requirements.txt --with dev | sed '/^kenlm @/d' | sed '/^torch @/d' | sed '/^libapi @/d' | sed '/^libcommon @/d' | sed '/^trec-car-tools @/d' | sed 's/^huggingface-hub @ git.*/huggingface-hub==0.15.1 ; python_full_version == \"3.9.15\" --hash=sha256:05b0fb0abbf1f625dfee864648ac3049fe225ac4371c7bafaca0c2d3a2f83445 --hash=sha256:a61b7d1a7769fe10119e730277c72ab99d95c48d86a3d6da3e9f3d0f632a4081/')"
+ run: bash -c "poetry run pip-audit --ignore-vuln GHSA-wfm5-v35h-vwf4 -r <(poetry export -f requirements.txt --with dev | sed '/^kenlm @/d' | sed '/^torch @/d' | sed '/^libapi @/d' | sed '/^libcommon @/d' | sed '/^trec-car-tools @/d' | sed 's/^huggingface-hub @ git.*/huggingface-hub==0.15.1 ; python_full_version == \"3.9.15\" --hash=sha256:05b0fb0abbf1f625dfee864648ac3049fe225ac4371c7bafaca0c2d3a2f83445 --hash=sha256:a61b7d1a7769fe10119e730277c72ab99d95c48d86a3d6da3e9f3d0f632a4081/')"
diff --git a/tools/Python.mk b/tools/Python.mk
index 91e40366..e45fc11f 100644
--- a/tools/Python.mk
+++ b/tools/Python.mk
@@ -31 +31 @@ pip-audit:
- bash -c "poetry run pip-audit -r <(poetry export -f requirements.txt --with dev | sed '/^kenlm @/d' |sed '/^torch @/d' | sed '/^libapi @/d' | sed '/^libcommon @/d' | sed '/^trec-car-tools @/d')"
+ bash -c "poetry run pip-audit --ignore-vuln GHSA-wfm5-v35h-vwf4 -r <(poetry export -f requirements.txt --with dev | sed '/^kenlm @/d' |sed '/^torch @/d' | sed '/^libapi @/d' | sed '/^libcommon @/d' | sed '/^trec-car-tools @/d')"
|
|
19f6480e0df33dd60f831ae2683ce56c36401993
|
Quentin Lhoest
| 2023-08-29T14:16:43 |
add error msg (#1741)
|
diff --git a/front/admin_ui/app.py b/front/admin_ui/app.py
index c63bdb55..83f863f6 100644
--- a/front/admin_ui/app.py
+++ b/front/admin_ui/app.py
@@ -212,2 +212,2 @@ with gr.Blocks() as demo:
- cached_responses_table: gr.update(value=None),
- jobs_table: gr.update(value=None)
+ cached_responses_table: gr.update(value=pd.DataFrame([{"error": f"❌ Failed to get status for {dataset} (error {response.status_code})"}])),
+ jobs_table: gr.update(value=pd.DataFrame([{"content": str(response.content)}]))
@@ -307 +307 @@ if __name__ == "__main__":
- demo.launch()
+ demo.launch()
\ No newline at end of file
|
|
060a008dacd9bbfd783d9476908aec51e73313a6
|
Polina Kazakova
| 2023-08-29T09:23:14 |
Raise custom disk error in job runners with cache when `PermissionError` is raised (#1738)
|
diff --git a/libs/libcommon/src/libcommon/exceptions.py b/libs/libcommon/src/libcommon/exceptions.py
index fd4c17e9..d7032deb 100644
--- a/libs/libcommon/src/libcommon/exceptions.py
+++ b/libs/libcommon/src/libcommon/exceptions.py
@@ -89,0 +90 @@ CacheableErrorCode = Literal[
+ "DiskError",
@@ -256,0 +258,13 @@ class DisabledViewerError(CacheableError):
+class DiskError(CacheableError):
+ """Disk-related issues, for example, incorrect permissions."""
+
+ def __init__(self, message: str, cause: Optional[BaseException] = None):
+ super().__init__(
+ message=message,
+ status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
+ code="DiskError",
+ cause=cause,
+ disclose_cause=False,
+ )
+
+
@@ -468,0 +483,7 @@ class SplitWithTooBigParquetError(CacheableError):
+class StatisticsComputationError(CacheableError):
+ """An unexpected behavior or error occurred during statistics computations."""
+
+ def __init__(self, message: str, cause: Optional[BaseException] = None):
+ super().__init__(message, HTTPStatus.INTERNAL_SERVER_ERROR, "ComputationError", cause, True)
+
+
@@ -515,7 +535,0 @@ class UnsupportedExternalFilesError(CacheableError):
-
-
-class StatisticsComputationError(CacheableError):
- """An unexpected behavior or error occurred during statistics computations."""
-
- def __init__(self, message: str, cause: Optional[BaseException] = None):
- super().__init__(message, HTTPStatus.INTERNAL_SERVER_ERROR, "ComputationError", cause, True)
diff --git a/services/worker/src/worker/job_runners/_job_runner_with_cache.py b/services/worker/src/worker/job_runners/_job_runner_with_cache.py
index 1eca7d3b..0c0c30c0 100644
--- a/services/worker/src/worker/job_runners/_job_runner_with_cache.py
+++ b/services/worker/src/worker/job_runners/_job_runner_with_cache.py
@@ -10,0 +11 @@ from typing import Optional
+from libcommon.exceptions import DiskError
@@ -56 +57,4 @@ class JobRunnerWithCache(JobRunner):
- self.cache_subdirectory = Path(init_dir(new_directory))
+ try:
+ self.cache_subdirectory = Path(init_dir(new_directory))
+ except PermissionError as e:
+ raise DiskError(f"Incorrect permissions on {new_directory}", e) from e
|
|
a6a92fa0219a1fa4bdd12d85b5337c34ca03f532
|
Sylvain Lesage
| 2023-08-28T16:16:38 |
feat: 🎸 create step dataset-hub-cache (#1732)
|
diff --git a/libs/libcommon/src/libcommon/config.py b/libs/libcommon/src/libcommon/config.py
index f4341e09..35f76992 100644
--- a/libs/libcommon/src/libcommon/config.py
+++ b/libs/libcommon/src/libcommon/config.py
@@ -21,0 +22 @@ from libcommon.constants import (
+ PROCESSING_STEP_DATASET_HUB_CACHE_VERSION,
@@ -370,0 +372,6 @@ class ProcessingGraphConfig:
+ "dataset-hub-cache": {
+ "input_type": "dataset",
+ "triggered_by": ["dataset-is-valid", "dataset-size"],
+ "job_runner_version": PROCESSING_STEP_DATASET_HUB_CACHE_VERSION,
+ "difficulty": 20,
+ },
diff --git a/libs/libcommon/src/libcommon/constants.py b/libs/libcommon/src/libcommon/constants.py
index e4633925..94195102 100644
--- a/libs/libcommon/src/libcommon/constants.py
+++ b/libs/libcommon/src/libcommon/constants.py
@@ -35,0 +36 @@ PROCESSING_STEP_DATASET_CONFIG_NAMES_VERSION = 1
+PROCESSING_STEP_DATASET_HUB_CACHE_VERSION = 1
diff --git a/libs/libcommon/tests/test_backfill_on_real_graph.py b/libs/libcommon/tests/test_backfill_on_real_graph.py
index 13cb97bb..d412b1cc 100644
--- a/libs/libcommon/tests/test_backfill_on_real_graph.py
+++ b/libs/libcommon/tests/test_backfill_on_real_graph.py
@@ -53,0 +54 @@ def test_plan_job_creation_and_termination() -> None:
+ "dataset-hub-cache,dataset,revision",
@@ -68 +69 @@ def test_plan_job_creation_and_termination() -> None:
- tasks=["CreateJobs,7"],
+ tasks=["CreateJobs,8"],
@@ -86,0 +88 @@ def test_plan_job_creation_and_termination() -> None:
+ "dataset-hub-cache,dataset,revision",
@@ -101,0 +104 @@ def test_plan_job_creation_and_termination() -> None:
+ "dataset-hub-cache,dataset,revision",
@@ -160,0 +164 @@ def test_plan_job_creation_and_termination() -> None:
+ "dataset-hub-cache,dataset,revision",
@@ -174,0 +179 @@ def test_plan_job_creation_and_termination() -> None:
+ "dataset-hub-cache,dataset,revision",
diff --git a/libs/libcommon/tests/test_processing_graph.py b/libs/libcommon/tests/test_processing_graph.py
index c00cf7e4..10f536a5 100644
--- a/libs/libcommon/tests/test_processing_graph.py
+++ b/libs/libcommon/tests/test_processing_graph.py
@@ -193 +193 @@ def graph() -> ProcessingGraph:
- [],
+ ["dataset-hub-cache"],
@@ -199 +199 @@ def graph() -> ProcessingGraph:
- [],
+ ["dataset-hub-cache"],
@@ -333,0 +334,22 @@ def graph() -> ProcessingGraph:
+ (
+ "dataset-hub-cache",
+ [],
+ ["dataset-is-valid", "dataset-size"],
+ [
+ "config-info",
+ "config-is-valid",
+ "config-parquet",
+ "config-parquet-and-info",
+ "config-parquet-metadata",
+ "config-size",
+ "config-split-names-from-info",
+ "config-split-names-from-streaming",
+ "dataset-config-names",
+ "dataset-is-valid",
+ "dataset-size",
+ "split-duckdb-index",
+ "split-first-rows-from-parquet",
+ "split-first-rows-from-streaming",
+ "split-is-valid",
+ ],
+ ),
diff --git a/services/worker/src/worker/dtos.py b/services/worker/src/worker/dtos.py
index 3e23217a..54c9d197 100644
--- a/services/worker/src/worker/dtos.py
+++ b/services/worker/src/worker/dtos.py
@@ -191,0 +192,7 @@ class IsValidResponse(TypedDict):
+class DatasetHubCacheResponse(TypedDict):
+ preview: bool
+ viewer: bool
+ partial: bool
+ num_rows: int
+
+
diff --git a/services/worker/src/worker/job_runner_factory.py b/services/worker/src/worker/job_runner_factory.py
index 5c79b92f..1372b859 100644
--- a/services/worker/src/worker/job_runner_factory.py
+++ b/services/worker/src/worker/job_runner_factory.py
@@ -29,0 +30 @@ from worker.job_runners.dataset.config_names import DatasetConfigNamesJobRunner
+from worker.job_runners.dataset.hub_cache import DatasetHubCacheJobRunner
@@ -253,0 +255,7 @@ class JobRunnerFactory(BaseJobRunnerFactory):
+ if job_type == DatasetHubCacheJobRunner.get_job_type():
+ return DatasetHubCacheJobRunner(
+ job_info=job_info,
+ app_config=self.app_config,
+ processing_step=processing_step,
+ )
+
@@ -276,0 +285 @@ class JobRunnerFactory(BaseJobRunnerFactory):
+ DatasetHubCacheJobRunner.get_job_type(),
diff --git a/services/worker/src/worker/job_runners/dataset/hub_cache.py b/services/worker/src/worker/job_runners/dataset/hub_cache.py
new file mode 100644
index 00000000..fff8337a
--- /dev/null
+++ b/services/worker/src/worker/job_runners/dataset/hub_cache.py
@@ -0,0 +1,91 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+from typing import Tuple
+
+from libcommon.constants import PROCESSING_STEP_DATASET_HUB_CACHE_VERSION
+from libcommon.exceptions import PreviousStepFormatError
+from libcommon.simple_cache import get_previous_step_or_raise
+
+from worker.dtos import DatasetHubCacheResponse, JobResult
+from worker.job_runners.dataset.dataset_job_runner import DatasetJobRunner
+
+
+def compute_hub_cache_response(dataset: str) -> Tuple[DatasetHubCacheResponse, float]:
+ """
+ Get the response of /hub-cache for one specific dataset on huggingface.co.
+
+
+ Its purpose is specific to the Hub, and we won't ensure backward compatibility for this step.
+ It provides information about:
+ - the capabilities of the dataset: preview and viewer
+ - the number of rows and if the dataset is partial
+
+ Args:
+ dataset (`str`):
+ A namespace (user or an organization) and a repo name separated
+ by a `/`.
+ Returns:
+ `Tuple[DatasetHubCacheResponse, float]`: The response and the progress.
+ """
+ logging.info(f"get hub_cache response for {dataset=}")
+
+ is_valid_response = get_previous_step_or_raise(kinds=["dataset-is-valid"], dataset=dataset)
+ content = is_valid_response.response["content"]
+ if (
+ "preview" not in content
+ or not isinstance(content["preview"], bool)
+ or "viewer" not in content
+ or not isinstance(content["viewer"], bool)
+ ):
+ raise PreviousStepFormatError(
+ "Previous step 'dataset-is-valid' did not return the expected content: 'preview', 'viewer' or 'progress'."
+ )
+ preview = content["preview"]
+ viewer = content["viewer"]
+ is_valid_progress = is_valid_response.response["progress"]
+
+ size_response = get_previous_step_or_raise(kinds=["dataset-size"], dataset=dataset)
+ content = size_response.response["content"]
+ if (
+ "partial" not in content
+ or not isinstance(content["partial"], bool)
+ or "size" not in content
+ or "dataset" not in content["size"]
+ or "num_rows" not in content["size"]["dataset"]
+ or not isinstance(content["size"]["dataset"]["num_rows"], int)
+ ):
+ raise PreviousStepFormatError(
+ "Previous step 'dataset-size' did not return the expected content: 'partial' or 'size.dataset.num_rows'."
+ )
+
+ partial = content["partial"]
+ num_rows = content["size"]["dataset"]["num_rows"]
+ size_progress = size_response.response["progress"]
+
+ progress = min((p for p in [is_valid_progress, size_progress] if p is not None), default=0.0)
+
+ return (
+ DatasetHubCacheResponse(
+ preview=preview,
+ viewer=viewer,
+ partial=partial,
+ num_rows=num_rows,
+ ),
+ progress,
+ )
+
+
+class DatasetHubCacheJobRunner(DatasetJobRunner):
+ @staticmethod
+ def get_job_type() -> str:
+ return "dataset-hub-cache"
+
+ @staticmethod
+ def get_job_runner_version() -> int:
+ return PROCESSING_STEP_DATASET_HUB_CACHE_VERSION
+
+ def compute(self) -> JobResult:
+ response_content, progress = compute_hub_cache_response(dataset=self.dataset)
+ return JobResult(response_content, progress=progress)
diff --git a/services/worker/tests/job_runners/dataset/test_hub_cache.py b/services/worker/tests/job_runners/dataset/test_hub_cache.py
new file mode 100644
index 00000000..dceda179
--- /dev/null
+++ b/services/worker/tests/job_runners/dataset/test_hub_cache.py
@@ -0,0 +1,155 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+from http import HTTPStatus
+from typing import Any, Callable, List
+
+import pytest
+from libcommon.processing_graph import ProcessingGraph
+from libcommon.resources import CacheMongoResource, QueueMongoResource
+from libcommon.simple_cache import CachedArtifactError, upsert_response
+from libcommon.utils import Priority
+
+from worker.config import AppConfig
+from worker.job_runners.dataset.hub_cache import DatasetHubCacheJobRunner
+
+from ..utils import UpstreamResponse
+
+
[email protected](autouse=True)
+def prepare_and_clean_mongo(app_config: AppConfig) -> None:
+ # prepare the database before each test, and clean it afterwards
+ pass
+
+
+GetJobRunner = Callable[[str, AppConfig], DatasetHubCacheJobRunner]
+
+DATASET = "dataset"
+
+UPSTREAM_RESPONSE_IS_VALID_OK: UpstreamResponse = UpstreamResponse(
+ kind="dataset-is-valid",
+ dataset=DATASET,
+ http_status=HTTPStatus.OK,
+ content={"preview": True, "viewer": False, "search": True},
+ progress=0.5,
+)
+UPSTREAM_RESPONSE_IS_VALID_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="dataset-is-valid",
+ dataset=DATASET,
+ http_status=HTTPStatus.INTERNAL_SERVER_ERROR,
+ content={},
+ progress=0.0,
+)
+UPSTREAM_RESPONSE_SIZE_OK: UpstreamResponse = UpstreamResponse(
+ kind="dataset-size",
+ dataset=DATASET,
+ http_status=HTTPStatus.OK,
+ content={"size": {"dataset": {"num_rows": 1000}}, "partial": False},
+ progress=0.2,
+)
+UPSTREAM_RESPONSE_SIZE_NO_PROGRESS: UpstreamResponse = UpstreamResponse(
+ kind="dataset-size",
+ dataset=DATASET,
+ http_status=HTTPStatus.OK,
+ content={"size": {"dataset": {"num_rows": 1000}}, "partial": True},
+ progress=None,
+)
+EXPECTED_OK = (
+ {"viewer": False, "preview": True, "partial": False, "num_rows": 1000},
+ 0.2,
+)
+EXPECTED_NO_PROGRESS = (
+ {"viewer": False, "preview": True, "partial": True, "num_rows": 1000},
+ 0.5,
+)
+
+
[email protected]
+def get_job_runner(
+ cache_mongo_resource: CacheMongoResource,
+ queue_mongo_resource: QueueMongoResource,
+) -> GetJobRunner:
+ def _get_job_runner(
+ dataset: str,
+ app_config: AppConfig,
+ ) -> DatasetHubCacheJobRunner:
+ processing_step_name = DatasetHubCacheJobRunner.get_job_type()
+ processing_graph = ProcessingGraph(app_config.processing_graph.specification)
+ return DatasetHubCacheJobRunner(
+ job_info={
+ "type": DatasetHubCacheJobRunner.get_job_type(),
+ "params": {
+ "dataset": dataset,
+ "config": None,
+ "split": None,
+ "revision": "revision",
+ },
+ "job_id": "job_id",
+ "priority": Priority.NORMAL,
+ "difficulty": 20,
+ },
+ app_config=app_config,
+ processing_step=processing_graph.get_processing_step(processing_step_name),
+ )
+
+ return _get_job_runner
+
+
[email protected](
+ "upstream_responses,expected",
+ [
+ (
+ [
+ UPSTREAM_RESPONSE_IS_VALID_OK,
+ UPSTREAM_RESPONSE_SIZE_OK,
+ ],
+ EXPECTED_OK,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_IS_VALID_OK,
+ UPSTREAM_RESPONSE_SIZE_NO_PROGRESS,
+ ],
+ EXPECTED_NO_PROGRESS,
+ ),
+ ],
+)
+def test_compute(
+ app_config: AppConfig,
+ get_job_runner: GetJobRunner,
+ upstream_responses: List[UpstreamResponse],
+ expected: Any,
+) -> None:
+ dataset = DATASET
+ for upstream_response in upstream_responses:
+ upsert_response(**upstream_response)
+ job_runner = get_job_runner(dataset, app_config)
+ compute_result = job_runner.compute()
+ assert compute_result.content == expected[0]
+ assert compute_result.progress == expected[1]
+
+
[email protected](
+ "upstream_responses,expectation",
+ [
+ (
+ [
+ UPSTREAM_RESPONSE_IS_VALID_ERROR,
+ UPSTREAM_RESPONSE_SIZE_OK,
+ ],
+ pytest.raises(CachedArtifactError),
+ )
+ ],
+)
+def test_compute_error(
+ app_config: AppConfig,
+ get_job_runner: GetJobRunner,
+ upstream_responses: List[UpstreamResponse],
+ expectation: Any,
+) -> None:
+ dataset = DATASET
+ for upstream_response in upstream_responses:
+ upsert_response(**upstream_response)
+ job_runner = get_job_runner(dataset, app_config)
+ with expectation:
+ job_runner.compute()
diff --git a/services/worker/tests/job_runners/utils.py b/services/worker/tests/job_runners/utils.py
index 04d80f76..932d7a32 100644
--- a/services/worker/tests/job_runners/utils.py
+++ b/services/worker/tests/job_runners/utils.py
@@ -17,0 +18 @@ class UpstreamResponse(_UpstreamResponse, total=False):
+ progress: Optional[float]
|
|
f78f0ff5e29593658bc4c1f18fdaaf42866b93d8
|
Quentin Lhoest
| 2023-08-28T16:14:56 |
block open-llm-leaderboard (#1734)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index abb4f17b..2511bf9f 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -132 +132 @@ parquetAndInfo:
- blockedDatasets: "Graphcore/gqa,Graphcore/gqa-lxmert,Graphcore/vqa,Graphcore/vqa-lxmert,echarlaix/gqa-lxmert,echarlaix/vqa,echarlaix/vqa-lxmert,KakologArchives/KakologArchives"
+ blockedDatasets: "Graphcore/gqa,Graphcore/gqa-lxmert,Graphcore/vqa,Graphcore/vqa-lxmert,echarlaix/gqa-lxmert,echarlaix/vqa,echarlaix/vqa-lxmert,KakologArchives/KakologArchives,open-llm-leaderboard/*"
diff --git a/services/worker/src/worker/job_runners/config/parquet_and_info.py b/services/worker/src/worker/job_runners/config/parquet_and_info.py
index 71737fd5..013d3fbc 100644
--- a/services/worker/src/worker/job_runners/config/parquet_and_info.py
+++ b/services/worker/src/worker/job_runners/config/parquet_and_info.py
@@ -8,0 +9 @@ from contextlib import ExitStack
+from fnmatch import fnmatch
@@ -194,0 +196,2 @@ def raise_if_blocked(
+ Patterns are supported, e.g. "open-llm-leaderboard/*"
+
@@ -201,5 +204,6 @@ def raise_if_blocked(
- if dataset in blocked_datasets:
- raise DatasetInBlockListError(
- "The parquet conversion has been disabled for this dataset for now. Please open an issue in"
- " https://github.com/huggingface/datasets-server if you want this dataset to be supported."
- )
+ for blocked_dataset in blocked_datasets:
+ if fnmatch(dataset, blocked_dataset):
+ raise DatasetInBlockListError(
+ "The parquet conversion has been disabled for this dataset for now. Please open an issue in"
+ " https://github.com/huggingface/datasets-server if you want this dataset to be supported."
+ )
|
|
44ab0bc336ddc99380e0b783277f47d92cadda79
|
Sylvain Lesage
| 2023-08-28T14:54:39 |
feat: 🎸 increase the number of pods for /search (#1736)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 915c7bfe..abb4f17b 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -331 +331 @@ search:
- replicas: 2
+ replicas: 12
|
|
adcd2932f1576ef7995c01e232867c491de15b88
|
Guillaume LEGENDRE
| 2023-08-28T14:49:33 |
fix tailscale (#1737)
|
diff --git a/.github/workflows/chart-pr.yml b/.github/workflows/chart-pr.yml
index 93880b23..3946060d 100644
--- a/.github/workflows/chart-pr.yml
+++ b/.github/workflows/chart-pr.yml
@@ -38 +38 @@ jobs:
- uses: tailscale/github-action@v1
+ uses: tailscale/github-action@main
@@ -40,0 +41 @@ jobs:
+ version: ${{ vars.TAILSCALE_CLIENT_VERSION }}
|
|
008c0c8bc7d6cc6d21927b2759cef96b05970edc
|
Quentin Lhoest
| 2023-08-27T16:11:20 |
Add TTL for unicity_id locks (#1728)
|
diff --git a/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230825170200_lock_add_ttl.py b/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230825170200_lock_add_ttl.py
new file mode 100644
index 00000000..258624ee
--- /dev/null
+++ b/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230825170200_lock_add_ttl.py
@@ -0,0 +1,30 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+
+from libcommon.constants import QUEUE_COLLECTION_LOCKS, QUEUE_MONGOENGINE_ALIAS
+from libcommon.queue import Lock
+from mongoengine.connection import get_db
+
+from mongodb_migration.check import check_documents
+from mongodb_migration.migration import Migration
+
+
+# connection already occurred in the main.py (caveat: we use globals)
+class MigrationAddTtlToQueueLock(Migration):
+ def up(self) -> None:
+ # See https://docs.mongoengine.org/guide/migration.html#example-1-addition-of-a-field
+ logging.info("If missing, add the ttl field to the locks")
+ db = get_db(QUEUE_MONGOENGINE_ALIAS)
+ db[QUEUE_COLLECTION_LOCKS].update_many({"ttl": {"$exists": False}}, [{"$set": {"ttl": None}}]) # type: ignore
+
+ def down(self) -> None:
+ logging.info("Remove the ttl field from all the locks")
+ db = get_db(QUEUE_MONGOENGINE_ALIAS)
+ db[QUEUE_COLLECTION_LOCKS].update_many({}, {"$unset": {"ttl": ""}})
+
+ def validate(self) -> None:
+ logging.info("Ensure that a random selection of locks have the 'ttl' field")
+
+ check_documents(DocCls=Lock, sample_size=10)
diff --git a/jobs/mongodb_migration/tests/migrations/test_20230825170200_lock_add_ttl.py b/jobs/mongodb_migration/tests/migrations/test_20230825170200_lock_add_ttl.py
new file mode 100644
index 00000000..852c6807
--- /dev/null
+++ b/jobs/mongodb_migration/tests/migrations/test_20230825170200_lock_add_ttl.py
@@ -0,0 +1,64 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2022 The HuggingFace Authors.
+
+from typing import Optional
+
+from libcommon.constants import QUEUE_COLLECTION_LOCKS, QUEUE_MONGOENGINE_ALIAS
+from libcommon.resources import MongoResource
+from mongoengine.connection import get_db
+
+from mongodb_migration.migrations._20230825170200_lock_add_ttl import (
+ MigrationAddTtlToQueueLock,
+)
+
+
+def assert_ttl(key: str, ttl: Optional[int]) -> None:
+ db = get_db(QUEUE_MONGOENGINE_ALIAS)
+ entry = db[QUEUE_COLLECTION_LOCKS].find_one({"key": key})
+ assert entry is not None
+ if ttl is None:
+ assert "ttl" not in entry or entry["ttl"] is None
+ else:
+ assert entry["ttl"] == ttl
+
+
+def test_lock_add_ttl(mongo_host: str) -> None:
+ with MongoResource(database="test_lock_add_ttl", host=mongo_host, mongoengine_alias="queue"):
+ db = get_db(QUEUE_MONGOENGINE_ALIAS)
+ db[QUEUE_COLLECTION_LOCKS].insert_many(
+ [
+ {
+ "key": "key1",
+ "owner": "job_id1",
+ "created_at": "2022-01-01T00:00:00.000000Z",
+ },
+ {
+ "key": "key2",
+ "owner": None,
+ "created_at": "2022-01-01T00:00:00.000000Z",
+ },
+ {
+ "key": "key3",
+ "owner": "job_id3",
+ "ttl": 600,
+ "created_at": "2022-01-01T00:00:00.000000Z",
+ },
+ ]
+ )
+
+ migration = MigrationAddTtlToQueueLock(
+ version="20230825170200",
+ description="add ttl field to locks",
+ )
+ migration.up()
+
+ assert_ttl("key1", None)
+ assert_ttl("key2", None)
+ assert_ttl("key3", 600)
+
+ migration.down()
+ assert_ttl("key1", None)
+ assert_ttl("key2", None)
+ assert_ttl("key3", None)
+
+ db[QUEUE_COLLECTION_LOCKS].drop()
diff --git a/libs/libcommon/src/libcommon/queue.py b/libs/libcommon/src/libcommon/queue.py
index c77ec220..ffd5d3ef 100644
--- a/libs/libcommon/src/libcommon/queue.py
+++ b/libs/libcommon/src/libcommon/queue.py
@@ -287 +287 @@ class Lock(Document):
- "partialFilterExpression": {"owner": None},
+ "partialFilterExpression": {"$or": [{"owner": None}, {"ttl": LOCK_TTL_SECONDS}]},
@@ -293,0 +294 @@ class Lock(Document):
+ ttl = IntField()
@@ -330 +331,3 @@ class lock(contextlib.AbstractContextManager["lock"]):
- def __init__(self, key: str, owner: str, sleeps: Sequence[float] = _default_sleeps) -> None:
+ def __init__(
+ self, key: str, owner: str, sleeps: Sequence[float] = _default_sleeps, ttl: Optional[int] = None
+ ) -> None:
@@ -333,0 +337,3 @@ class lock(contextlib.AbstractContextManager["lock"]):
+ self.ttl = ttl
+ if ttl is not None and ttl != LOCK_TTL_SECONDS:
+ raise ValueError(f"Only TTL of LOCK_TTL_SECONDS={LOCK_TTL_SECONDS} is supported by the TTL index.")
@@ -343,0 +350 @@ class lock(contextlib.AbstractContextManager["lock"]):
+ ttl=self.ttl,
@@ -666 +673 @@ class Queue:
- with lock(key=job.unicity_id, owner=lock_owner, sleeps=[0.1] * RETRIES):
+ with lock(key=job.unicity_id, owner=lock_owner, sleeps=[0.1] * RETRIES, ttl=LOCK_TTL_SECONDS):
|
|
7f2ab512aab2c710869a386f43b8e898c32ff173
|
Andrea Francis Soria Jimenez
| 2023-08-25T19:38:33 |
fix: Change score alias name in FST query (#1730)
|
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index 5e7a5960..be4310a9 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -59,2 +59,2 @@ FTS_COMMAND_COUNT = (
- "SELECT COUNT(*) FROM (SELECT __hf_index_id, fts_main_data.match_bm25(__hf_index_id, ?) AS score FROM"
- " data) A WHERE score IS NOT NULL;"
+ "SELECT COUNT(*) FROM (SELECT __hf_index_id, fts_main_data.match_bm25(__hf_index_id, ?) AS __hf_fts_score FROM"
+ " data) A WHERE __hf_fts_score IS NOT NULL;"
@@ -64,2 +64,2 @@ FTS_COMMAND = (
- "SELECT * EXCLUDE (score) FROM (SELECT *, fts_main_data.match_bm25(__hf_index_id, ?) AS score FROM "
- "data) A WHERE score IS NOT NULL ORDER BY __hf_index_id OFFSET {offset} LIMIT {length};"
+ "SELECT * EXCLUDE (__hf_fts_score) FROM (SELECT *, fts_main_data.match_bm25(__hf_index_id, ?) AS __hf_fts_score"
+ " FROM data) A WHERE __hf_fts_score IS NOT NULL ORDER BY __hf_index_id OFFSET {offset} LIMIT {length};"
|
|
9443cf55c19e312688a33e9dbb6d4a9e13972e19
|
Polina Kazakova
| 2023-08-25T14:45:27 |
Download parquet files with huggingface_hub instead of duckdb in `split-descriptive-statistics` (#1719)
|
diff --git a/e2e/tests/test_11_api.py b/e2e/tests/test_11_api.py
index d380be47..fcdac99a 100644
--- a/e2e/tests/test_11_api.py
+++ b/e2e/tests/test_11_api.py
@@ -61,0 +62 @@ def test_auth_e2e(
+ ("/statistics", "split"),
diff --git a/services/worker/src/worker/config.py b/services/worker/src/worker/config.py
index 1a33da61..660bfb2f 100644
--- a/services/worker/src/worker/config.py
+++ b/services/worker/src/worker/config.py
@@ -297,0 +298 @@ class DescriptiveStatisticsConfig:
+ parquet_revision: str = PARQUET_AND_INFO_TARGET_REVISION
@@ -303,0 +305 @@ class DescriptiveStatisticsConfig:
+ parquet_revision = env.str(name="PARQUET_AND_INFO_TARGET_REVISION", default=PARQUET_AND_INFO_TARGET_REVISION)
@@ -306,0 +309 @@ class DescriptiveStatisticsConfig:
+ parquet_revision=parquet_revision,
diff --git a/services/worker/src/worker/job_runners/split/descriptive_statistics.py b/services/worker/src/worker/job_runners/split/descriptive_statistics.py
index 15548c9e..01de5099 100644
--- a/services/worker/src/worker/job_runners/split/descriptive_statistics.py
+++ b/services/worker/src/worker/job_runners/split/descriptive_statistics.py
@@ -2,0 +3 @@
+
@@ -4,0 +6 @@ import logging
+import os
@@ -10,0 +13 @@ import pandas as pd
+from huggingface_hub import hf_hub_download
@@ -31 +34 @@ from worker.utils import check_split_exists
-PARQUET_FILENAME = "dataset.parquet"
+REPO_TYPE = "dataset"
@@ -38,0 +42,2 @@ NUMERICAL_DTYPES = INTEGER_DTYPES + FLOAT_DTYPES
+BINS_TABLE_NAME = "bins" # name of a table with bin edges data used to compute histogram
+
@@ -40,3 +44,0 @@ NUMERICAL_DTYPES = INTEGER_DTYPES + FLOAT_DTYPES
-COPY_PARQUET_DATA_COMMAND = """
-COPY (SELECT * FROM read_parquet({parquet_files_urls})) TO '{local_parquet_path}' (FORMAT PARQUET);
-"""
@@ -55,2 +57,2 @@ COMPUTE_HIST_COMMAND = """
- JOIN bins ON ({column_name} >= bin_min AND {column_name} < bin_max) GROUP BY bin_id;
-""" # `bins` is the name of preinjected table with bin edges data
+ JOIN {bins_table_name} ON ({column_name} >= bin_min AND {column_name} < bin_max) GROUP BY bin_id;
+"""
@@ -143,2 +145,5 @@ def compute_histogram(
- con.sql("CREATE OR REPLACE TEMPORARY TABLE bins AS SELECT * from bins_df")
- compute_hist_command = COMPUTE_HIST_COMMAND.format(parquet_filename=parquet_filename, column_name=column_name)
+ # create auxiliary table with bin edges
+ con.sql(f"CREATE OR REPLACE TEMPORARY TABLE {BINS_TABLE_NAME} AS SELECT * from bins_df") # nosec
+ compute_hist_command = COMPUTE_HIST_COMMAND.format(
+ parquet_filename=parquet_filename, bins_table_name=BINS_TABLE_NAME, column_name=column_name
+ )
@@ -248,0 +254,2 @@ def compute_descriptive_statistics_response(
+ hf_token: Optional[str],
+ parquet_revision: str,
@@ -251,0 +259,42 @@ def compute_descriptive_statistics_response(
+ """
+ Compute statistics and get response for the `split-descriptive-statistics` step.
+ Currently, integers, floats and ClassLabel features are supported.
+ Args:
+ dataset (`str`):
+ Name of a dataset.
+ config (`str`):
+ Requested dataset configuration name.
+ split (`str`):
+ Requested dataset split.
+ local_parquet_directory (`Path`):
+ Path to a local directory where the dataset's parquet files are stored. We download these files locally
+ because it enables fast querying and statistics computation.
+ hf_token (`str`, `optional`):
+ An app authentication token with read access to all the datasets.
+ parquet_revision (`str`):
+ The git revision (e.g. "ref/convert/parquet") from where to download the dataset's parquet files.
+ histogram_num_bins (`int`):
+ (Maximum) number of bins to compute histogram for numerical data.
+ The resulting number of bins might be lower than the requested one for integer data.
+ max_parquet_size_bytes (`int`):
+ The maximum size in bytes of the dataset's parquet files to compute statistics.
+ Datasets with bigger size are ignored.
+
+ Returns:
+ `SplitDescriptiveStatisticsResponse`: An object with the statistics response for a requested split, per each
+ numerical (int and float) or ClassLabel feature.
+
+ Raises the following errors:
+ - [`libcommon.exceptions.PreviousStepFormatError`]
+ If the content of the previous step does not have the expected format.
+ - [`libcommon.exceptions.ParquetResponseEmptyError`]
+ If response for `config-parquet-and-info` doesn't have any parquet files.
+ - [`libcommon.exceptions.SplitWithTooBigParquetError`]
+ If requested split's parquet files size exceeds the provided `max_parquet_size_bytes`.
+ - [`libcommon.exceptions.NoSupportedFeaturesError`]
+ If requested dataset doesn't have any supported for statistics computation features.
+ Currently, floats, integers and ClassLabels are supported.
+ - [`libcommon.exceptions.StatisticsComputationError`]
+ If there was some unexpected behaviour during statistics computation.
+ """
+
@@ -293 +342,18 @@ def compute_descriptive_statistics_response(
- parquet_files_urls = [parquet_file["url"] for parquet_file in split_parquet_files]
+ parquet_filenames = [parquet_file["filename"] for parquet_file in split_parquet_files]
+
+ # store data as local parquet files for fast querying
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
+ logging.info(f"Downloading remote parquet files to a local directory {local_parquet_directory}. ")
+ for parquet_filename in parquet_filenames:
+ hf_hub_download(
+ repo_type=REPO_TYPE,
+ revision=parquet_revision,
+ repo_id=dataset,
+ filename=f"{config}/{split}/{parquet_filename}",
+ local_dir=local_parquet_directory,
+ local_dir_use_symlinks=False,
+ token=hf_token,
+ cache_dir=local_parquet_directory,
+ )
+
+ local_parquet_glob_path = Path(local_parquet_directory) / config / f"{split}/*.parquet"
@@ -318,9 +383,0 @@ def compute_descriptive_statistics_response(
- # store data as local parquet file for fast querying
- local_parquet_path = (
- Path(local_parquet_directory) / PARQUET_FILENAME if local_parquet_directory else Path(PARQUET_FILENAME)
- )
- logging.info(f"Downloading remote data to a local parquet file {local_parquet_path}. ")
- con.sql(
- COPY_PARQUET_DATA_COMMAND.format(parquet_files_urls=parquet_files_urls, local_parquet_path=local_parquet_path)
- )
-
@@ -338 +395 @@ def compute_descriptive_statistics_response(
- parquet_filename=local_parquet_path,
+ parquet_filename=local_parquet_glob_path,
@@ -355 +412 @@ def compute_descriptive_statistics_response(
- parquet_filename=local_parquet_path,
+ parquet_filename=local_parquet_glob_path,
@@ -408,0 +466,2 @@ class SplitDescriptiveStatisticsJobRunner(SplitJobRunnerWithCache):
+ hf_token=self.app_config.common.hf_token,
+ parquet_revision=self.descriptive_statistics_config.parquet_revision,
diff --git a/services/worker/tests/fixtures/hub.py b/services/worker/tests/fixtures/hub.py
index ff6a5008..35037c8f 100644
--- a/services/worker/tests/fixtures/hub.py
+++ b/services/worker/tests/fixtures/hub.py
@@ -198,0 +199,11 @@ def hub_gated_duckdb_index(datasets: Mapping[str, Dataset]) -> Iterator[str]:
[email protected](scope="session")
+def hub_gated_descriptive_statistics(datasets: Mapping[str, Dataset]) -> Iterator[str]:
+ repo_id = create_hub_dataset_repo(
+ prefix="descriptive_statistics_gated",
+ dataset=datasets["descriptive_statistics"],
+ gated="auto",
+ )
+ yield repo_id
+ delete_hub_dataset_repo(repo_id=repo_id)
+
+
@@ -872,0 +884,11 @@ def hub_responses_descriptive_statistics(hub_public_descriptive_statistics: str)
+
+
[email protected]
+def hub_responses_gated_descriptive_statistics(hub_gated_descriptive_statistics: str) -> HubDatasetTest:
+ return {
+ "name": hub_gated_descriptive_statistics,
+ "config_names_response": create_config_names_response(hub_gated_descriptive_statistics),
+ "splits_response": create_splits_response(hub_gated_descriptive_statistics),
+ "first_rows_response": None,
+ "parquet_and_info_response": None,
+ }
diff --git a/services/worker/tests/job_runners/split/test_descriptive_statistics.py b/services/worker/tests/job_runners/split/test_descriptive_statistics.py
index f849d793..a47a3ad7 100644
--- a/services/worker/tests/job_runners/split/test_descriptive_statistics.py
+++ b/services/worker/tests/job_runners/split/test_descriptive_statistics.py
@@ -219,0 +220 @@ def descriptive_statistics_expected(datasets: Mapping[str, Dataset]) -> dict: #
+ ("gated", None),
@@ -228,0 +230 @@ def test_compute(
+ hub_responses_gated_descriptive_statistics: HubDatasetTest,
@@ -236,0 +239 @@ def test_compute(
+ "gated": hub_responses_gated_descriptive_statistics,
|
|
1847b40e7fe51dfef1c24c2330e801a1e4a6d4a5
|
Quentin Lhoest
| 2023-08-25T10:20:04 |
Use features in search (#1725)
|
diff --git a/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230824154900_cache_add_features_field_in_split_duckdb_index.py b/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230824154900_cache_add_features_field_in_split_duckdb_index.py
new file mode 100644
index 00000000..bd3f09db
--- /dev/null
+++ b/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230824154900_cache_add_features_field_in_split_duckdb_index.py
@@ -0,0 +1,46 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+
+from libcommon.constants import CACHE_COLLECTION_RESPONSES, CACHE_MONGOENGINE_ALIAS
+from libcommon.simple_cache import CachedResponseDocument
+from mongoengine.connection import get_db
+
+from mongodb_migration.check import check_documents
+from mongodb_migration.migration import Migration
+
+
+# connection already occurred in the main.py (caveat: we use globals)
+class MigrationAddFeaturesToSplitDuckdbIndexCacheResponse(Migration):
+ def up(self) -> None:
+ # See https://docs.mongoengine.org/guide/migration.html#example-1-addition-of-a-field
+ logging.info(
+ "If missing, add the features field with the default value (None) to the cached results of"
+ " split-duckdb-index"
+ )
+ db = get_db(CACHE_MONGOENGINE_ALIAS)
+ db[CACHE_COLLECTION_RESPONSES].update_many(
+ {
+ "kind": "split-duckdb-index",
+ "http_status": 200,
+ "content.features": {"$exists": False},
+ },
+ {"$set": {"content.features": None}},
+ )
+
+ def down(self) -> None:
+ logging.info("Remove the features field from all the cached results")
+ db = get_db(CACHE_MONGOENGINE_ALIAS)
+ db[CACHE_COLLECTION_RESPONSES].update_many(
+ {
+ "kind": "split-duckdb-index",
+ "http_status": 200,
+ },
+ {"$unset": {"content.features": ""}},
+ )
+
+ def validate(self) -> None:
+ logging.info("Ensure that a random selection of cached results have the 'features' field")
+
+ check_documents(DocCls=CachedResponseDocument, sample_size=10)
diff --git a/jobs/mongodb_migration/tests/migrations/test_20230824154900_cache_add_features_field_in_split_duckdb_index.py b/jobs/mongodb_migration/tests/migrations/test_20230824154900_cache_add_features_field_in_split_duckdb_index.py
new file mode 100644
index 00000000..0a018e4b
--- /dev/null
+++ b/jobs/mongodb_migration/tests/migrations/test_20230824154900_cache_add_features_field_in_split_duckdb_index.py
@@ -0,0 +1,118 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2022 The HuggingFace Authors.
+from typing import Any, Dict, List
+
+from libcommon.constants import CACHE_COLLECTION_RESPONSES, CACHE_MONGOENGINE_ALIAS
+from libcommon.resources import MongoResource
+from mongoengine.connection import get_db
+
+from mongodb_migration.migrations._20230824154900_cache_add_features_field_in_split_duckdb_index import (
+ MigrationAddFeaturesToSplitDuckdbIndexCacheResponse,
+)
+
+
+def assert_features(dataset: str, kind: str) -> None:
+ db = get_db(CACHE_MONGOENGINE_ALIAS)
+ entry = db[CACHE_COLLECTION_RESPONSES].find_one({"dataset": dataset, "kind": kind})
+ assert entry is not None
+ assert entry["content"]["features"] is None
+
+
+def assert_unchanged(dataset: str, kind: str) -> None:
+ db = get_db(CACHE_MONGOENGINE_ALIAS)
+ entry = db[CACHE_COLLECTION_RESPONSES].find_one({"dataset": dataset, "kind": kind})
+ assert entry is not None
+ assert "features" not in entry["content"]
+
+
+cache: List[Dict[str, Any]] = [
+ {
+ "config": "lhoestq--demo1",
+ "dataset": "lhoestq/demo1",
+ "kind": "split-duckdb-index",
+ "split": "train",
+ "content": {
+ "dataset": "lhoestq/demo1",
+ "config": "default",
+ "split": "train",
+ "url": "https://huggingface.co/.../index.duckdb",
+ "filename": "index.duckdb",
+ "size": 5038,
+ },
+ "dataset_git_revision": "87ecf163bedca9d80598b528940a9c4f99e14c11",
+ "details": None,
+ "error_code": None,
+ "http_status": 200,
+ "job_runner_version": 3,
+ "progress": 1.0,
+ },
+ {
+ "config": "lhoestq--error",
+ "dataset": "lhoestq/error",
+ "kind": "split-duckdb-index",
+ "split": "train",
+ "content": {"error": "Streaming is not supported for lhoestq/error"},
+ "dataset_git_revision": "ec3c8d414af3dfe600399f5e6ef2c682938676f3",
+ "details": {
+ "error": "Streaming is not supported for lhoestq/error",
+ "cause_exception": "TypeError",
+ "cause_message": "Streaming is not supported for lhoestq/error",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ (
+ ' File "/src/services/worker/src/worker/job_manager.py", line 163, in process\n '
+ " job_result = self.job_runner.compute()\n"
+ ),
+ (
+ ' File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line'
+ " 932, in compute\n compute_config_parquet_and_info_response(\n"
+ ),
+ (
+ ' File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line'
+ " 825, in compute_config_parquet_and_info_response\n raise_if_not_supported(\n"
+ ),
+ (
+ ' File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line'
+ " 367, in raise_if_not_supported\n raise_if_too_big_from_external_data_files(\n"
+ ),
+ (
+ ' File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line'
+ " 447, in raise_if_too_big_from_external_data_files\n "
+ " builder._split_generators(mock_dl_manager)\n"
+ ),
+ (
+ " File"
+ ' "/tmp/modules-cache/datasets_modules/.../error.py",'
+ ' line 190, in _split_generators\n raise TypeError("Streaming is not supported for'
+ ' lhoestq/error")\n'
+ ),
+ "TypeError: Streaming is not supported for lhoestq/error\n",
+ ],
+ },
+ "error_code": "UnexpectedError",
+ "http_status": 500,
+ "job_runner_version": 3,
+ "progress": None,
+ },
+]
+
+
+def test_cache_add_features(mongo_host: str) -> None:
+ with MongoResource(database="test_cache_add_features", host=mongo_host, mongoengine_alias="cache"):
+ db = get_db(CACHE_MONGOENGINE_ALIAS)
+ db[CACHE_COLLECTION_RESPONSES].insert_many(cache)
+
+ migration = MigrationAddFeaturesToSplitDuckdbIndexCacheResponse(
+ version="20230824154900",
+ description="add features field to split-duckdb-index",
+ )
+ migration.up()
+
+ assert_features("lhoestq/demo1", kind="split-duckdb-index")
+ assert_unchanged("lhoestq/error", kind="split-duckdb-index")
+
+ migration.down()
+ assert_unchanged("lhoestq/demo1", kind="split-duckdb-index")
+ assert_unchanged("lhoestq/error", kind="split-duckdb-index")
+
+ db[CACHE_COLLECTION_RESPONSES].drop()
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index 408cfa51..5e7a5960 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -16 +16 @@ import pyarrow as pa
-from datasets import Audio, Features, Image, Value
+from datasets import Audio, Features, Value
@@ -56 +56 @@ MAX_ROWS = 100
-UNSUPPORTED_FEATURES = [Value("binary"), Audio(), Image()]
+UNSUPPORTED_FEATURES = [Value("binary"), Audio()]
@@ -162,0 +163 @@ def create_response(
+ features: Features,
@@ -165,2 +165,0 @@ def create_response(
- features = Features.from_arrow_schema(pa_table.schema)
-
@@ -330,0 +330,4 @@ def create_search_endpoint(
+ if "features" in content and isinstance(content["features"], dict):
+ features = Features.from_dict(content["features"])
+ else:
+ features = Features.from_arrow_schema(pa_table.schema)
@@ -338,0 +342 @@ def create_search_endpoint(
+ features,
diff --git a/services/worker/src/worker/job_runners/split/duckdb_index.py b/services/worker/src/worker/job_runners/split/duckdb_index.py
index ba42e53a..33061ae4 100644
--- a/services/worker/src/worker/job_runners/split/duckdb_index.py
+++ b/services/worker/src/worker/job_runners/split/duckdb_index.py
@@ -7 +7 @@ from pathlib import Path
-from typing import List, Optional, Set
+from typing import Any, List, Optional, Set
@@ -61,0 +62,4 @@ HUB_DOWNLOAD_CACHE_FOLDER = "cache"
+class DuckdbIndexWithFeatures(SplitHubFile):
+ features: Optional[dict[str, Any]]
+
+
@@ -76 +80 @@ def compute_index_rows(
-) -> SplitHubFile:
+) -> DuckdbIndexWithFeatures:
@@ -245 +249,4 @@ def compute_index_rows(
- return SplitHubFile(
+ # we added the __hf_index_id column for the index
+ features["__hf_index_id"] = {"dtype": "int64", "_type": "Value"}
+
+ return DuckdbIndexWithFeatures(
@@ -257,0 +265 @@ def compute_index_rows(
+ features=features,
diff --git a/services/worker/tests/job_runners/split/test_duckdb_index.py b/services/worker/tests/job_runners/split/test_duckdb_index.py
index 687e6492..925346d4 100644
--- a/services/worker/tests/job_runners/split/test_duckdb_index.py
+++ b/services/worker/tests/job_runners/split/test_duckdb_index.py
@@ -8,0 +9 @@ from typing import Callable, Optional
+import datasets
@@ -207,0 +209 @@ def test_compute(
+ features = content["features"]
@@ -209,0 +212 @@ def test_compute(
+ assert datasets.Features.from_dict(features) is not None
|
|
201142fc3a95be0e2ccd8f577e3e3d8b596bd092
|
Quentin Lhoest
| 2023-08-24T15:16:43 |
block KakologArchives/KakologArchives (#1724)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 72fc224b..915c7bfe 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -132 +132 @@ parquetAndInfo:
- blockedDatasets: "Graphcore/gqa,Graphcore/gqa-lxmert,Graphcore/vqa,Graphcore/vqa-lxmert,echarlaix/gqa-lxmert,echarlaix/vqa,echarlaix/vqa-lxmert"
+ blockedDatasets: "Graphcore/gqa,Graphcore/gqa-lxmert,Graphcore/vqa,Graphcore/vqa-lxmert,echarlaix/gqa-lxmert,echarlaix/vqa,echarlaix/vqa-lxmert,KakologArchives/KakologArchives"
|
|
07a290a9eaaa71f2597b9e1376294a1aa8461eac
|
Sylvain Lesage
| 2023-08-23T21:41:57 |
fix: 🐛 expose X-Error-Code and X-Revision headers to browser (#1723)
|
diff --git a/libs/libapi/src/libapi/utils.py b/libs/libapi/src/libapi/utils.py
index 68053db4..e39833b6 100644
--- a/libs/libapi/src/libapi/utils.py
+++ b/libs/libapi/src/libapi/utils.py
@@ -55,0 +56,7 @@ def get_json_response(
+# these headers are exposed to the client (browser)
+EXPOSED_HEADERS = [
+ "X-Error-Code",
+ "X-Revision",
+]
+
+
diff --git a/services/admin/src/admin/app.py b/services/admin/src/admin/app.py
index 8c712f84..e6bf4475 100644
--- a/services/admin/src/admin/app.py
+++ b/services/admin/src/admin/app.py
@@ -34,0 +35 @@ from admin.routes.pending_jobs import create_pending_jobs_endpoint
+from admin.utils import EXPOSED_HEADERS
@@ -63 +64,6 @@ def create_app() -> Starlette:
- CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], allow_credentials=True
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+ allow_credentials=True,
+ expose_headers=EXPOSED_HEADERS,
diff --git a/services/admin/src/admin/utils.py b/services/admin/src/admin/utils.py
index 2644012d..12c357b8 100644
--- a/services/admin/src/admin/utils.py
+++ b/services/admin/src/admin/utils.py
@@ -101,0 +102,5 @@ def get_json_response(
+EXPOSED_HEADERS = [
+ "X-Error-Code",
+]
+
+
diff --git a/services/api/src/api/app.py b/services/api/src/api/app.py
index b7e050d3..dadbe2cd 100644
--- a/services/api/src/api/app.py
+++ b/services/api/src/api/app.py
@@ -8,0 +9 @@ from libapi.routes.metrics import create_metrics_endpoint
+from libapi.utils import EXPOSED_HEADERS
@@ -46 +47,6 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], allow_credentials=True
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+ allow_credentials=True,
+ expose_headers=EXPOSED_HEADERS,
diff --git a/services/rows/src/rows/app.py b/services/rows/src/rows/app.py
index 15c6523b..4bf9d410 100644
--- a/services/rows/src/rows/app.py
+++ b/services/rows/src/rows/app.py
@@ -8,0 +9 @@ from libapi.routes.metrics import create_metrics_endpoint
+from libapi.utils import EXPOSED_HEADERS
@@ -49 +50,6 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], allow_credentials=True
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+ allow_credentials=True,
+ expose_headers=EXPOSED_HEADERS,
diff --git a/services/search/src/search/app.py b/services/search/src/search/app.py
index 9a3b1536..0b631e88 100644
--- a/services/search/src/search/app.py
+++ b/services/search/src/search/app.py
@@ -8,0 +9 @@ from libapi.routes.metrics import create_metrics_endpoint
+from libapi.utils import EXPOSED_HEADERS
@@ -54 +55,6 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], allow_credentials=True
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+ allow_credentials=True,
+ expose_headers=EXPOSED_HEADERS,
|
|
34c8a31f1c81994323d785f143421fe4c43849b4
|
Andrea Francis Soria Jimenez
| 2023-08-23T20:00:12 |
Increase resources and change queue metrics time (#1721)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index b888d79a..72fc224b 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -198,2 +198,2 @@ queueMetricsCollector:
- schedule: "*/2 * * * *"
- # every two minutes
+ schedule: "0 */2 * * *"
+ # every two hours
@@ -351 +351 @@ workers:
- replicas: 50
+ replicas: 100
@@ -368 +368 @@ workers:
- replicas: 20
+ replicas: 50
|
|
64455374b42782e8f78cf72d5ab239ab6541c1c2
|
Andrea Francis Soria Jimenez
| 2023-08-23T13:52:40 |
Download parquet in split-duckdb-index (#1717)
|
diff --git a/services/worker/src/worker/job_runners/split/duckdb_index.py b/services/worker/src/worker/job_runners/split/duckdb_index.py
index 5c9921d1..ba42e53a 100644
--- a/services/worker/src/worker/job_runners/split/duckdb_index.py
+++ b/services/worker/src/worker/job_runners/split/duckdb_index.py
@@ -4,0 +5 @@ import logging
+import os
@@ -8,0 +10 @@ import duckdb
+from huggingface_hub import hf_hub_download
@@ -55,0 +58,2 @@ SET_EXTENSIONS_DIRECTORY_COMMAND = "SET extension_directory='{directory}';"
+REPO_TYPE = "dataset"
+HUB_DOWNLOAD_CACHE_FOLDER = "cache"
@@ -99,3 +103,2 @@ def compute_index_rows(
- parquet_urls = [parquet_file["url"] for parquet_file in split_parquet_files]
-
- if not parquet_urls:
+ parquet_file_names = [parquet_file["filename"] for parquet_file in split_parquet_files]
+ if not parquet_file_names:
@@ -141 +144,16 @@ def compute_index_rows(
- create_command_sql = f"{CREATE_TABLE_COMMAND.format(columns=column_names)} read_parquet({parquet_urls});"
+ # see https://pypi.org/project/hf-transfer/ for more details about how to enable hf_transfer
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
+ for parquet_file in parquet_file_names:
+ hf_hub_download(
+ repo_type=REPO_TYPE,
+ revision=target_revision,
+ repo_id=dataset,
+ filename=f"{config}/{split}/{parquet_file}",
+ local_dir=duckdb_index_file_directory,
+ local_dir_use_symlinks=False,
+ token=hf_token,
+ cache_dir=duckdb_index_file_directory,
+ )
+
+ all_split_parquets = f"{duckdb_index_file_directory}/{config}/{split}/*.parquet"
+ create_command_sql = f"{CREATE_TABLE_COMMAND.format(columns=column_names)} '{all_split_parquets}';"
diff --git a/services/worker/tests/fixtures/hub.py b/services/worker/tests/fixtures/hub.py
index 74c201a0..ff6a5008 100644
--- a/services/worker/tests/fixtures/hub.py
+++ b/services/worker/tests/fixtures/hub.py
@@ -191,0 +192,7 @@ def hub_gated_csv(csv_path: str) -> Iterator[str]:
[email protected](scope="session")
+def hub_gated_duckdb_index(datasets: Mapping[str, Dataset]) -> Iterator[str]:
+ repo_id = create_hub_dataset_repo(prefix="duckdb_index_gated", dataset=datasets["duckdb_index"], gated="auto")
+ yield repo_id
+ delete_hub_dataset_repo(repo_id=repo_id)
+
+
@@ -845,0 +853,11 @@ def hub_responses_duckdb_index(hub_public_duckdb_index: str) -> HubDatasetTest:
[email protected]
+def hub_responses_gated_duckdb_index(hub_gated_duckdb_index: str) -> HubDatasetTest:
+ return {
+ "name": hub_gated_duckdb_index,
+ "config_names_response": create_config_names_response(hub_gated_duckdb_index),
+ "splits_response": create_splits_response(hub_gated_duckdb_index),
+ "first_rows_response": create_first_rows_response(hub_gated_duckdb_index, TEXT_cols, TEXT_rows),
+ "parquet_and_info_response": create_parquet_and_info_response(dataset=hub_gated_duckdb_index, data_type="csv"),
+ }
+
+
diff --git a/services/worker/tests/job_runners/split/test_duckdb_index.py b/services/worker/tests/job_runners/split/test_duckdb_index.py
index 87997d25..687e6492 100644
--- a/services/worker/tests/job_runners/split/test_duckdb_index.py
+++ b/services/worker/tests/job_runners/split/test_duckdb_index.py
@@ -129,0 +130 @@ def get_parquet_job_runner(
+ ("gated", None, None),
@@ -139,0 +141 @@ def test_compute(
+ hub_responses_gated_duckdb_index: HubDatasetTest,
@@ -144 +146,5 @@ def test_compute(
- hub_datasets = {"public": hub_responses_public, "duckdb_index": hub_responses_duckdb_index}
+ hub_datasets = {
+ "public": hub_responses_public,
+ "duckdb_index": hub_responses_duckdb_index,
+ "gated": hub_responses_gated_duckdb_index,
+ }
@@ -178,4 +184 @@ def test_compute(
- # simulate more than one parquet file to index
- extra_parquet_file = config_parquet["parquet_files"][0]
- config_parquet["parquet_files"].append(extra_parquet_file)
-
+ # TODO: simulate more than one parquet file to index
@@ -210 +213 @@ def test_compute(
- duckdb_file = requests.get(url)
+ duckdb_file = requests.get(url, headers={"authorization": f"Bearer {app_config.common.hf_token}"})
@@ -222 +225 @@ def test_compute(
- assert record_count[0] == (10,) # dataset has 5 rows but since parquet file was duplicate it is 10
+ assert record_count[0] == (5,)
|
|
2f827a6674e7696b1bdcb286e2a9a01f3a857dd1
|
Quentin Lhoest
| 2023-08-22T19:50:52 |
start job only if waiting (#1716)
|
diff --git a/libs/libcommon/src/libcommon/queue.py b/libs/libcommon/src/libcommon/queue.py
index a0db6ba1..c77ec220 100644
--- a/libs/libcommon/src/libcommon/queue.py
+++ b/libs/libcommon/src/libcommon/queue.py
@@ -683 +683 @@ class Queue:
- first_job.update(
+ if not JobDocument.objects(pk=str(first_job.pk), status=Status.WAITING).update(
@@ -688 +688,2 @@ class Queue:
- )
+ ):
+ raise AlreadyStartedJobError(f"job {job.unicity_id} has been started by another worker")
@@ -690,8 +691,6 @@ class Queue:
- for job in waiting_jobs.skip(1):
- # TODO: try to do a bulk update (not sure it's possible)
- job.update(
- finished_at=datetime,
- status=Status.CANCELLED,
- write_concern={"w": "majority", "fsync": True},
- read_concern={"level": "majority"},
- )
+ waiting_jobs(status=Status.WAITING).update(
+ finished_at=datetime,
+ status=Status.CANCELLED,
+ write_concern={"w": "majority", "fsync": True},
+ read_concern={"level": "majority"},
+ )
|
|
87162a157df8559d700e9d18e229182d2e197076
|
Andrea Francis Soria Jimenez
| 2023-08-21T15:47:04 |
Reduce resources (#1715)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 7e6f7eb7..b888d79a 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -351 +351 @@ workers:
- replicas: 96
+ replicas: 50
@@ -368 +368 @@ workers:
- replicas: 32
+ replicas: 20
|
|
3baae47d68d7e1c34d7fb4e78f2deaf15a2d10ea
|
Quentin Lhoest
| 2023-08-21T10:43:35 |
Update requirements.txt (#1714)
|
diff --git a/front/admin_ui/requirements.txt b/front/admin_ui/requirements.txt
index 3f903ace..72b506fd 100644
--- a/front/admin_ui/requirements.txt
+++ b/front/admin_ui/requirements.txt
@@ -6 +6 @@ requests>=2.28.1
-huggingface-hub~=0.15.1
+huggingface-hub~=0.16.4
|
|
020420ec8339ef2e7f5a53d8f3ad9ac301089aba
|
Sylvain Lesage
| 2023-08-18T21:23:10 |
New attempt jwt array (#1711)
|
diff --git a/chart/Chart.yaml b/chart/Chart.yaml
index 84f404b9..483a7337 100644
--- a/chart/Chart.yaml
+++ b/chart/Chart.yaml
@@ -21 +21 @@ type: application
-version: 1.16.3
+version: 1.17.0
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index efe374e1..7e6f7eb7 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -78,0 +79 @@ secrets:
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-prod-datasets-server-jwt-additional-public-keys"
@@ -90,0 +92,3 @@ secrets:
+ hfJwtAdditionalPublicKeys:
+ fromSecret: true
+ secretName: "datasets-server-prod-secrets"
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index 7769b640..4a38838b 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -74,0 +75 @@ secrets:
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-ephemeral-datasets-server-jwt-additional-public-keys"
@@ -86,0 +88,3 @@ secrets:
+ hfJwtAdditionalPublicKeys:
+ fromSecret: true
+ secretName: "datasets-server-staging-secrets"
diff --git a/chart/templates/_env/_envHf.tpl b/chart/templates/_env/_envHf.tpl
new file mode 100644
index 00000000..991ecdc1
--- /dev/null
+++ b/chart/templates/_env/_envHf.tpl
@@ -0,0 +1,33 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2022 The HuggingFace Authors.
+
+{{- define "envHf" -}}
+- name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+- name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+- name: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
+ {{- if .Values.secrets.hfJwtAdditionalPublicKeys.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfJwtAdditionalPublicKeys.secretName | quote }}
+ key: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfJwtAdditionalPublicKeys.value | quote }}
+ {{- end }}
+- name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+- name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+- name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value | quote }}
+ {{- end }}
+{{- end -}}
diff --git a/chart/templates/services/api/_container.tpl b/chart/templates/services/api/_container.tpl
index f64b68c5..2288c02a 100644
--- a/chart/templates/services/api/_container.tpl
+++ b/chart/templates/services/api/_container.tpl
@@ -11,0 +12 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -15,18 +15,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/templates/services/rows/_container.tpl b/chart/templates/services/rows/_container.tpl
index 4787ff77..94881190 100644
--- a/chart/templates/services/rows/_container.tpl
+++ b/chart/templates/services/rows/_container.tpl
@@ -13,0 +14 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -17,18 +17,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/templates/services/search/_container.tpl b/chart/templates/services/search/_container.tpl
index b9b3776d..6cced994 100644
--- a/chart/templates/services/search/_container.tpl
+++ b/chart/templates/services/search/_container.tpl
@@ -12,0 +13 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -15,18 +15,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/values.yaml b/chart/values.yaml
index 1e0a888b..066ca07c 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -105,0 +106,7 @@ secrets:
+ # a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub.
+ # The public keys must be in PEM format and include "\n" for line breaks
+ # ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
+ hfJwtAdditionalPublicKeys:
+ fromSecret: false
+ secretName: ""
+ value: ""
diff --git a/libs/libapi/README.md b/libs/libapi/README.md
index 8ab47fe8..dc629059 100644
--- a/libs/libapi/README.md
+++ b/libs/libapi/README.md
@@ -14 +14,2 @@ Set environment variables to configure the application (`API_` prefix):
-- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'X-Api-Key' header). If not set, the JWT are ignored. Defaults to empty.
+- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'Authorization' header). If not set, the JWT is ignored. Defaults to empty.
+- `API_HF_JWT_ADDITIONAL_PUBLIC_KEYS`: a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub. The public keys must be in PEM format and include "\n" for line breaks ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
diff --git a/libs/libapi/poetry.lock b/libs/libapi/poetry.lock
index 8b6904f5..ce06d623 100644
--- a/libs/libapi/poetry.lock
+++ b/libs/libapi/poetry.lock
@@ -722,0 +723,19 @@ idna = ["idna (>=2.1)"]
+[[package]]
+name = "ecdsa"
+version = "0.18.0"
+description = "ECDSA cryptographic signature library (pure python)"
+category = "dev"
+optional = false
+python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*"
+files = [
+ {file = "ecdsa-0.18.0-py2.py3-none-any.whl", hash = "sha256:80600258e7ed2f16b9aa1d7c295bd70194109ad5a30fdee0eaeefef1d4c559dd"},
+ {file = "ecdsa-0.18.0.tar.gz", hash = "sha256:190348041559e21b22a1d65cee485282ca11a6f81d503fddb84d5017e9ed1e49"},
+]
+
+[package.dependencies]
+six = ">=1.9.0"
+
+[package.extras]
+gmpy = ["gmpy"]
+gmpy2 = ["gmpy2"]
+
@@ -3185 +3204 @@ python-versions = "3.9.15"
-content-hash = "9f4fbf1058f6ec31e437c39104086dac3ead6792fb7b266eca4f5594ea5cd24c"
+content-hash = "e1e35aa88fd0f434afbf760992df6845ceb5fdd56b9c996d02ff7d8b846e073a"
diff --git a/libs/libapi/pyproject.toml b/libs/libapi/pyproject.toml
index 42d43247..7f93caca 100644
--- a/libs/libapi/pyproject.toml
+++ b/libs/libapi/pyproject.toml
@@ -21,0 +22 @@ black = "^22.12.0"
+ecdsa = "^0.18.0"
@@ -52,0 +54 @@ module = [
+ "ecdsa.*",
diff --git a/libs/libapi/src/libapi/authentication.py b/libs/libapi/src/libapi/authentication.py
index 9ce8345e..cd80bd3a 100644
--- a/libs/libapi/src/libapi/authentication.py
+++ b/libs/libapi/src/libapi/authentication.py
@@ -5 +5 @@ import logging
-from typing import Literal, Optional
+from typing import List, Literal, Optional
@@ -58 +58 @@ def auth_check(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -76 +76 @@ def auth_check(
- hf_jwt_public_key (str|None): the public key to use to decode the JWT token
+ hf_jwt_public_keys (List[str]|None): the public keys to use to decode the JWT token
@@ -86 +86 @@ def auth_check(
- if (jwt_token := get_jwt_token(request)) and hf_jwt_public_key and hf_jwt_algorithm:
+ if (jwt_token := get_jwt_token(request)) and hf_jwt_public_keys and hf_jwt_algorithm:
@@ -88 +88 @@ def auth_check(
- dataset=dataset, token=jwt_token, public_key=hf_jwt_public_key, algorithm=hf_jwt_algorithm
+ dataset=dataset, token=jwt_token, public_keys=hf_jwt_public_keys, algorithm=hf_jwt_algorithm
diff --git a/libs/libapi/src/libapi/config.py b/libs/libapi/src/libapi/config.py
index a533253a..f80bea97 100644
--- a/libs/libapi/src/libapi/config.py
+++ b/libs/libapi/src/libapi/config.py
@@ -4,2 +4,2 @@
-from dataclasses import dataclass
-from typing import Optional
+from dataclasses import dataclass, field
+from typing import List, Optional
@@ -33,0 +34 @@ API_HF_JWT_PUBLIC_KEY_URL = None
+API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: List[str] = []
@@ -45,0 +47 @@ class ApiConfig:
+ hf_jwt_additional_public_keys: List[str] = field(default_factory=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy)
@@ -61,0 +64,3 @@ class ApiConfig:
+ hf_jwt_additional_public_keys=env.list(
+ name="HF_JWT_ADDITIONAL_PUBLIC_KEYS", default=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy()
+ ),
diff --git a/libs/libapi/src/libapi/exceptions.py b/libs/libapi/src/libapi/exceptions.py
index bb28ae3b..ea993334 100644
--- a/libs/libapi/src/libapi/exceptions.py
+++ b/libs/libapi/src/libapi/exceptions.py
@@ -15 +14,0 @@ ApiErrorCode = Literal[
- "JWKError",
@@ -20,0 +20 @@ ApiErrorCode = Literal[
+ "JWTKeysError",
@@ -83,2 +83,2 @@ class InvalidParameterError(ApiError):
-class JWKError(ApiError):
- """The JWT key (JWK) could not be fetched or parsed."""
+class JWTKeysError(ApiError):
+ """The public keys for decoding JWT could not be created."""
@@ -87 +87 @@ class JWKError(ApiError):
- super().__init__(message, HTTPStatus.INTERNAL_SERVER_ERROR, "JWKError", cause=cause, disclose_cause=False)
+ super().__init__(message, HTTPStatus.INTERNAL_SERVER_ERROR, "JWTKeysError", cause=cause, disclose_cause=False)
diff --git a/libs/libapi/src/libapi/jwt_token.py b/libs/libapi/src/libapi/jwt_token.py
index b3ec5b74..e27719d3 100644
--- a/libs/libapi/src/libapi/jwt_token.py
+++ b/libs/libapi/src/libapi/jwt_token.py
@@ -5 +5 @@ import logging
-from typing import Any, Optional, Union
+from typing import Any, List, Optional, Union
@@ -32 +31,0 @@ from libapi.exceptions import (
- JWKError,
@@ -37,0 +37 @@ from libapi.exceptions import (
+ JWTKeysError,
@@ -43,0 +44,12 @@ SYMMETRIC_ALGORITHMS = (HMACAlgorithm,)
+SupportedAlgorithm = Union[ECAlgorithm, OKPAlgorithm, RSAAlgorithm, RSAPSSAlgorithm, HMACAlgorithm]
+SupportedKey = Union[
+ Ed448PrivateKey,
+ Ed448PublicKey,
+ Ed25519PrivateKey,
+ Ed25519PublicKey,
+ EllipticCurvePrivateKey,
+ EllipticCurvePublicKey,
+ RSAPrivateKey,
+ RSAPublicKey,
+ bytes,
+]
@@ -46,12 +58 @@ SYMMETRIC_ALGORITHMS = (HMACAlgorithm,)
-def is_public_key(
- key: Union[
- EllipticCurvePublicKey,
- EllipticCurvePrivateKey,
- Ed25519PublicKey,
- Ed448PublicKey,
- Ed25519PrivateKey,
- Ed448PrivateKey,
- RSAPrivateKey,
- RSAPublicKey,
- ]
-) -> bool:
+def is_public_key(key: SupportedKey) -> bool:
@@ -61,6 +62,3 @@ def is_public_key(
-def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
- """parse the input JSON to extract the public key
-
- Note that the return type is Any in order not to enter in too much details. See
- https://github.com/jpadilla/pyjwt/blob/777efa2f51249f63b0f95804230117723eca5d09/jwt/algorithms.py#L629-L651
- In our case, the type should be cryptography.hazmat.backends.openssl.ed25519._Ed25519PublicKey
+def create_algorithm(algorithm_name: str) -> SupportedAlgorithm:
+ """
+ Create an algorithm object from the algorithm name.
@@ -69,2 +67 @@ def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
- keys (Any): the JSON to parse
- hf_jwt_algorithm (str): the JWT algorithm to use.
+ algorithm_name (str): the algorithm name
@@ -73 +70,4 @@ def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
- str: the public key
+ SupportedAlgorithm: the algorithm object
+
+ Raises:
+ RuntimeError: if the algorithm is not supported
@@ -76,2 +76,2 @@ def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
- expected_algorithm = jwt.get_algorithm_by_name(hf_jwt_algorithm)
- if not isinstance(expected_algorithm, (*ASYMMETRIC_ALGORITHMS, *SYMMETRIC_ALGORITHMS)):
+ algorithm = jwt.get_algorithm_by_name(algorithm_name)
+ if not isinstance(algorithm, (*ASYMMETRIC_ALGORITHMS, *SYMMETRIC_ALGORITHMS)):
@@ -80 +80,7 @@ def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
- raise RuntimeError(f"Invalid algorithm for JWT verification: {hf_jwt_algorithm} is not supported") from err
+ raise RuntimeError(f"Invalid algorithm for JWT verification: {algorithm_name} is not supported") from err
+ return algorithm
+
+
+def _key_to_pem(key: SupportedKey, algorithm: SupportedAlgorithm) -> str:
+ """
+ Convert the key to PEM format.
@@ -82,2 +88,38 @@ def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
- if not isinstance(keys, list):
- raise ValueError("Payload from moon must be a list of JWK formatted keys.")
+ Args:
+ key (SupportedKey): the key to convert
+
+ Returns:
+ str: the key in PEM format (PKCS#8)
+
+ Raises:
+ RuntimeError: if the key is not a public key
+ """
+ if isinstance(algorithm, SYMMETRIC_ALGORITHMS) or isinstance(key, bytes):
+ return key.decode("utf-8") # type: ignore
+ if not is_public_key(key):
+ raise RuntimeError("Failed to parse JWT key: the provided key is a private key")
+ return key.public_bytes( # type: ignore
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
+ ).decode("utf-8")
+ # ^ we assume that the key contain UTF-8 encoded bytes, which is why we use type ignore for mypy
+
+
+def parse_jwt_public_key_json(payload: Any, algorithm: SupportedAlgorithm) -> str:
+ """
+ Parse the payload (JSON format) to extract the public key, validating that it's a public key, and that it is
+ compatible with the algorithm
+
+ Args:
+ keys (Any): the JSON to parse. It must be a list of keys in JWK format
+ algorithm (SupportedAlgorithm): the algorithm the key should implement
+
+ Returns:
+ str: the public key in PEM format
+
+ Raises:
+ RuntimeError: if the payload is not compatible with the algorithm, or if the key is not public
+ ValueError: if the input is not a list
+ """
+ if not isinstance(payload, list) or not payload:
+ raise ValueError("Payload must be a list of JWK formatted keys.")
@@ -85,10 +127 @@ def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
- key = expected_algorithm.from_jwk(keys[0])
- if not isinstance(expected_algorithm, ASYMMETRIC_ALGORITHMS) or isinstance(key, bytes):
- return key.decode("utf-8")
- if not is_public_key(key):
- raise RuntimeError("Failed to parse JWT key: the provided key is a private key")
- return key.public_bytes(
- encoding=serialization.Encoding.PEM,
- format=serialization.PublicFormat.SubjectPublicKeyInfo,
- ).decode("utf-8")
- # ^ we assume that the key contain UTF-8 encoded bytes, which is why we use type ignore for mypy
+ key = algorithm.from_jwk(payload[0])
@@ -96,0 +130 @@ def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
+ return _key_to_pem(key, algorithm)
@@ -99 +133,24 @@ def parse_jwt_public_key(keys: Any, hf_jwt_algorithm: str) -> str:
-def fetch_jwt_public_key(
+def parse_jwt_public_key_pem(payload: str, algorithm: SupportedAlgorithm) -> str:
+ """
+ Parse the input string to validate it's a public key in PEM format, and that it is compatible
+ with the algorithm
+
+ Args:
+ key (str): the key to parse. It should be a public key in PEM format
+ algorithm (SupportedAlgorithm): the algorithm the key should implement
+
+ Returns:
+ str: the public key in PEM format
+
+ Raises:
+ RuntimeError: if the payload is not compatible with the algorithm, or if the key is not public
+ ValueError: if the input is not a list
+ """
+ try:
+ key = algorithm.prepare_key(payload)
+ except (jwt.InvalidKeyError, KeyError) as err:
+ raise RuntimeError(f"Failed to parse JWT key: {err.args[0]}") from err
+ return _key_to_pem(key, algorithm)
+
+
+def fetch_jwt_public_key_json(
@@ -101 +157,0 @@ def fetch_jwt_public_key(
- hf_jwt_algorithm: str,
@@ -103,2 +159,3 @@ def fetch_jwt_public_key(
-) -> str:
- """fetch the public key to decode the JWT token from the input URL
+) -> Any:
+ """
+ Fetch the public key from the input URL
@@ -110 +166,0 @@ def fetch_jwt_public_key(
- hf_jwt_algorithm (str): the JWT algorithm to use.
@@ -115 +171,4 @@ def fetch_jwt_public_key(
- str: the public key
+ Any: the response JSON payload
+
+ Raises:
+ RuntimeError: if the request fails
@@ -120 +179,52 @@ def fetch_jwt_public_key(
- return parse_jwt_public_key(keys=response.json(), hf_jwt_algorithm=hf_jwt_algorithm)
+ return response.json()
+ except Exception as err:
+ raise RuntimeError(f"Failed to fetch the JWT public key from {url}. ") from err
+
+
+def get_jwt_public_keys(
+ algorithm_name: Optional[str] = None,
+ public_key_url: Optional[str] = None,
+ additional_public_keys: Optional[List[str]] = None,
+ timeout_seconds: Optional[float] = None,
+) -> List[str]:
+ """
+ Get the public keys to use to decode the JWT token.
+
+ The keys can be created by two mechanisms:
+ - one key can be fetched from the public_key_url (must be in JWK format, ie. JSON)
+ - additional keys can be provided as a list of PEM formatted keys
+ All of these keys are then converted to PEM format (PKCS#8) and returned as a list. The remote key is first.
+ The keys must be compatible with the algorithm.
+
+ Args:
+ algorithm_name (str|None): the algorithm to use to decode the JWT token. If not provided, no keys will be
+ returned
+ public_key_url (str|None): the URL to fetch the public key from
+ additional_public_keys (List[str]|None): additional public keys to use to decode the JWT token
+ timeout_seconds (float|None): the timeout in seconds for fetching the remote key
+
+ Returns:
+ List[str]: the list of public keys in PEM format
+
+ Raises:
+ JWTKeysError: if some exception occurred while creating the public keys. Some reasons: if the algorithm
+ is not supported, if a payload could not be parsed, if a key is not compatible with the algorithm,
+ if a key is not public, if th remote key could not be fetch or parsed
+ """
+ try:
+ keys: List[str] = []
+ if not algorithm_name:
+ return keys
+ algorithm = create_algorithm(algorithm_name)
+ if public_key_url:
+ payload = fetch_jwt_public_key_json(
+ url=public_key_url,
+ hf_timeout_seconds=timeout_seconds,
+ )
+ keys.append(parse_jwt_public_key_json(payload=payload, algorithm=algorithm))
+ if additional_public_keys:
+ keys.extend(
+ parse_jwt_public_key_pem(payload=payload, algorithm=algorithm) for payload in additional_public_keys
+ )
+ logging.debug(f"JWT public keys are: {', '.join(keys)}.")
+ return keys
@@ -122 +232 @@ def fetch_jwt_public_key(
- raise JWKError(f"Failed to fetch or parse the JWT public key from {url}. ", cause=err) from err
+ raise JWTKeysError("Failed to create the JWT public keys.") from err
@@ -125 +235,3 @@ def fetch_jwt_public_key(
-def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, verify_exp: Optional[bool] = True) -> None:
+def validate_jwt(
+ dataset: str, token: Any, public_keys: List[str], algorithm: str, verify_exp: Optional[bool] = True
+) -> None:
@@ -137 +249 @@ def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, veri
- public_key (str): the public key to use to decode the JWT token
+ public_keys (List[str]): the public keys to use to decode the JWT token. They are tried in order.
@@ -142 +254,7 @@ def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, veri
-
+ JWTInvalidSignature: if the signature verification failed
+ JWTMissingRequiredClaim: if a claim is missing in the JWT payload
+ JWTExpiredSignature: if the JWT signature has expired
+ JWTInvalidKeyOrAlgorithm: if the key used to verify the signature is not compatible with the algorithm
+ JWTInvalidClaimSub: if the 'sub' claim in JWT payload is invalid
+ JWTInvalidClaimRead: if the 'read' claim in JWT payload is invalid
+ UnexpectedApiError: if another error occurred while decoding the JWT
@@ -144,30 +262,32 @@ def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, veri
- try:
- decoded = jwt.decode(
- jwt=token,
- key=public_key,
- algorithms=[algorithm],
- options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
- )
- logging.debug(f"Decoded JWT is: '{public_key}'.")
- except jwt.exceptions.MissingRequiredClaimError as e:
- raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
- except jwt.exceptions.ExpiredSignatureError as e:
- raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
- except jwt.exceptions.InvalidSignatureError as e:
- raise JWTInvalidSignature(
- "The JWT signature verification failed. Check the signing key and the algorithm.", e
- ) from e
- except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
- raise JWTInvalidKeyOrAlgorithm(
- (
- "The key used to verify the signature is not compatible with the algorithm. Check the signing key and"
- " the algorithm."
- ),
- e,
- ) from e
- except Exception as e:
- logging.debug(
- f"Missing public key '{public_key}' or algorithm '{algorithm}' to decode JWT token. Skipping JWT"
- " validation."
- )
- raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
+ for public_key in public_keys:
+ logging.debug(f"Trying to decode the JWT with key #{public_keys.index(public_key)}: {public_key}.")
+ try:
+ decoded = jwt.decode(
+ jwt=token,
+ key=public_key,
+ algorithms=[algorithm],
+ options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
+ )
+ logging.debug(f"Decoded JWT is: '{public_key}'.")
+ break
+ except jwt.exceptions.InvalidSignatureError as e:
+ if public_key == public_keys[-1]:
+ raise JWTInvalidSignature(
+ "The JWT signature verification failed. Check the signing key and the algorithm.", e
+ ) from e
+ logging.debug(f"JWT signature verification failed with key: '{public_key}'. Trying next key.")
+ except jwt.exceptions.MissingRequiredClaimError as e:
+ raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
+ except jwt.exceptions.ExpiredSignatureError as e:
+ raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
+
+ except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
+ raise JWTInvalidKeyOrAlgorithm(
+ (
+ "The key used to verify the signature is not compatible with the algorithm. Check the signing key"
+ " and the algorithm."
+ ),
+ e,
+ ) from e
+ except Exception as e:
+ raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
diff --git a/libs/libapi/tests/test_authentication.py b/libs/libapi/tests/test_authentication.py
index 2a1d8e3f..6bb37c8b 100644
--- a/libs/libapi/tests/test_authentication.py
+++ b/libs/libapi/tests/test_authentication.py
@@ -196 +196 @@ def assert_auth_headers(
- hf_jwt_public_key=public_key,
+ hf_jwt_public_keys=[public_key],
diff --git a/libs/libapi/tests/test_jwt_token.py b/libs/libapi/tests/test_jwt_token.py
index 5926cd51..6c347358 100644
--- a/libs/libapi/tests/test_jwt_token.py
+++ b/libs/libapi/tests/test_jwt_token.py
@@ -6 +6,2 @@ from contextlib import nullcontext as does_not_raise
-from typing import Any, Dict
+from typing import Any, Dict, List, Optional
+from unittest.mock import patch
@@ -9,0 +11 @@ import pytest
+from ecdsa import Ed25519, SigningKey
@@ -10,0 +13 @@ import pytest
+from libapi.config import ApiConfig
@@ -16,0 +20 @@ from libapi.exceptions import (
+ JWTKeysError,
@@ -19 +23,27 @@ from libapi.exceptions import (
-from libapi.jwt_token import parse_jwt_public_key, validate_jwt
+from libapi.jwt_token import (
+ create_algorithm,
+ get_jwt_public_keys,
+ parse_jwt_public_key_json,
+ parse_jwt_public_key_pem,
+ validate_jwt,
+)
+
+algorithm_name_eddsa = "EdDSA"
+algorithm_name_rs256 = "RS256"
+algorithm_name_hs256 = "HS256"
+algorithm_name_unknown = "unknown"
+
+
[email protected](
+ "algorithm_name,expectation",
+ [
+ (algorithm_name_eddsa, does_not_raise()),
+ (algorithm_name_rs256, does_not_raise()),
+ (algorithm_name_hs256, does_not_raise()),
+ (algorithm_name_unknown, pytest.raises(RuntimeError)),
+ ],
+)
+def test_create_algorithm(algorithm_name: str, expectation: Any) -> None:
+ with expectation:
+ create_algorithm(algorithm_name)
+
@@ -21,3 +51,4 @@ from libapi.jwt_token import parse_jwt_public_key, validate_jwt
-HUB_JWT_KEYS = [{"crv": "Ed25519", "x": "-RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM", "kty": "OKP"}]
-HUB_JWT_ALGORITHM = "EdDSA"
-HUB_JWT_PUBLIC_KEY = """-----BEGIN PUBLIC KEY-----
+algorithm_eddsa = create_algorithm(algorithm_name_eddsa)
+eddsa_public_key_json_payload = {"crv": "Ed25519", "x": "-RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM", "kty": "OKP"}
+# ^ given by https://huggingface.co/api/keys/jwt (as of 2023/08/18)
+eddsa_public_key_pem = """-----BEGIN PUBLIC KEY-----
@@ -27,10 +58,8 @@ MCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=
-UNSUPPORTED_ALGORITHM_JWT_KEYS = [
- {
- "alg": "EC",
- "crv": "P-256",
- "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
- "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
- "use": "enc",
- "kid": "1",
- }
-]
+another_algorithm_public_key_json_payload = {
+ "alg": "EC",
+ "crv": "P-256",
+ "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
+ "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
+ "use": "enc",
+ "kid": "1",
+}
@@ -40 +69 @@ UNSUPPORTED_ALGORITHM_JWT_KEYS = [
- "keys,expectation",
+ "payload,expected_pem,expectation",
@@ -42,3 +71,4 @@ UNSUPPORTED_ALGORITHM_JWT_KEYS = [
- (HUB_JWT_KEYS, does_not_raise()),
- ([], pytest.raises(Exception)),
- (UNSUPPORTED_ALGORITHM_JWT_KEYS, pytest.raises(Exception)),
+ ([], None, pytest.raises(ValueError)),
+ (eddsa_public_key_json_payload, None, pytest.raises(ValueError)),
+ ([another_algorithm_public_key_json_payload], None, pytest.raises(RuntimeError)),
+ ([eddsa_public_key_json_payload], eddsa_public_key_pem, does_not_raise()),
@@ -47,4 +77 @@ UNSUPPORTED_ALGORITHM_JWT_KEYS = [
-def test_parse_jwk(
- keys: str,
- expectation: Any,
-) -> None:
+def test_parse_jwt_public_key_json(payload: Any, expected_pem: str, expectation: Any) -> None:
@@ -52,2 +79,10 @@ def test_parse_jwk(
- key = parse_jwt_public_key(keys=keys, hf_jwt_algorithm=HUB_JWT_ALGORITHM)
- assert key == HUB_JWT_PUBLIC_KEY
+ pem = parse_jwt_public_key_json(algorithm=algorithm_eddsa, payload=payload)
+ if expected_pem:
+ assert pem == expected_pem
+
+
+eddsa_public_key_pem_with_bad_linebreaks = (
+ "-----BEGIN PUBLIC KEY-----\\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\\n-----END PUBLIC"
+ " KEY-----"
+)
+
@@ -54,0 +90,12 @@ def test_parse_jwk(
[email protected](
+ "payload,expected_pem,expectation",
+ [
+ (eddsa_public_key_pem_with_bad_linebreaks, None, pytest.raises(Exception)),
+ (eddsa_public_key_pem, eddsa_public_key_pem, does_not_raise()),
+ ],
+)
+def test_parse_jwt_public_key_pem(payload: Any, expected_pem: str, expectation: Any) -> None:
+ with expectation:
+ pem = parse_jwt_public_key_pem(algorithm=algorithm_eddsa, payload=payload)
+ if expected_pem:
+ assert pem == expected_pem
@@ -56 +103,79 @@ def test_parse_jwk(
-HUB_JWT_TOKEN_FOR_SEVERO_GLUE = (
+
+private_key_ok = SigningKey.generate(curve=Ed25519)
+private_key_pem_ok = private_key_ok.to_pem(format="pkcs8")
+public_key_pem_ok = private_key_ok.get_verifying_key().to_pem().decode("utf-8")
+
+other_private_key = SigningKey.generate(curve=Ed25519)
+other_private_key_pem = other_private_key.to_pem(format="pkcs8")
+other_public_key_pem = other_private_key.get_verifying_key().to_pem().decode("utf-8")
+
+
[email protected](
+ "keys_env_var,expected_keys",
+ [
+ ("", []),
+ (public_key_pem_ok, [public_key_pem_ok]),
+ (f"{public_key_pem_ok},{public_key_pem_ok}", [public_key_pem_ok, public_key_pem_ok]),
+ (f"{public_key_pem_ok},{other_public_key_pem}", [public_key_pem_ok, other_public_key_pem]),
+ (
+ f"{public_key_pem_ok},{other_public_key_pem},{eddsa_public_key_pem}",
+ [public_key_pem_ok, other_public_key_pem, eddsa_public_key_pem],
+ ),
+ ],
+)
+def test_get_jwt_public_keys_from_env(keys_env_var: str, expected_keys: List[str]) -> None:
+ monkeypatch = pytest.MonkeyPatch()
+ monkeypatch.setenv("API_HF_JWT_ADDITIONAL_PUBLIC_KEYS", keys_env_var)
+ api_config = ApiConfig.from_env(hf_endpoint="")
+ assert (
+ get_jwt_public_keys(
+ algorithm_name=algorithm_name_eddsa,
+ additional_public_keys=api_config.hf_jwt_additional_public_keys,
+ )
+ == expected_keys
+ )
+ monkeypatch.undo()
+
+
[email protected](
+ "remote_payload,keys_payload,expected_keys,expectation",
+ [
+ ([], [], None, pytest.raises(JWTKeysError)),
+ ([another_algorithm_public_key_json_payload], [], None, pytest.raises(JWTKeysError)),
+ (None, [eddsa_public_key_pem_with_bad_linebreaks], None, pytest.raises(JWTKeysError)),
+ ([eddsa_public_key_json_payload], [], [eddsa_public_key_pem], does_not_raise()),
+ (
+ None,
+ [public_key_pem_ok, other_public_key_pem, eddsa_public_key_pem],
+ [public_key_pem_ok, other_public_key_pem, eddsa_public_key_pem],
+ does_not_raise(),
+ ),
+ (
+ [eddsa_public_key_json_payload],
+ [public_key_pem_ok, other_public_key_pem, eddsa_public_key_pem],
+ [eddsa_public_key_pem, public_key_pem_ok, other_public_key_pem, eddsa_public_key_pem],
+ does_not_raise(),
+ ),
+ ],
+)
+def test_get_jwt_public_keys(
+ remote_payload: Any, keys_payload: List[str], expected_keys: List[str], expectation: Any
+) -> None:
+ def fake_fetch(
+ url: str,
+ hf_timeout_seconds: Optional[float] = None,
+ ) -> Any:
+ return remote_payload
+
+ with patch("libapi.jwt_token.fetch_jwt_public_key_json", wraps=fake_fetch):
+ with expectation:
+ keys = get_jwt_public_keys(
+ algorithm_name=algorithm_name_eddsa,
+ public_key_url=None if remote_payload is None else "mock",
+ additional_public_keys=keys_payload,
+ )
+ if expected_keys:
+ assert keys == expected_keys
+
+
+token_for_severo_glue = (
@@ -60 +185 @@ HUB_JWT_TOKEN_FOR_SEVERO_GLUE = (
-DATASET_SEVERO_GLUE = "severo/glue"
+dataset_severo_glue = "severo/glue"
@@ -65,4 +190,4 @@ def test_is_jwt_valid_with_ec() -> None:
- dataset=DATASET_SEVERO_GLUE,
- token=HUB_JWT_TOKEN_FOR_SEVERO_GLUE,
- public_key=HUB_JWT_PUBLIC_KEY,
- algorithm=HUB_JWT_ALGORITHM,
+ dataset=dataset_severo_glue,
+ token=token_for_severo_glue,
+ public_keys=[eddsa_public_key_pem],
+ algorithm=algorithm_name_eddsa,
@@ -74,19 +198,0 @@ def test_is_jwt_valid_with_ec() -> None:
-private_key = """-----BEGIN RSA PRIVATE KEY-----
-MIIBOQIBAAJAZTmplhS/Jd73ycVut7TglMObheQqXM7RZYlwazLU4wpfIVIwOh9I
-sCZGSgLyFq42KWIikKLEs/yqx3pRGfq+rwIDAQABAkAMyF9WCICq86Eu5bO5lynV
-H26AVfPTjHp87AI6R00C7p9n8hO/DhHaHpc3InOSsXsw9d2hmz37jwwBFiwMHMMh
-AiEAtbttHlIO+yO29oXw4P6+yO11lMy1UpT1sPVTnR9TXbUCIQCOl7Zuyy2ZY9ZW
-pDhW91x/14uXjnLXPypgY9bcfggJUwIhAJQG1LzrzjQWRUPMmgZKuhBkC3BmxhM8
-LlwzmCXVjEw5AiA7JnAFEb9+q82T71d3q/DxD0bWvb6hz5ASoBfXK2jGBQIgbaQp
-h4Tk6UJuj1xgKNs75Pk3pG2tj8AQiuBk3l62vRU=
------END RSA PRIVATE KEY-----"""
-public_key_ok = """-----BEGIN PUBLIC KEY-----
-MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAZTmplhS/Jd73ycVut7TglMObheQqXM7R
-ZYlwazLU4wpfIVIwOh9IsCZGSgLyFq42KWIikKLEs/yqx3pRGfq+rwIDAQAB
------END PUBLIC KEY-----"""
-other_public_key = """-----BEGIN PUBLIC KEY-----
-MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAecoNIHMXczWkzTp9ePEcx6vPibrZVz/z
-xYGX6G2jFcwFdsrO9nCecrtpSw5lwjW40aNVL9NL9yxPxDi2dyq4wQIDAQAB
------END PUBLIC KEY-----"""
-
-
@@ -107,2 +213,2 @@ payload_ok = {"sub": sub_ok, "read": read_ok, "exp": exp_ok}
-algorithm_ok = "RS256"
-algorithm_wrong = "HS256"
+algorithm_ok = algorithm_name_eddsa
+algorithm_wrong = algorithm_name_rs256
@@ -112 +218 @@ def encode_jwt(payload: Dict[str, Any]) -> str:
- return jwt.encode(payload, private_key, algorithm=algorithm_ok)
+ return jwt.encode(payload, private_key_pem_ok, algorithm=algorithm_ok)
@@ -115 +221,5 @@ def encode_jwt(payload: Dict[str, Any]) -> str:
-def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, algorithm: str = algorithm_ok) -> None:
+def assert_jwt(
+ token: str, expectation: Any, public_keys: Optional[List[str]] = None, algorithm: str = algorithm_ok
+) -> None:
+ if public_keys is None:
+ public_keys = [public_key_pem_ok]
@@ -117 +227 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- validate_jwt(dataset=dataset_ok, token=token, public_key=public_key, algorithm=algorithm)
+ validate_jwt(dataset=dataset_ok, token=token, public_keys=public_keys, algorithm=algorithm)
@@ -121 +231 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- "public_key,expectation",
+ "public_keys,expectation",
@@ -123,2 +233,4 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- (other_public_key, pytest.raises(JWTInvalidSignature)),
- (public_key_ok, does_not_raise()),
+ ([other_public_key_pem], pytest.raises(JWTInvalidSignature)),
+ ([public_key_pem_ok], does_not_raise()),
+ ([public_key_pem_ok, other_public_key_pem], does_not_raise()),
+ ([other_public_key_pem, public_key_pem_ok], does_not_raise()),
@@ -127,2 +239,2 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
-def test_validate_jwt_public_key(public_key: str, expectation: Any) -> None:
- assert_jwt(encode_jwt(payload_ok), expectation, public_key=public_key)
+def test_validate_jwt_public_keys(public_keys: List[str], expectation: Any) -> None:
+ assert_jwt(encode_jwt(payload_ok), expectation, public_keys=public_keys)
diff --git a/services/api/src/api/app.py b/services/api/src/api/app.py
index 85625f38..b7e050d3 100644
--- a/services/api/src/api/app.py
+++ b/services/api/src/api/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -37,8 +37,5 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
+ hf_jwt_public_keys = get_jwt_public_keys(
+ algorithm_name=app_config.api.hf_jwt_algorithm,
+ public_key_url=app_config.api.hf_jwt_public_key_url,
+ additional_public_keys=app_config.api.hf_jwt_additional_public_keys,
+ timeout_seconds=app_config.api.hf_timeout_seconds,
@@ -72 +69 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/api/src/api/routes/endpoint.py b/services/api/src/api/routes/endpoint.py
index b3820ae1..75e023f6 100644
--- a/services/api/src/api/routes/endpoint.py
+++ b/services/api/src/api/routes/endpoint.py
@@ -231 +231 @@ def create_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -277 +277 @@ def create_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/rows/src/rows/app.py b/services/rows/src/rows/app.py
index d792fc80..15c6523b 100644
--- a/services/rows/src/rows/app.py
+++ b/services/rows/src/rows/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -40,8 +40,5 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
+ hf_jwt_public_keys = get_jwt_public_keys(
+ algorithm_name=app_config.api.hf_jwt_algorithm,
+ public_key_url=app_config.api.hf_jwt_public_key_url,
+ additional_public_keys=app_config.api.hf_jwt_additional_public_keys,
+ timeout_seconds=app_config.api.hf_timeout_seconds,
@@ -79 +76 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index fbad46a6..da447a97 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -92 +92 @@ def create_rows_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -140 +140 @@ def create_rows_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/search/src/search/app.py b/services/search/src/search/app.py
index ba71f39a..9a3b1536 100644
--- a/services/search/src/search/app.py
+++ b/services/search/src/search/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -45,8 +45,5 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
+ hf_jwt_public_keys = get_jwt_public_keys(
+ algorithm_name=app_config.api.hf_jwt_algorithm,
+ public_key_url=app_config.api.hf_jwt_public_key_url,
+ additional_public_keys=app_config.api.hf_jwt_additional_public_keys,
+ timeout_seconds=app_config.api.hf_timeout_seconds,
@@ -85 +82 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index 299e14a9..408cfa51 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -204 +204 @@ def create_search_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -251 +251 @@ def create_search_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/tools/docker-compose-base.yml b/tools/docker-compose-base.yml
index 52bb9a40..27b5326c 100644
--- a/tools/docker-compose-base.yml
+++ b/tools/docker-compose-base.yml
@@ -36,0 +37,8 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index 3de9d546..23af5ce9 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -72,7 +71,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -109,7 +101,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -146,7 +131,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-base.yml b/tools/docker-compose-dev-base.yml
index a4a02e69..c85ea249 100644
--- a/tools/docker-compose-dev-base.yml
+++ b/tools/docker-compose-dev-base.yml
@@ -47,0 +48,8 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index ca42d26a..92ba68c5 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -74,7 +73,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -111,7 +103,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -149,7 +134,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
|
|
213f28b1f4e699b246439ade86fd77e26197dcf3
|
Sylvain Lesage
| 2023-08-18T15:58:38 |
Revert "Create jwt array again (#1708)" (#1709)
|
diff --git a/chart/Chart.yaml b/chart/Chart.yaml
index 483a7337..84f404b9 100644
--- a/chart/Chart.yaml
+++ b/chart/Chart.yaml
@@ -21 +21 @@ type: application
-version: 1.17.0
+version: 1.16.3
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 7e6f7eb7..efe374e1 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -79 +78,0 @@ secrets:
- API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-prod-datasets-server-jwt-additional-public-keys"
@@ -92,3 +90,0 @@ secrets:
- hfJwtAdditionalPublicKeys:
- fromSecret: true
- secretName: "datasets-server-prod-secrets"
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index 4a38838b..7769b640 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -75 +74,0 @@ secrets:
- API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-ephemeral-datasets-server-jwt-additional-public-keys"
@@ -88,3 +86,0 @@ secrets:
- hfJwtAdditionalPublicKeys:
- fromSecret: true
- secretName: "datasets-server-staging-secrets"
diff --git a/chart/templates/_env/_envHf.tpl b/chart/templates/_env/_envHf.tpl
deleted file mode 100644
index 991ecdc1..00000000
--- a/chart/templates/_env/_envHf.tpl
+++ /dev/null
@@ -1,33 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2022 The HuggingFace Authors.
-
-{{- define "envHf" -}}
-- name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
-- name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
-- name: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
- {{- if .Values.secrets.hfJwtAdditionalPublicKeys.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfJwtAdditionalPublicKeys.secretName | quote }}
- key: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfJwtAdditionalPublicKeys.value | quote }}
- {{- end }}
-- name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
-- name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
-- name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value | quote }}
- {{- end }}
-{{- end -}}
diff --git a/chart/templates/services/api/_container.tpl b/chart/templates/services/api/_container.tpl
index 2288c02a..f64b68c5 100644
--- a/chart/templates/services/api/_container.tpl
+++ b/chart/templates/services/api/_container.tpl
@@ -12 +11,0 @@
- {{ include "envHf" . | nindent 2 }}
@@ -15,0 +15,18 @@
+ - name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+ - name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+ - name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+ - name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+ - name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value }}
+ {{- end }}
diff --git a/chart/templates/services/rows/_container.tpl b/chart/templates/services/rows/_container.tpl
index 94881190..4787ff77 100644
--- a/chart/templates/services/rows/_container.tpl
+++ b/chart/templates/services/rows/_container.tpl
@@ -14 +13,0 @@
- {{ include "envHf" . | nindent 2 }}
@@ -17,0 +17,18 @@
+ - name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+ - name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+ - name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+ - name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+ - name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value }}
+ {{- end }}
diff --git a/chart/templates/services/search/_container.tpl b/chart/templates/services/search/_container.tpl
index 6cced994..b9b3776d 100644
--- a/chart/templates/services/search/_container.tpl
+++ b/chart/templates/services/search/_container.tpl
@@ -13 +12,0 @@
- {{ include "envHf" . | nindent 2 }}
@@ -15,0 +15,18 @@
+ - name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+ - name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+ - name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+ - name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+ - name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value }}
+ {{- end }}
diff --git a/chart/values.yaml b/chart/values.yaml
index 066ca07c..1e0a888b 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -106,7 +105,0 @@ secrets:
- # a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub.
- # The public keys must be in PEM format and include "\n" for line breaks
- # ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
- hfJwtAdditionalPublicKeys:
- fromSecret: false
- secretName: ""
- value: ""
diff --git a/libs/libapi/README.md b/libs/libapi/README.md
index dc629059..8ab47fe8 100644
--- a/libs/libapi/README.md
+++ b/libs/libapi/README.md
@@ -14,2 +14 @@ Set environment variables to configure the application (`API_` prefix):
-- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'Authorization' header). If not set, the JWT is ignored. Defaults to empty.
-- `API_HF_JWT_ADDITIONAL_PUBLIC_KEYS`: a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub. The public keys must be in PEM format and include "\n" for line breaks ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
+- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'X-Api-Key' header). If not set, the JWT are ignored. Defaults to empty.
diff --git a/libs/libapi/src/libapi/authentication.py b/libs/libapi/src/libapi/authentication.py
index cd80bd3a..9ce8345e 100644
--- a/libs/libapi/src/libapi/authentication.py
+++ b/libs/libapi/src/libapi/authentication.py
@@ -5 +5 @@ import logging
-from typing import List, Literal, Optional
+from typing import Literal, Optional
@@ -58 +58 @@ def auth_check(
- hf_jwt_public_keys: Optional[List[str]] = None,
+ hf_jwt_public_key: Optional[str] = None,
@@ -76 +76 @@ def auth_check(
- hf_jwt_public_keys (List[str]|None): the public keys to use to decode the JWT token
+ hf_jwt_public_key (str|None): the public key to use to decode the JWT token
@@ -86 +86 @@ def auth_check(
- if (jwt_token := get_jwt_token(request)) and hf_jwt_public_keys and hf_jwt_algorithm:
+ if (jwt_token := get_jwt_token(request)) and hf_jwt_public_key and hf_jwt_algorithm:
@@ -88 +88 @@ def auth_check(
- dataset=dataset, token=jwt_token, public_keys=hf_jwt_public_keys, algorithm=hf_jwt_algorithm
+ dataset=dataset, token=jwt_token, public_key=hf_jwt_public_key, algorithm=hf_jwt_algorithm
diff --git a/libs/libapi/src/libapi/config.py b/libs/libapi/src/libapi/config.py
index f80bea97..a533253a 100644
--- a/libs/libapi/src/libapi/config.py
+++ b/libs/libapi/src/libapi/config.py
@@ -4,2 +4,2 @@
-from dataclasses import dataclass, field
-from typing import List, Optional
+from dataclasses import dataclass
+from typing import Optional
@@ -34 +33,0 @@ API_HF_JWT_PUBLIC_KEY_URL = None
-API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: List[str] = []
@@ -47 +45,0 @@ class ApiConfig:
- hf_jwt_additional_public_keys: List[str] = field(default_factory=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy)
@@ -64,3 +61,0 @@ class ApiConfig:
- hf_jwt_additional_public_keys=env.list(
- name="HF_JWT_ADDITIONAL_PUBLIC_KEYS", default=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy()
- ),
diff --git a/libs/libapi/src/libapi/jwt_token.py b/libs/libapi/src/libapi/jwt_token.py
index 2951c192..b3ec5b74 100644
--- a/libs/libapi/src/libapi/jwt_token.py
+++ b/libs/libapi/src/libapi/jwt_token.py
@@ -5 +5 @@ import logging
-from typing import Any, List, Optional, Union
+from typing import Any, Optional, Union
@@ -31 +30,0 @@ from jwt.algorithms import (
-from libapi.config import ApiConfig
@@ -126,17 +125 @@ def fetch_jwt_public_key(
-def get_jwt_public_keys(api_config: ApiConfig) -> List[str]:
- return (
- [
- fetch_jwt_public_key(
- url=api_config.hf_jwt_public_key_url,
- hf_jwt_algorithm=api_config.hf_jwt_algorithm,
- hf_timeout_seconds=api_config.hf_timeout_seconds,
- )
- ]
- if api_config.hf_jwt_public_key_url and api_config.hf_jwt_algorithm
- else []
- ) + api_config.hf_jwt_additional_public_keys
-
-
-def validate_jwt(
- dataset: str, token: Any, public_keys: List[str], algorithm: str, verify_exp: Optional[bool] = True
-) -> None:
+def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, verify_exp: Optional[bool] = True) -> None:
@@ -154 +137 @@ def validate_jwt(
- public_keys (List[str]): the public keys to use to decode the JWT token. They are tried in order.
+ public_key (str): the public key to use to decode the JWT token
@@ -161,31 +144,30 @@ def validate_jwt(
- for public_key in public_keys:
- try:
- decoded = jwt.decode(
- jwt=token,
- key=public_key,
- algorithms=[algorithm],
- options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
- )
- logging.debug(f"Decoded JWT is: '{public_key}'.")
- break
- except jwt.exceptions.InvalidSignatureError as e:
- if public_key == public_keys[-1]:
- raise JWTInvalidSignature(
- "The JWT signature verification failed. Check the signing key and the algorithm.", e
- ) from e
- logging.debug(f"JWT signature verification failed with key: '{public_key}'. Trying next key.")
- except jwt.exceptions.MissingRequiredClaimError as e:
- raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
- except jwt.exceptions.ExpiredSignatureError as e:
- raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
-
- except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
- raise JWTInvalidKeyOrAlgorithm(
- (
- "The key used to verify the signature is not compatible with the algorithm. Check the signing key"
- " and the algorithm."
- ),
- e,
- ) from e
- except Exception as e:
- raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
+ try:
+ decoded = jwt.decode(
+ jwt=token,
+ key=public_key,
+ algorithms=[algorithm],
+ options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
+ )
+ logging.debug(f"Decoded JWT is: '{public_key}'.")
+ except jwt.exceptions.MissingRequiredClaimError as e:
+ raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
+ except jwt.exceptions.ExpiredSignatureError as e:
+ raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
+ except jwt.exceptions.InvalidSignatureError as e:
+ raise JWTInvalidSignature(
+ "The JWT signature verification failed. Check the signing key and the algorithm.", e
+ ) from e
+ except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
+ raise JWTInvalidKeyOrAlgorithm(
+ (
+ "The key used to verify the signature is not compatible with the algorithm. Check the signing key and"
+ " the algorithm."
+ ),
+ e,
+ ) from e
+ except Exception as e:
+ logging.debug(
+ f"Missing public key '{public_key}' or algorithm '{algorithm}' to decode JWT token. Skipping JWT"
+ " validation."
+ )
+ raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
diff --git a/libs/libapi/tests/test_authentication.py b/libs/libapi/tests/test_authentication.py
index 6bb37c8b..2a1d8e3f 100644
--- a/libs/libapi/tests/test_authentication.py
+++ b/libs/libapi/tests/test_authentication.py
@@ -196 +196 @@ def assert_auth_headers(
- hf_jwt_public_keys=[public_key],
+ hf_jwt_public_key=public_key,
diff --git a/libs/libapi/tests/test_jwt_token.py b/libs/libapi/tests/test_jwt_token.py
index 25dbab13..5926cd51 100644
--- a/libs/libapi/tests/test_jwt_token.py
+++ b/libs/libapi/tests/test_jwt_token.py
@@ -6 +6 @@ from contextlib import nullcontext as does_not_raise
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict
@@ -11 +10,0 @@ import pytest
-from libapi.config import ApiConfig
@@ -20 +19 @@ from libapi.exceptions import (
-from libapi.jwt_token import get_jwt_public_keys, parse_jwt_public_key, validate_jwt
+from libapi.jwt_token import parse_jwt_public_key, validate_jwt
@@ -40,29 +38,0 @@ UNSUPPORTED_ALGORITHM_JWT_KEYS = [
[email protected](
- "keys_env_var,expected_keys",
- [
- ("", []),
- (
- (
- "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END"
- " PUBLIC KEY-----\n"
- ),
- [HUB_JWT_PUBLIC_KEY],
- ),
- (
- (
- "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END"
- " PUBLIC KEY-----\n,-----BEGIN PUBLIC"
- " KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END PUBLIC KEY-----\n"
- ),
- [HUB_JWT_PUBLIC_KEY, HUB_JWT_PUBLIC_KEY],
- ),
- ],
-)
-def test_get_jwt_public_keys(keys_env_var: str, expected_keys: List[str]) -> None:
- monkeypatch = pytest.MonkeyPatch()
- monkeypatch.setenv("API_HF_JWT_ADDITIONAL_PUBLIC_KEYS", keys_env_var)
- api_config = ApiConfig.from_env(hf_endpoint="")
- assert get_jwt_public_keys(api_config) == expected_keys
- monkeypatch.undo()
-
-
@@ -97 +67 @@ def test_is_jwt_valid_with_ec() -> None:
- public_keys=[HUB_JWT_PUBLIC_KEY],
+ public_key=HUB_JWT_PUBLIC_KEY,
@@ -145,5 +115 @@ def encode_jwt(payload: Dict[str, Any]) -> str:
-def assert_jwt(
- token: str, expectation: Any, public_keys: Optional[List[str]] = None, algorithm: str = algorithm_ok
-) -> None:
- if public_keys is None:
- public_keys = [public_key_ok]
+def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, algorithm: str = algorithm_ok) -> None:
@@ -151 +117 @@ def assert_jwt(
- validate_jwt(dataset=dataset_ok, token=token, public_keys=public_keys, algorithm=algorithm)
+ validate_jwt(dataset=dataset_ok, token=token, public_key=public_key, algorithm=algorithm)
@@ -155 +121 @@ def assert_jwt(
- "public_keys,expectation",
+ "public_key,expectation",
@@ -157,4 +123,2 @@ def assert_jwt(
- ([other_public_key], pytest.raises(JWTInvalidSignature)),
- ([public_key_ok], does_not_raise()),
- ([public_key_ok, other_public_key], does_not_raise()),
- ([other_public_key, public_key_ok], does_not_raise()),
+ (other_public_key, pytest.raises(JWTInvalidSignature)),
+ (public_key_ok, does_not_raise()),
@@ -163,2 +127,2 @@ def assert_jwt(
-def test_validate_jwt_public_key(public_keys: List[str], expectation: Any) -> None:
- assert_jwt(encode_jwt(payload_ok), expectation, public_keys=public_keys)
+def test_validate_jwt_public_key(public_key: str, expectation: Any) -> None:
+ assert_jwt(encode_jwt(payload_ok), expectation, public_key=public_key)
diff --git a/services/api/src/api/app.py b/services/api/src/api/app.py
index 195adb72..85625f38 100644
--- a/services/api/src/api/app.py
+++ b/services/api/src/api/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import get_jwt_public_keys
+from libapi.jwt_token import fetch_jwt_public_key
@@ -37 +37,9 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
+ hf_jwt_public_key = (
+ fetch_jwt_public_key(
+ url=app_config.api.hf_jwt_public_key_url,
+ hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
+ hf_timeout_seconds=app_config.api.hf_timeout_seconds,
+ )
+ if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
+ else None
+ )
@@ -64 +72 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/api/src/api/routes/endpoint.py b/services/api/src/api/routes/endpoint.py
index 75e023f6..b3820ae1 100644
--- a/services/api/src/api/routes/endpoint.py
+++ b/services/api/src/api/routes/endpoint.py
@@ -231 +231 @@ def create_endpoint(
- hf_jwt_public_keys: Optional[List[str]] = None,
+ hf_jwt_public_key: Optional[str] = None,
@@ -277 +277 @@ def create_endpoint(
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/rows/src/rows/app.py b/services/rows/src/rows/app.py
index 2a678198..d792fc80 100644
--- a/services/rows/src/rows/app.py
+++ b/services/rows/src/rows/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import get_jwt_public_keys
+from libapi.jwt_token import fetch_jwt_public_key
@@ -40 +40,9 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
+ hf_jwt_public_key = (
+ fetch_jwt_public_key(
+ url=app_config.api.hf_jwt_public_key_url,
+ hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
+ hf_timeout_seconds=app_config.api.hf_timeout_seconds,
+ )
+ if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
+ else None
+ )
@@ -71 +79 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index da447a97..fbad46a6 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -92 +92 @@ def create_rows_endpoint(
- hf_jwt_public_keys: Optional[List[str]] = None,
+ hf_jwt_public_key: Optional[str] = None,
@@ -140 +140 @@ def create_rows_endpoint(
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/search/src/search/app.py b/services/search/src/search/app.py
index a0b89074..ba71f39a 100644
--- a/services/search/src/search/app.py
+++ b/services/search/src/search/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import get_jwt_public_keys
+from libapi.jwt_token import fetch_jwt_public_key
@@ -45 +45,9 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
+ hf_jwt_public_key = (
+ fetch_jwt_public_key(
+ url=app_config.api.hf_jwt_public_key_url,
+ hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
+ hf_timeout_seconds=app_config.api.hf_timeout_seconds,
+ )
+ if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
+ else None
+ )
@@ -77 +85 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index 408cfa51..299e14a9 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -204 +204 @@ def create_search_endpoint(
- hf_jwt_public_keys: Optional[List[str]] = None,
+ hf_jwt_public_key: Optional[str] = None,
@@ -251 +251 @@ def create_search_endpoint(
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/tools/docker-compose-base.yml b/tools/docker-compose-base.yml
index 27b5326c..52bb9a40 100644
--- a/tools/docker-compose-base.yml
+++ b/tools/docker-compose-base.yml
@@ -37,8 +36,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index 23af5ce9..3de9d546 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -71,0 +72,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -101,0 +109,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -131,0 +146,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-base.yml b/tools/docker-compose-dev-base.yml
index c85ea249..a4a02e69 100644
--- a/tools/docker-compose-dev-base.yml
+++ b/tools/docker-compose-dev-base.yml
@@ -48,8 +47,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
- API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index 92ba68c5..ca42d26a 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -73,0 +74,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -103,0 +111,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -134,0 +149,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
|
|
45cd1298b62f8f923eb6bb7763ef8824a397e242
|
Sylvain Lesage
| 2023-08-18T15:03:53 |
Create jwt array again (#1708)
|
diff --git a/chart/Chart.yaml b/chart/Chart.yaml
index 84f404b9..483a7337 100644
--- a/chart/Chart.yaml
+++ b/chart/Chart.yaml
@@ -21 +21 @@ type: application
-version: 1.16.3
+version: 1.17.0
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index efe374e1..7e6f7eb7 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -78,0 +79 @@ secrets:
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-prod-datasets-server-jwt-additional-public-keys"
@@ -90,0 +92,3 @@ secrets:
+ hfJwtAdditionalPublicKeys:
+ fromSecret: true
+ secretName: "datasets-server-prod-secrets"
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index 7769b640..4a38838b 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -74,0 +75 @@ secrets:
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-ephemeral-datasets-server-jwt-additional-public-keys"
@@ -86,0 +88,3 @@ secrets:
+ hfJwtAdditionalPublicKeys:
+ fromSecret: true
+ secretName: "datasets-server-staging-secrets"
diff --git a/chart/templates/_env/_envHf.tpl b/chart/templates/_env/_envHf.tpl
new file mode 100644
index 00000000..991ecdc1
--- /dev/null
+++ b/chart/templates/_env/_envHf.tpl
@@ -0,0 +1,33 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2022 The HuggingFace Authors.
+
+{{- define "envHf" -}}
+- name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+- name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+- name: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
+ {{- if .Values.secrets.hfJwtAdditionalPublicKeys.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfJwtAdditionalPublicKeys.secretName | quote }}
+ key: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfJwtAdditionalPublicKeys.value | quote }}
+ {{- end }}
+- name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+- name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+- name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value | quote }}
+ {{- end }}
+{{- end -}}
diff --git a/chart/templates/services/api/_container.tpl b/chart/templates/services/api/_container.tpl
index f64b68c5..2288c02a 100644
--- a/chart/templates/services/api/_container.tpl
+++ b/chart/templates/services/api/_container.tpl
@@ -11,0 +12 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -15,18 +15,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/templates/services/rows/_container.tpl b/chart/templates/services/rows/_container.tpl
index 4787ff77..94881190 100644
--- a/chart/templates/services/rows/_container.tpl
+++ b/chart/templates/services/rows/_container.tpl
@@ -13,0 +14 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -17,18 +17,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/templates/services/search/_container.tpl b/chart/templates/services/search/_container.tpl
index b9b3776d..6cced994 100644
--- a/chart/templates/services/search/_container.tpl
+++ b/chart/templates/services/search/_container.tpl
@@ -12,0 +13 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -15,18 +15,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/values.yaml b/chart/values.yaml
index 1e0a888b..066ca07c 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -105,0 +106,7 @@ secrets:
+ # a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub.
+ # The public keys must be in PEM format and include "\n" for line breaks
+ # ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
+ hfJwtAdditionalPublicKeys:
+ fromSecret: false
+ secretName: ""
+ value: ""
diff --git a/libs/libapi/README.md b/libs/libapi/README.md
index 8ab47fe8..dc629059 100644
--- a/libs/libapi/README.md
+++ b/libs/libapi/README.md
@@ -14 +14,2 @@ Set environment variables to configure the application (`API_` prefix):
-- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'X-Api-Key' header). If not set, the JWT are ignored. Defaults to empty.
+- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'Authorization' header). If not set, the JWT is ignored. Defaults to empty.
+- `API_HF_JWT_ADDITIONAL_PUBLIC_KEYS`: a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub. The public keys must be in PEM format and include "\n" for line breaks ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
diff --git a/libs/libapi/src/libapi/authentication.py b/libs/libapi/src/libapi/authentication.py
index 9ce8345e..cd80bd3a 100644
--- a/libs/libapi/src/libapi/authentication.py
+++ b/libs/libapi/src/libapi/authentication.py
@@ -5 +5 @@ import logging
-from typing import Literal, Optional
+from typing import List, Literal, Optional
@@ -58 +58 @@ def auth_check(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -76 +76 @@ def auth_check(
- hf_jwt_public_key (str|None): the public key to use to decode the JWT token
+ hf_jwt_public_keys (List[str]|None): the public keys to use to decode the JWT token
@@ -86 +86 @@ def auth_check(
- if (jwt_token := get_jwt_token(request)) and hf_jwt_public_key and hf_jwt_algorithm:
+ if (jwt_token := get_jwt_token(request)) and hf_jwt_public_keys and hf_jwt_algorithm:
@@ -88 +88 @@ def auth_check(
- dataset=dataset, token=jwt_token, public_key=hf_jwt_public_key, algorithm=hf_jwt_algorithm
+ dataset=dataset, token=jwt_token, public_keys=hf_jwt_public_keys, algorithm=hf_jwt_algorithm
diff --git a/libs/libapi/src/libapi/config.py b/libs/libapi/src/libapi/config.py
index a533253a..f80bea97 100644
--- a/libs/libapi/src/libapi/config.py
+++ b/libs/libapi/src/libapi/config.py
@@ -4,2 +4,2 @@
-from dataclasses import dataclass
-from typing import Optional
+from dataclasses import dataclass, field
+from typing import List, Optional
@@ -33,0 +34 @@ API_HF_JWT_PUBLIC_KEY_URL = None
+API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: List[str] = []
@@ -45,0 +47 @@ class ApiConfig:
+ hf_jwt_additional_public_keys: List[str] = field(default_factory=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy)
@@ -61,0 +64,3 @@ class ApiConfig:
+ hf_jwt_additional_public_keys=env.list(
+ name="HF_JWT_ADDITIONAL_PUBLIC_KEYS", default=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy()
+ ),
diff --git a/libs/libapi/src/libapi/jwt_token.py b/libs/libapi/src/libapi/jwt_token.py
index b3ec5b74..2951c192 100644
--- a/libs/libapi/src/libapi/jwt_token.py
+++ b/libs/libapi/src/libapi/jwt_token.py
@@ -5 +5 @@ import logging
-from typing import Any, Optional, Union
+from typing import Any, List, Optional, Union
@@ -30,0 +31 @@ from jwt.algorithms import (
+from libapi.config import ApiConfig
@@ -125 +126,17 @@ def fetch_jwt_public_key(
-def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, verify_exp: Optional[bool] = True) -> None:
+def get_jwt_public_keys(api_config: ApiConfig) -> List[str]:
+ return (
+ [
+ fetch_jwt_public_key(
+ url=api_config.hf_jwt_public_key_url,
+ hf_jwt_algorithm=api_config.hf_jwt_algorithm,
+ hf_timeout_seconds=api_config.hf_timeout_seconds,
+ )
+ ]
+ if api_config.hf_jwt_public_key_url and api_config.hf_jwt_algorithm
+ else []
+ ) + api_config.hf_jwt_additional_public_keys
+
+
+def validate_jwt(
+ dataset: str, token: Any, public_keys: List[str], algorithm: str, verify_exp: Optional[bool] = True
+) -> None:
@@ -137 +154 @@ def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, veri
- public_key (str): the public key to use to decode the JWT token
+ public_keys (List[str]): the public keys to use to decode the JWT token. They are tried in order.
@@ -144,30 +161,31 @@ def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, veri
- try:
- decoded = jwt.decode(
- jwt=token,
- key=public_key,
- algorithms=[algorithm],
- options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
- )
- logging.debug(f"Decoded JWT is: '{public_key}'.")
- except jwt.exceptions.MissingRequiredClaimError as e:
- raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
- except jwt.exceptions.ExpiredSignatureError as e:
- raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
- except jwt.exceptions.InvalidSignatureError as e:
- raise JWTInvalidSignature(
- "The JWT signature verification failed. Check the signing key and the algorithm.", e
- ) from e
- except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
- raise JWTInvalidKeyOrAlgorithm(
- (
- "The key used to verify the signature is not compatible with the algorithm. Check the signing key and"
- " the algorithm."
- ),
- e,
- ) from e
- except Exception as e:
- logging.debug(
- f"Missing public key '{public_key}' or algorithm '{algorithm}' to decode JWT token. Skipping JWT"
- " validation."
- )
- raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
+ for public_key in public_keys:
+ try:
+ decoded = jwt.decode(
+ jwt=token,
+ key=public_key,
+ algorithms=[algorithm],
+ options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
+ )
+ logging.debug(f"Decoded JWT is: '{public_key}'.")
+ break
+ except jwt.exceptions.InvalidSignatureError as e:
+ if public_key == public_keys[-1]:
+ raise JWTInvalidSignature(
+ "The JWT signature verification failed. Check the signing key and the algorithm.", e
+ ) from e
+ logging.debug(f"JWT signature verification failed with key: '{public_key}'. Trying next key.")
+ except jwt.exceptions.MissingRequiredClaimError as e:
+ raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
+ except jwt.exceptions.ExpiredSignatureError as e:
+ raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
+
+ except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
+ raise JWTInvalidKeyOrAlgorithm(
+ (
+ "The key used to verify the signature is not compatible with the algorithm. Check the signing key"
+ " and the algorithm."
+ ),
+ e,
+ ) from e
+ except Exception as e:
+ raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
diff --git a/libs/libapi/tests/test_authentication.py b/libs/libapi/tests/test_authentication.py
index 2a1d8e3f..6bb37c8b 100644
--- a/libs/libapi/tests/test_authentication.py
+++ b/libs/libapi/tests/test_authentication.py
@@ -196 +196 @@ def assert_auth_headers(
- hf_jwt_public_key=public_key,
+ hf_jwt_public_keys=[public_key],
diff --git a/libs/libapi/tests/test_jwt_token.py b/libs/libapi/tests/test_jwt_token.py
index 5926cd51..25dbab13 100644
--- a/libs/libapi/tests/test_jwt_token.py
+++ b/libs/libapi/tests/test_jwt_token.py
@@ -6 +6 @@ from contextlib import nullcontext as does_not_raise
-from typing import Any, Dict
+from typing import Any, Dict, List, Optional
@@ -10,0 +11 @@ import pytest
+from libapi.config import ApiConfig
@@ -19 +20 @@ from libapi.exceptions import (
-from libapi.jwt_token import parse_jwt_public_key, validate_jwt
+from libapi.jwt_token import get_jwt_public_keys, parse_jwt_public_key, validate_jwt
@@ -38,0 +40,29 @@ UNSUPPORTED_ALGORITHM_JWT_KEYS = [
[email protected](
+ "keys_env_var,expected_keys",
+ [
+ ("", []),
+ (
+ (
+ "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END"
+ " PUBLIC KEY-----\n"
+ ),
+ [HUB_JWT_PUBLIC_KEY],
+ ),
+ (
+ (
+ "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END"
+ " PUBLIC KEY-----\n,-----BEGIN PUBLIC"
+ " KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END PUBLIC KEY-----\n"
+ ),
+ [HUB_JWT_PUBLIC_KEY, HUB_JWT_PUBLIC_KEY],
+ ),
+ ],
+)
+def test_get_jwt_public_keys(keys_env_var: str, expected_keys: List[str]) -> None:
+ monkeypatch = pytest.MonkeyPatch()
+ monkeypatch.setenv("API_HF_JWT_ADDITIONAL_PUBLIC_KEYS", keys_env_var)
+ api_config = ApiConfig.from_env(hf_endpoint="")
+ assert get_jwt_public_keys(api_config) == expected_keys
+ monkeypatch.undo()
+
+
@@ -67 +97 @@ def test_is_jwt_valid_with_ec() -> None:
- public_key=HUB_JWT_PUBLIC_KEY,
+ public_keys=[HUB_JWT_PUBLIC_KEY],
@@ -115 +145,5 @@ def encode_jwt(payload: Dict[str, Any]) -> str:
-def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, algorithm: str = algorithm_ok) -> None:
+def assert_jwt(
+ token: str, expectation: Any, public_keys: Optional[List[str]] = None, algorithm: str = algorithm_ok
+) -> None:
+ if public_keys is None:
+ public_keys = [public_key_ok]
@@ -117 +151 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- validate_jwt(dataset=dataset_ok, token=token, public_key=public_key, algorithm=algorithm)
+ validate_jwt(dataset=dataset_ok, token=token, public_keys=public_keys, algorithm=algorithm)
@@ -121 +155 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- "public_key,expectation",
+ "public_keys,expectation",
@@ -123,2 +157,4 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- (other_public_key, pytest.raises(JWTInvalidSignature)),
- (public_key_ok, does_not_raise()),
+ ([other_public_key], pytest.raises(JWTInvalidSignature)),
+ ([public_key_ok], does_not_raise()),
+ ([public_key_ok, other_public_key], does_not_raise()),
+ ([other_public_key, public_key_ok], does_not_raise()),
@@ -127,2 +163,2 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
-def test_validate_jwt_public_key(public_key: str, expectation: Any) -> None:
- assert_jwt(encode_jwt(payload_ok), expectation, public_key=public_key)
+def test_validate_jwt_public_key(public_keys: List[str], expectation: Any) -> None:
+ assert_jwt(encode_jwt(payload_ok), expectation, public_keys=public_keys)
diff --git a/services/api/src/api/app.py b/services/api/src/api/app.py
index 85625f38..195adb72 100644
--- a/services/api/src/api/app.py
+++ b/services/api/src/api/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -37,9 +37 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
- )
+ hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
@@ -72 +64 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/api/src/api/routes/endpoint.py b/services/api/src/api/routes/endpoint.py
index b3820ae1..75e023f6 100644
--- a/services/api/src/api/routes/endpoint.py
+++ b/services/api/src/api/routes/endpoint.py
@@ -231 +231 @@ def create_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -277 +277 @@ def create_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/rows/src/rows/app.py b/services/rows/src/rows/app.py
index d792fc80..2a678198 100644
--- a/services/rows/src/rows/app.py
+++ b/services/rows/src/rows/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -40,9 +40 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
- )
+ hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
@@ -79 +71 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index fbad46a6..da447a97 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -92 +92 @@ def create_rows_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -140 +140 @@ def create_rows_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/search/src/search/app.py b/services/search/src/search/app.py
index ba71f39a..a0b89074 100644
--- a/services/search/src/search/app.py
+++ b/services/search/src/search/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -45,9 +45 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
- )
+ hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
@@ -85 +77 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index 299e14a9..408cfa51 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -204 +204 @@ def create_search_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -251 +251 @@ def create_search_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/tools/docker-compose-base.yml b/tools/docker-compose-base.yml
index 52bb9a40..27b5326c 100644
--- a/tools/docker-compose-base.yml
+++ b/tools/docker-compose-base.yml
@@ -36,0 +37,8 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index 3de9d546..23af5ce9 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -72,7 +71,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -109,7 +101,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -146,7 +131,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-base.yml b/tools/docker-compose-dev-base.yml
index a4a02e69..c85ea249 100644
--- a/tools/docker-compose-dev-base.yml
+++ b/tools/docker-compose-dev-base.yml
@@ -47,0 +48,8 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index ca42d26a..92ba68c5 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -74,7 +73,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -111,7 +103,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -149,7 +134,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
|
|
59c59e801d8dc4648a0bbd7708202448c1f2d6ae
|
Sylvain Lesage
| 2023-08-18T14:50:34 |
Revert both (#1707)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 7e6f7eb7..efe374e1 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -79 +78,0 @@ secrets:
- API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-prod-datasets-server-jwt-additional-public-keys"
@@ -92,3 +90,0 @@ secrets:
- hfJwtAdditionalPublicKeys:
- fromSecret: true
- secretName: "datasets-server-prod-secrets"
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index 4a38838b..7769b640 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -75 +74,0 @@ secrets:
- API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-ephemeral-datasets-server-jwt-additional-public-keys"
@@ -88,3 +86,0 @@ secrets:
- hfJwtAdditionalPublicKeys:
- fromSecret: true
- secretName: "datasets-server-staging-secrets"
diff --git a/chart/templates/_env/_envHf.tpl b/chart/templates/_env/_envHf.tpl
deleted file mode 100644
index dff10fa6..00000000
--- a/chart/templates/_env/_envHf.tpl
+++ /dev/null
@@ -1,33 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2022 The HuggingFace Authors.
-
-{{- define "envHf" -}}
-- name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
-- name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
-- name: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
- {{- if .Values.secrets.hfJwtAdditionalPublicKeys.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfJwtAdditionalPublicKeys.secretName | quote }}
- key: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfJwtAdditionalPublicKeys.value | quote }}
- {{- end }}
-- name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
-- name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
-- name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value | quote }}
- {{- end }}
-{{- end -}}
diff --git a/chart/templates/services/api/_container.tpl b/chart/templates/services/api/_container.tpl
index 2288c02a..f64b68c5 100644
--- a/chart/templates/services/api/_container.tpl
+++ b/chart/templates/services/api/_container.tpl
@@ -12 +11,0 @@
- {{ include "envHf" . | nindent 2 }}
@@ -15,0 +15,18 @@
+ - name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+ - name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+ - name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+ - name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+ - name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value }}
+ {{- end }}
diff --git a/chart/templates/services/rows/_container.tpl b/chart/templates/services/rows/_container.tpl
index 94881190..4787ff77 100644
--- a/chart/templates/services/rows/_container.tpl
+++ b/chart/templates/services/rows/_container.tpl
@@ -14 +13,0 @@
- {{ include "envHf" . | nindent 2 }}
@@ -17,0 +17,18 @@
+ - name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+ - name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+ - name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+ - name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+ - name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value }}
+ {{- end }}
diff --git a/chart/templates/services/search/_container.tpl b/chart/templates/services/search/_container.tpl
index 6cced994..b9b3776d 100644
--- a/chart/templates/services/search/_container.tpl
+++ b/chart/templates/services/search/_container.tpl
@@ -13 +12,0 @@
- {{ include "envHf" . | nindent 2 }}
@@ -15,0 +15,18 @@
+ - name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+ - name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+ - name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+ - name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+ - name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value }}
+ {{- end }}
diff --git a/chart/values.yaml b/chart/values.yaml
index 066ca07c..1e0a888b 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -106,7 +105,0 @@ secrets:
- # a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub.
- # The public keys must be in PEM format and include "\n" for line breaks
- # ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
- hfJwtAdditionalPublicKeys:
- fromSecret: false
- secretName: ""
- value: ""
diff --git a/libs/libapi/README.md b/libs/libapi/README.md
index dc629059..8ab47fe8 100644
--- a/libs/libapi/README.md
+++ b/libs/libapi/README.md
@@ -14,2 +14 @@ Set environment variables to configure the application (`API_` prefix):
-- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'Authorization' header). If not set, the JWT is ignored. Defaults to empty.
-- `API_HF_JWT_ADDITIONAL_PUBLIC_KEYS`: a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub. The public keys must be in PEM format and include "\n" for line breaks ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
+- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'X-Api-Key' header). If not set, the JWT are ignored. Defaults to empty.
diff --git a/libs/libapi/src/libapi/authentication.py b/libs/libapi/src/libapi/authentication.py
index cd80bd3a..9ce8345e 100644
--- a/libs/libapi/src/libapi/authentication.py
+++ b/libs/libapi/src/libapi/authentication.py
@@ -5 +5 @@ import logging
-from typing import List, Literal, Optional
+from typing import Literal, Optional
@@ -58 +58 @@ def auth_check(
- hf_jwt_public_keys: Optional[List[str]] = None,
+ hf_jwt_public_key: Optional[str] = None,
@@ -76 +76 @@ def auth_check(
- hf_jwt_public_keys (List[str]|None): the public keys to use to decode the JWT token
+ hf_jwt_public_key (str|None): the public key to use to decode the JWT token
@@ -86 +86 @@ def auth_check(
- if (jwt_token := get_jwt_token(request)) and hf_jwt_public_keys and hf_jwt_algorithm:
+ if (jwt_token := get_jwt_token(request)) and hf_jwt_public_key and hf_jwt_algorithm:
@@ -88 +88 @@ def auth_check(
- dataset=dataset, token=jwt_token, public_keys=hf_jwt_public_keys, algorithm=hf_jwt_algorithm
+ dataset=dataset, token=jwt_token, public_key=hf_jwt_public_key, algorithm=hf_jwt_algorithm
diff --git a/libs/libapi/src/libapi/config.py b/libs/libapi/src/libapi/config.py
index f80bea97..a533253a 100644
--- a/libs/libapi/src/libapi/config.py
+++ b/libs/libapi/src/libapi/config.py
@@ -4,2 +4,2 @@
-from dataclasses import dataclass, field
-from typing import List, Optional
+from dataclasses import dataclass
+from typing import Optional
@@ -34 +33,0 @@ API_HF_JWT_PUBLIC_KEY_URL = None
-API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: List[str] = []
@@ -47 +45,0 @@ class ApiConfig:
- hf_jwt_additional_public_keys: List[str] = field(default_factory=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy)
@@ -64,3 +61,0 @@ class ApiConfig:
- hf_jwt_additional_public_keys=env.list(
- name="HF_JWT_ADDITIONAL_PUBLIC_KEYS", default=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy()
- ),
diff --git a/libs/libapi/src/libapi/jwt_token.py b/libs/libapi/src/libapi/jwt_token.py
index 2951c192..b3ec5b74 100644
--- a/libs/libapi/src/libapi/jwt_token.py
+++ b/libs/libapi/src/libapi/jwt_token.py
@@ -5 +5 @@ import logging
-from typing import Any, List, Optional, Union
+from typing import Any, Optional, Union
@@ -31 +30,0 @@ from jwt.algorithms import (
-from libapi.config import ApiConfig
@@ -126,17 +125 @@ def fetch_jwt_public_key(
-def get_jwt_public_keys(api_config: ApiConfig) -> List[str]:
- return (
- [
- fetch_jwt_public_key(
- url=api_config.hf_jwt_public_key_url,
- hf_jwt_algorithm=api_config.hf_jwt_algorithm,
- hf_timeout_seconds=api_config.hf_timeout_seconds,
- )
- ]
- if api_config.hf_jwt_public_key_url and api_config.hf_jwt_algorithm
- else []
- ) + api_config.hf_jwt_additional_public_keys
-
-
-def validate_jwt(
- dataset: str, token: Any, public_keys: List[str], algorithm: str, verify_exp: Optional[bool] = True
-) -> None:
+def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, verify_exp: Optional[bool] = True) -> None:
@@ -154 +137 @@ def validate_jwt(
- public_keys (List[str]): the public keys to use to decode the JWT token. They are tried in order.
+ public_key (str): the public key to use to decode the JWT token
@@ -161,31 +144,30 @@ def validate_jwt(
- for public_key in public_keys:
- try:
- decoded = jwt.decode(
- jwt=token,
- key=public_key,
- algorithms=[algorithm],
- options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
- )
- logging.debug(f"Decoded JWT is: '{public_key}'.")
- break
- except jwt.exceptions.InvalidSignatureError as e:
- if public_key == public_keys[-1]:
- raise JWTInvalidSignature(
- "The JWT signature verification failed. Check the signing key and the algorithm.", e
- ) from e
- logging.debug(f"JWT signature verification failed with key: '{public_key}'. Trying next key.")
- except jwt.exceptions.MissingRequiredClaimError as e:
- raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
- except jwt.exceptions.ExpiredSignatureError as e:
- raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
-
- except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
- raise JWTInvalidKeyOrAlgorithm(
- (
- "The key used to verify the signature is not compatible with the algorithm. Check the signing key"
- " and the algorithm."
- ),
- e,
- ) from e
- except Exception as e:
- raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
+ try:
+ decoded = jwt.decode(
+ jwt=token,
+ key=public_key,
+ algorithms=[algorithm],
+ options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
+ )
+ logging.debug(f"Decoded JWT is: '{public_key}'.")
+ except jwt.exceptions.MissingRequiredClaimError as e:
+ raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
+ except jwt.exceptions.ExpiredSignatureError as e:
+ raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
+ except jwt.exceptions.InvalidSignatureError as e:
+ raise JWTInvalidSignature(
+ "The JWT signature verification failed. Check the signing key and the algorithm.", e
+ ) from e
+ except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
+ raise JWTInvalidKeyOrAlgorithm(
+ (
+ "The key used to verify the signature is not compatible with the algorithm. Check the signing key and"
+ " the algorithm."
+ ),
+ e,
+ ) from e
+ except Exception as e:
+ logging.debug(
+ f"Missing public key '{public_key}' or algorithm '{algorithm}' to decode JWT token. Skipping JWT"
+ " validation."
+ )
+ raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
diff --git a/libs/libapi/tests/test_authentication.py b/libs/libapi/tests/test_authentication.py
index 6bb37c8b..2a1d8e3f 100644
--- a/libs/libapi/tests/test_authentication.py
+++ b/libs/libapi/tests/test_authentication.py
@@ -196 +196 @@ def assert_auth_headers(
- hf_jwt_public_keys=[public_key],
+ hf_jwt_public_key=public_key,
diff --git a/libs/libapi/tests/test_jwt_token.py b/libs/libapi/tests/test_jwt_token.py
index 25dbab13..5926cd51 100644
--- a/libs/libapi/tests/test_jwt_token.py
+++ b/libs/libapi/tests/test_jwt_token.py
@@ -6 +6 @@ from contextlib import nullcontext as does_not_raise
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict
@@ -11 +10,0 @@ import pytest
-from libapi.config import ApiConfig
@@ -20 +19 @@ from libapi.exceptions import (
-from libapi.jwt_token import get_jwt_public_keys, parse_jwt_public_key, validate_jwt
+from libapi.jwt_token import parse_jwt_public_key, validate_jwt
@@ -40,29 +38,0 @@ UNSUPPORTED_ALGORITHM_JWT_KEYS = [
[email protected](
- "keys_env_var,expected_keys",
- [
- ("", []),
- (
- (
- "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END"
- " PUBLIC KEY-----\n"
- ),
- [HUB_JWT_PUBLIC_KEY],
- ),
- (
- (
- "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END"
- " PUBLIC KEY-----\n,-----BEGIN PUBLIC"
- " KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END PUBLIC KEY-----\n"
- ),
- [HUB_JWT_PUBLIC_KEY, HUB_JWT_PUBLIC_KEY],
- ),
- ],
-)
-def test_get_jwt_public_keys(keys_env_var: str, expected_keys: List[str]) -> None:
- monkeypatch = pytest.MonkeyPatch()
- monkeypatch.setenv("API_HF_JWT_ADDITIONAL_PUBLIC_KEYS", keys_env_var)
- api_config = ApiConfig.from_env(hf_endpoint="")
- assert get_jwt_public_keys(api_config) == expected_keys
- monkeypatch.undo()
-
-
@@ -97 +67 @@ def test_is_jwt_valid_with_ec() -> None:
- public_keys=[HUB_JWT_PUBLIC_KEY],
+ public_key=HUB_JWT_PUBLIC_KEY,
@@ -145,5 +115 @@ def encode_jwt(payload: Dict[str, Any]) -> str:
-def assert_jwt(
- token: str, expectation: Any, public_keys: Optional[List[str]] = None, algorithm: str = algorithm_ok
-) -> None:
- if public_keys is None:
- public_keys = [public_key_ok]
+def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, algorithm: str = algorithm_ok) -> None:
@@ -151 +117 @@ def assert_jwt(
- validate_jwt(dataset=dataset_ok, token=token, public_keys=public_keys, algorithm=algorithm)
+ validate_jwt(dataset=dataset_ok, token=token, public_key=public_key, algorithm=algorithm)
@@ -155 +121 @@ def assert_jwt(
- "public_keys,expectation",
+ "public_key,expectation",
@@ -157,4 +123,2 @@ def assert_jwt(
- ([other_public_key], pytest.raises(JWTInvalidSignature)),
- ([public_key_ok], does_not_raise()),
- ([public_key_ok, other_public_key], does_not_raise()),
- ([other_public_key, public_key_ok], does_not_raise()),
+ (other_public_key, pytest.raises(JWTInvalidSignature)),
+ (public_key_ok, does_not_raise()),
@@ -163,2 +127,2 @@ def assert_jwt(
-def test_validate_jwt_public_key(public_keys: List[str], expectation: Any) -> None:
- assert_jwt(encode_jwt(payload_ok), expectation, public_keys=public_keys)
+def test_validate_jwt_public_key(public_key: str, expectation: Any) -> None:
+ assert_jwt(encode_jwt(payload_ok), expectation, public_key=public_key)
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index 3efed875..59cb63ae 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -146,0 +147,6 @@ class CacheTotalMetricDocument(Document):
+ "indexes": [
+ {
+ "fields": ["kind", "http_status", "error_code"],
+ "unique": True,
+ }
+ ],
diff --git a/services/api/src/api/app.py b/services/api/src/api/app.py
index 195adb72..85625f38 100644
--- a/services/api/src/api/app.py
+++ b/services/api/src/api/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import get_jwt_public_keys
+from libapi.jwt_token import fetch_jwt_public_key
@@ -37 +37,9 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
+ hf_jwt_public_key = (
+ fetch_jwt_public_key(
+ url=app_config.api.hf_jwt_public_key_url,
+ hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
+ hf_timeout_seconds=app_config.api.hf_timeout_seconds,
+ )
+ if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
+ else None
+ )
@@ -64 +72 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/api/src/api/routes/endpoint.py b/services/api/src/api/routes/endpoint.py
index 75e023f6..b3820ae1 100644
--- a/services/api/src/api/routes/endpoint.py
+++ b/services/api/src/api/routes/endpoint.py
@@ -231 +231 @@ def create_endpoint(
- hf_jwt_public_keys: Optional[List[str]] = None,
+ hf_jwt_public_key: Optional[str] = None,
@@ -277 +277 @@ def create_endpoint(
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/rows/src/rows/app.py b/services/rows/src/rows/app.py
index 2a678198..d792fc80 100644
--- a/services/rows/src/rows/app.py
+++ b/services/rows/src/rows/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import get_jwt_public_keys
+from libapi.jwt_token import fetch_jwt_public_key
@@ -40 +40,9 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
+ hf_jwt_public_key = (
+ fetch_jwt_public_key(
+ url=app_config.api.hf_jwt_public_key_url,
+ hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
+ hf_timeout_seconds=app_config.api.hf_timeout_seconds,
+ )
+ if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
+ else None
+ )
@@ -71 +79 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index da447a97..fbad46a6 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -92 +92 @@ def create_rows_endpoint(
- hf_jwt_public_keys: Optional[List[str]] = None,
+ hf_jwt_public_key: Optional[str] = None,
@@ -140 +140 @@ def create_rows_endpoint(
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/search/src/search/app.py b/services/search/src/search/app.py
index a0b89074..ba71f39a 100644
--- a/services/search/src/search/app.py
+++ b/services/search/src/search/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import get_jwt_public_keys
+from libapi.jwt_token import fetch_jwt_public_key
@@ -45 +45,9 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
+ hf_jwt_public_key = (
+ fetch_jwt_public_key(
+ url=app_config.api.hf_jwt_public_key_url,
+ hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
+ hf_timeout_seconds=app_config.api.hf_timeout_seconds,
+ )
+ if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
+ else None
+ )
@@ -77 +85 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index 408cfa51..299e14a9 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -204 +204 @@ def create_search_endpoint(
- hf_jwt_public_keys: Optional[List[str]] = None,
+ hf_jwt_public_key: Optional[str] = None,
@@ -251 +251 @@ def create_search_endpoint(
- hf_jwt_public_keys=hf_jwt_public_keys,
+ hf_jwt_public_key=hf_jwt_public_key,
diff --git a/tools/docker-compose-base.yml b/tools/docker-compose-base.yml
index 27b5326c..52bb9a40 100644
--- a/tools/docker-compose-base.yml
+++ b/tools/docker-compose-base.yml
@@ -37,8 +36,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index 23af5ce9..3de9d546 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -71,0 +72,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -101,0 +109,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -131,0 +146,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-base.yml b/tools/docker-compose-dev-base.yml
index c85ea249..a4a02e69 100644
--- a/tools/docker-compose-dev-base.yml
+++ b/tools/docker-compose-dev-base.yml
@@ -48,8 +47,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
- API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index 92ba68c5..ca42d26a 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -73,0 +74,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -103,0 +111,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -134,0 +149,7 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
|
|
f1ca820bbdf9c9a22de46b81e802bab11c7f633d
|
Sylvain Lesage
| 2023-08-18T14:48:25 |
Revert "Add unique compound index to cache metric (#1703)" (#1706)
|
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index 59cb63ae..3efed875 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -147,6 +146,0 @@ class CacheTotalMetricDocument(Document):
- "indexes": [
- {
- "fields": ["kind", "http_status", "error_code"],
- "unique": True,
- }
- ],
|
|
1837ce7077d6972360580b761cfabee0cac229a7
|
Sylvain Lesage
| 2023-08-18T13:58:15 |
Use multiple keys for jwt decoding (#1704)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index efe374e1..7e6f7eb7 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -78,0 +79 @@ secrets:
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-prod-datasets-server-jwt-additional-public-keys"
@@ -90,0 +92,3 @@ secrets:
+ hfJwtAdditionalPublicKeys:
+ fromSecret: true
+ secretName: "datasets-server-prod-secrets"
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index 7769b640..4a38838b 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -74,0 +75 @@ secrets:
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: "hub-ephemeral-datasets-server-jwt-additional-public-keys"
@@ -86,0 +88,3 @@ secrets:
+ hfJwtAdditionalPublicKeys:
+ fromSecret: true
+ secretName: "datasets-server-staging-secrets"
diff --git a/chart/templates/_env/_envHf.tpl b/chart/templates/_env/_envHf.tpl
new file mode 100644
index 00000000..dff10fa6
--- /dev/null
+++ b/chart/templates/_env/_envHf.tpl
@@ -0,0 +1,33 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2022 The HuggingFace Authors.
+
+{{- define "envHf" -}}
+- name: API_HF_AUTH_PATH
+ value: {{ .Values.hf.authPath | quote }}
+- name: API_HF_JWT_PUBLIC_KEY_URL
+ value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
+- name: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
+ {{- if .Values.secrets.hfJwtAdditionalPublicKeys.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfJwtAdditionalPublicKeys.secretName | quote }}
+ key: API_HF_JWT_ADDITIONAL_PUBLIC_KEYS
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfJwtAdditionalPublicKeys.value | quote }}
+ {{- end }}
+- name: API_HF_JWT_ALGORITHM
+ value: {{ .Values.hf.jwtAlgorithm | quote }}
+- name: API_HF_TIMEOUT_SECONDS
+ value: {{ .Values.hf.timeoutSeconds | quote }}
+- name: API_HF_WEBHOOK_SECRET
+ {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
+ key: WEBHOOK_SECRET
+ optional: false
+ {{- else }}
+ value: {{ .Values.secrets.hfWebhookSecret.value | quote }}
+ {{- end }}
+{{- end -}}
diff --git a/chart/templates/services/api/_container.tpl b/chart/templates/services/api/_container.tpl
index f64b68c5..2288c02a 100644
--- a/chart/templates/services/api/_container.tpl
+++ b/chart/templates/services/api/_container.tpl
@@ -11,0 +12 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -15,18 +15,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/templates/services/rows/_container.tpl b/chart/templates/services/rows/_container.tpl
index 4787ff77..94881190 100644
--- a/chart/templates/services/rows/_container.tpl
+++ b/chart/templates/services/rows/_container.tpl
@@ -13,0 +14 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -17,18 +17,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/templates/services/search/_container.tpl b/chart/templates/services/search/_container.tpl
index b9b3776d..6cced994 100644
--- a/chart/templates/services/search/_container.tpl
+++ b/chart/templates/services/search/_container.tpl
@@ -12,0 +13 @@
+ {{ include "envHf" . | nindent 2 }}
@@ -15,18 +15,0 @@
- - name: API_HF_AUTH_PATH
- value: {{ .Values.hf.authPath | quote }}
- - name: API_HF_JWT_PUBLIC_KEY_URL
- value: {{ .Values.hf.jwtPublicKeyUrl | quote }}
- - name: API_HF_JWT_ALGORITHM
- value: {{ .Values.hf.jwtAlgorithm | quote }}
- - name: API_HF_TIMEOUT_SECONDS
- value: {{ .Values.hf.timeoutSeconds | quote }}
- - name: API_HF_WEBHOOK_SECRET
- {{- if .Values.secrets.hfWebhookSecret.fromSecret }}
- valueFrom:
- secretKeyRef:
- name: {{ .Values.secrets.hfWebhookSecret.secretName | quote }}
- key: WEBHOOK_SECRET
- optional: false
- {{- else }}
- value: {{ .Values.secrets.hfWebhookSecret.value }}
- {{- end }}
diff --git a/chart/values.yaml b/chart/values.yaml
index 1e0a888b..066ca07c 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -105,0 +106,7 @@ secrets:
+ # a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub.
+ # The public keys must be in PEM format and include "\n" for line breaks
+ # ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
+ hfJwtAdditionalPublicKeys:
+ fromSecret: false
+ secretName: ""
+ value: ""
diff --git a/libs/libapi/README.md b/libs/libapi/README.md
index 8ab47fe8..dc629059 100644
--- a/libs/libapi/README.md
+++ b/libs/libapi/README.md
@@ -14 +14,2 @@ Set environment variables to configure the application (`API_` prefix):
-- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'X-Api-Key' header). If not set, the JWT are ignored. Defaults to empty.
+- `API_HF_JWT_PUBLIC_KEY_URL`: the URL where the "Hub JWT public key" is published. The "Hub JWT public key" must be in JWK format. It helps to decode a JWT sent by the Hugging Face Hub, for example, to bypass the external authentication check (JWT in the 'Authorization' header). If not set, the JWT is ignored. Defaults to empty.
+- `API_HF_JWT_ADDITIONAL_PUBLIC_KEYS`: a comma-separated list of additional public keys to use to decode the JWT sent by the Hugging Face Hub. The public keys must be in PEM format and include "\n" for line breaks ("-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----\n"). Defaults to empty.
diff --git a/libs/libapi/src/libapi/authentication.py b/libs/libapi/src/libapi/authentication.py
index 9ce8345e..cd80bd3a 100644
--- a/libs/libapi/src/libapi/authentication.py
+++ b/libs/libapi/src/libapi/authentication.py
@@ -5 +5 @@ import logging
-from typing import Literal, Optional
+from typing import List, Literal, Optional
@@ -58 +58 @@ def auth_check(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -76 +76 @@ def auth_check(
- hf_jwt_public_key (str|None): the public key to use to decode the JWT token
+ hf_jwt_public_keys (List[str]|None): the public keys to use to decode the JWT token
@@ -86 +86 @@ def auth_check(
- if (jwt_token := get_jwt_token(request)) and hf_jwt_public_key and hf_jwt_algorithm:
+ if (jwt_token := get_jwt_token(request)) and hf_jwt_public_keys and hf_jwt_algorithm:
@@ -88 +88 @@ def auth_check(
- dataset=dataset, token=jwt_token, public_key=hf_jwt_public_key, algorithm=hf_jwt_algorithm
+ dataset=dataset, token=jwt_token, public_keys=hf_jwt_public_keys, algorithm=hf_jwt_algorithm
diff --git a/libs/libapi/src/libapi/config.py b/libs/libapi/src/libapi/config.py
index a533253a..f80bea97 100644
--- a/libs/libapi/src/libapi/config.py
+++ b/libs/libapi/src/libapi/config.py
@@ -4,2 +4,2 @@
-from dataclasses import dataclass
-from typing import Optional
+from dataclasses import dataclass, field
+from typing import List, Optional
@@ -33,0 +34 @@ API_HF_JWT_PUBLIC_KEY_URL = None
+API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: List[str] = []
@@ -45,0 +47 @@ class ApiConfig:
+ hf_jwt_additional_public_keys: List[str] = field(default_factory=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy)
@@ -61,0 +64,3 @@ class ApiConfig:
+ hf_jwt_additional_public_keys=env.list(
+ name="HF_JWT_ADDITIONAL_PUBLIC_KEYS", default=API_HF_JWT_ADDITIONAL_PUBLIC_KEYS.copy()
+ ),
diff --git a/libs/libapi/src/libapi/jwt_token.py b/libs/libapi/src/libapi/jwt_token.py
index b3ec5b74..2951c192 100644
--- a/libs/libapi/src/libapi/jwt_token.py
+++ b/libs/libapi/src/libapi/jwt_token.py
@@ -5 +5 @@ import logging
-from typing import Any, Optional, Union
+from typing import Any, List, Optional, Union
@@ -30,0 +31 @@ from jwt.algorithms import (
+from libapi.config import ApiConfig
@@ -125 +126,17 @@ def fetch_jwt_public_key(
-def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, verify_exp: Optional[bool] = True) -> None:
+def get_jwt_public_keys(api_config: ApiConfig) -> List[str]:
+ return (
+ [
+ fetch_jwt_public_key(
+ url=api_config.hf_jwt_public_key_url,
+ hf_jwt_algorithm=api_config.hf_jwt_algorithm,
+ hf_timeout_seconds=api_config.hf_timeout_seconds,
+ )
+ ]
+ if api_config.hf_jwt_public_key_url and api_config.hf_jwt_algorithm
+ else []
+ ) + api_config.hf_jwt_additional_public_keys
+
+
+def validate_jwt(
+ dataset: str, token: Any, public_keys: List[str], algorithm: str, verify_exp: Optional[bool] = True
+) -> None:
@@ -137 +154 @@ def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, veri
- public_key (str): the public key to use to decode the JWT token
+ public_keys (List[str]): the public keys to use to decode the JWT token. They are tried in order.
@@ -144,30 +161,31 @@ def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, veri
- try:
- decoded = jwt.decode(
- jwt=token,
- key=public_key,
- algorithms=[algorithm],
- options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
- )
- logging.debug(f"Decoded JWT is: '{public_key}'.")
- except jwt.exceptions.MissingRequiredClaimError as e:
- raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
- except jwt.exceptions.ExpiredSignatureError as e:
- raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
- except jwt.exceptions.InvalidSignatureError as e:
- raise JWTInvalidSignature(
- "The JWT signature verification failed. Check the signing key and the algorithm.", e
- ) from e
- except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
- raise JWTInvalidKeyOrAlgorithm(
- (
- "The key used to verify the signature is not compatible with the algorithm. Check the signing key and"
- " the algorithm."
- ),
- e,
- ) from e
- except Exception as e:
- logging.debug(
- f"Missing public key '{public_key}' or algorithm '{algorithm}' to decode JWT token. Skipping JWT"
- " validation."
- )
- raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
+ for public_key in public_keys:
+ try:
+ decoded = jwt.decode(
+ jwt=token,
+ key=public_key,
+ algorithms=[algorithm],
+ options={"require": ["exp", "sub", "read"], "verify_exp": verify_exp},
+ )
+ logging.debug(f"Decoded JWT is: '{public_key}'.")
+ break
+ except jwt.exceptions.InvalidSignatureError as e:
+ if public_key == public_keys[-1]:
+ raise JWTInvalidSignature(
+ "The JWT signature verification failed. Check the signing key and the algorithm.", e
+ ) from e
+ logging.debug(f"JWT signature verification failed with key: '{public_key}'. Trying next key.")
+ except jwt.exceptions.MissingRequiredClaimError as e:
+ raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
+ except jwt.exceptions.ExpiredSignatureError as e:
+ raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
+
+ except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
+ raise JWTInvalidKeyOrAlgorithm(
+ (
+ "The key used to verify the signature is not compatible with the algorithm. Check the signing key"
+ " and the algorithm."
+ ),
+ e,
+ ) from e
+ except Exception as e:
+ raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
diff --git a/libs/libapi/tests/test_authentication.py b/libs/libapi/tests/test_authentication.py
index 2a1d8e3f..6bb37c8b 100644
--- a/libs/libapi/tests/test_authentication.py
+++ b/libs/libapi/tests/test_authentication.py
@@ -196 +196 @@ def assert_auth_headers(
- hf_jwt_public_key=public_key,
+ hf_jwt_public_keys=[public_key],
diff --git a/libs/libapi/tests/test_jwt_token.py b/libs/libapi/tests/test_jwt_token.py
index 5926cd51..25dbab13 100644
--- a/libs/libapi/tests/test_jwt_token.py
+++ b/libs/libapi/tests/test_jwt_token.py
@@ -6 +6 @@ from contextlib import nullcontext as does_not_raise
-from typing import Any, Dict
+from typing import Any, Dict, List, Optional
@@ -10,0 +11 @@ import pytest
+from libapi.config import ApiConfig
@@ -19 +20 @@ from libapi.exceptions import (
-from libapi.jwt_token import parse_jwt_public_key, validate_jwt
+from libapi.jwt_token import get_jwt_public_keys, parse_jwt_public_key, validate_jwt
@@ -38,0 +40,29 @@ UNSUPPORTED_ALGORITHM_JWT_KEYS = [
[email protected](
+ "keys_env_var,expected_keys",
+ [
+ ("", []),
+ (
+ (
+ "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END"
+ " PUBLIC KEY-----\n"
+ ),
+ [HUB_JWT_PUBLIC_KEY],
+ ),
+ (
+ (
+ "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END"
+ " PUBLIC KEY-----\n,-----BEGIN PUBLIC"
+ " KEY-----\nMCowBQYDK2VwAyEA+RBhgyNluwaIL5KFJb6ZOL2H1nmyI8mW4Z2EHGDGCXM=\n-----END PUBLIC KEY-----\n"
+ ),
+ [HUB_JWT_PUBLIC_KEY, HUB_JWT_PUBLIC_KEY],
+ ),
+ ],
+)
+def test_get_jwt_public_keys(keys_env_var: str, expected_keys: List[str]) -> None:
+ monkeypatch = pytest.MonkeyPatch()
+ monkeypatch.setenv("API_HF_JWT_ADDITIONAL_PUBLIC_KEYS", keys_env_var)
+ api_config = ApiConfig.from_env(hf_endpoint="")
+ assert get_jwt_public_keys(api_config) == expected_keys
+ monkeypatch.undo()
+
+
@@ -67 +97 @@ def test_is_jwt_valid_with_ec() -> None:
- public_key=HUB_JWT_PUBLIC_KEY,
+ public_keys=[HUB_JWT_PUBLIC_KEY],
@@ -115 +145,5 @@ def encode_jwt(payload: Dict[str, Any]) -> str:
-def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, algorithm: str = algorithm_ok) -> None:
+def assert_jwt(
+ token: str, expectation: Any, public_keys: Optional[List[str]] = None, algorithm: str = algorithm_ok
+) -> None:
+ if public_keys is None:
+ public_keys = [public_key_ok]
@@ -117 +151 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- validate_jwt(dataset=dataset_ok, token=token, public_key=public_key, algorithm=algorithm)
+ validate_jwt(dataset=dataset_ok, token=token, public_keys=public_keys, algorithm=algorithm)
@@ -121 +155 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- "public_key,expectation",
+ "public_keys,expectation",
@@ -123,2 +157,4 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
- (other_public_key, pytest.raises(JWTInvalidSignature)),
- (public_key_ok, does_not_raise()),
+ ([other_public_key], pytest.raises(JWTInvalidSignature)),
+ ([public_key_ok], does_not_raise()),
+ ([public_key_ok, other_public_key], does_not_raise()),
+ ([other_public_key, public_key_ok], does_not_raise()),
@@ -127,2 +163,2 @@ def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, al
-def test_validate_jwt_public_key(public_key: str, expectation: Any) -> None:
- assert_jwt(encode_jwt(payload_ok), expectation, public_key=public_key)
+def test_validate_jwt_public_key(public_keys: List[str], expectation: Any) -> None:
+ assert_jwt(encode_jwt(payload_ok), expectation, public_keys=public_keys)
diff --git a/services/api/src/api/app.py b/services/api/src/api/app.py
index 85625f38..195adb72 100644
--- a/services/api/src/api/app.py
+++ b/services/api/src/api/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -37,9 +37 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
- )
+ hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
@@ -72 +64 @@ def create_app_with_config(app_config: AppConfig, endpoint_config: EndpointConfi
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/api/src/api/routes/endpoint.py b/services/api/src/api/routes/endpoint.py
index b3820ae1..75e023f6 100644
--- a/services/api/src/api/routes/endpoint.py
+++ b/services/api/src/api/routes/endpoint.py
@@ -231 +231 @@ def create_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -277 +277 @@ def create_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/rows/src/rows/app.py b/services/rows/src/rows/app.py
index d792fc80..2a678198 100644
--- a/services/rows/src/rows/app.py
+++ b/services/rows/src/rows/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -40,9 +40 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
- )
+ hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
@@ -79 +71 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index fbad46a6..da447a97 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -92 +92 @@ def create_rows_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -140 +140 @@ def create_rows_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/search/src/search/app.py b/services/search/src/search/app.py
index ba71f39a..a0b89074 100644
--- a/services/search/src/search/app.py
+++ b/services/search/src/search/app.py
@@ -6 +6 @@ from libapi.config import UvicornConfig
-from libapi.jwt_token import fetch_jwt_public_key
+from libapi.jwt_token import get_jwt_public_keys
@@ -45,9 +45 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key = (
- fetch_jwt_public_key(
- url=app_config.api.hf_jwt_public_key_url,
- hf_jwt_algorithm=app_config.api.hf_jwt_algorithm,
- hf_timeout_seconds=app_config.api.hf_timeout_seconds,
- )
- if app_config.api.hf_jwt_public_key_url and app_config.api.hf_jwt_algorithm
- else None
- )
+ hf_jwt_public_keys = get_jwt_public_keys(app_config.api)
@@ -85 +77 @@ def create_app_with_config(app_config: AppConfig) -> Starlette:
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index 299e14a9..408cfa51 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -204 +204 @@ def create_search_endpoint(
- hf_jwt_public_key: Optional[str] = None,
+ hf_jwt_public_keys: Optional[List[str]] = None,
@@ -251 +251 @@ def create_search_endpoint(
- hf_jwt_public_key=hf_jwt_public_key,
+ hf_jwt_public_keys=hf_jwt_public_keys,
diff --git a/tools/docker-compose-base.yml b/tools/docker-compose-base.yml
index 52bb9a40..27b5326c 100644
--- a/tools/docker-compose-base.yml
+++ b/tools/docker-compose-base.yml
@@ -36,0 +37,8 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index 3de9d546..23af5ce9 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -72,7 +71,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -109,7 +101,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -146,7 +131,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-base.yml b/tools/docker-compose-dev-base.yml
index a4a02e69..c85ea249 100644
--- a/tools/docker-compose-dev-base.yml
+++ b/tools/docker-compose-dev-base.yml
@@ -47,0 +48,8 @@ services:
+ # service
+ API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
+ API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
+ API_HF_JWT_ADDITIONAL_PUBLIC_KEYS: ${API_HF_JWT_ADDITIONAL_PUBLIC_KEYS-}
+ API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
+ API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
+ API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
+ API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index ca42d26a..92ba68c5 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -74,7 +73,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -111,7 +103,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://hub-ci.huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-1.0}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
@@ -149,7 +134,0 @@ services:
- # service
- API_HF_AUTH_PATH: ${API_HF_AUTH_PATH-/api/datasets/%s/auth-check}
- API_HF_JWT_PUBLIC_KEY_URL: ${API_HF_JWT_PUBLIC_KEY_URL-https://huggingface.co/api/keys/jwt}
- API_HF_JWT_ALGORITHM: ${API_HF_JWT_ALGORITHM-EdDSA}
- API_HF_TIMEOUT_SECONDS: ${API_HF_TIMEOUT_SECONDS-0.2}
- API_MAX_AGE_LONG: ${API_MAX_AGE_LONG-120}
- API_MAX_AGE_SHORT: ${API_MAX_AGE_SHORT-10}
|
|
ab99a259cbf9f961a5286a583239db8d50677e8e
|
Andrea Francis Soria Jimenez
| 2023-08-17T21:13:58 |
Add unique compound index to cache metric (#1703)
|
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index 3efed875..59cb63ae 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -146,0 +147,6 @@ class CacheTotalMetricDocument(Document):
+ "indexes": [
+ {
+ "fields": ["kind", "http_status", "error_code"],
+ "unique": True,
+ }
+ ],
|
|
3bef3f91f9d508fc67ecdc93720f952a9724bf5b
|
Andrea Francis Soria Jimenez
| 2023-08-17T20:32:18 |
Temporarily delete index (#1702)
|
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index aad7c819..3efed875 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -147 +146,0 @@ class CacheTotalMetricDocument(Document):
- "indexes": [("kind", "http_status", "error_code")],
|
|
641bfb9981e9268be7cc2193d28909d82a42d46e
|
Andrea Francis Soria Jimenez
| 2023-08-17T19:15:46 |
Set collect cache metrics as default schedule (#1701)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 90eb793d..efe374e1 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -192,4 +191,0 @@ backfill:
-cacheMetricsCollector:
- action: "collect-cache-metrics"
- schedule: "*/10 * * * *"
-
|
|
65ba08c5a65ad47cc238f4f0a3c1ffbfcb369b52
|
Quentin Lhoest
| 2023-08-17T18:41:30 |
Parquet renames docs (#1691)
|
diff --git a/docs/source/analyze_data.mdx b/docs/source/analyze_data.mdx
index e6c1a673..1c7231f1 100644
--- a/docs/source/analyze_data.mdx
+++ b/docs/source/analyze_data.mdx
@@ -27 +27 @@ print(data)
- {'dataset': 'codeparrot/codecomplex', 'config': 'codeparrot--codecomplex', 'split': 'train', 'url': 'https://huggingface.co/datasets/codeparrot/codecomplex/resolve/refs%2Fconvert%2Fparquet/codeparrot--codecomplex/json-train.parquet', 'filename': 'json-train.parquet', 'size': 4115908}
+ {'dataset': 'codeparrot/codecomplex', 'config': 'default', 'split': 'train', 'url': 'https://huggingface.co/datasets/codeparrot/codecomplex/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet', 'filename': '0000.parquet', 'size': 4115908}
@@ -40 +40 @@ import pandas as pd
-url = "https://huggingface.co/datasets/codeparrot/codecomplex/resolve/refs%2Fconvert%2Fparquet/codeparrot--codecomplex/json-train.parquet"
+url = "https://huggingface.co/datasets/codeparrot/codecomplex/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet"
diff --git a/docs/source/duckdb.mdx b/docs/source/duckdb.mdx
index b55fcd6c..67bb9da2 100644
--- a/docs/source/duckdb.mdx
+++ b/docs/source/duckdb.mdx
@@ -10 +10 @@ import duckdb
-url = "https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00000-of-00002.parquet"
+url = "https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0000.parquet"
@@ -25 +25 @@ con.exec('LOAD httpfs');
-const url = "https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00000-of-00002.parquet"
+const url = "https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0000.parquet"
diff --git a/docs/source/openapi.json b/docs/source/openapi.json
index ae4cd5f4..6314d09b 100644
--- a/docs/source/openapi.json
+++ b/docs/source/openapi.json
@@ -1414 +1414 @@
- "value": "yangdong--ecqa"
+ "value": "default"
@@ -1455 +1455 @@
- "value": "yangdong--ecqa"
+ "value": "default"
@@ -2179 +2179 @@
- "description": "Try with https://datasets-server.huggingface.co/first-rows?dataset=huggan/horse2zebra&config=huggan--horse2zebra-aligned&split=train.",
+ "description": "Try with https://datasets-server.huggingface.co/first-rows?dataset=huggan/horse2zebra&config=default&split=train.",
@@ -2182 +2182 @@
- "config": "huggan--horse2zebra-aligned",
+ "config": "default",
@@ -2205 +2205 @@
- "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/0/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/default/train/0/imageA/image.jpg",
@@ -2210 +2210 @@
- "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/0/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/default/train/0/imageB/image.jpg",
@@ -2221 +2221 @@
- "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/1/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/default/train/1/imageA/image.jpg",
@@ -2226 +2226 @@
- "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/1/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/default/train/1/imageB/image.jpg",
@@ -2237 +2237 @@
- "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/2/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/default/train/2/imageA/image.jpg",
@@ -2242 +2242 @@
- "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/2/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/default/train/2/imageB/image.jpg",
@@ -2637 +2637 @@
- "description": "Try with https://datasets-server.huggingface.co/rows?dataset=huggan/horse2zebra&config=huggan--horse2zebra-aligned&split=train&offset=234&length=3.",
+ "description": "Try with https://datasets-server.huggingface.co/rows?dataset=huggan/horse2zebra&config=default&split=train&offset=234&length=3.",
@@ -2656 +2656 @@
- "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/234/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/default/train/234/imageA/image.jpg",
@@ -2661 +2661 @@
- "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/234/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/default/train/234/imageB/image.jpg",
@@ -2672 +2672 @@
- "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/235/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/default/train/235/imageA/image.jpg",
@@ -2677 +2677 @@
- "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/235/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/default/train/235/imageB/image.jpg",
@@ -2688 +2688 @@
- "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/236/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/default/train/236/imageA/image.jpg",
@@ -2693 +2693 @@
- "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/236/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/default/train/236/imageB/image.jpg",
@@ -3358 +3358 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-test.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/test/0000.parquet",
@@ -3366 +3366 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-train.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/train/0000.parquet",
@@ -3374 +3374 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-validation.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/validation/0000.parquet",
@@ -3382 +3382 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-test.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/test/0000.parquet",
@@ -3390 +3390 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-train.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/train/0000.parquet",
@@ -3398 +3398 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-validation.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/validation/0000.parquet",
@@ -3417 +3417 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-test.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/test/0000.parquet",
@@ -3425 +3425 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-train.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/train/0000.parquet",
@@ -3433 +3433 @@
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-validation.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/validation/0000.parquet",
@@ -3460 +3460 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3462 +3462 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-test.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/test/0000.parquet",
@@ -3468 +3468 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3470 +3470 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00000-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet",
@@ -3476 +3476 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3478 +3478 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00001-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0001.parquet",
@@ -3484 +3484 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3486 +3486 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00002-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0002.parquet",
@@ -3492 +3492 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3494 +3494 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00003-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0003.parquet",
@@ -3500 +3500 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3502 +3502 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00004-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0004.parquet",
@@ -3508 +3508 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3510 +3510 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00005-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0005.parquet",
@@ -3516 +3516 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3518 +3518 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00006-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0006.parquet",
@@ -3524 +3524 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3526 +3526 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00007-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0007.parquet",
@@ -3532 +3532 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3534 +3534 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00008-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0008.parquet",
@@ -3540 +3540 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3542 +3542 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00009-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0009.parquet",
@@ -3548 +3548 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3550 +3550 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00010-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0010.parquet",
@@ -3556 +3556 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3558 +3558 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00011-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0011.parquet",
@@ -3564 +3564 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3566 +3566 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00012-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0012.parquet",
@@ -3572 +3572 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3574 +3574 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00013-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0013.parquet",
@@ -3580 +3580 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3582 +3582 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00014-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0014.parquet",
@@ -3588 +3588 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3590 +3590 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00015-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0015.parquet",
@@ -3596 +3596 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3598 +3598 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00016-of-00017.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/train/0016.parquet",
@@ -3604 +3604 @@
- "config": "alexandrainst--danish-wit",
+ "config": "default",
@@ -3606 +3606 @@
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-val.parquet",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/default/val/0000.parquet",
@@ -3615,0 +3616,107 @@
+ "partial parquet export": {
+ "summary": "c4 (en): the parquet export is partial (first 5GB)",
+ "description": "Try with https://datasets-server.huggingface.co/parquet?dataset=c4&config=en",
+ "value": {
+ "parquet_files": [
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0000.parquet",
+ "filename": "0000.parquet",
+ "size": 309207547
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0001.parquet",
+ "filename": "0001.parquet",
+ "size": 308665905
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0002.parquet",
+ "filename": "0002.parquet",
+ "size": 309066442
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0003.parquet",
+ "filename": "0003.parquet",
+ "size": 309257276
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0004.parquet",
+ "filename": "0004.parquet",
+ "size": 309040649
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0005.parquet",
+ "filename": "0005.parquet",
+ "size": 308850445
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0006.parquet",
+ "filename": "0006.parquet",
+ "size": 308432549
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0007.parquet",
+ "filename": "0007.parquet",
+ "size": 308621018
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0008.parquet",
+ "filename": "0008.parquet",
+ "size": 309109536
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial-train/0009.parquet",
+ "filename": "0009.parquet",
+ "size": 300817682
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "validation",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial/validation/0000.parquet",
+ "filename": "0000.parquet",
+ "size": 308896113
+ },
+ {
+ "dataset": "c4",
+ "config": "en",
+ "split": "validation",
+ "url": "https://huggingface.co/datasets/c4/resolve/refs%2Fconvert%2Fparquet/en/partial/validation/0001.parquet",
+ "filename": "0001.parquet",
+ "size": 200085262
+ }
+ ],
+ "pending": [],
+ "failed": [],
+ "partial": true
+ }
+ },
diff --git a/docs/source/pandas.mdx b/docs/source/pandas.mdx
index f15c4d29..02f5078b 100644
--- a/docs/source/pandas.mdx
+++ b/docs/source/pandas.mdx
@@ -11 +11 @@ df = (
- pd.read_parquet("https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00000-of-00002.parquet")
+ pd.read_parquet("https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0000.parquet")
diff --git a/docs/source/parquet.mdx b/docs/source/parquet.mdx
index 14f70954..be88c56c 100644
--- a/docs/source/parquet.mdx
+++ b/docs/source/parquet.mdx
@@ -7 +7 @@ Datasets can be published in any format (CSV, JSONL, directories of images, etc.
-In order for Datasets Server to generate a Parquet version of a dataset, the dataset must be *public* and it must be *less than 5GB* in size.
+In order for Datasets Server to generate a Parquet version of a dataset, the dataset must be *public*.
@@ -66,2 +66,2 @@ The endpoint also gives the filename and size of each file:
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-test.parquet",
- "filename": "duorc-test.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/test/0000.parquet",
+ "filename": "0000.parquet",
@@ -74,2 +74,2 @@ The endpoint also gives the filename and size of each file:
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-train.parquet",
- "filename": "duorc-train.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/train/0000.parquet",
+ "filename": "0000.parquet",
@@ -82,2 +82,2 @@ The endpoint also gives the filename and size of each file:
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-validation.parquet",
- "filename": "duorc-validation.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/validation/0000.parquet",
+ "filename": "0000.parquet",
@@ -90,2 +90,2 @@ The endpoint also gives the filename and size of each file:
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-test.parquet",
- "filename": "duorc-test.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/test/0000.parquet",
+ "filename": "0000.parquet",
@@ -98,2 +98,2 @@ The endpoint also gives the filename and size of each file:
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-train.parquet",
- "filename": "duorc-train.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/train/0000.parquet",
+ "filename": "0000.parquet",
@@ -106,2 +106,2 @@ The endpoint also gives the filename and size of each file:
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-validation.parquet",
- "filename": "duorc-validation.parquet",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/validation/0000.parquet",
+ "filename": "0000.parquet",
@@ -125,2 +125,2 @@ Big datasets are partitioned into Parquet files (shards) of about 500MB each. Th
- "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/amazon_polarity-test.parquet",
- "filename": "amazon_polarity-test.parquet",
+ "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/test/0000.parquet",
+ "filename": "0000.parquet",
@@ -133,2 +133,2 @@ Big datasets are partitioned into Parquet files (shards) of about 500MB each. Th
- "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/amazon_polarity-train-00000-of-00004.parquet",
- "filename": "amazon_polarity-train-00000-of-00004.parquet",
+ "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/train/0000.parquet",
+ "filename": "0000.parquet",
@@ -141,2 +141,2 @@ Big datasets are partitioned into Parquet files (shards) of about 500MB each. Th
- "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/amazon_polarity-train-00001-of-00004.parquet",
- "filename": "amazon_polarity-train-00001-of-00004.parquet",
+ "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/train/0001.parquet",
+ "filename": "0001.parquet",
@@ -149,2 +149,2 @@ Big datasets are partitioned into Parquet files (shards) of about 500MB each. Th
- "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/amazon_polarity-train-00002-of-00004.parquet",
- "filename": "amazon_polarity-train-00002-of-00004.parquet",
+ "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/train/0002.parquet",
+ "filename": "0002.parquet",
@@ -157,2 +157,2 @@ Big datasets are partitioned into Parquet files (shards) of about 500MB each. Th
- "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/amazon_polarity-train-00003-of-00004.parquet",
- "filename": "amazon_polarity-train-00003-of-00004.parquet",
+ "url": "https://huggingface.co/datasets/amazon_polarity/resolve/refs%2Fconvert%2Fparquet/amazon_polarity/train/0003.parquet",
+ "filename": "0003.parquet",
@@ -167,0 +168,6 @@ To read and query the Parquet files, take a look at the [Query datasets from Dat
+## Partially converted datasets
+
+The Parquet version can be partial if the dataset is not already in Parquet format or if it is bigger than 5GB.
+
+In that case the Parquet files are generated up to 5GB and placed in a split directory prefixed with "partial", e.g. "partial-train" instead of "train".
+
@@ -289 +295 @@ curl https://huggingface.co/api/datasets/duorc/parquet/ParaphraseRC/train \
-Each parquet file can also be accessed using its shard index: `https://huggingface.co/api/datasets/duorc/parquet/ParaphraseRC/train/0.parquet` redirects to `https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-train.parquet` for example.
+Each parquet file can also be accessed using its shard index: `https://huggingface.co/api/datasets/duorc/parquet/ParaphraseRC/train/0.parquet` redirects to `https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/train/0000.parquet` for example.
diff --git a/docs/source/polars.mdx b/docs/source/polars.mdx
index a02c2167..a5327748 100644
--- a/docs/source/polars.mdx
+++ b/docs/source/polars.mdx
@@ -18,2 +18,2 @@ urls
-['https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00000-of-00002.parquet',
- 'https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00001-of-00002.parquet']
+['https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0000.parquet',
+ 'https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0001.parquet']
@@ -28 +28 @@ df = (
- pl.read_parquet("https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00000-of-00002.parquet")
+ pl.read_parquet("https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0000.parquet")
@@ -95 +95 @@ q = (
- pl.scan_parquet("https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/blog_authorship_corpus-train-00000-of-00002.parquet")
+ pl.scan_parquet("https://huggingface.co/datasets/blog_authorship_corpus/resolve/refs%2Fconvert%2Fparquet/blog_authorship_corpus/train/0000.parquet")
diff --git a/docs/source/quick_start.mdx b/docs/source/quick_start.mdx
index b798b8e8..e299c6aa 100644
--- a/docs/source/quick_start.mdx
+++ b/docs/source/quick_start.mdx
@@ -432,3 +432,3 @@ print(data)
- {'dataset': 'rotten_tomatoes', 'config': 'default', 'split': 'test', 'url': 'https://huggingface.co/datasets/rotten_tomatoes/resolve/refs%2Fconvert%2Fparquet/default/rotten_tomatoes-test.parquet', 'filename': 'rotten_tomatoes-test.parquet', 'size': 92206},
- {'dataset': 'rotten_tomatoes', 'config': 'default', 'split': 'train', 'url': 'https://huggingface.co/datasets/rotten_tomatoes/resolve/refs%2Fconvert%2Fparquet/default/rotten_tomatoes-train.parquet', 'filename': 'rotten_tomatoes-train.parquet', 'size': 698845},
- {'dataset': 'rotten_tomatoes', 'config': 'default', 'split': 'validation', 'url': 'https://huggingface.co/datasets/rotten_tomatoes/resolve/refs%2Fconvert%2Fparquet/default/rotten_tomatoes-validation.parquet', 'filename': 'rotten_tomatoes-validation.parquet', 'size': 90001}
+ {'dataset': 'rotten_tomatoes', 'config': 'default', 'split': 'test', 'url': 'https://huggingface.co/datasets/rotten_tomatoes/resolve/refs%2Fconvert%2Fparquet/default/test/0000.parquet', 'filename': '0000.parquet', 'size': 92206},
+ {'dataset': 'rotten_tomatoes', 'config': 'default', 'split': 'train', 'url': 'https://huggingface.co/datasets/rotten_tomatoes/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet', 'filename': '0000.parquet' 'size': 698845},
+ {'dataset': 'rotten_tomatoes', 'config': 'default', 'split': 'validation', 'url': 'https://huggingface.co/datasets/rotten_tomatoes/resolve/refs%2Fconvert%2Fparquet/default/validation/0000.parquet', 'filename': '0000.parquet' 'size': 90001}
|
|
320d1a510eb7902c2dd123284e160af0a2b623f0
|
Quentin Lhoest
| 2023-08-17T18:05:10 |
Fix start job lock owner (#1699)
|
diff --git a/libs/libcommon/src/libcommon/queue.py b/libs/libcommon/src/libcommon/queue.py
index 6973705c..a0db6ba1 100644
--- a/libs/libcommon/src/libcommon/queue.py
+++ b/libs/libcommon/src/libcommon/queue.py
@@ -14,0 +15 @@ from typing import Generic, List, Literal, Optional, Sequence, Type, TypedDict,
+from uuid import uuid4
@@ -659,0 +661,3 @@ class Queue:
+ # uuid is used to differentiate between workers
+ # otherwise another worker might acquire the lock
+ lock_owner = str(uuid4())
@@ -662 +666 @@ class Queue:
- with lock(key=job.unicity_id, owner=str(job.pk), sleeps=[0.1] * RETRIES):
+ with lock(key=job.unicity_id, owner=lock_owner, sleeps=[0.1] * RETRIES):
|
|
657b4a3b41eae0a9a52cda8b242b425aed8b895d
|
Andrea Francis Soria Jimenez
| 2023-08-17T17:20:20 |
Remove unique index (#1700)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index efe374e1..90eb793d 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -191,0 +192,4 @@ backfill:
+cacheMetricsCollector:
+ action: "collect-cache-metrics"
+ schedule: "*/10 * * * *"
+
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index 7d89142d..aad7c819 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -138 +138 @@ class CacheTotalMetricDocument(Document):
- kind = StringField(required=True, unique_with=["http_status", "error_code"])
+ kind = StringField(required=True)
|
|
b2a5d1c079c74b4e3dc5a980314e009fe64725a2
|
Andrea Francis Soria Jimenez
| 2023-08-17T16:31:50 |
Rollback queue incremental metrics (#1698)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index a6ad32ac..efe374e1 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -194,2 +194,2 @@ queueMetricsCollector:
- schedule: "*/10 * * * *"
- # every ten minutes, then it will be changed to default
+ schedule: "*/2 * * * *"
+ # every two minutes
diff --git a/e2e/tests/test_31_admin_metrics.py b/e2e/tests/test_31_admin_metrics.py
index 3a5a9a33..95129960 100644
--- a/e2e/tests/test_31_admin_metrics.py
+++ b/e2e/tests/test_31_admin_metrics.py
@@ -34,2 +34 @@ def test_metrics() -> None:
- # the queue metrics are computed each time a job is created and processed
- # they should exists at least for some of jobs types
+ # the queue metrics are computed by the background jobs. Here, in the e2e tests, we don't run them,
@@ -38 +37 @@ def test_metrics() -> None:
- assert has_metric(
+ assert not has_metric(
diff --git a/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py b/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py
index 39c42d2b..434583c7 100644
--- a/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py
+++ b/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py
@@ -15,10 +15,3 @@ def collect_queue_metrics(processing_graph: ProcessingGraph) -> None:
- job_type = processing_step.job_type
- query_set = JobTotalMetricDocument.objects(job_type=job_type, status=status)
- current_metric = query_set.first()
- if current_metric is not None:
- current_total = current_metric.total
- logging.info(
- f"{job_type=} {status=} current_total={current_total} new_total="
- f"{new_total} difference={int(new_total)-current_total}" # type: ignore
- )
- query_set.upsert_one(total=new_total)
+ JobTotalMetricDocument.objects(job_type=processing_step.job_type, status=status).upsert_one(
+ total=new_total
+ )
diff --git a/jobs/cache_maintenance/tests/test_collect_queue_metrics.py b/jobs/cache_maintenance/tests/test_collect_queue_metrics.py
index a0f5d090..3710201e 100644
--- a/jobs/cache_maintenance/tests/test_collect_queue_metrics.py
+++ b/jobs/cache_maintenance/tests/test_collect_queue_metrics.py
@@ -25,0 +26 @@ def test_collect_queue_metrics() -> None:
+ assert JobTotalMetricDocument.objects().count() == 0
@@ -29 +30 @@ def test_collect_queue_metrics() -> None:
- job_metrics = JobTotalMetricDocument.objects()
+ job_metrics = JobTotalMetricDocument.objects().all()
diff --git a/libs/libcommon/src/libcommon/queue.py b/libs/libcommon/src/libcommon/queue.py
index 2aeacba4..6973705c 100644
--- a/libs/libcommon/src/libcommon/queue.py
+++ b/libs/libcommon/src/libcommon/queue.py
@@ -398,23 +397,0 @@ def release_locks(owner: str) -> None:
-def _update_metrics(job_type: str, status: str, increase_by: int) -> None:
- JobTotalMetricDocument.objects(job_type=job_type, status=status).update(
- upsert=True,
- write_concern={"w": "majority", "fsync": True},
- read_concern={"level": "majority"},
- inc__total=increase_by,
- )
-
-
-def increase_metric(job_type: str, status: str) -> None:
- _update_metrics(job_type=job_type, status=status, increase_by=DEFAULT_INCREASE_AMOUNT)
-
-
-def decrease_metric(job_type: str, status: str) -> None:
- _update_metrics(job_type=job_type, status=status, increase_by=DEFAULT_DECREASE_AMOUNT)
-
-
-def update_metrics_for_updated_job(job: Optional[JobDocument], status: str) -> None:
- if job is not None:
- decrease_metric(job_type=job.type, status=job.status)
- increase_metric(job_type=job.type, status=status)
-
-
@@ -464 +440,0 @@ class Queue:
- increase_metric(job_type=job_type, status=Status.WAITING)
@@ -512,2 +487,0 @@ class Queue:
- for job in jobs:
- increase_metric(job_type=job.type, status=Status.WAITING)
@@ -532,2 +505,0 @@ class Queue:
- for existing_job in existing.all():
- update_metrics_for_updated_job(existing_job, status=Status.CANCELLED)
@@ -707 +678,0 @@ class Queue:
- update_metrics_for_updated_job(job=first_job, status=Status.STARTED)
@@ -717 +687,0 @@ class Queue:
- update_metrics_for_updated_job(job=job, status=Status.CANCELLED)
@@ -865 +834,0 @@ class Queue:
- update_metrics_for_updated_job(job=job, status=finished_status)
diff --git a/libs/libcommon/tests/test_orchestrator.py b/libs/libcommon/tests/test_orchestrator.py
index ec1fb82d..955e2cb7 100644
--- a/libs/libcommon/tests/test_orchestrator.py
+++ b/libs/libcommon/tests/test_orchestrator.py
@@ -11 +11 @@ from libcommon.processing_graph import Artifact, ProcessingGraph
-from libcommon.queue import JobDocument, JobTotalMetricDocument, Queue
+from libcommon.queue import JobDocument, Queue
@@ -39 +38,0 @@ from .utils import (
- STEP_DG,
@@ -41 +39,0 @@ from .utils import (
- assert_metric,
@@ -114 +111,0 @@ def test_after_job_plan_delete() -> None:
- assert_metric(job_type=STEP_DG, status=Status.WAITING, total=2)
@@ -246 +242,0 @@ def test_set_revision_handle_existing_jobs(
- assert_metric(job_type=STEP_DA, status=Status.WAITING, total=2)
@@ -285 +280,0 @@ def test_has_pending_ancestor_jobs(
- assert len(pending_artifacts) == JobTotalMetricDocument.objects().count()
diff --git a/libs/libcommon/tests/test_queue.py b/libs/libcommon/tests/test_queue.py
index 97d1a42c..ef8e47db 100644
--- a/libs/libcommon/tests/test_queue.py
+++ b/libs/libcommon/tests/test_queue.py
@@ -18,8 +18 @@ from libcommon.constants import QUEUE_TTL_SECONDS
-from libcommon.queue import (
- EmptyQueueError,
- JobDocument,
- JobTotalMetricDocument,
- Lock,
- Queue,
- lock,
-)
+from libcommon.queue import EmptyQueueError, JobDocument, Lock, Queue, lock
@@ -29,2 +21,0 @@ from libcommon.utils import Priority, Status, get_datetime
-from .utils import assert_metric
-
@@ -50 +40,0 @@ def test_add_job() -> None:
- assert JobTotalMetricDocument.objects().count() == 0
@@ -53 +42,0 @@ def test_add_job() -> None:
- assert_metric(job_type=test_type, status=Status.WAITING, total=1)
@@ -58 +46,0 @@ def test_add_job() -> None:
- assert_metric(job_type=test_type, status=Status.WAITING, total=2)
@@ -67,2 +54,0 @@ def test_add_job() -> None:
- assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
- assert_metric(job_type=test_type, status=Status.STARTED, total=1)
@@ -77,3 +62,0 @@ def test_add_job() -> None:
- assert_metric(job_type=test_type, status=Status.WAITING, total=1)
- assert_metric(job_type=test_type, status=Status.STARTED, total=1)
- assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
@@ -87,4 +69,0 @@ def test_add_job() -> None:
- assert_metric(job_type=test_type, status=Status.WAITING, total=1)
- assert_metric(job_type=test_type, status=Status.STARTED, total=0)
- assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
- assert_metric(job_type=test_type, status=Status.SUCCESS, total=1)
@@ -95,4 +73,0 @@ def test_add_job() -> None:
- assert_metric(job_type=test_type, status=Status.WAITING, total=0)
- assert_metric(job_type=test_type, status=Status.STARTED, total=1)
- assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
- assert_metric(job_type=test_type, status=Status.SUCCESS, total=1)
@@ -102,4 +76,0 @@ def test_add_job() -> None:
- assert_metric(job_type=test_type, status=Status.WAITING, total=0)
- assert_metric(job_type=test_type, status=Status.STARTED, total=1)
- assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
- assert_metric(job_type=test_type, status=Status.SUCCESS, total=1)
@@ -109,4 +79,0 @@ def test_add_job() -> None:
- assert_metric(job_type=test_type, status=Status.WAITING, total=0)
- assert_metric(job_type=test_type, status=Status.STARTED, total=0)
- assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
- assert_metric(job_type=test_type, status=Status.SUCCESS, total=2)
@@ -142,2 +108,0 @@ def test_cancel_jobs_by_job_id(
- assert_metric(job_type=test_type, status=Status.WAITING, total=waiting_jobs)
-
@@ -152,2 +116,0 @@ def test_cancel_jobs_by_job_id(
- assert_metric(job_type=test_type, status=Status.WAITING, total=1)
- assert_metric(job_type=test_type, status=Status.STARTED, total=1)
@@ -156 +118,0 @@ def test_cancel_jobs_by_job_id(
- assert_metric(job_type=test_type, status=Status.CANCELLED, total=expected_canceled_number)
@@ -163 +124,0 @@ def test_cancel_jobs_by_job_id_wrong_format() -> None:
- assert JobTotalMetricDocument.objects().count() == 0
diff --git a/libs/libcommon/tests/utils.py b/libs/libcommon/tests/utils.py
index 0f7c9bb5..3ee60d34 100644
--- a/libs/libcommon/tests/utils.py
+++ b/libs/libcommon/tests/utils.py
@@ -10 +10 @@ from libcommon.processing_graph import Artifact, ProcessingGraph
-from libcommon.queue import JobTotalMetricDocument, Queue
+from libcommon.queue import Queue
@@ -367,6 +366,0 @@ def artifact_id_to_job_info(artifact_id: str) -> JobInfo:
-
-
-def assert_metric(job_type: str, status: str, total: int) -> None:
- metric = JobTotalMetricDocument.objects(job_type=job_type, status=status).first()
- assert metric is not None
- assert metric.total == total
|
|
f8af3ca5fa9b1161eca1e368cb7ae46ad3fe4591
|
Sylvain Lesage
| 2023-08-17T16:08:48 |
feat: 🎸 allow passing JWT on authorization header + raise error is invalid (#1693)
|
diff --git a/docs/source/openapi.json b/docs/source/openapi.json
index d02f031e..ae4cd5f4 100644
--- a/docs/source/openapi.json
+++ b/docs/source/openapi.json
@@ -1269 +1269 @@
- "HuggingFaceCookie": {
+ "CookieHuggingFace": {
@@ -1275 +1275 @@
- "HuggingFaceToken": {
+ "AuthorizationHuggingFaceApiToken": {
@@ -1279,0 +1280,6 @@
+ },
+ "AuthorizationHuggingFaceJWT": {
+ "type": "http",
+ "description": "A JWT generated by the HuggingFace Hub, when it calls the API. This mechanism only works for JWT signed with the HuggingFace Hub's key. It gives access to the public datasets, and to the [gated datasets](https://huggingface.co/docs/hub/datasets-gated) for which the user has accepted the conditions.",
+ "scheme": "bearer",
+ "bearerFormat": "A JWT, prefixed with `jwt:`."
@@ -1684 +1690 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
@@ -1687 +1693,4 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceApiToken": []
+ },
+ {
+ "AuthorizationHuggingFaceJWT": []
@@ -1980 +1989,4 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
+ },
+ {
+ "AuthorizationHuggingFaceApiToken": []
@@ -1983 +1995 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceJWT": []
@@ -2500 +2512,4 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
+ },
+ {
+ "AuthorizationHuggingFaceApiToken": []
@@ -2503 +2518 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceJWT": []
@@ -2970 +2985 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
@@ -2973 +2988,4 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceApiToken": []
+ },
+ {
+ "AuthorizationHuggingFaceJWT": []
@@ -3297 +3315 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
@@ -3300 +3318,4 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceApiToken": []
+ },
+ {
+ "AuthorizationHuggingFaceJWT": []
@@ -3812 +3833,4 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
+ },
+ {
+ "AuthorizationHuggingFaceApiToken": []
@@ -3815 +3839 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceJWT": []
@@ -3955 +3979 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
@@ -3958 +3982,4 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceApiToken": []
+ },
+ {
+ "AuthorizationHuggingFaceJWT": []
@@ -4254 +4281 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
@@ -4257 +4284,4 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceApiToken": []
+ },
+ {
+ "AuthorizationHuggingFaceJWT": []
@@ -4505 +4535,4 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
+ },
+ {
+ "AuthorizationHuggingFaceApiToken": []
@@ -4508 +4541 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceJWT": []
@@ -4680 +4713,4 @@
- "HuggingFaceCookie": []
+ "CookieHuggingFace": []
+ },
+ {
+ "AuthorizationHuggingFaceApiToken": []
@@ -4683 +4719 @@
- "HuggingFaceToken": []
+ "AuthorizationHuggingFaceJWT": []
diff --git a/libs/libapi/src/libapi/authentication.py b/libs/libapi/src/libapi/authentication.py
index b423a07a..9ce8345e 100644
--- a/libs/libapi/src/libapi/authentication.py
+++ b/libs/libapi/src/libapi/authentication.py
@@ -18 +18 @@ from libapi.exceptions import (
-from libapi.jwt_token import is_jwt_valid
+from libapi.jwt_token import validate_jwt
@@ -40,0 +41,13 @@ class RequestAuth(AuthBase):
+def get_jwt_token(request: Optional[Request] = None) -> Optional[str]:
+ if not request:
+ return None
+ # x-api-token is deprecated and will be removed in the future
+ if token := request.headers.get("x-api-key"):
+ return token
+ authorization = request.headers.get("authorization")
+ if not authorization:
+ return None
+ token = authorization.removeprefix("Bearer jwt:")
+ return None if token == authorization else token
+
+
@@ -72,2 +85,5 @@ def auth_check(
- with StepProfiler(method="auth_check", step="prepare parameters"):
- if request:
+ with StepProfiler(method="auth_check", step="check JWT"):
+ if (jwt_token := get_jwt_token(request)) and hf_jwt_public_key and hf_jwt_algorithm:
+ validate_jwt(
+ dataset=dataset, token=jwt_token, public_key=hf_jwt_public_key, algorithm=hf_jwt_algorithm
+ )
@@ -75 +91,2 @@ def auth_check(
- f"Looking if jwt is passed in request headers {request.headers} to bypass authentication."
+ "By-passing the authentication step, because a valid JWT was passed in headers"
+ f" for dataset {dataset}. JWT was: {jwt_token}"
@@ -77,19 +94,2 @@ def auth_check(
- HEADER = "x-api-key"
- if token := request.headers.get(HEADER):
- if is_jwt_valid(
- dataset=dataset, token=token, public_key=hf_jwt_public_key, algorithm=hf_jwt_algorithm
- ):
- logging.debug(
- f"By-passing the authentication step, because a valid JWT was passed in header: '{HEADER}'"
- f" for dataset {dataset}. JWT was: {token}"
- )
- return True
- logging.debug(
- f"Error while validating the JWT passed in header: '{HEADER}' for dataset {dataset}. Trying"
- f" with the following authentication mechanisms. JWT was: {token}"
- )
- else:
- logging.debug(
- f"No JWT was passed in header: '{HEADER}' for dataset {dataset}. Trying with the following"
- " authentication mechanisms."
- )
+ return True
+ with StepProfiler(method="auth_check", step="prepare parameters"):
@@ -131 +131 @@ def auth_check(
- elif response.status_code in [403, 404]:
+ elif response.status_code in {403, 404}:
diff --git a/libs/libapi/src/libapi/exceptions.py b/libs/libapi/src/libapi/exceptions.py
index 2f14c6fd..bb28ae3b 100644
--- a/libs/libapi/src/libapi/exceptions.py
+++ b/libs/libapi/src/libapi/exceptions.py
@@ -15,0 +16,6 @@ ApiErrorCode = Literal[
+ "JWTExpiredSignature",
+ "JWTInvalidClaimRead",
+ "JWTInvalidClaimSub",
+ "JWTInvalidKeyOrAlgorithm",
+ "JWTInvalidSignature",
+ "JWTMissingRequiredClaim",
@@ -42 +48 @@ class AuthCheckHubRequestError(ApiError):
- """Raised when the external authentication check failed or timed out."""
+ """The external authentication check failed or timed out."""
@@ -51 +57 @@ class ExternalAuthenticatedError(ApiError):
- """Raised when the external authentication check failed while the user was authenticated.
+ """The external authentication check failed while the user was authenticated.
@@ -54 +60,4 @@ class ExternalAuthenticatedError(ApiError):
- we don't know if the dataset exist or not. It's also coherent with how the Hugging Face Hub works."""
+ we don't know if the dataset exist or not. It's also coherent with how the Hugging Face Hub works.
+
+ TODO: should we return DatasetNotFoundError instead? maybe the error code is leaking existence of private datasets.
+ """
@@ -61 +70 @@ class ExternalUnauthenticatedError(ApiError):
- """Raised when the external authentication check failed while the user was unauthenticated."""
+ """The external authentication check failed while the user was unauthenticated."""
@@ -68 +77 @@ class InvalidParameterError(ApiError):
- """Raised when a parameter has an invalid value."""
+ """A parameter has an invalid value."""
@@ -75 +84 @@ class JWKError(ApiError):
- """Raised when the JWT key (JWK) could not be fetched or parsed."""
+ """The JWT key (JWK) could not be fetched or parsed."""
@@ -82 +91 @@ class MissingRequiredParameterError(ApiError):
- """Raised when a required parameter is missing."""
+ """A required parameter is missing."""
@@ -89 +98 @@ class ResponseNotFoundError(ApiError):
- """Raised when the response has not been found."""
+ """The response has not been found."""
@@ -96 +105 @@ class ResponseNotReadyError(ApiError):
- """Raised when the response has not been processed yet."""
+ """The response has not been processed yet."""
@@ -103 +112 @@ class TransformRowsProcessingError(ApiError):
- """Raised when there was an error when transforming rows to list."""
+ """There was an error when transforming rows to list."""
@@ -108,0 +118,42 @@ class TransformRowsProcessingError(ApiError):
+class JWTExpiredSignature(ApiError):
+ """The JWT signature has expired."""
+
+ def __init__(self, message: str, cause: Optional[BaseException] = None):
+ super().__init__(message, HTTPStatus.UNAUTHORIZED, "JWTExpiredSignature", cause, True)
+
+
+class JWTInvalidClaimRead(ApiError):
+ """The 'read' claim in the JWT payload is invalid."""
+
+ def __init__(self, message: str, cause: Optional[BaseException] = None):
+ super().__init__(message, HTTPStatus.UNAUTHORIZED, "JWTInvalidClaimRead", cause, True)
+
+
+class JWTInvalidClaimSub(ApiError):
+ """The 'sub' claim in the JWT payload is invalid."""
+
+ def __init__(self, message: str, cause: Optional[BaseException] = None):
+ super().__init__(message, HTTPStatus.UNAUTHORIZED, "JWTInvalidClaimSub", cause, True)
+
+
+class JWTInvalidKeyOrAlgorithm(ApiError):
+ """The key and the algorithm used to verify the JWT signature are not compatible."""
+
+ def __init__(self, message: str, cause: Optional[BaseException] = None):
+ super().__init__(message, HTTPStatus.UNAUTHORIZED, "JWTInvalidKeyOrAlgorithm", cause, True)
+
+
+class JWTInvalidSignature(ApiError):
+ """The JWT signature verification failed."""
+
+ def __init__(self, message: str, cause: Optional[BaseException] = None):
+ super().__init__(message, HTTPStatus.UNAUTHORIZED, "JWTInvalidSignature", cause, True)
+
+
+class JWTMissingRequiredClaim(ApiError):
+ """A claim is missing in the JWT payload."""
+
+ def __init__(self, message: str, cause: Optional[BaseException] = None):
+ super().__init__(message, HTTPStatus.UNAUTHORIZED, "JWTMissingRequiredClaim", cause, True)
+
+
@@ -110 +161 @@ class UnexpectedApiError(ApiError):
- """Raised when the server raised an unexpected error."""
+ """The server raised an unexpected error."""
diff --git a/libs/libapi/src/libapi/jwt_token.py b/libs/libapi/src/libapi/jwt_token.py
index 1fcf3707..b3ec5b74 100644
--- a/libs/libapi/src/libapi/jwt_token.py
+++ b/libs/libapi/src/libapi/jwt_token.py
@@ -31 +31,10 @@ from jwt.algorithms import (
-from libapi.exceptions import JWKError
+from libapi.exceptions import (
+ JWKError,
+ JWTExpiredSignature,
+ JWTInvalidClaimRead,
+ JWTInvalidClaimSub,
+ JWTInvalidKeyOrAlgorithm,
+ JWTInvalidSignature,
+ JWTMissingRequiredClaim,
+ UnexpectedApiError,
+)
@@ -116,3 +125 @@ def fetch_jwt_public_key(
-def is_jwt_valid(
- dataset: str, token: Any, public_key: Optional[str], algorithm: Optional[str], verify_exp: Optional[bool] = True
-) -> bool:
+def validate_jwt(dataset: str, token: Any, public_key: str, algorithm: str, verify_exp: Optional[bool] = True) -> None:
@@ -122,3 +129,2 @@ def is_jwt_valid(
- The JWT is decoded with the public key, and the "sub" claim must be:
- {"repoName": <...>, "repoType": "dataset", "read": true}
- where <...> is the dataset identifier.
+ The JWT is decoded with the public key, and the payload must be:
+ {"sub": "datasets/<...dataset identifier...>", "read": true, "exp": <...date...>}
@@ -126 +132 @@ def is_jwt_valid(
- Returns True only if all the conditions are met. Else, it returns False.
+ Raise an exception if any of the condition is not met.
@@ -131,2 +137,2 @@ def is_jwt_valid(
- public_key (str|None): the public key to use to decode the JWT token
- algorithm (str|None): the algorithm to use to decode the JWT token
+ public_key (str): the public key to use to decode the JWT token
+ algorithm (str): the algorithm to use to decode the JWT token
@@ -135,2 +141,2 @@ def is_jwt_valid(
- Returns:
- bool: True if the JWT is valid for the input dataset, else False
+ Raise:
+
@@ -138,6 +143,0 @@ def is_jwt_valid(
- if not public_key or not algorithm:
- logging.debug(
- f"Missing public key '{public_key}' or algorithm '{algorithm}' to decode JWT token. Skipping JWT"
- " validation."
- )
- return False
@@ -152 +152,17 @@ def is_jwt_valid(
- except Exception:
+ except jwt.exceptions.MissingRequiredClaimError as e:
+ raise JWTMissingRequiredClaim("A claim is missing in the JWT payload.", e) from e
+ except jwt.exceptions.ExpiredSignatureError as e:
+ raise JWTExpiredSignature("The JWT signature has expired. Try to refresh the token.", e) from e
+ except jwt.exceptions.InvalidSignatureError as e:
+ raise JWTInvalidSignature(
+ "The JWT signature verification failed. Check the signing key and the algorithm.", e
+ ) from e
+ except (jwt.exceptions.InvalidKeyError, jwt.exceptions.InvalidAlgorithmError) as e:
+ raise JWTInvalidKeyOrAlgorithm(
+ (
+ "The key used to verify the signature is not compatible with the algorithm. Check the signing key and"
+ " the algorithm."
+ ),
+ e,
+ ) from e
+ except Exception as e:
@@ -157 +173 @@ def is_jwt_valid(
- return False
+ raise UnexpectedApiError("An error has occurred while decoding the JWT.", e) from e
@@ -160 +176,4 @@ def is_jwt_valid(
- return False
+ raise JWTInvalidClaimSub(
+ "The 'sub' claim in JWT payload is invalid. It should be in the form 'datasets/<...dataset"
+ " identifier...>'."
+ )
@@ -162 +181,2 @@ def is_jwt_valid(
- return read is True
+ if read is not True:
+ raise JWTInvalidClaimRead("The 'read' claim in JWT payload is invalid. It should be set to 'true'.")
diff --git a/libs/libapi/tests/test_authentication.py b/libs/libapi/tests/test_authentication.py
index e0451dd6..2a1d8e3f 100644
--- a/libs/libapi/tests/test_authentication.py
+++ b/libs/libapi/tests/test_authentication.py
@@ -7 +7 @@ from contextlib import nullcontext as does_not_raise
-from typing import Any, Dict, Mapping, Optional
+from typing import Any, Mapping, Optional
@@ -38,2 +37,0 @@ ZYlwazLU4wpfIVIwOh9IsCZGSgLyFq42KWIikKLEs/yqx3pRGfq+rwIDAQAB
-
-dataset_ok = "dataset"
@@ -42,2 +39,0 @@ read_ok = True
-sub_ok = f"datasets/{dataset_ok}"
-payload_ok = {"sub": sub_ok, "read": read_ok, "exp": exp_ok}
@@ -45,0 +42,11 @@ algorithm_rs256 = "RS256"
+dataset_public = "dataset_public"
+dataset_protected_with_access = "dataset_protected_with_access"
+dataset_protected_without_access = "dataset_protected_without_access"
+dataset_inexistent = "dataset_inexistent"
+dataset_throttled = "dataset_throttled"
+
+cookie_ok = "cookie ok"
+cookie_wrong = "cookie wrong"
+api_token_ok = "api token ok"
+api_token_wrong = "api token wrong"
+
@@ -48,8 +55,8 @@ def auth_callback(request: WerkzeugRequest) -> WerkzeugResponse:
- # return 401 if a cookie has been provided, 404 if a token has been provided,
- # and 200 if none has been provided
- #
- # caveat: the returned status codes don't simulate the reality
- # they're just used to check every case
- return WerkzeugResponse(
- status=401 if request.headers.get("cookie") else 404 if request.headers.get("authorization") else 200
- )
+ """Simulates the https://huggingface.co/api/datasets/%s/auth-check Hub API endpoint.
+
+ It returns:
+ - 200: if the user can access the dataset
+ - 401: if the user is not authenticated
+ - 403: if the user is authenticated but can't access the dataset
+ - 404: if the user is authenticated but the dataset doesn't exist
+ - 429: if the user is authenticated but the request is throttled
@@ -56,0 +64,2 @@ def auth_callback(request: WerkzeugRequest) -> WerkzeugResponse:
+ Args:
+ request (WerkzeugRequest): the request sent to the endpoint
@@ -58,2 +67,23 @@ def auth_callback(request: WerkzeugRequest) -> WerkzeugResponse:
-def test_no_auth_check() -> None:
- assert auth_check("dataset")
+ Returns:
+ WerkzeugResponse: the response sent by the endpoint
+ """
+ dataset = request.path.split("/")[-2]
+ if dataset == dataset_public:
+ # a public dataset always has read access
+ return WerkzeugResponse(status=200)
+ if request.headers.get("cookie") != cookie_ok and request.headers.get("authorization") != f"Bearer {api_token_ok}":
+ # the user is not authenticated
+ return WerkzeugResponse(status=401)
+ if dataset == dataset_protected_with_access:
+ # the user is authenticated and has access to the dataset
+ return WerkzeugResponse(status=200)
+ if dataset == dataset_protected_without_access:
+ # the user is authenticated but doesn't have access to the dataset
+ return WerkzeugResponse(status=403)
+ if dataset == dataset_inexistent:
+ # the user is authenticated but the dataset doesn't exist
+ return WerkzeugResponse(status=404)
+ if dataset == dataset_throttled:
+ # the user is authenticated but the request is throttled (too many requests)
+ return WerkzeugResponse(status=429)
+ raise RuntimeError(f"Unexpected dataset: {dataset}")
@@ -62 +92,5 @@ def test_no_auth_check() -> None:
-def test_invalid_auth_check_url() -> None:
+def test_no_external_auth_check() -> None:
+ assert auth_check(dataset_public)
+
+
+def test_invalid_external_auth_check_url() -> None:
@@ -64 +98 @@ def test_invalid_auth_check_url() -> None:
- auth_check("dataset", external_auth_url="https://auth.check/")
+ auth_check(dataset_public, external_auth_url="https://doesnotexist/")
@@ -69 +103 @@ def test_unreachable_external_auth_check_service() -> None:
- auth_check("dataset", external_auth_url="https://auth.check/%s")
+ auth_check(dataset_public, external_auth_url="https://doesnotexist/%s")
@@ -141,9 +175,7 @@ def create_request(headers: Mapping[str, str]) -> Request:
[email protected](
- "headers,expectation",
- [
- ({"Cookie": "some cookie"}, pytest.raises(ExternalUnauthenticatedError)),
- ({"Authorization": "Bearer invalid"}, pytest.raises(ExternalAuthenticatedError)),
- ({}, does_not_raise()),
- ],
-)
-def test_valid_responses_with_request(
+def get_jwt(dataset: str) -> str:
+ return jwt.encode(
+ {"sub": f"datasets/{dataset}", "read": read_ok, "exp": exp_ok}, private_key, algorithm=algorithm_rs256
+ )
+
+
+def assert_auth_headers(
@@ -152,0 +185 @@ def test_valid_responses_with_request(
+ dataset: str,
@@ -156 +188,0 @@ def test_valid_responses_with_request(
- dataset = "dataset"
@@ -163,0 +196,2 @@ def test_valid_responses_with_request(
+ hf_jwt_public_key=public_key,
+ hf_jwt_algorithm=algorithm_rs256,
@@ -167,2 +201,21 @@ def test_valid_responses_with_request(
-def raise_value_error(request: WerkzeugRequest) -> WerkzeugResponse:
- return WerkzeugResponse(status=500) # <- will raise ValueError in auth_check
[email protected](
+ "headers,expectation",
+ [
+ ({}, does_not_raise()),
+ ({"Authorization": f"Bearer {api_token_wrong}"}, does_not_raise()),
+ ({"Authorization": api_token_ok}, does_not_raise()),
+ ({"Cookie": cookie_wrong}, does_not_raise()),
+ ({"Authorization": f"Bearer {api_token_ok}"}, does_not_raise()),
+ ({"Cookie": cookie_ok}, does_not_raise()),
+ ({"X-Api-Key": get_jwt(dataset_public)}, does_not_raise()),
+ ({"Authorization": f"Bearer {get_jwt(dataset_public)}"}, does_not_raise()),
+ ],
+)
+def test_external_auth_service_dataset_public(
+ httpserver: HTTPServer,
+ hf_endpoint: str,
+ hf_auth_path: str,
+ headers: Mapping[str, str],
+ expectation: Any,
+) -> None:
+ assert_auth_headers(httpserver, hf_endpoint, hf_auth_path, dataset_public, headers, expectation)
@@ -172 +225 @@ def raise_value_error(request: WerkzeugRequest) -> WerkzeugResponse:
- "hf_jwt_public_key,header,payload,expectation",
+ "headers,expectation",
@@ -174,6 +227,8 @@ def raise_value_error(request: WerkzeugRequest) -> WerkzeugResponse:
- (None, None, payload_ok, pytest.raises(ValueError)),
- (None, "X-Api-Key", payload_ok, pytest.raises(ValueError)),
- (public_key, None, payload_ok, pytest.raises(ValueError)),
- (public_key, "X-Api-Key", {}, pytest.raises(ValueError)),
- (public_key, "X-Api-Key", payload_ok, does_not_raise()),
- (public_key, "x-api-key", payload_ok, does_not_raise()),
+ ({}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": f"Bearer {api_token_wrong}"}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": api_token_ok}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Cookie": cookie_wrong}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": f"Bearer {api_token_ok}"}, does_not_raise()),
+ ({"Cookie": cookie_ok}, does_not_raise()),
+ ({"X-Api-Key": get_jwt(dataset_protected_with_access)}, does_not_raise()),
+ ({"Authorization": f"Bearer jwt:{get_jwt(dataset_protected_with_access)}"}, does_not_raise()),
@@ -182 +237 @@ def raise_value_error(request: WerkzeugRequest) -> WerkzeugResponse:
-def test_bypass_auth_public_key(
+def test_external_auth_service_dataset_protected_with_access(
@@ -186,3 +241 @@ def test_bypass_auth_public_key(
- hf_jwt_public_key: Optional[str],
- header: Optional[str],
- payload: Dict[str, str],
+ headers: Mapping[str, str],
@@ -191,11 +244,70 @@ def test_bypass_auth_public_key(
- external_auth_url = hf_endpoint + hf_auth_path
- httpserver.expect_request(hf_auth_path % dataset_ok).respond_with_handler(raise_value_error)
- headers = {header: jwt.encode(payload, private_key, algorithm=algorithm_rs256)} if header else {}
- with expectation:
- auth_check(
- dataset=dataset_ok,
- external_auth_url=external_auth_url,
- request=create_request(headers=headers),
- hf_jwt_public_key=hf_jwt_public_key,
- hf_jwt_algorithm=algorithm_rs256,
- )
+ assert_auth_headers(httpserver, hf_endpoint, hf_auth_path, dataset_protected_with_access, headers, expectation)
+
+
[email protected](
+ "headers,expectation",
+ [
+ ({}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": f"Bearer {api_token_wrong}"}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": api_token_ok}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Cookie": cookie_wrong}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": f"Bearer {api_token_ok}"}, pytest.raises(ExternalAuthenticatedError)),
+ ({"Cookie": cookie_ok}, pytest.raises(ExternalAuthenticatedError)),
+ ({"X-Api-Key": get_jwt(dataset_protected_without_access)}, does_not_raise()),
+ ({"Authorization": f"Bearer jwt:{get_jwt(dataset_protected_without_access)}"}, does_not_raise()),
+ ],
+)
+def test_external_auth_service_dataset_protected_without_access(
+ httpserver: HTTPServer,
+ hf_endpoint: str,
+ hf_auth_path: str,
+ headers: Mapping[str, str],
+ expectation: Any,
+) -> None:
+ assert_auth_headers(httpserver, hf_endpoint, hf_auth_path, dataset_protected_without_access, headers, expectation)
+
+
[email protected](
+ "headers,expectation",
+ [
+ ({}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": f"Bearer {api_token_wrong}"}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": api_token_ok}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Cookie": cookie_wrong}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": f"Bearer {api_token_ok}"}, pytest.raises(ExternalAuthenticatedError)),
+ ({"Cookie": cookie_ok}, pytest.raises(ExternalAuthenticatedError)),
+ ({"X-Api-Key": get_jwt(dataset_inexistent)}, does_not_raise()),
+ ({"Authorization": f"Bearer jwt:{get_jwt(dataset_inexistent)}"}, does_not_raise()),
+ ],
+)
+def test_external_auth_service_dataset_inexistent(
+ httpserver: HTTPServer,
+ hf_endpoint: str,
+ hf_auth_path: str,
+ headers: Mapping[str, str],
+ expectation: Any,
+) -> None:
+ assert_auth_headers(httpserver, hf_endpoint, hf_auth_path, dataset_inexistent, headers, expectation)
+
+
[email protected](
+ "headers,expectation",
+ [
+ ({}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": f"Bearer {api_token_wrong}"}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": api_token_ok}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Cookie": cookie_wrong}, pytest.raises(ExternalUnauthenticatedError)),
+ ({"Authorization": f"Bearer {api_token_ok}"}, pytest.raises(ValueError)),
+ ({"Cookie": cookie_ok}, pytest.raises(ValueError)),
+ ({"X-Api-Key": get_jwt(dataset_throttled)}, does_not_raise()),
+ ({"Authorization": f"Bearer jwt:{get_jwt(dataset_throttled)}"}, does_not_raise()),
+ ],
+)
+def test_external_auth_service_dataset_throttled(
+ httpserver: HTTPServer,
+ hf_endpoint: str,
+ hf_auth_path: str,
+ headers: Mapping[str, str],
+ expectation: Any,
+) -> None:
+ assert_auth_headers(httpserver, hf_endpoint, hf_auth_path, dataset_throttled, headers, expectation)
diff --git a/libs/libapi/tests/test_jwt_token.py b/libs/libapi/tests/test_jwt_token.py
index 0060cfb0..5926cd51 100644
--- a/libs/libapi/tests/test_jwt_token.py
+++ b/libs/libapi/tests/test_jwt_token.py
@@ -6 +6 @@ from contextlib import nullcontext as does_not_raise
-from typing import Any, Dict, Optional
+from typing import Any, Dict
@@ -11 +11,9 @@ import pytest
-from libapi.jwt_token import is_jwt_valid, parse_jwt_public_key
+from libapi.exceptions import (
+ JWTExpiredSignature,
+ JWTInvalidClaimRead,
+ JWTInvalidClaimSub,
+ JWTInvalidKeyOrAlgorithm,
+ JWTInvalidSignature,
+ JWTMissingRequiredClaim,
+)
+from libapi.jwt_token import parse_jwt_public_key, validate_jwt
@@ -40 +48 @@ def test_parse_jwk(
- keys: Any,
+ keys: str,
@@ -56,10 +64,7 @@ def test_is_jwt_valid_with_ec() -> None:
- assert (
- is_jwt_valid(
- dataset=DATASET_SEVERO_GLUE,
- token=HUB_JWT_TOKEN_FOR_SEVERO_GLUE,
- public_key=HUB_JWT_PUBLIC_KEY,
- algorithm=HUB_JWT_ALGORITHM,
- verify_exp=False,
- # This is a test token generated on 2023/03/14, so we don't want to verify the exp.
- )
- is True
+ validate_jwt(
+ dataset=DATASET_SEVERO_GLUE,
+ token=HUB_JWT_TOKEN_FOR_SEVERO_GLUE,
+ public_key=HUB_JWT_PUBLIC_KEY,
+ algorithm=HUB_JWT_ALGORITHM,
+ verify_exp=False,
+ # This is a test token generated on 2023/03/14, so we don't want to verify the exp.
@@ -78 +83 @@ h4Tk6UJuj1xgKNs75Pk3pG2tj8AQiuBk3l62vRU=
-public_key = """-----BEGIN PUBLIC KEY-----
+public_key_ok = """-----BEGIN PUBLIC KEY-----
@@ -102 +107,11 @@ payload_ok = {"sub": sub_ok, "read": read_ok, "exp": exp_ok}
-algorithm_rs256 = "RS256"
+algorithm_ok = "RS256"
+algorithm_wrong = "HS256"
+
+
+def encode_jwt(payload: Dict[str, Any]) -> str:
+ return jwt.encode(payload, private_key, algorithm=algorithm_ok)
+
+
+def assert_jwt(token: str, expectation: Any, public_key: str = public_key_ok, algorithm: str = algorithm_ok) -> None:
+ with expectation:
+ validate_jwt(dataset=dataset_ok, token=token, public_key=public_key, algorithm=algorithm)
@@ -106 +121 @@ algorithm_rs256 = "RS256"
- "public_key,payload,expected",
+ "public_key,expectation",
@@ -108,13 +123,2 @@ algorithm_rs256 = "RS256"
- (None, payload_ok, False),
- (other_public_key, payload_ok, False),
- (public_key, {}, False),
- (public_key, {"sub": dataset_ok}, False),
- (public_key, {"sub": sub_wrong_1, "read": read_ok, "exp": exp_ok}, False),
- (public_key, {"sub": sub_wrong_2, "read": read_ok, "exp": exp_ok}, False),
- (public_key, {"sub": sub_wrong_3, "read": read_ok, "exp": exp_ok}, False),
- (public_key, {"sub": sub_wrong_4, "read": read_ok, "exp": exp_ok}, False),
- (public_key, {"sub": sub_ok, "read": read_wrong_1, "exp": exp_ok}, False),
- (public_key, {"sub": sub_ok, "read": read_wrong_2, "exp": exp_ok}, False),
- (public_key, {"sub": sub_ok, "read": read_ok, "exp": wrong_exp_1}, False),
- (public_key, {"sub": sub_ok, "read": read_ok, "exp": wrong_exp_2}, False),
- (public_key, payload_ok, True),
+ (other_public_key, pytest.raises(JWTInvalidSignature)),
+ (public_key_ok, does_not_raise()),
@@ -123,3 +127,71 @@ algorithm_rs256 = "RS256"
-def test_is_jwt_valid(public_key: Optional[str], payload: Dict[str, str], expected: bool) -> None:
- token = jwt.encode(payload, private_key, algorithm=algorithm_rs256)
- assert is_jwt_valid(dataset=dataset_ok, token=token, public_key=public_key, algorithm=algorithm_rs256) is expected
+def test_validate_jwt_public_key(public_key: str, expectation: Any) -> None:
+ assert_jwt(encode_jwt(payload_ok), expectation, public_key=public_key)
+
+
[email protected](
+ "algorithm,expectation",
+ [
+ (algorithm_wrong, pytest.raises(JWTInvalidKeyOrAlgorithm)),
+ (algorithm_ok, does_not_raise()),
+ ],
+)
+def test_validate_jwt_algorithm(algorithm: str, expectation: Any) -> None:
+ assert_jwt(encode_jwt(payload_ok), expectation, algorithm=algorithm)
+
+
[email protected](
+ "payload,expectation",
+ [
+ ({}, pytest.raises(JWTMissingRequiredClaim)),
+ ({"sub": sub_ok}, pytest.raises(JWTMissingRequiredClaim)),
+ ({"read": read_ok}, pytest.raises(JWTMissingRequiredClaim)),
+ ({"exp": exp_ok}, pytest.raises(JWTMissingRequiredClaim)),
+ ({"read": read_ok, "exp": exp_ok}, pytest.raises(JWTMissingRequiredClaim)),
+ ({"sub": sub_ok, "exp": exp_ok}, pytest.raises(JWTMissingRequiredClaim)),
+ ({"sub": sub_ok, "read": read_ok}, pytest.raises(JWTMissingRequiredClaim)),
+ ({"sub": sub_ok, "read": read_ok, "exp": exp_ok}, does_not_raise()),
+ ],
+)
+def test_validate_jwt_content_format(payload: Dict[str, str], expectation: Any) -> None:
+ assert_jwt(encode_jwt(payload), expectation)
+
+
[email protected](
+ "read,expectation",
+ [
+ (read_wrong_1, pytest.raises(JWTInvalidClaimRead)),
+ (read_wrong_2, pytest.raises(JWTInvalidClaimRead)),
+ (read_ok, does_not_raise()),
+ ],
+)
+def test_validate_jwt_read(read: str, expectation: Any) -> None:
+ assert_jwt(encode_jwt({"sub": sub_ok, "read": read, "exp": exp_ok}), expectation)
+
+
[email protected](
+ "sub,expectation",
+ [
+ (sub_wrong_1, pytest.raises(JWTInvalidClaimSub)),
+ (sub_wrong_2, pytest.raises(JWTInvalidClaimSub)),
+ (sub_wrong_3, pytest.raises(JWTInvalidClaimSub)),
+ (sub_wrong_4, pytest.raises(JWTInvalidClaimSub)),
+ (sub_ok, does_not_raise()),
+ ],
+)
+def test_validate_jwt_subject(sub: str, expectation: Any) -> None:
+ assert_jwt(encode_jwt({"sub": sub, "read": read_ok, "exp": exp_ok}), expectation)
+
+
[email protected](
+ "expiration,expectation",
+ [
+ (wrong_exp_1, pytest.raises(JWTExpiredSignature)),
+ (wrong_exp_2, pytest.raises(JWTExpiredSignature)),
+ (exp_ok, does_not_raise()),
+ ],
+)
+def test_validate_jwt_expiration(expiration: str, expectation: Any) -> None:
+ assert_jwt(
+ encode_jwt({"sub": sub_ok, "read": read_ok, "exp": expiration}),
+ expectation,
+ )
|
|
5af6fc35828e8e5990726f9cccc419a7aee1745b
|
Andrea Francis Soria Jimenez
| 2023-08-17T15:10:32 |
Add unique constraint (#1697)
|
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index aad7c819..7d89142d 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -138 +138 @@ class CacheTotalMetricDocument(Document):
- kind = StringField(required=True)
+ kind = StringField(required=True, unique_with=["http_status", "error_code"])
|
|
7ea0171705354f7c3c6a4d47340d6c77429b0618
|
Andrea Francis Soria Jimenez
| 2023-08-17T13:56:33 |
Lock queue metrics while update (#1695)
|
diff --git a/libs/libcommon/src/libcommon/queue.py b/libs/libcommon/src/libcommon/queue.py
index 4cb0fe79..2aeacba4 100644
--- a/libs/libcommon/src/libcommon/queue.py
+++ b/libs/libcommon/src/libcommon/queue.py
@@ -399 +399,6 @@ def _update_metrics(job_type: str, status: str, increase_by: int) -> None:
- JobTotalMetricDocument.objects(job_type=job_type, status=status).upsert_one(inc__total=increase_by)
+ JobTotalMetricDocument.objects(job_type=job_type, status=status).update(
+ upsert=True,
+ write_concern={"w": "majority", "fsync": True},
+ read_concern={"level": "majority"},
+ inc__total=increase_by,
+ )
|
|
13630f275b8eb45db0f7e4cff67b75bebdb65d5a
|
Quentin Lhoest
| 2023-08-16T15:55:51 |
Increase config-parquet-and-info version (#1692)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index e880b161..a6ad32ac 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -347 +347 @@ workers:
- replicas: 24
+ replicas: 96
@@ -364 +364 @@ workers:
- replicas: 8
+ replicas: 32
diff --git a/libs/libcommon/src/libcommon/constants.py b/libs/libcommon/src/libcommon/constants.py
index bbc93b45..e4633925 100644
--- a/libs/libcommon/src/libcommon/constants.py
+++ b/libs/libcommon/src/libcommon/constants.py
@@ -29 +29 @@ PROCESSING_STEP_CONFIG_OPT_IN_OUT_URLS_COUNT_VERSION = 3
-PROCESSING_STEP_CONFIG_PARQUET_AND_INFO_VERSION = 3
+PROCESSING_STEP_CONFIG_PARQUET_AND_INFO_VERSION = 4
|
|
9b07e466422af7f5f59c2718b4c88603476883cf
|
Quentin Lhoest
| 2023-08-16T15:35:21 |
Rename parquet files (#1685)
|
diff --git a/services/rows/tests/routes/test_rows.py b/services/rows/tests/routes/test_rows.py
index 68bfec92..666c2355 100644
--- a/services/rows/tests/routes/test_rows.py
+++ b/services/rows/tests/routes/test_rows.py
@@ -46 +46 @@ def ds_fs(ds: Dataset, tmpfs: AbstractFileSystem) -> Generator[AbstractFileSyste
- with tmpfs.open("plain_text/ds-train.parquet", "wb") as f:
+ with tmpfs.open("default/train/0000.parquet", "wb") as f:
@@ -60 +60 @@ def ds_sharded_fs(ds: Dataset, tmpfs: AbstractFileSystem) -> Generator[AbstractF
- with tmpfs.open(f"plain_text/ds_sharded-train-{shard_idx:05d}-of-{num_shards:05d}.parquet", "wb") as f:
+ with tmpfs.open(f"default/train/{shard_idx:04d}.parquet", "wb") as f:
@@ -73 +73 @@ def ds_image_fs(ds_image: Dataset, tmpfs: AbstractFileSystem) -> Generator[Abstr
- with tmpfs.open("plain_text/ds_image-train.parquet", "wb") as f:
+ with tmpfs.open("default/train/0000.parquet", "wb") as f:
@@ -99 +99 @@ def dataset_with_config_parquet() -> dict[str, Any]:
- "config": "plain_text",
+ "config": "default",
@@ -101,2 +101,2 @@ def dataset_with_config_parquet() -> dict[str, Any]:
- "url": "https://fake.huggingface.co/datasets/ds/resolve/refs%2Fconvert%2Fparquet/plain_text/ds-train.parquet", # noqa: E501
- "filename": "ds-train.parquet",
+ "url": "https://fake.huggingface.co/datasets/ds/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet", # noqa: E501
+ "filename": "0000.parquet",
@@ -110 +110 @@ def dataset_with_config_parquet() -> dict[str, Any]:
- config="plain_text",
+ config="default",
@@ -126 +126 @@ def dataset_with_config_parquet_metadata(
- "config": "plain_text",
+ "config": "default",
@@ -128,5 +128,5 @@ def dataset_with_config_parquet_metadata(
- "url": "https://fake.huggingface.co/datasets/ds/resolve/refs%2Fconvert%2Fparquet/plain_text/ds-train.parquet", # noqa: E501
- "filename": "ds-train.parquet",
- "size": ds_fs.info("plain_text/ds-train.parquet")["size"],
- "num_rows": pq.read_metadata(ds_fs.open("plain_text/ds-train.parquet")).num_rows,
- "parquet_metadata_subpath": "ds/--/plain_text/ds-train.parquet",
+ "url": "https://fake.huggingface.co/datasets/ds/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet", # noqa: E501
+ "filename": "0000.parquet",
+ "size": ds_fs.info("default/train/0000.parquet")["size"],
+ "num_rows": pq.read_metadata(ds_fs.open("default/train/0000.parquet")).num_rows,
+ "parquet_metadata_subpath": "ds/--/default/train/0000.parquet",
@@ -139 +139 @@ def dataset_with_config_parquet_metadata(
- config="plain_text",
+ config="default",
@@ -169 +169 @@ def dataset_sharded_with_config_parquet() -> dict[str, Any]:
- "config": "plain_text",
+ "config": "default",
@@ -171,2 +171,2 @@ def dataset_sharded_with_config_parquet() -> dict[str, Any]:
- "url": f"https://fake.huggingface.co/datasets/ds/resolve/refs%2Fconvert%2Fparquet/plain_text/ds_sharded-train-{shard_idx:05d}-of-{num_shards:05d}.parquet", # noqa: E501
- "filename": f"ds_sharded-train-{shard_idx:05d}-of-{num_shards:05d}.parquet",
+ "url": f"https://fake.huggingface.co/datasets/ds/resolve/refs%2Fconvert%2Fparquet/default/train{shard_idx:04d}.parquet", # noqa: E501
+ "filename": f"{shard_idx:04d}.parquet",
@@ -181 +181 @@ def dataset_sharded_with_config_parquet() -> dict[str, Any]:
- config="plain_text",
+ config="default",
@@ -197 +197 @@ def dataset_sharded_with_config_parquet_metadata(
- "config": "plain_text",
+ "config": "default",
@@ -205 +205 @@ def dataset_sharded_with_config_parquet_metadata(
- for parquet_file_path in ds_sharded_fs.glob("plain_text/*.parquet")
+ for parquet_file_path in ds_sharded_fs.glob("default/**.parquet")
@@ -211 +211 @@ def dataset_sharded_with_config_parquet_metadata(
- config="plain_text",
+ config="default",
@@ -225 +225 @@ def dataset_image_with_config_parquet() -> dict[str, Any]:
- "config": "plain_text",
+ "config": "default",
@@ -227,2 +227,2 @@ def dataset_image_with_config_parquet() -> dict[str, Any]:
- "url": "https://fake.huggingface.co/datasets/ds/resolve/refs%2Fconvert%2Fparquet/plain_text/ds_image-train.parquet", # noqa: E501
- "filename": "ds_image-train.parquet",
+ "url": "https://fake.huggingface.co/datasets/ds/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet", # noqa: E501
+ "filename": "0000.parquet",
@@ -236 +236 @@ def dataset_image_with_config_parquet() -> dict[str, Any]:
- config="plain_text",
+ config="default",
@@ -265 +265 @@ def rows_index_with_parquet_metadata(
- with ds_sharded_fs.open("plain_text/ds_sharded-train-00000-of-00004.parquet") as f:
+ with ds_sharded_fs.open("default/train/0003.parquet") as f:
@@ -267 +267 @@ def rows_index_with_parquet_metadata(
- yield indexer.get_rows_index("ds_sharded", "plain_text", "train")
+ yield indexer.get_rows_index("ds_sharded", "default", "train")
@@ -273 +273 @@ def test_indexer_get_rows_index_with_parquet_metadata(
- with ds_fs.open("plain_text/ds-train.parquet") as f:
+ with ds_fs.open("default/train/0000.parquet") as f:
@@ -275 +275 @@ def test_indexer_get_rows_index_with_parquet_metadata(
- index = indexer.get_rows_index("ds", "plain_text", "train")
+ index = indexer.get_rows_index("ds", "default", "train")
@@ -295 +295 @@ def test_indexer_get_rows_index_sharded_with_parquet_metadata(
- with ds_sharded_fs.open("plain_text/ds_sharded-train-00000-of-00004.parquet") as f:
+ with ds_sharded_fs.open("default/train/0003.parquet") as f:
@@ -297 +297 @@ def test_indexer_get_rows_index_sharded_with_parquet_metadata(
- index = indexer.get_rows_index("ds_sharded", "plain_text", "train")
+ index = indexer.get_rows_index("ds_sharded", "default", "train")
@@ -326 +326 @@ def test_create_response(ds: Dataset, app_config: AppConfig, cached_assets_direc
- config="plain_text",
+ config="default",
@@ -350 +350 @@ def test_create_response_with_image(
- config="plain_text",
+ config="default",
@@ -366 +366 @@ def test_create_response_with_image(
- "src": "http://localhost/cached-assets/ds_image/--/plain_text/train/0/image/image.jpg",
+ "src": "http://localhost/cached-assets/ds_image/--/default/train/0/image/image.jpg",
@@ -374 +374 @@ def test_create_response_with_image(
- cached_image_path = Path(cached_assets_directory) / "ds_image/--/plain_text/train/0/image/image.jpg"
+ cached_image_path = Path(cached_assets_directory) / "ds_image/--/default/train/0/image/image.jpg"
@@ -380 +380 @@ def test_update_last_modified_date_of_rows_in_assets_dir(tmp_path: Path) -> None
- split_dir = cached_assets_directory / "ds/--/plain_text/train"
+ split_dir = cached_assets_directory / "ds/--/default/train"
@@ -388 +388 @@ def test_update_last_modified_date_of_rows_in_assets_dir(tmp_path: Path) -> None
- config="plain_text",
+ config="default",
diff --git a/services/worker/src/worker/job_runners/config/parquet.py b/services/worker/src/worker/job_runners/config/parquet.py
index 9c022402..963f3f77 100644
--- a/services/worker/src/worker/job_runners/config/parquet.py
+++ b/services/worker/src/worker/job_runners/config/parquet.py
@@ -44 +44 @@ def compute_parquet_response(dataset: str, config: str) -> ConfigParquetResponse
- parquet_files.sort(key=lambda x: x["filename"]) # type: ignore
+ parquet_files.sort(key=lambda x: (x["split"], x["filename"]))
diff --git a/services/worker/src/worker/job_runners/config/parquet_and_info.py b/services/worker/src/worker/job_runners/config/parquet_and_info.py
index 18fc4e84..71737fd5 100644
--- a/services/worker/src/worker/job_runners/config/parquet_and_info.py
+++ b/services/worker/src/worker/job_runners/config/parquet_and_info.py
@@ -101,0 +102,4 @@ MAX_OPERATIONS_PER_COMMIT = 500
+# For paths like "en/partial-train/0000.parquet" in the C4 dataset.
+# Note that "-" is forbidden for split names so it doesn't create directory names collisions.
+PARTIAL_SPLIT_PREFIX = "partial-"
+
@@ -131,5 +135,3 @@ class ParquetFile:
- if self.partial:
- # Using 4 digits is ok since MAX_FILES_PER_DIRECTORY == 10_000
- return f"{self.config}/partial/{self.split}/{self.shard_idx:04d}.parquet"
- else:
- return f'{self.config}/{self.local_file.removeprefix(f"{self.local_dir}/")}'
+ partial_prefix = PARTIAL_SPLIT_PREFIX if self.partial else ""
+ # Using 4 digits is ok since MAX_FILES_PER_DIRECTORY == 10_000
+ return f"{self.config}/{partial_prefix}{self.split}/{self.shard_idx:04d}.parquet"
@@ -139 +140,0 @@ filename_pattern = re.compile("^[0-9]{4}\\.parquet$")
-legacy_filename_pattern = re.compile(r"(?P<builder>[\.\w-]+?)-(?P<split>\w+(\.\w+)*?)(-[0-9]{5}-of-[0-9]{5})?.parquet")
@@ -144 +145 @@ def parse_repo_filename(filename: str) -> Tuple[str, str]:
- return parse_legacy_repo_filename(filename)
+ raise ValueError(f"Cannot parse {filename}")
@@ -146,2 +146,0 @@ def parse_repo_filename(filename: str) -> Tuple[str, str]:
- if len(parts) == 4 and parts[1] == "partial":
- parts.pop(1)
@@ -151,12 +150,2 @@ def parse_repo_filename(filename: str) -> Tuple[str, str]:
- return config, split
-
-
-def parse_legacy_repo_filename(filename: str) -> Tuple[str, str]:
- parts = filename.split("/")
- if len(parts) != 2:
- raise ValueError(f"Invalid filename: {filename}")
- config, fname = parts
- m = legacy_filename_pattern.match(fname)
- if not m:
- raise ValueError(f"Cannot parse {filename}")
- split = m.group("split")
+ if split.startswith(PARTIAL_SPLIT_PREFIX):
+ split = split[len(PARTIAL_SPLIT_PREFIX) :] # noqa: E203
@@ -607 +595,0 @@ def copy_parquet_files(builder: DatasetBuilder) -> List[CommitOperationCopy]:
- num_shards = len(data_files[split])
@@ -608,0 +597 @@ def copy_parquet_files(builder: DatasetBuilder) -> List[CommitOperationCopy]:
+ # data_file format for hub files is hf://datasets/{repo_id}@{revision}/{path_in_repo}
@@ -612,2 +601 @@ def copy_parquet_files(builder: DatasetBuilder) -> List[CommitOperationCopy]:
- filename_suffix = f"-{shard_idx:05d}-of-{num_shards:05d}" if num_shards > 1 else ""
- path_in_repo = f"{builder.config.name}/{builder.dataset_name}-{split}{filename_suffix}.parquet"
+ path_in_repo = f"{builder.config.name}/{split}/{shard_idx:04d}.parquet"
diff --git a/services/worker/tests/fixtures/hub.py b/services/worker/tests/fixtures/hub.py
index b7d39441..74c201a0 100644
--- a/services/worker/tests/fixtures/hub.py
+++ b/services/worker/tests/fixtures/hub.py
@@ -463,5 +463 @@ def create_parquet_and_info_response(
- dataset_name = dataset.split("/")[-1]
- if partial:
- filename = "0000.parquet"
- else:
- filename = f"{dataset_name}-train.parquet"
+ filename = "0000.parquet"
@@ -487,0 +484 @@ def create_parquet_and_info_response(
+ partial_prefix = "partial-" if partial else ""
@@ -497 +494 @@ def create_parquet_and_info_response(
- filename=f"{config}/partial/{split}/{filename}" if partial else f"{config}/{filename}",
+ filename=f"{config}/{partial_prefix}{split}/{filename}",
diff --git a/services/worker/tests/job_runners/config/test_parquet.py b/services/worker/tests/job_runners/config/test_parquet.py
index f2c2d161..a4f9b9ae 100644
--- a/services/worker/tests/job_runners/config/test_parquet.py
+++ b/services/worker/tests/job_runners/config/test_parquet.py
@@ -132,2 +132,2 @@ def get_job_runner(
- url="url2",
- filename="parquet-train-00001-of-05534.parquet",
+ url="url1",
+ filename="0000.parquet",
@@ -140,2 +140,2 @@ def get_job_runner(
- url="url1",
- filename="parquet-train-00000-of-05534.parquet",
+ url="url2",
+ filename="0001.parquet",
@@ -149 +149 @@ def get_job_runner(
- filename="parquet-test-00000-of-00001.parquet",
+ filename="0000.parquet",
@@ -164 +164 @@ def get_job_runner(
- filename="parquet-test-00000-of-00001.parquet",
+ filename="0000.parquet",
@@ -172 +172 @@ def get_job_runner(
- filename="parquet-train-00000-of-05534.parquet",
+ filename="0000.parquet",
@@ -180 +180 @@ def get_job_runner(
- filename="parquet-train-00001-of-05534.parquet",
+ filename="0001.parquet",
diff --git a/services/worker/tests/job_runners/config/test_parquet_and_info.py b/services/worker/tests/job_runners/config/test_parquet_and_info.py
index 5ed90f98..f3dbd42b 100644
--- a/services/worker/tests/job_runners/config/test_parquet_and_info.py
+++ b/services/worker/tests/job_runners/config/test_parquet_and_info.py
@@ -191 +191 @@ def test_compute_legacy_configs(
- fnmatch(file, "first/*.parquet") or fnmatch(file, "second/*.parquet")
+ fnmatch(file, "first/*/*.parquet") or fnmatch(file, "second/*/*.parquet")
@@ -218 +218 @@ def test_compute_legacy_configs(
- assert all(fnmatch(file, "first/*") for file in updated_repo_files.difference({".gitattributes"}))
+ assert all(fnmatch(file, "first/*/*.parquet") for file in updated_repo_files.difference({".gitattributes"}))
@@ -408 +408 @@ def test_partially_converted_if_big_non_parquet(
- assert content["parquet_files"][0]["url"].endswith("/partial/train/0000.parquet")
+ assert content["parquet_files"][0]["url"].endswith("/partial-train/0000.parquet")
@@ -590,17 +590,8 @@ def test_previous_step_error(
- ("config/builder-split.parquet", "split", "config", False),
- ("config/builder-with-dashes-split.parquet", "split", "config", False),
- ("config/builder-split-00000-of-00001.parquet", "split", "config", False),
- ("config/builder-with-dashes-split-00000-of-00001.parquet", "split", "config", False),
- ("config/builder-split.with.dots-00000-of-00001.parquet", "split.with.dots", "config", False),
- (
- "config/builder-with-dashes-caveat-asplitwithdashesisnotsupported-00000-of-00001.parquet",
- "asplitwithdashesisnotsupported",
- "config",
- False,
- ),
- ("config/partial/split/0000.parquet", "split", "config", False),
- ("config/partial/split.with.dots/0000.parquet", "split.with.dots", "config", False),
- ("config/partial/toomanyzeros/00000.parquet", "toomanyzeros", "config", True),
- ("builder-split-00000-of-00001.parquet", "split", "config", True),
- ("plain_text/openwebtext-10k-train.parquet", "train", "plain_text", False),
- ("plain_text/openwebtext-10k-train-00000-of-00001.parquet", "train", "plain_text", False),
+ ("config/split/0000.parquet", "split", "config", False),
+ ("config/split.with.dots/0000.parquet", "split.with.dots", "config", False),
+ ("config/partial-split/0000.parquet", "split", "config", False),
+ ("config/partial-split.with.dots/0000.parquet", "split.with.dots", "config", False),
+ ("config/partial-toomanyzeros/00000.parquet", "toomanyzeros", "config", True),
+ ("config/builder-split.parquet", "split", "config", True),
+ ("plain_text/train/0000.parquet", "train", "plain_text", False),
+ ("plain_text/train/0001.parquet", "train", "plain_text", False),
diff --git a/services/worker/tests/job_runners/split/test_first_rows_from_parquet.py b/services/worker/tests/job_runners/split/test_first_rows_from_parquet.py
index 06d2222f..09af04ff 100644
--- a/services/worker/tests/job_runners/split/test_first_rows_from_parquet.py
+++ b/services/worker/tests/job_runners/split/test_first_rows_from_parquet.py
@@ -89 +89 @@ def ds_fs(ds: Dataset, tmpfs: AbstractFileSystem) -> Generator[AbstractFileSyste
- with tmpfs.open("config/dataset-split.parquet", "wb") as f:
+ with tmpfs.open("config/train/0000.parquet", "wb") as f:
@@ -113 +113 @@ def test_compute(
- parquet_file = ds_fs.open("config/dataset-split.parquet")
+ parquet_file = ds_fs.open("config/train/0000.parquet")
@@ -115 +115 @@ def test_compute(
- "https://fake.huggingface.co/datasets/dataset/resolve/refs%2Fconvert%2Fparquet/config/dataset-split.parquet"
+ "https://fake.huggingface.co/datasets/dataset/resolve/refs%2Fconvert%2Fparquet/config/train/0000.parquet"
@@ -117 +117 @@ def test_compute(
- fake_metadata_subpath = "fake-parquet-metadata/dataset/config/dataset-split.parquet"
+ fake_metadata_subpath = "fake-parquet-metadata/dataset/config/train/0000.parquet"
@@ -126 +126 @@ def test_compute(
- "filename": "dataset-split.parquet",
+ "filename": "0000.parquet",
@@ -142 +142 @@ def test_compute(
- parquet_metadata = pq.read_metadata(ds_fs.open("config/dataset-split.parquet"))
+ parquet_metadata = pq.read_metadata(ds_fs.open("config/train/0000.parquet"))
@@ -174,2 +174,2 @@ def test_compute(
- assert len(response["rows"]) == 3 # testing file has 3 rows see config/dataset-split.parquet file
- assert len(response["features"]) == 2 # testing file has 2 columns see config/dataset-split.parquet file
+ assert len(response["rows"]) == 3 # testing file has 3 rows see config/train/0000.parquet file
+ assert len(response["features"]) == 2 # testing file has 2 columns see config/train/0000.parquet file
|
|
9ef82d0b6e6eeabd18fafac8ee4a9bd38a5915c5
|
Sylvain Lesage
| 2023-08-16T15:20:56 |
feat: 🎸 add num_rows_per_page in /rows and /search responses (#1688)
|
diff --git a/docs/source/openapi.json b/docs/source/openapi.json
index 8841032c..d02f031e 100644
--- a/docs/source/openapi.json
+++ b/docs/source/openapi.json
@@ -314 +314 @@
- "required": ["features", "rows", "num_total_rows"],
+ "required": ["features", "rows", "num_rows_total", "num_rows_per_page"],
@@ -328 +328,4 @@
- "num_total_rows": {
+ "num_rows_total": {
+ "type": "integer"
+ },
+ "num_rows_per_page": {
@@ -2613 +2616,2 @@
- "num_total_rows": 25000
+ "num_rows_total": 25000,
+ "num_rows_per_page": 100
@@ -2682 +2686,2 @@
- "num_total_rows": 1334
+ "num_rows_total": 1334,
+ "num_rows_per_page": 100
@@ -2767 +2772,2 @@
- "num_total_rows": 5777
+ "num_rows_total": 5777,
+ "num_rows_per_page": 100
@@ -3092 +3098,2 @@
- "num_total_rows": 624
+ "num_rows_total": 624,
+ "num_rows_per_page": 100
diff --git a/e2e/tests/test_52_search.py b/e2e/tests/test_52_search.py
index cf36652c..1caab51b 100644
--- a/e2e/tests/test_52_search.py
+++ b/e2e/tests/test_52_search.py
@@ -36 +36,2 @@ def test_search_endpoint(
- assert "num_total_rows" in content, search_response
+ assert "num_rows_total" in content, search_response
+ assert "num_rows_per_page" in content, search_response
@@ -39 +40,2 @@ def test_search_endpoint(
- num_total_rows = content["num_total_rows"]
+ num_rows_total = content["num_rows_total"]
+ num_rows_per_page = content["num_rows_per_page"]
@@ -42 +44,2 @@ def test_search_endpoint(
- assert num_total_rows == 3
+ assert num_rows_total == 3
+ assert num_rows_per_page == 100
diff --git a/libs/libcommon/src/libcommon/parquet_utils.py b/libs/libcommon/src/libcommon/parquet_utils.py
index c80e8a1c..10651bf0 100644
--- a/libs/libcommon/src/libcommon/parquet_utils.py
+++ b/libs/libcommon/src/libcommon/parquet_utils.py
@@ -58 +58 @@ class ParquetIndexWithMetadata:
- num_total_rows: int = field(init=False)
+ num_rows_total: int = field(init=False)
@@ -65 +65 @@ class ParquetIndexWithMetadata:
- self.num_total_rows = sum(self.num_rows)
+ self.num_rows_total = sum(self.num_rows)
diff --git a/libs/libcommon/src/libcommon/utils.py b/libs/libcommon/src/libcommon/utils.py
index 0f1711d7..b495c759 100644
--- a/libs/libcommon/src/libcommon/utils.py
+++ b/libs/libcommon/src/libcommon/utils.py
@@ -97 +97,2 @@ class PaginatedResponse(TypedDict):
- num_total_rows: int
+ num_rows_total: int
+ num_rows_per_page: int
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index 9d871922..fbad46a6 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -60 +60 @@ def create_response(
- num_total_rows: int,
+ num_rows_total: int,
@@ -79 +79,2 @@ def create_response(
- num_total_rows=num_total_rows,
+ num_rows_total=num_rows_total,
+ num_rows_per_page=MAX_ROWS,
@@ -200 +201 @@ def create_rows_endpoint(
- num_total_rows=rows_index.parquet_index.num_total_rows,
+ num_rows_total=rows_index.parquet_index.num_rows_total,
diff --git a/services/rows/tests/routes/test_rows.py b/services/rows/tests/routes/test_rows.py
index 673b93de..68bfec92 100644
--- a/services/rows/tests/routes/test_rows.py
+++ b/services/rows/tests/routes/test_rows.py
@@ -279 +279 @@ def test_indexer_get_rows_index_with_parquet_metadata(
- assert index.parquet_index.num_total_rows == 2
+ assert index.parquet_index.num_rows_total == 2
@@ -301 +301 @@ def test_indexer_get_rows_index_sharded_with_parquet_metadata(
- assert index.parquet_index.num_total_rows == 8
+ assert index.parquet_index.num_rows_total == 8
@@ -334 +334 @@ def test_create_response(ds: Dataset, app_config: AppConfig, cached_assets_direc
- num_total_rows=10,
+ num_rows_total=10,
@@ -341 +341,2 @@ def test_create_response(ds: Dataset, app_config: AppConfig, cached_assets_direc
- assert response["num_total_rows"] == 10
+ assert response["num_rows_total"] == 10
+ assert response["num_rows_per_page"] == 100
@@ -357 +358 @@ def test_create_response_with_image(
- num_total_rows=10,
+ num_rows_total=10,
diff --git a/services/search/src/search/routes/search.py b/services/search/src/search/routes/search.py
index 79bea59f..299e14a9 100644
--- a/services/search/src/search/routes/search.py
+++ b/services/search/src/search/routes/search.py
@@ -108,2 +108,2 @@ def full_text_search(index_file_location: str, query: str, offset: int, length:
- num_total_rows = count_result[0][0] # it will always return a non empty list with one element in a tuple
- logging.debug(f"got {num_total_rows=} results for {query=}")
+ num_rows_total = count_result[0][0] # it will always return a non empty list with one element in a tuple
+ logging.debug(f"got {num_rows_total=} results for {query=}")
@@ -116 +116 @@ def full_text_search(index_file_location: str, query: str, offset: int, length:
- return (num_total_rows, pa_table)
+ return (num_rows_total, pa_table)
@@ -163 +163 @@ def create_response(
- num_total_rows: int,
+ num_rows_total: int,
@@ -189 +189,2 @@ def create_response(
- num_total_rows=num_total_rows,
+ num_rows_total=num_rows_total,
+ num_rows_per_page=MAX_ROWS,
@@ -305 +306 @@ def create_search_endpoint(
- (num_total_rows, pa_table) = full_text_search(index_file_location, query, offset, length)
+ (num_rows_total, pa_table) = full_text_search(index_file_location, query, offset, length)
@@ -338 +339 @@ def create_search_endpoint(
- num_total_rows,
+ num_rows_total,
diff --git a/services/search/tests/routes/test_search.py b/services/search/tests/routes/test_search.py
index 5a6bc20a..a2131654 100644
--- a/services/search/tests/routes/test_search.py
+++ b/services/search/tests/routes/test_search.py
@@ -24 +24 @@ def test_get_download_folder(duckdb_index_cache_directory: StrPath) -> None:
- "query,offset,length,expected_result, expected_num_total_rows",
+ "query,offset,length,expected_result, expected_num_rows_total",
@@ -59 +59 @@ def test_full_text_search(
- query: str, offset: int, length: int, expected_result: Any, expected_num_total_rows: int
+ query: str, offset: int, length: int, expected_result: Any, expected_num_rows_total: int
@@ -89,2 +89,2 @@ def test_full_text_search(
- (num_total_rows, pa_table) = full_text_search(index_file_location, query, offset, length)
- assert num_total_rows is not None
+ (num_rows_total, pa_table) = full_text_search(index_file_location, query, offset, length)
+ assert num_rows_total is not None
@@ -92 +92 @@ def test_full_text_search(
- assert num_total_rows == expected_num_total_rows
+ assert num_rows_total == expected_num_rows_total
|
|
839dd7d0e097550c661c230a664d12db8f0caee3
|
Andrea Francis Soria Jimenez
| 2023-08-15T20:14:17 |
Incremental queue metrics (#1684)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 724b7059..e880b161 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -194,2 +194,2 @@ queueMetricsCollector:
- schedule: "*/2 * * * *"
- # every two minutes
+ schedule: "*/10 * * * *"
+ # every ten minutes, then it will be changed to default
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index 7905703e..7769b640 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -153,2 +153,2 @@ queueMetricsCollector:
- schedule: "*/2 * * * *"
- # every two minutes
+ schedule: "*/10 * * * *"
+ # every ten minutes, then it will be changed to default
diff --git a/chart/templates/cron-jobs/backfill/_container.tpl b/chart/templates/cron-jobs/backfill/_container.tpl
index 12899c8c..aaf62c04 100644
--- a/chart/templates/cron-jobs/backfill/_container.tpl
+++ b/chart/templates/cron-jobs/backfill/_container.tpl
@@ -15 +14,0 @@
- {{ include "envMetrics" . | nindent 2 }}
diff --git a/chart/templates/cron-jobs/cache-metrics-collector/_container.tpl b/chart/templates/cron-jobs/cache-metrics-collector/_container.tpl
index 54894e3f..07b9d6a4 100644
--- a/chart/templates/cron-jobs/cache-metrics-collector/_container.tpl
+++ b/chart/templates/cron-jobs/cache-metrics-collector/_container.tpl
@@ -16 +15,0 @@
- {{ include "envMetrics" . | nindent 2 }}
diff --git a/chart/templates/cron-jobs/delete-indexes/_container.tpl b/chart/templates/cron-jobs/delete-indexes/_container.tpl
index 547bd1da..6c8e4d2b 100644
--- a/chart/templates/cron-jobs/delete-indexes/_container.tpl
+++ b/chart/templates/cron-jobs/delete-indexes/_container.tpl
@@ -17 +16,0 @@
- {{ include "envMetrics" . | nindent 2 }}
diff --git a/chart/templates/cron-jobs/queue-metrics-collector/_container.tpl b/chart/templates/cron-jobs/queue-metrics-collector/_container.tpl
index 4b1d557b..c1cc0ee7 100644
--- a/chart/templates/cron-jobs/queue-metrics-collector/_container.tpl
+++ b/chart/templates/cron-jobs/queue-metrics-collector/_container.tpl
@@ -16 +15,0 @@
- {{ include "envMetrics" . | nindent 2 }}
diff --git a/chart/templates/cron-jobs/queue-metrics-collector/job.yaml b/chart/templates/cron-jobs/queue-metrics-collector/job.yaml
index 1260d45a..bee728f2 100644
--- a/chart/templates/cron-jobs/queue-metrics-collector/job.yaml
+++ b/chart/templates/cron-jobs/queue-metrics-collector/job.yaml
@@ -15 +15 @@ spec:
- ttlSecondsAfterFinished: 300
+ ttlSecondsAfterFinished: 3600
diff --git a/chart/templates/jobs/cache-maintenance/_container.tpl b/chart/templates/jobs/cache-maintenance/_container.tpl
index 4b79a2cf..1e0a8775 100644
--- a/chart/templates/jobs/cache-maintenance/_container.tpl
+++ b/chart/templates/jobs/cache-maintenance/_container.tpl
@@ -12 +11,0 @@
- {{ include "envMetrics" . | nindent 2 }}
diff --git a/chart/templates/services/admin/_container.tpl b/chart/templates/services/admin/_container.tpl
index 5e9d9042..0a80f027 100644
--- a/chart/templates/services/admin/_container.tpl
+++ b/chart/templates/services/admin/_container.tpl
@@ -13 +12,0 @@
- {{ include "envMetrics" . | nindent 2 }}
diff --git a/chart/values.yaml b/chart/values.yaml
index 5e2bd89b..1e0a888b 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -344,2 +344 @@ queueMetricsCollector:
- schedule: "*/5 * * * *"
- # every five minutes
+ schedule: "14 00 * * *"
diff --git a/e2e/tests/test_31_admin_metrics.py b/e2e/tests/test_31_admin_metrics.py
index 9503af49..3a5a9a33 100644
--- a/e2e/tests/test_31_admin_metrics.py
+++ b/e2e/tests/test_31_admin_metrics.py
@@ -34 +34,2 @@ def test_metrics() -> None:
- # the queue metrics are computed by the background jobs. Here, in the e2e tests, we don't run them,
+ # the queue metrics are computed each time a job is created and processed
+ # they should exists at least for some of jobs types
@@ -37 +38 @@ def test_metrics() -> None:
- assert not has_metric(
+ assert has_metric(
@@ -54 +55 @@ def test_metrics() -> None:
- # the assets metrics, on the other end, are computed at runtime, so we should see them
+ # the disk usage metrics, on the other end, are computed at runtime, so we should see them
@@ -59,0 +61,24 @@ def test_metrics() -> None:
+
+ assert has_metric(
+ name="descriptive_statistics_disk_usage",
+ labels={"type": "total", "pid": "[0-9]*"},
+ metric_names=metric_names,
+ ), "descriptive_statistics_disk_usage"
+
+ assert has_metric(
+ name="duckdb_disk_usage",
+ labels={"type": "total", "pid": "[0-9]*"},
+ metric_names=metric_names,
+ ), "duckdb_disk_usage"
+
+ assert has_metric(
+ name="hf_datasets_disk_usage",
+ labels={"type": "total", "pid": "[0-9]*"},
+ metric_names=metric_names,
+ ), "hf_datasets_disk_usage"
+
+ assert has_metric(
+ name="parquet_metadata_disk_usage",
+ labels={"type": "total", "pid": "[0-9]*"},
+ metric_names=metric_names,
+ ), "parquet_metadata_disk_usage"
diff --git a/jobs/cache_maintenance/src/cache_maintenance/cache_metrics.py b/jobs/cache_maintenance/src/cache_maintenance/cache_metrics.py
index b325a70c..4a7b1fc9 100644
--- a/jobs/cache_maintenance/src/cache_maintenance/cache_metrics.py
+++ b/jobs/cache_maintenance/src/cache_maintenance/cache_metrics.py
@@ -29 +29 @@ def collect_cache_metrics() -> None:
- logging.info("metrics have been collected")
+ logging.info("cache metrics have been collected")
diff --git a/jobs/cache_maintenance/src/cache_maintenance/config.py b/jobs/cache_maintenance/src/cache_maintenance/config.py
index 010aa074..5e7641d9 100644
--- a/jobs/cache_maintenance/src/cache_maintenance/config.py
+++ b/jobs/cache_maintenance/src/cache_maintenance/config.py
@@ -12 +11,0 @@ from libcommon.config import (
- MetricsConfig,
@@ -68 +66,0 @@ class JobConfig:
- metrics: MetricsConfig = field(default_factory=MetricsConfig)
@@ -83 +80,0 @@ class JobConfig:
- metrics=MetricsConfig.from_env(),
diff --git a/jobs/cache_maintenance/src/cache_maintenance/main.py b/jobs/cache_maintenance/src/cache_maintenance/main.py
index 5b17d7a1..7fc5e14e 100644
--- a/jobs/cache_maintenance/src/cache_maintenance/main.py
+++ b/jobs/cache_maintenance/src/cache_maintenance/main.py
@@ -10,5 +10 @@ from libcommon.processing_graph import ProcessingGraph
-from libcommon.resources import (
- CacheMongoResource,
- MetricsMongoResource,
- QueueMongoResource,
-)
+from libcommon.resources import CacheMongoResource, QueueMongoResource
@@ -44,3 +39,0 @@ def run_job() -> None:
- MetricsMongoResource(
- database=job_config.metrics.mongo_database, host=job_config.metrics.mongo_url
- ) as metrics_resource,
@@ -54,3 +46,0 @@ def run_job() -> None:
- if not metrics_resource.is_available():
- logging.warning("The connection to the metrics database could not be established. The action is skipped.")
- return
diff --git a/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py b/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py
index 660445f9..39c42d2b 100644
--- a/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py
+++ b/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py
@@ -6 +5,0 @@ import logging
-from libcommon.metrics import JobTotalMetricDocument
@@ -8 +7 @@ from libcommon.processing_graph import ProcessingGraph
-from libcommon.queue import Queue
+from libcommon.queue import JobTotalMetricDocument, Queue
@@ -12 +11 @@ def collect_queue_metrics(processing_graph: ProcessingGraph) -> None:
- logging.info("collecting jobs metrics")
+ logging.info("collecting queue metrics")
@@ -15,2 +14,12 @@ def collect_queue_metrics(processing_graph: ProcessingGraph) -> None:
- for status, total in queue.get_jobs_count_by_status(job_type=processing_step.job_type).items():
- JobTotalMetricDocument.objects(queue=processing_step.job_type, status=status).upsert_one(total=total)
+ for status, new_total in queue.get_jobs_count_by_status(job_type=processing_step.job_type).items():
+ job_type = processing_step.job_type
+ query_set = JobTotalMetricDocument.objects(job_type=job_type, status=status)
+ current_metric = query_set.first()
+ if current_metric is not None:
+ current_total = current_metric.total
+ logging.info(
+ f"{job_type=} {status=} current_total={current_total} new_total="
+ f"{new_total} difference={int(new_total)-current_total}" # type: ignore
+ )
+ query_set.upsert_one(total=new_total)
+ logging.info("queue metrics have been collected")
diff --git a/jobs/cache_maintenance/tests/conftest.py b/jobs/cache_maintenance/tests/conftest.py
index 46639105..ad491836 100644
--- a/jobs/cache_maintenance/tests/conftest.py
+++ b/jobs/cache_maintenance/tests/conftest.py
@@ -6 +5,0 @@ from typing import Iterator
-from libcommon.metrics import _clean_metrics_database
@@ -8,5 +7 @@ from libcommon.queue import _clean_queue_database
-from libcommon.resources import (
- CacheMongoResource,
- MetricsMongoResource,
- QueueMongoResource,
-)
+from libcommon.resources import CacheMongoResource, QueueMongoResource
@@ -25 +19,0 @@ def monkeypatch_session() -> Iterator[MonkeyPatch]:
- monkeypatch_session.setenv("METRICS_MONGO_DATABASE", "datasets_server_metrics_test")
@@ -33,5 +27 @@ def job_config(monkeypatch_session: MonkeyPatch) -> JobConfig:
- if (
- "test" not in job_config.cache.mongo_database
- or "test" not in job_config.queue.mongo_database
- or "test" not in job_config.metrics.mongo_database
- ):
+ if "test" not in job_config.cache.mongo_database or "test" not in job_config.queue.mongo_database:
@@ -54,9 +43,0 @@ def queue_mongo_resource(job_config: JobConfig) -> Iterator[QueueMongoResource]:
-
-
-@fixture(autouse=True)
-def metrics_mongo_resource(job_config: JobConfig) -> Iterator[MetricsMongoResource]:
- with MetricsMongoResource(
- database=job_config.metrics.mongo_database, host=job_config.metrics.mongo_url
- ) as resource:
- yield resource
- _clean_metrics_database()
diff --git a/jobs/cache_maintenance/tests/test_collect_queue_metrics.py b/jobs/cache_maintenance/tests/test_collect_queue_metrics.py
index f8d3220e..a0f5d090 100644
--- a/jobs/cache_maintenance/tests/test_collect_queue_metrics.py
+++ b/jobs/cache_maintenance/tests/test_collect_queue_metrics.py
@@ -4,3 +3,0 @@
-from http import HTTPStatus
-
-from libcommon.metrics import JobTotalMetricDocument
@@ -8,2 +5 @@ from libcommon.processing_graph import ProcessingGraph
-from libcommon.queue import Queue
-from libcommon.simple_cache import upsert_response
+from libcommon.queue import JobTotalMetricDocument, Queue
@@ -16,5 +11,0 @@ def test_collect_queue_metrics() -> None:
- dataset = "test_dataset"
- config = None
- split = None
- content = {"some": "content"}
-
@@ -35,8 +25,0 @@ def test_collect_queue_metrics() -> None:
- upsert_response(
- kind=processing_step.cache_kind,
- dataset=dataset,
- config=config,
- split=split,
- content=content,
- http_status=HTTPStatus.OK,
- )
diff --git a/jobs/mongodb_migration/src/mongodb_migration/collector.py b/jobs/mongodb_migration/src/mongodb_migration/collector.py
index e3278bb5..38693a20 100644
--- a/jobs/mongodb_migration/src/mongodb_migration/collector.py
+++ b/jobs/mongodb_migration/src/mongodb_migration/collector.py
@@ -5,0 +6,6 @@ from typing import List
+from libcommon.constants import (
+ CACHE_METRICS_COLLECTION,
+ METRICS_MONGOENGINE_ALIAS,
+ QUEUE_METRICS_COLLECTION,
+)
+
@@ -11,0 +18 @@ from mongodb_migration.deletion_migrations import (
+from mongodb_migration.drop_migrations import MigrationDropCollection
@@ -56,3 +62,0 @@ from mongodb_migration.migrations._20230705160600_queue_job_add_difficulty impor
-from mongodb_migration.migrations._20230811063600_cache_metrics_drop_collection import (
- MigrationDropCacheMetricsCollection,
-)
@@ -251 +255,12 @@ class MigrationsCollector:
- MigrationDropCacheMetricsCollection(version="20230811063600", description="drop cache metrics collection"),
+ MigrationDropCollection(
+ version="20230811063600",
+ description="drop cache metrics collection",
+ alias=METRICS_MONGOENGINE_ALIAS,
+ collection_name=CACHE_METRICS_COLLECTION,
+ ),
+ MigrationDropCollection(
+ version="20230814121400",
+ description="drop queue metrics collection",
+ alias=METRICS_MONGOENGINE_ALIAS,
+ collection_name=QUEUE_METRICS_COLLECTION,
+ ),
diff --git a/jobs/mongodb_migration/src/mongodb_migration/config.py b/jobs/mongodb_migration/src/mongodb_migration/config.py
index 770b4352..2f56cbfb 100644
--- a/jobs/mongodb_migration/src/mongodb_migration/config.py
+++ b/jobs/mongodb_migration/src/mongodb_migration/config.py
@@ -7 +7,21 @@ from environs import Env
-from libcommon.config import CacheConfig, LogConfig, MetricsConfig, QueueConfig
+from libcommon.config import CacheConfig, LogConfig, QueueConfig
+
+# TODO: Remove this config once all the collections in metrics db have been removed
+METRICS_MONGO_DATABASE = "datasets_server_metrics"
+METRICS_MONGO_URL = "mongodb://localhost:27017"
+
+
+@dataclass(frozen=True)
+class MetricsConfig:
+ mongo_database: str = METRICS_MONGO_DATABASE
+ mongo_url: str = METRICS_MONGO_URL
+
+ @classmethod
+ def from_env(cls) -> "MetricsConfig":
+ env = Env(expand_vars=True)
+ with env.prefixed("METRICS_"):
+ return cls(
+ mongo_database=env.str(name="MONGO_DATABASE", default=METRICS_MONGO_DATABASE),
+ mongo_url=env.str(name="MONGO_URL", default=METRICS_MONGO_URL),
+ )
+
diff --git a/jobs/mongodb_migration/src/mongodb_migration/drop_migrations.py b/jobs/mongodb_migration/src/mongodb_migration/drop_migrations.py
new file mode 100644
index 00000000..70a0072f
--- /dev/null
+++ b/jobs/mongodb_migration/src/mongodb_migration/drop_migrations.py
@@ -0,0 +1,32 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+
+from mongoengine.connection import get_db
+
+from mongodb_migration.migration import IrreversibleMigrationError, Migration
+
+
+class MigrationDropCollection(Migration):
+ def __init__(self, version: str, description: str, collection_name: str, alias: str):
+ super().__init__(version=version, description=description)
+ self.collection_name = collection_name
+ self.alias = alias
+
+ def up(self) -> None:
+ logging.info(f"drop {self.collection_name} collection from {self.alias}")
+
+ db = get_db(self.alias)
+ db[self.collection_name].drop()
+
+ def down(self) -> None:
+ raise IrreversibleMigrationError("This migration does not support rollback")
+
+ def validate(self) -> None:
+ logging.info("check that collection does not exist")
+
+ db = get_db(self.alias)
+ collections = db.list_collection_names() # type: ignore
+ if self.collection_name in collections:
+ raise ValueError(f"found collection with name {self.collection_name}")
diff --git a/jobs/mongodb_migration/src/mongodb_migration/migration.py b/jobs/mongodb_migration/src/mongodb_migration/migration.py
index b4e9fa77..9fc54a62 100644
--- a/jobs/mongodb_migration/src/mongodb_migration/migration.py
+++ b/jobs/mongodb_migration/src/mongodb_migration/migration.py
@@ -11 +10,0 @@ from libcommon.constants import (
- METRICS_COLLECTION_JOB_TOTAL_METRIC,
@@ -13,0 +13 @@ from libcommon.constants import (
+ QUEUE_METRICS_COLLECTION,
@@ -71 +71 @@ class MetricsMigration(Migration):
- COLLECTION_JOB_TOTAL_METRIC: str = METRICS_COLLECTION_JOB_TOTAL_METRIC
+ COLLECTION_JOB_TOTAL_METRIC: str = QUEUE_METRICS_COLLECTION
diff --git a/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230811063600_cache_metrics_drop_collection.py b/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230811063600_cache_metrics_drop_collection.py
deleted file mode 100644
index f025776b..00000000
--- a/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230811063600_cache_metrics_drop_collection.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2023 The HuggingFace Authors.
-
-import logging
-
-from libcommon.constants import CACHE_METRICS_COLLECTION, METRICS_MONGOENGINE_ALIAS
-from mongoengine.connection import get_db
-
-from mongodb_migration.migration import IrreversibleMigrationError, Migration
-
-
-class MigrationDropCacheMetricsCollection(Migration):
- def up(self) -> None:
- # drop collection from metrics database, it will be recreated in cache database
- logging.info(f"drop {CACHE_METRICS_COLLECTION} collection from {METRICS_MONGOENGINE_ALIAS}")
-
- db = get_db(METRICS_MONGOENGINE_ALIAS)
- db[CACHE_METRICS_COLLECTION].drop()
-
- def down(self) -> None:
- raise IrreversibleMigrationError("This migration does not support rollback")
-
- def validate(self) -> None:
- logging.info("check that collection does not exist")
-
- db = get_db(METRICS_MONGOENGINE_ALIAS)
- collections = db.list_collection_names() # type: ignore
- if CACHE_METRICS_COLLECTION in collections:
- raise ValueError(f"found collection with name {CACHE_METRICS_COLLECTION}")
diff --git a/jobs/mongodb_migration/tests/test_deletion_migrations.py b/jobs/mongodb_migration/tests/test_deletion_migrations.py
index 351a2247..77711b89 100644
--- a/jobs/mongodb_migration/tests/test_deletion_migrations.py
+++ b/jobs/mongodb_migration/tests/test_deletion_migrations.py
@@ -8 +7,0 @@ from libcommon.constants import (
- METRICS_COLLECTION_JOB_TOTAL_METRIC,
@@ -10,0 +10 @@ from libcommon.constants import (
+ QUEUE_METRICS_COLLECTION,
@@ -91 +91 @@ def test_metrics_deletion_migration(mongo_host: str) -> None:
- db[METRICS_COLLECTION_JOB_TOTAL_METRIC].insert_many([{"queue": job_type, "status": "waiting", "total": 0}])
+ db[QUEUE_METRICS_COLLECTION].insert_many([{"queue": job_type, "status": "waiting", "total": 0}])
@@ -93 +93 @@ def test_metrics_deletion_migration(mongo_host: str) -> None:
- assert db[METRICS_COLLECTION_JOB_TOTAL_METRIC].find_one(
+ assert db[QUEUE_METRICS_COLLECTION].find_one(
@@ -108,3 +108 @@ def test_metrics_deletion_migration(mongo_host: str) -> None:
- assert not db[METRICS_COLLECTION_JOB_TOTAL_METRIC].find_one(
- {"queue": job_type}
- ) # Ensure 0 records after deletion
+ assert not db[QUEUE_METRICS_COLLECTION].find_one({"queue": job_type}) # Ensure 0 records after deletion
@@ -113 +111 @@ def test_metrics_deletion_migration(mongo_host: str) -> None:
- db[METRICS_COLLECTION_JOB_TOTAL_METRIC].drop()
+ db[QUEUE_METRICS_COLLECTION].drop()
diff --git a/jobs/mongodb_migration/tests/migrations/test_20230811063600_cache_metrics_drop_collection.py b/jobs/mongodb_migration/tests/test_drop_migrations.py
similarity index 70%
rename from jobs/mongodb_migration/tests/migrations/test_20230811063600_cache_metrics_drop_collection.py
rename to jobs/mongodb_migration/tests/test_drop_migrations.py
index aac71e39..1f48c721 100644
--- a/jobs/mongodb_migration/tests/migrations/test_20230811063600_cache_metrics_drop_collection.py
+++ b/jobs/mongodb_migration/tests/test_drop_migrations.py
@@ -8,0 +9 @@ from pytest import raises
+from mongodb_migration.drop_migrations import MigrationDropCollection
@@ -10,3 +10,0 @@ from mongodb_migration.migration import IrreversibleMigrationError
-from mongodb_migration.migrations._20230811063600_cache_metrics_drop_collection import (
- MigrationDropCacheMetricsCollection,
-)
@@ -15,4 +13,2 @@ from mongodb_migration.migrations._20230811063600_cache_metrics_drop_collection
-def test_drop_cache_metrics_collection(mongo_host: str) -> None:
- with MongoResource(
- database="test_drop_cache_metrics_collection", host=mongo_host, mongoengine_alias=METRICS_MONGOENGINE_ALIAS
- ):
+def test_drop_collection(mongo_host: str) -> None:
+ with MongoResource(database="test_drop_collection", host=mongo_host, mongoengine_alias=METRICS_MONGOENGINE_ALIAS):
@@ -33,2 +29,5 @@ def test_drop_cache_metrics_collection(mongo_host: str) -> None:
- migration = MigrationDropCacheMetricsCollection(
- version="20230811063600", description="drop cache metrics collection"
+ migration = MigrationDropCollection(
+ version="20230811063600",
+ description="drop cache metrics collection",
+ alias=METRICS_MONGOENGINE_ALIAS,
+ collection_name=CACHE_METRICS_COLLECTION,
diff --git a/libs/libcommon/README.md b/libs/libcommon/README.md
index 1b16130a..18aeffd5 100644
--- a/libs/libcommon/README.md
+++ b/libs/libcommon/README.md
@@ -39,7 +38,0 @@ Set environment variables to configure the job queues to precompute API response
-
-## Metrics configuration
-
-Set environment variables to configure the storage of calculated metrics in a MongoDB database:
-
-- `METRICS_MONGO_DATABASE`: name of the database used for storing the metrics. Defaults to `datasets_server_metrics`.
-- `METRICS_MONGO_URL`: URL used to connect to the MongoDB server. Defaults to `mongodb://localhost:27017`.
diff --git a/libs/libcommon/src/libcommon/config.py b/libs/libcommon/src/libcommon/config.py
index 56be859b..f4341e09 100644
--- a/libs/libcommon/src/libcommon/config.py
+++ b/libs/libcommon/src/libcommon/config.py
@@ -187,19 +186,0 @@ class QueueConfig:
-METRICS_MONGO_DATABASE = "datasets_server_metrics"
-METRICS_MONGO_URL = "mongodb://localhost:27017"
-
-
-@dataclass(frozen=True)
-class MetricsConfig:
- mongo_database: str = METRICS_MONGO_DATABASE
- mongo_url: str = METRICS_MONGO_URL
-
- @classmethod
- def from_env(cls) -> "MetricsConfig":
- env = Env(expand_vars=True)
- with env.prefixed("METRICS_"):
- return cls(
- mongo_database=env.str(name="MONGO_DATABASE", default=METRICS_MONGO_DATABASE),
- mongo_url=env.str(name="MONGO_URL", default=METRICS_MONGO_URL),
- )
-
-
diff --git a/libs/libcommon/src/libcommon/constants.py b/libs/libcommon/src/libcommon/constants.py
index c854d912..bbc93b45 100644
--- a/libs/libcommon/src/libcommon/constants.py
+++ b/libs/libcommon/src/libcommon/constants.py
@@ -13 +13 @@ CACHE_METRICS_COLLECTION = "cacheTotalMetric"
-METRICS_COLLECTION_JOB_TOTAL_METRIC = "jobTotalMetric"
+QUEUE_METRICS_COLLECTION = "jobTotalMetric"
diff --git a/libs/libcommon/src/libcommon/metrics.py b/libs/libcommon/src/libcommon/metrics.py
deleted file mode 100644
index 520d2531..00000000
--- a/libs/libcommon/src/libcommon/metrics.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2022 The HuggingFace Authors.
-
-import types
-from typing import Generic, Type, TypeVar
-
-from bson import ObjectId
-from mongoengine import Document
-from mongoengine.fields import DateTimeField, IntField, ObjectIdField, StringField
-from mongoengine.queryset.queryset import QuerySet
-
-from libcommon.constants import (
- METRICS_COLLECTION_JOB_TOTAL_METRIC,
- METRICS_MONGOENGINE_ALIAS,
-)
-from libcommon.utils import get_datetime
-
-# START monkey patching ### hack ###
-# see https://github.com/sbdchd/mongo-types#install
-U = TypeVar("U", bound=Document)
-
-
-def no_op(self, x): # type: ignore
- return self
-
-
-QuerySet.__class_getitem__ = types.MethodType(no_op, QuerySet)
-
-
-class QuerySetManager(Generic[U]):
- def __get__(self, instance: object, cls: Type[U]) -> QuerySet[U]:
- return QuerySet(cls, cls._get_collection())
-
-
-# END monkey patching ### hack ###
-
-
-class JobTotalMetricDocument(Document):
- """Jobs total metric in mongoDB database, used to compute prometheus metrics.
-
- Args:
- queue (`str`): queue name
- status (`str`): job status see libcommon.queue.Status
- total (`int`): total of jobs
- created_at (`datetime`): when the metric has been created.
- """
-
- id = ObjectIdField(db_field="_id", primary_key=True, default=ObjectId)
- queue = StringField(required=True)
- status = StringField(required=True)
- total = IntField(required=True, default=0)
- created_at = DateTimeField(default=get_datetime)
-
- meta = {
- "collection": METRICS_COLLECTION_JOB_TOTAL_METRIC,
- "db_alias": METRICS_MONGOENGINE_ALIAS,
- "indexes": [("queue", "status")],
- }
- objects = QuerySetManager["JobTotalMetricDocument"]()
-
-
-# only for the tests
-def _clean_metrics_database() -> None:
- JobTotalMetricDocument.drop_collection() # type: ignore
diff --git a/libs/libcommon/src/libcommon/prometheus.py b/libs/libcommon/src/libcommon/prometheus.py
index 26c29e3b..e482ed21 100644
--- a/libs/libcommon/src/libcommon/prometheus.py
+++ b/libs/libcommon/src/libcommon/prometheus.py
@@ -19 +19 @@ from psutil import disk_usage
-from libcommon.metrics import JobTotalMetricDocument
+from libcommon.queue import JobTotalMetricDocument
@@ -93 +93 @@ def update_queue_jobs_total() -> None:
- QUEUE_JOBS_TOTAL.labels(queue=job_metric.queue, status=job_metric.status).set(job_metric.total)
+ QUEUE_JOBS_TOTAL.labels(queue=job_metric.job_type, status=job_metric.status).set(job_metric.total)
diff --git a/libs/libcommon/src/libcommon/queue.py b/libs/libcommon/src/libcommon/queue.py
index 25c1f43a..4cb0fe79 100644
--- a/libs/libcommon/src/libcommon/queue.py
+++ b/libs/libcommon/src/libcommon/queue.py
@@ -17,0 +18 @@ import pytz
+from bson import ObjectId
@@ -20 +21,7 @@ from mongoengine.errors import DoesNotExist, NotUniqueError
-from mongoengine.fields import DateTimeField, EnumField, IntField, StringField
+from mongoengine.fields import (
+ DateTimeField,
+ EnumField,
+ IntField,
+ ObjectIdField,
+ StringField,
+)
@@ -28,0 +36 @@ from libcommon.constants import (
+ QUEUE_METRICS_COLLECTION,
@@ -240,0 +249,28 @@ class JobDocument(Document):
+DEFAULT_INCREASE_AMOUNT = 1
+DEFAULT_DECREASE_AMOUNT = -1
+
+
+class JobTotalMetricDocument(Document):
+ """Jobs total metric in mongoDB database, used to compute prometheus metrics.
+
+ Args:
+ job_type (`str`): job type
+ status (`str`): job status see libcommon.queue.Status
+ total (`int`): total of jobs
+ created_at (`datetime`): when the metric has been created.
+ """
+
+ id = ObjectIdField(db_field="_id", primary_key=True, default=ObjectId)
+ job_type = StringField(required=True, unique_with="status")
+ status = StringField(required=True)
+ total = IntField(required=True, default=0)
+ created_at = DateTimeField(default=get_datetime)
+
+ meta = {
+ "collection": QUEUE_METRICS_COLLECTION,
+ "db_alias": QUEUE_MONGOENGINE_ALIAS,
+ "indexes": [("job_type", "status")],
+ }
+ objects = QuerySetManager["JobTotalMetricDocument"]()
+
+
@@ -361,0 +398,18 @@ def release_locks(owner: str) -> None:
+def _update_metrics(job_type: str, status: str, increase_by: int) -> None:
+ JobTotalMetricDocument.objects(job_type=job_type, status=status).upsert_one(inc__total=increase_by)
+
+
+def increase_metric(job_type: str, status: str) -> None:
+ _update_metrics(job_type=job_type, status=status, increase_by=DEFAULT_INCREASE_AMOUNT)
+
+
+def decrease_metric(job_type: str, status: str) -> None:
+ _update_metrics(job_type=job_type, status=status, increase_by=DEFAULT_DECREASE_AMOUNT)
+
+
+def update_metrics_for_updated_job(job: Optional[JobDocument], status: str) -> None:
+ if job is not None:
+ decrease_metric(job_type=job.type, status=job.status)
+ increase_metric(job_type=job.type, status=status)
+
+
@@ -404,0 +459 @@ class Queue:
+ increase_metric(job_type=job_type, status=Status.WAITING)
@@ -451,0 +507,2 @@ class Queue:
+ for job in jobs:
+ increase_metric(job_type=job.type, status=Status.WAITING)
@@ -469,0 +527,2 @@ class Queue:
+ for existing_job in existing.all():
+ update_metrics_for_updated_job(existing_job, status=Status.CANCELLED)
@@ -642,0 +702 @@ class Queue:
+ update_metrics_for_updated_job(job=first_job, status=Status.STARTED)
@@ -651,0 +712 @@ class Queue:
+ update_metrics_for_updated_job(job=job, status=Status.CANCELLED)
@@ -798,0 +860 @@ class Queue:
+ update_metrics_for_updated_job(job=job, status=finished_status)
@@ -949,0 +1012 @@ class Queue:
+ # no need to update metrics since it is just the last_heartbeat
@@ -983,0 +1047 @@ def _clean_queue_database() -> None:
+ JobTotalMetricDocument.drop_collection() # type: ignore
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index 1cd70304..aad7c819 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -171,3 +171 @@ def increase_metric(kind: str, http_status: HTTPStatus, error_code: Optional[str
- CacheTotalMetricDocument.objects(kind=kind, http_status=http_status, error_code=error_code).upsert_one(
- inc__total=DEFAULT_INCREASE_AMOUNT
- )
+ _update_metrics(kind=kind, http_status=http_status, error_code=error_code, increase_by=DEFAULT_INCREASE_AMOUNT)
@@ -177,3 +175 @@ def decrease_metric(kind: str, http_status: HTTPStatus, error_code: Optional[str
- CacheTotalMetricDocument.objects(kind=kind, http_status=http_status, error_code=error_code).upsert_one(
- inc__total=DEFAULT_DECREASE_AMOUNT
- )
+ _update_metrics(kind=kind, http_status=http_status, error_code=error_code, increase_by=DEFAULT_DECREASE_AMOUNT)
diff --git a/libs/libcommon/tests/conftest.py b/libs/libcommon/tests/conftest.py
index a3fb0fcf..58658323 100644
--- a/libs/libcommon/tests/conftest.py
+++ b/libs/libcommon/tests/conftest.py
@@ -9 +8,0 @@ from pytest import fixture
-from libcommon.metrics import _clean_metrics_database
@@ -11,5 +10 @@ from libcommon.queue import _clean_queue_database
-from libcommon.resources import (
- CacheMongoResource,
- MetricsMongoResource,
- QueueMongoResource,
-)
+from libcommon.resources import CacheMongoResource, QueueMongoResource
@@ -91,12 +85,0 @@ def cache_mongo_resource(cache_mongo_host: str) -> Iterator[CacheMongoResource]:
-
-
-@fixture
-def metrics_mongo_resource(metrics_mongo_host: str) -> Iterator[MetricsMongoResource]:
- database = "datasets_server_metrics_test"
- host = metrics_mongo_host
- if "test" not in database:
- raise ValueError("Test must be launched on a test mongo database")
- with MetricsMongoResource(database=database, host=host) as metrics_mongo_resource:
- yield metrics_mongo_resource
- _clean_metrics_database()
- metrics_mongo_resource.release()
diff --git a/libs/libcommon/tests/test_orchestrator.py b/libs/libcommon/tests/test_orchestrator.py
index 8563cad5..ec1fb82d 100644
--- a/libs/libcommon/tests/test_orchestrator.py
+++ b/libs/libcommon/tests/test_orchestrator.py
@@ -11 +11 @@ from libcommon.processing_graph import Artifact, ProcessingGraph
-from libcommon.queue import JobDocument, Queue
+from libcommon.queue import JobDocument, JobTotalMetricDocument, Queue
@@ -38,0 +39 @@ from .utils import (
+ STEP_DG,
@@ -39,0 +41 @@ from .utils import (
+ assert_metric,
@@ -111,0 +114 @@ def test_after_job_plan_delete() -> None:
+ assert_metric(job_type=STEP_DG, status=Status.WAITING, total=2)
@@ -243 +246 @@ def test_set_revision_handle_existing_jobs(
-
+ assert_metric(job_type=STEP_DA, status=Status.WAITING, total=2)
@@ -282 +285 @@ def test_has_pending_ancestor_jobs(
-
+ assert len(pending_artifacts) == JobTotalMetricDocument.objects().count()
diff --git a/libs/libcommon/tests/test_prometheus.py b/libs/libcommon/tests/test_prometheus.py
index 2fcdae58..ed496882 100644
--- a/libs/libcommon/tests/test_prometheus.py
+++ b/libs/libcommon/tests/test_prometheus.py
@@ -10 +9,0 @@ import pytest
-from libcommon.metrics import JobTotalMetricDocument
@@ -21 +20,2 @@ from libcommon.prometheus import (
-from libcommon.resources import CacheMongoResource, MetricsMongoResource
+from libcommon.queue import JobTotalMetricDocument
+from libcommon.resources import CacheMongoResource, QueueMongoResource
@@ -176 +176 @@ def test_cache_metrics(cache_mongo_resource: CacheMongoResource) -> None:
-def test_queue_metrics(metrics_mongo_resource: MetricsMongoResource) -> None:
+def test_queue_metrics(queue_mongo_resource: QueueMongoResource) -> None:
@@ -180 +180 @@ def test_queue_metrics(metrics_mongo_resource: MetricsMongoResource) -> None:
- "queue": "dummy",
+ "job_type": "dummy",
diff --git a/libs/libcommon/tests/test_queue.py b/libs/libcommon/tests/test_queue.py
index 842d6ac9..97d1a42c 100644
--- a/libs/libcommon/tests/test_queue.py
+++ b/libs/libcommon/tests/test_queue.py
@@ -18 +18,8 @@ from libcommon.constants import QUEUE_TTL_SECONDS
-from libcommon.queue import EmptyQueueError, JobDocument, Lock, Queue, lock
+from libcommon.queue import (
+ EmptyQueueError,
+ JobDocument,
+ JobTotalMetricDocument,
+ Lock,
+ Queue,
+ lock,
+)
@@ -21,0 +29,2 @@ from libcommon.utils import Priority, Status, get_datetime
+from .utils import assert_metric
+
@@ -40,0 +50 @@ def test_add_job() -> None:
+ assert JobTotalMetricDocument.objects().count() == 0
@@ -42,0 +53,2 @@ def test_add_job() -> None:
+ assert_metric(job_type=test_type, status=Status.WAITING, total=1)
+
@@ -45,0 +58 @@ def test_add_job() -> None:
+ assert_metric(job_type=test_type, status=Status.WAITING, total=2)
@@ -53,0 +67,3 @@ def test_add_job() -> None:
+ assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
+ assert_metric(job_type=test_type, status=Status.STARTED, total=1)
+
@@ -60,0 +77,3 @@ def test_add_job() -> None:
+ assert_metric(job_type=test_type, status=Status.WAITING, total=1)
+ assert_metric(job_type=test_type, status=Status.STARTED, total=1)
+ assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
@@ -67,0 +87,5 @@ def test_add_job() -> None:
+ assert_metric(job_type=test_type, status=Status.WAITING, total=1)
+ assert_metric(job_type=test_type, status=Status.STARTED, total=0)
+ assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
+ assert_metric(job_type=test_type, status=Status.SUCCESS, total=1)
+
@@ -70,0 +95,5 @@ def test_add_job() -> None:
+ assert_metric(job_type=test_type, status=Status.WAITING, total=0)
+ assert_metric(job_type=test_type, status=Status.STARTED, total=1)
+ assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
+ assert_metric(job_type=test_type, status=Status.SUCCESS, total=1)
+
@@ -72,0 +102,5 @@ def test_add_job() -> None:
+ assert_metric(job_type=test_type, status=Status.WAITING, total=0)
+ assert_metric(job_type=test_type, status=Status.STARTED, total=1)
+ assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
+ assert_metric(job_type=test_type, status=Status.SUCCESS, total=1)
+
@@ -74,0 +109,5 @@ def test_add_job() -> None:
+ assert_metric(job_type=test_type, status=Status.WAITING, total=0)
+ assert_metric(job_type=test_type, status=Status.STARTED, total=0)
+ assert_metric(job_type=test_type, status=Status.CANCELLED, total=1)
+ assert_metric(job_type=test_type, status=Status.SUCCESS, total=2)
+
@@ -98,0 +138 @@ def test_cancel_jobs_by_job_id(
+ waiting_jobs = 0
@@ -100,0 +141,3 @@ def test_cancel_jobs_by_job_id(
+ waiting_jobs += 1
+ assert_metric(job_type=test_type, status=Status.WAITING, total=waiting_jobs)
+
@@ -108,0 +152,2 @@ def test_cancel_jobs_by_job_id(
+ assert_metric(job_type=test_type, status=Status.WAITING, total=1)
+ assert_metric(job_type=test_type, status=Status.STARTED, total=1)
@@ -110,0 +156 @@ def test_cancel_jobs_by_job_id(
+ assert_metric(job_type=test_type, status=Status.CANCELLED, total=expected_canceled_number)
@@ -116,0 +163 @@ def test_cancel_jobs_by_job_id_wrong_format() -> None:
+ assert JobTotalMetricDocument.objects().count() == 0
diff --git a/libs/libcommon/tests/utils.py b/libs/libcommon/tests/utils.py
index 3ee60d34..0f7c9bb5 100644
--- a/libs/libcommon/tests/utils.py
+++ b/libs/libcommon/tests/utils.py
@@ -10 +10 @@ from libcommon.processing_graph import Artifact, ProcessingGraph
-from libcommon.queue import Queue
+from libcommon.queue import JobTotalMetricDocument, Queue
@@ -366,0 +367,6 @@ def artifact_id_to_job_info(artifact_id: str) -> JobInfo:
+
+
+def assert_metric(job_type: str, status: str, total: int) -> None:
+ metric = JobTotalMetricDocument.objects(job_type=job_type, status=status).first()
+ assert metric is not None
+ assert metric.total == total
diff --git a/services/admin/src/admin/app.py b/services/admin/src/admin/app.py
index 91ab96de..8c712f84 100644
--- a/services/admin/src/admin/app.py
+++ b/services/admin/src/admin/app.py
@@ -7,6 +7 @@ from libcommon.processing_graph import ProcessingGraph
-from libcommon.resources import (
- CacheMongoResource,
- MetricsMongoResource,
- QueueMongoResource,
- Resource,
-)
+from libcommon.resources import CacheMongoResource, QueueMongoResource, Resource
@@ -60,4 +55 @@ def create_app() -> Starlette:
- metrics_resource = MetricsMongoResource(
- database=app_config.metrics.mongo_database, host=app_config.metrics.mongo_url
- )
- resources: list[Resource] = [cache_resource, queue_resource, metrics_resource]
+ resources: list[Resource] = [cache_resource, queue_resource]
@@ -68,2 +59,0 @@ def create_app() -> Starlette:
- if not metrics_resource.is_available():
- raise RuntimeError("The connection to the metrics database could not be established. Exiting.")
diff --git a/services/admin/src/admin/config.py b/services/admin/src/admin/config.py
index a4f4c0de..75e8a19a 100644
--- a/services/admin/src/admin/config.py
+++ b/services/admin/src/admin/config.py
@@ -13 +12,0 @@ from libcommon.config import (
- MetricsConfig,
@@ -142 +140,0 @@ class AppConfig:
- metrics: MetricsConfig = field(default_factory=MetricsConfig)
@@ -159 +156,0 @@ class AppConfig:
- metrics=MetricsConfig.from_env(),
diff --git a/services/admin/tests/conftest.py b/services/admin/tests/conftest.py
index 8c7f72d1..1cd7c0ef 100644
--- a/services/admin/tests/conftest.py
+++ b/services/admin/tests/conftest.py
@@ -6 +5,0 @@ from typing import Iterator
-from libcommon.metrics import _clean_metrics_database
@@ -9,5 +8 @@ from libcommon.queue import _clean_queue_database
-from libcommon.resources import (
- CacheMongoResource,
- MetricsMongoResource,
- QueueMongoResource,
-)
+from libcommon.resources import CacheMongoResource, QueueMongoResource
@@ -30 +24,0 @@ def monkeypatch_session(hf_endpoint: str, hf_token: str) -> Iterator[MonkeyPatch
- monkeypatch_session.setenv("METRICS_MONGO_DATABASE", "datasets_server_metrics_test")
@@ -68,9 +61,0 @@ def queue_mongo_resource(app_config: AppConfig) -> Iterator[QueueMongoResource]:
-
-
-@fixture(autouse=True)
-def metrics_mongo_resource(app_config: AppConfig) -> Iterator[MetricsMongoResource]:
- with MetricsMongoResource(
- database=app_config.metrics.mongo_database, host=app_config.metrics.mongo_url
- ) as resource:
- yield resource
- _clean_metrics_database()
|
|
6c0d89ae9b2eb6f091589e01b56880a91dcf252e
|
Quentin Lhoest
| 2023-08-14T22:31:46 |
fix legacy_filename_pattern (#1680)
|
diff --git a/services/worker/src/worker/job_runners/config/parquet_and_info.py b/services/worker/src/worker/job_runners/config/parquet_and_info.py
index 2bcb2b9b..18fc4e84 100644
--- a/services/worker/src/worker/job_runners/config/parquet_and_info.py
+++ b/services/worker/src/worker/job_runners/config/parquet_and_info.py
@@ -139 +139 @@ filename_pattern = re.compile("^[0-9]{4}\\.parquet$")
-legacy_filename_pattern = re.compile(r"(?P<builder>[\w-]+?)-(?P<split>\w+(\.\w+)*?)(-[0-9]{5}-of-[0-9]{5})?.parquet")
+legacy_filename_pattern = re.compile(r"(?P<builder>[\.\w-]+?)-(?P<split>\w+(\.\w+)*?)(-[0-9]{5}-of-[0-9]{5})?.parquet")
|
|
2fd9a6d27ccb1c6d64518901190bb064b37e4ba6
|
Sylvain Lesage
| 2023-08-14T18:51:00 |
feat: 🎸 be more specific in OpenAPI type (#1682)
|
diff --git a/docs/source/openapi.json b/docs/source/openapi.json
index 3d01e658..8841032c 100644
--- a/docs/source/openapi.json
+++ b/docs/source/openapi.json
@@ -221 +221 @@
- "type": "object"
+ "$ref": "#/components/schemas/CustomError"
@@ -1763,0 +1764,93 @@
+ },
+ "one of the config has an error": {
+ "summary": "one of the configs require manual download, and fails to give the split names",
+ "description": "Try with https://datasets-server.huggingface.co/splits?dataset=superb.",
+ "value": {
+ "splits": [
+ {
+ "dataset": "superb",
+ "config": "asr",
+ "split": "train"
+ },
+ {
+ "dataset": "superb",
+ "config": "asr",
+ "split": "validation"
+ },
+ {
+ "dataset": "superb",
+ "config": "asr",
+ "split": "test"
+ },
+ {
+ "dataset": "superb",
+ "config": "ic",
+ "split": "train"
+ },
+ {
+ "dataset": "superb",
+ "config": "ic",
+ "split": "validation"
+ },
+ {
+ "dataset": "superb",
+ "config": "ic",
+ "split": "test"
+ },
+ {
+ "dataset": "superb",
+ "config": "ks",
+ "split": "train"
+ },
+ {
+ "dataset": "superb",
+ "config": "ks",
+ "split": "validation"
+ },
+ {
+ "dataset": "superb",
+ "config": "ks",
+ "split": "test"
+ },
+ {
+ "dataset": "superb",
+ "config": "sd",
+ "split": "train"
+ },
+ { "dataset": "superb", "config": "sd", "split": "dev" },
+ {
+ "dataset": "superb",
+ "config": "sd",
+ "split": "test"
+ },
+ {
+ "dataset": "superb",
+ "config": "si",
+ "split": "train"
+ },
+ {
+ "dataset": "superb",
+ "config": "si",
+ "split": "validation"
+ },
+ { "dataset": "superb", "config": "si", "split": "test" }
+ ],
+ "pending": [],
+ "failed": [
+ {
+ "dataset": "superb",
+ "config": "er",
+ "error": {
+ "error": "dataset=superb requires manual download.",
+ "cause_exception": "ManualDownloadError",
+ "cause_message": " The dataset superb with config er requires manual data.\n Please follow the manual download instructions:\n\nPlease download the IEMOCAP dataset after submitting the request form here:\nhttps://sail.usc.edu/iemocap/iemocap_release.htm\nHaving downloaded the dataset you can extract it with `tar -xvzf IEMOCAP_full_release.tar.gz`\nwhich should create a folder called `IEMOCAP_full_release`\n\n Manual data can be loaded with:\n datasets.load_dataset(\"superb\", data_dir=\"<path/to/manual/data>\")",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 299, in raise_if_requires_manual_download\n builder._check_manual_download(\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py\", line 932, in _check_manual_download\n raise ManualDownloadError(\n",
+ "datasets.builder.ManualDownloadError: The dataset superb with config er requires manual data.\n Please follow the manual download instructions:\n\nPlease download the IEMOCAP dataset after submitting the request form here:\nhttps://sail.usc.edu/iemocap/iemocap_release.htm\nHaving downloaded the dataset you can extract it with `tar -xvzf IEMOCAP_full_release.tar.gz`\nwhich should create a folder called `IEMOCAP_full_release`\n\n Manual data can be loaded with:\n datasets.load_dataset(\"superb\", data_dir=\"<path/to/manual/data>\")\n"
+ ]
+ }
+ }
+ ]
+ }
|
|
4e6c05dd1b03276b8117469c5b1ac82a4d8429df
|
Sylvain Lesage
| 2023-08-14T16:56:32 |
Some refactors (#1679)
|
diff --git a/chart/templates/services/admin/_container.tpl b/chart/templates/services/admin/_container.tpl
index 85919f20..5e9d9042 100644
--- a/chart/templates/services/admin/_container.tpl
+++ b/chart/templates/services/admin/_container.tpl
@@ -9 +8,0 @@
- {{ include "envAssets" . | nindent 2 }}
@@ -14,0 +14,2 @@
+ # storage
+ {{ include "envAssets" . | nindent 2 }}
@@ -16 +17,4 @@
- {{ include "envWorker" . | nindent 2 }}
+ - name: DUCKDB_INDEX_CACHE_DIRECTORY
+ value: {{ .Values.duckDBIndex.cacheDirectory | quote }}
+ - name: DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY
+ value: {{ .Values.descriptiveStatistics.cacheDirectory | quote }}
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index 73099d37..3de9d546 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -32,3 +32,4 @@ services:
- - assets:${ASSETS_STORAGE_DIRECTORY-/assets}:rw
- - duckdb-index:${DUCKDB_INDEX_CACHE_DIRECTORY-/duckdb-index}:rw
- - parquet-metadata:${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}:rw
+ - assets:${ASSETS_STORAGE_DIRECTORY-/assets}:ro
+ - duckdb-index:${DUCKDB_INDEX_CACHE_DIRECTORY-/duckdb-index}:ro
+ - parquet-metadata:${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}:ro
+ - descriptive-statistics:${DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY-/stats-cache}:ro
@@ -54 +55 @@ services:
- PARQUET_METADATA_STORAGE_DIRECTORY: ${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}
+ DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY: ${DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY-/stats-cache}
@@ -55,0 +57 @@ services:
+ PARQUET_METADATA_STORAGE_DIRECTORY: ${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}
@@ -170,0 +173 @@ services:
+ - descriptive-statistics:${DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY-/stats-cache}:rw
@@ -228,0 +232 @@ volumes:
+ descriptive-statistics:
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index 3d14f2de..ca42d26a 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -34,3 +34,4 @@ services:
- - assets:${ASSETS_STORAGE_DIRECTORY-/assets}:rw
- - duckdb-index:${DUCKDB_INDEX_CACHE_DIRECTORY-/duckdb-index}:rw
- - parquet-metadata:${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}:rw
+ - assets:${ASSETS_STORAGE_DIRECTORY-/assets}:ro
+ - duckdb-index:${DUCKDB_INDEX_CACHE_DIRECTORY-/duckdb-index}:ro
+ - parquet-metadata:${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}:ro
+ - descriptive-statistics:${DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY-/stats-cache}:ro
@@ -56 +57 @@ services:
- PARQUET_METADATA_STORAGE_DIRECTORY: ${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}
+ DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY: ${DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY-/stats-cache}
@@ -57,0 +59 @@ services:
+ PARQUET_METADATA_STORAGE_DIRECTORY: ${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}
@@ -176,0 +179 @@ services:
+ - descriptive-statistics:${DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY-/stats-cache}:rw
@@ -188 +191 @@ services:
- DUCKDB_INDEX_COMMIT_MESSAGE: ${DUCKDB_INDEX_COMMIT_MESSAGE-Update duckdb index files}
+ DUCKDB_INDEX_COMMIT_MESSAGE: ${DUCKDB_INDEX_COMMIT_MESSAGE-Update duckdb index file}
@@ -232,0 +236 @@ volumes:
+ descriptive-statistics:
|
|
66a69725deda4d1c3f929125b90ffbbc5fcbe196
|
Sylvain Lesage
| 2023-08-14T16:56:17 |
fix: 🐛 fix the optional types in OpenAPI (#1681)
|
diff --git a/docs/source/openapi.json b/docs/source/openapi.json
index c426cc06..3d01e658 100644
--- a/docs/source/openapi.json
+++ b/docs/source/openapi.json
@@ -809,3 +809 @@
- "split": {
- "type": ["string", "null"]
- }
+ "split": { "anyOf": [{ "type": "string" }, { "type": "null" }] }
@@ -987 +985 @@
- "SizeResponse": {
+ "DatasetSizeResponse": {
@@ -989 +987 @@
- "required": ["size", "partial"],
+ "required": ["size", "pending", "failed", "partial"],
@@ -993 +991 @@
- "required": ["splits"],
+ "required": ["dataset", "configs", "splits"],
@@ -998,3 +995,0 @@
- "config": {
- "$ref": "#/components/schemas/ConfigSize"
- },
@@ -1025,0 +1021,34 @@
+ "ConfigSizeResponse": {
+ "type": "object",
+ "required": ["size", "partial"],
+ "properties": {
+ "size": {
+ "type": "object",
+ "required": ["config", "splits"],
+ "properties": {
+ "config": {
+ "$ref": "#/components/schemas/ConfigSize"
+ },
+ "splits": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/SplitSize"
+ }
+ }
+ }
+ },
+ "partial": {
+ "$ref": "#/components/schemas/Partial"
+ }
+ }
+ },
+ "SizeResponse": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/DatasetSizeResponse"
+ },
+ {
+ "$ref": "#/components/schemas/ConfigSizeResponse"
+ }
+ ]
+ },
@@ -1058,3 +1087 @@
- "full_scan": {
- "type": ["boolean", "null"]
- }
+ "full_scan": { "anyOf": [{ "type": "boolean" }, { "type": "null" }] }
|
|
aad4704e68ced5a44f7f7c2e1efeb3793ff94a00
|
Andrea Francis Soria Jimenez
| 2023-08-14T13:56:16 |
Fix disk metrics (#1678)
|
diff --git a/libs/libcommon/src/libcommon/prometheus.py b/libs/libcommon/src/libcommon/prometheus.py
index bb348721..26c29e3b 100644
--- a/libs/libcommon/src/libcommon/prometheus.py
+++ b/libs/libcommon/src/libcommon/prometheus.py
@@ -106,4 +106,4 @@ def update_disk_gauge(gauge: Gauge, directory: StrPath) -> None:
- ASSETS_DISK_USAGE.labels(type="total").set(total)
- ASSETS_DISK_USAGE.labels(type="used").set(used)
- ASSETS_DISK_USAGE.labels(type="free").set(free)
- ASSETS_DISK_USAGE.labels(type="percent").set(percent)
+ gauge.labels(type="total").set(total)
+ gauge.labels(type="used").set(used)
+ gauge.labels(type="free").set(free)
+ gauge.labels(type="percent").set(percent)
|
|
6ba8c958bce89cfc071e51da2ae97b9b7a286e47
|
Sylvain Lesage
| 2023-08-11T20:51:44 |
feat: 🎸 add metrics for all the volumes (#1674)
|
diff --git a/chart/Chart.yaml b/chart/Chart.yaml
index d6f9eb5c..84f404b9 100644
--- a/chart/Chart.yaml
+++ b/chart/Chart.yaml
@@ -21 +21 @@ type: application
-version: 1.16.2
+version: 1.16.3
diff --git a/chart/templates/_volumeMounts/_volumeMountDescriptiveStatistics.tpl b/chart/templates/_volumeMounts/_volumeMountDescriptiveStatistics.tpl
index 85b8db07..006a0bdd 100644
--- a/chart/templates/_volumeMounts/_volumeMountDescriptiveStatistics.tpl
+++ b/chart/templates/_volumeMounts/_volumeMountDescriptiveStatistics.tpl
@@ -3,0 +4,8 @@
+{{- define "volumeMountDescriptiveStatisticsRO" -}}
+- mountPath: {{ .Values.descriptiveStatistics.cacheDirectory | quote }}
+ mountPropagation: None
+ name: volume-descriptive-statistics
+ subPath: "{{ include "descriptiveStatistics.subpath" . }}"
+ readOnly: true
+{{- end -}}
+
diff --git a/chart/templates/_volumeMounts/_volumeMountDuckDBIndex.tpl b/chart/templates/_volumeMounts/_volumeMountDuckDBIndex.tpl
index 38743458..5653f7d8 100644
--- a/chart/templates/_volumeMounts/_volumeMountDuckDBIndex.tpl
+++ b/chart/templates/_volumeMounts/_volumeMountDuckDBIndex.tpl
@@ -3,0 +4,8 @@
+{{- define "volumeMountDuckDBIndexRO" -}}
+- mountPath: {{ .Values.duckDBIndex.cacheDirectory | quote }}
+ mountPropagation: None
+ name: volume-duckdb-index
+ subPath: "{{ include "duckDBIndex.subpath" . }}"
+ readOnly: true
+{{- end -}}
+
diff --git a/chart/templates/_volumeMounts/_volumeMountHfDatasetsCache.tpl b/chart/templates/_volumeMounts/_volumeMountHfDatasetsCache.tpl
index cd5ccda0..33d2941a 100644
--- a/chart/templates/_volumeMounts/_volumeMountHfDatasetsCache.tpl
+++ b/chart/templates/_volumeMounts/_volumeMountHfDatasetsCache.tpl
@@ -3,0 +4,8 @@
+{{- define "volumeMountHfDatasetsCacheRO" -}}
+- mountPath: {{ .Values.hfDatasetsCache.cacheDirectory | quote }}
+ mountPropagation: None
+ name: volume-hf-datasets-cache
+ subPath: "{{ include "hfDatasetsCache.subpath" . }}"
+ readOnly: true
+{{- end -}}
+
diff --git a/chart/templates/services/admin/_container.tpl b/chart/templates/services/admin/_container.tpl
index e23a6d44..85919f20 100644
--- a/chart/templates/services/admin/_container.tpl
+++ b/chart/templates/services/admin/_container.tpl
@@ -14,0 +15,4 @@
+ {{ include "envParquetMetadata" . | nindent 2 }}
+ {{ include "envWorker" . | nindent 2 }}
+ - name: DATASETS_BASED_HF_DATASETS_CACHE
+ value: {{ .Values.hfDatasetsCache.cacheDirectory | quote }}
@@ -39,0 +44,4 @@
+ {{ include "volumeMountDescriptiveStatisticsRO" . | nindent 2 }}
+ {{ include "volumeMountDuckDBIndexRO" . | nindent 2 }}
+ {{ include "volumeMountHfDatasetsCacheRO" . | nindent 2 }}
+ {{ include "volumeMountParquetMetadataRO" . | nindent 2 }}
diff --git a/chart/templates/services/admin/deployment.yaml b/chart/templates/services/admin/deployment.yaml
index 0ce17115..6a003507 100644
--- a/chart/templates/services/admin/deployment.yaml
+++ b/chart/templates/services/admin/deployment.yaml
@@ -28,0 +29,4 @@ spec:
+ {{ include "initContainerDescriptiveStatistics" . | nindent 8 }}
+ {{ include "initContainerDuckDBIndex" . | nindent 8 }}
+ {{ include "initContainerHfDatasetsCache" . | nindent 8 }}
+ {{ include "initContainerParquetMetadata" . | nindent 8 }}
@@ -32 +36,6 @@ spec:
- volumes: {{ include "volumeNfs" . | nindent 8 }}
+ volumes:
+ {{ include "volumeDescriptiveStatistics" . | nindent 8 }}
+ {{ include "volumeDuckDBIndex" . | nindent 8 }}
+ {{ include "volumeHfDatasetsCache" . | nindent 8 }}
+ {{ include "volumeNfs" . | nindent 8 }}
+ {{ include "volumeParquetMetadata" . | nindent 8 }}
diff --git a/libs/libcommon/src/libcommon/constants.py b/libs/libcommon/src/libcommon/constants.py
index 5d7a7926..c854d912 100644
--- a/libs/libcommon/src/libcommon/constants.py
+++ b/libs/libcommon/src/libcommon/constants.py
@@ -7,0 +8 @@ CACHED_ASSETS_CACHE_APPNAME = "datasets_server_cached_assets"
+HF_DATASETS_CACHE_APPNAME = "hf_datasets_cache"
diff --git a/libs/libcommon/src/libcommon/prometheus.py b/libs/libcommon/src/libcommon/prometheus.py
index 5c336bcc..bb348721 100644
--- a/libs/libcommon/src/libcommon/prometheus.py
+++ b/libs/libcommon/src/libcommon/prometheus.py
@@ -56 +56,25 @@ ASSETS_DISK_USAGE = Gauge(
- documentation="Usage of the disk where the assets are stored",
+ documentation="Usage of the disk where the assets and cached_assets are stored",
+ labelnames=["type"],
+ multiprocess_mode="liveall",
+)
+DESCRIPTIVE_STATISTICS_DISK_USAGE = Gauge(
+ name="descriptive_statistics_disk_usage",
+ documentation="Usage of the disk where the descriptive statistics temporary files are stored (workers)",
+ labelnames=["type"],
+ multiprocess_mode="liveall",
+)
+DUCKDB_DISK_USAGE = Gauge(
+ name="duckdb_disk_usage",
+ documentation="Usage of the disk where the temporary duckdb files are stored (/search)",
+ labelnames=["type"],
+ multiprocess_mode="liveall",
+)
+HF_DATASETS_DISK_USAGE = Gauge(
+ name="hf_datasets_disk_usage",
+ documentation="Usage of the disk where the HF datasets library stores its cache (workers)",
+ labelnames=["type"],
+ multiprocess_mode="liveall",
+)
+PARQUET_METADATA_DISK_USAGE = Gauge(
+ name="parquet_metadata_disk_usage",
+ documentation="Usage of the disk where the parquet metadata are stored (workers, used by /rows)",
@@ -79 +103 @@ def update_responses_in_cache_total() -> None:
-def update_assets_disk_usage(assets_directory: StrPath) -> None:
+def update_disk_gauge(gauge: Gauge, directory: StrPath) -> None:
@@ -81 +105 @@ def update_assets_disk_usage(assets_directory: StrPath) -> None:
- total, used, free, percent = disk_usage(str(assets_directory))
+ total, used, free, percent = disk_usage(str(directory))
@@ -87,0 +112,20 @@ def update_assets_disk_usage(assets_directory: StrPath) -> None:
+def update_assets_disk_usage(directory: StrPath) -> None:
+ update_disk_gauge(ASSETS_DISK_USAGE, directory)
+
+
+def update_descriptive_statistics_disk_usage(directory: StrPath) -> None:
+ update_disk_gauge(DESCRIPTIVE_STATISTICS_DISK_USAGE, directory)
+
+
+def update_duckdb_disk_usage(directory: StrPath) -> None:
+ update_disk_gauge(DUCKDB_DISK_USAGE, directory)
+
+
+def update_hf_datasets_disk_usage(directory: StrPath) -> None:
+ update_disk_gauge(HF_DATASETS_DISK_USAGE, directory)
+
+
+def update_parquet_metadata_disk_usage(directory: StrPath) -> None:
+ update_disk_gauge(PARQUET_METADATA_DISK_USAGE, directory)
+
+
diff --git a/libs/libcommon/src/libcommon/storage.py b/libs/libcommon/src/libcommon/storage.py
index 24e0b2b3..02aed6b3 100644
--- a/libs/libcommon/src/libcommon/storage.py
+++ b/libs/libcommon/src/libcommon/storage.py
@@ -16,0 +17 @@ from libcommon.constants import (
+ HF_DATASETS_CACHE_APPNAME,
@@ -99,0 +101,14 @@ def init_duckdb_index_cache_dir(directory: Optional[StrPath] = None) -> StrPath:
+def init_hf_datasets_cache_dir(directory: Optional[StrPath] = None) -> StrPath:
+ """Initialize the cache directory for the datasets library.
+
+ If directory is None, it will be set to the default cache location on the machine.
+
+ Args:
+ directory (Optional[Union[str, PathLike[str]]], optional): The directory to initialize. Defaults to None.
+
+ Returns:
+ Union[str, PathLike[str]]: The directory.
+ """
+ return init_dir(directory, appname=HF_DATASETS_CACHE_APPNAME)
+
+
diff --git a/libs/libcommon/tests/test_prometheus.py b/libs/libcommon/tests/test_prometheus.py
index 821502e3..2fcdae58 100644
--- a/libs/libcommon/tests/test_prometheus.py
+++ b/libs/libcommon/tests/test_prometheus.py
@@ -217 +217 @@ def test_assets_metrics(usage_type: str, tmp_path: Path) -> None:
- update_assets_disk_usage(assets_directory=tmp_path)
+ update_assets_disk_usage(directory=tmp_path)
diff --git a/services/admin/src/admin/app.py b/services/admin/src/admin/app.py
index 8f8cf8cc..91ab96de 100644
--- a/services/admin/src/admin/app.py
+++ b/services/admin/src/admin/app.py
@@ -13 +13,8 @@ from libcommon.resources import (
-from libcommon.storage import exists, init_assets_dir
+from libcommon.storage import (
+ exists,
+ init_assets_dir,
+ init_duckdb_index_cache_dir,
+ init_hf_datasets_cache_dir,
+ init_parquet_metadata_dir,
+ init_statistics_cache_dir,
+)
@@ -40,0 +48,5 @@ def create_app() -> Starlette:
+ duckdb_index_cache_directory = init_duckdb_index_cache_dir(directory=app_config.duckdb_index.cache_directory)
+ hf_datasets_cache_directory = init_hf_datasets_cache_dir(app_config.datasets_based.hf_datasets_cache)
+ parquet_metadata_directory = init_parquet_metadata_dir(directory=app_config.parquet_metadata.storage_directory)
+ statistics_cache_directory = init_statistics_cache_dir(app_config.descriptive_statistics.cache_directory)
+
@@ -51 +62,0 @@ def create_app() -> Starlette:
-
@@ -69 +80,10 @@ def create_app() -> Starlette:
- Route("/metrics", endpoint=create_metrics_endpoint(assets_directory=assets_directory)),
+ Route(
+ "/metrics",
+ endpoint=create_metrics_endpoint(
+ assets_directory=assets_directory,
+ descriptive_statistics_directory=statistics_cache_directory,
+ duckdb_directory=duckdb_index_cache_directory,
+ hf_datasets_directory=hf_datasets_cache_directory,
+ parquet_metadata_directory=parquet_metadata_directory,
+ ),
+ ),
diff --git a/services/admin/src/admin/config.py b/services/admin/src/admin/config.py
index da5ef8af..a4f4c0de 100644
--- a/services/admin/src/admin/config.py
+++ b/services/admin/src/admin/config.py
@@ -13,0 +14 @@ from libcommon.config import (
+ ParquetMetadataConfig,
@@ -79,0 +81,48 @@ class AdminConfig:
+DATASETS_BASED_HF_DATASETS_CACHE = None
+
+
+@dataclass(frozen=True)
+class DatasetsBasedConfig:
+ hf_datasets_cache: Optional[str] = DATASETS_BASED_HF_DATASETS_CACHE
+
+ @classmethod
+ def from_env(cls) -> "DatasetsBasedConfig":
+ env = Env(expand_vars=True)
+ with env.prefixed("DATASETS_BASED_"):
+ return cls(
+ hf_datasets_cache=env.str(name="HF_DATASETS_CACHE", default=DATASETS_BASED_HF_DATASETS_CACHE),
+ )
+
+
+DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY = None
+
+
+@dataclass(frozen=True)
+class DescriptiveStatisticsConfig:
+ cache_directory: Optional[str] = DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY
+
+ @classmethod
+ def from_env(cls) -> "DescriptiveStatisticsConfig":
+ env = Env(expand_vars=True)
+ with env.prefixed("DESCRIPTIVE_STATISTICS_"):
+ return cls(
+ cache_directory=env.str(name="CACHE_DIRECTORY", default=DESCRIPTIVE_STATISTICS_CACHE_DIRECTORY),
+ )
+
+
+DUCKDB_INDEX_CACHE_DIRECTORY = None
+
+
+@dataclass(frozen=True)
+class DuckDBIndexConfig:
+ cache_directory: Optional[str] = DUCKDB_INDEX_CACHE_DIRECTORY
+
+ @classmethod
+ def from_env(cls) -> "DuckDBIndexConfig":
+ env = Env(expand_vars=True)
+ with env.prefixed("DUCKDB_INDEX_"):
+ return cls(
+ cache_directory=env.str(name="CACHE_DIRECTORY", default=DUCKDB_INDEX_CACHE_DIRECTORY),
+ )
+
+
@@ -85,0 +135,3 @@ class AppConfig:
+ datasets_based: DatasetsBasedConfig = field(default_factory=DatasetsBasedConfig)
+ descriptive_statistics: DescriptiveStatisticsConfig = field(default_factory=DescriptiveStatisticsConfig)
+ duckdb_index: DuckDBIndexConfig = field(default_factory=DuckDBIndexConfig)
@@ -86,0 +139 @@ class AppConfig:
+ parquet_metadata: ParquetMetadataConfig = field(default_factory=ParquetMetadataConfig)
@@ -97,0 +151,3 @@ class AppConfig:
+ datasets_based=DatasetsBasedConfig.from_env(),
+ descriptive_statistics=DescriptiveStatisticsConfig.from_env(),
+ duckdb_index=DuckDBIndexConfig.from_env(),
@@ -98,0 +155 @@ class AppConfig:
+ parquet_metadata=ParquetMetadataConfig.from_env(),
diff --git a/services/admin/src/admin/routes/metrics.py b/services/admin/src/admin/routes/metrics.py
index e61500f0..871017bf 100644
--- a/services/admin/src/admin/routes/metrics.py
+++ b/services/admin/src/admin/routes/metrics.py
@@ -8,0 +9,4 @@ from libcommon.prometheus import (
+ update_descriptive_statistics_disk_usage,
+ update_duckdb_disk_usage,
+ update_hf_datasets_disk_usage,
+ update_parquet_metadata_disk_usage,
@@ -20 +24,7 @@ from admin.utils import Endpoint
-def create_metrics_endpoint(assets_directory: StrPath) -> Endpoint:
+def create_metrics_endpoint(
+ assets_directory: StrPath,
+ descriptive_statistics_directory: StrPath,
+ duckdb_directory: StrPath,
+ hf_datasets_directory: StrPath,
+ parquet_metadata_directory: StrPath,
+) -> Endpoint:
@@ -27 +37,5 @@ def create_metrics_endpoint(assets_directory: StrPath) -> Endpoint:
- update_assets_disk_usage(assets_directory=assets_directory)
+ update_assets_disk_usage(directory=assets_directory)
+ update_descriptive_statistics_disk_usage(directory=descriptive_statistics_directory)
+ update_duckdb_disk_usage(directory=duckdb_directory)
+ update_hf_datasets_disk_usage(directory=hf_datasets_directory)
+ update_parquet_metadata_disk_usage(directory=parquet_metadata_directory)
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index 60048ef1..73099d37 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -30,0 +31,4 @@ services:
+ volumes:
+ - assets:${ASSETS_STORAGE_DIRECTORY-/assets}:rw
+ - duckdb-index:${DUCKDB_INDEX_CACHE_DIRECTORY-/duckdb-index}:rw
+ - parquet-metadata:${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}:rw
@@ -47,0 +52,4 @@ services:
+ # storage
+ ASSETS_STORAGE_DIRECTORY: ${ASSETS_STORAGE_DIRECTORY-/assets}
+ PARQUET_METADATA_STORAGE_DIRECTORY: ${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}
+ DUCKDB_INDEX_CACHE_DIRECTORY: ${DUCKDB_INDEX_CACHE_DIRECTORY-/duckdb-index}
@@ -219,9 +226,0 @@ volumes:
- splits-datasets-cache:
- splits-modules-cache:
- splits-numba-cache:
- first-rows-datasets-cache:
- first-rows-modules-cache:
- first-rows-numba-cache:
- parquet-datasets-cache:
- parquet-modules-cache:
- parquet-numba-cache:
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index 0f736ae1..3d14f2de 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -32,0 +33,4 @@ services:
+ volumes:
+ - assets:${ASSETS_STORAGE_DIRECTORY-/assets}:rw
+ - duckdb-index:${DUCKDB_INDEX_CACHE_DIRECTORY-/duckdb-index}:rw
+ - parquet-metadata:${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}:rw
@@ -49,0 +54,4 @@ services:
+ # storage
+ ASSETS_STORAGE_DIRECTORY: ${ASSETS_STORAGE_DIRECTORY-/assets}
+ PARQUET_METADATA_STORAGE_DIRECTORY: ${PARQUET_METADATA_STORAGE_DIRECTORY-/parquet_metadata}
+ DUCKDB_INDEX_CACHE_DIRECTORY: ${DUCKDB_INDEX_CACHE_DIRECTORY-/duckdb-index}
@@ -223,9 +230,0 @@ volumes:
- splits-datasets-cache:
- splits-modules-cache:
- splits-numba-cache:
- first-rows-datasets-cache:
- first-rows-modules-cache:
- first-rows-numba-cache:
- parquet-datasets-cache:
- parquet-modules-cache:
- parquet-numba-cache:
|
|
0e3476541d1a4ebe6862e924e3661d92c2e0635e
|
Sylvain Lesage
| 2023-08-11T20:42:26 |
fix: 🐛 fix vulnerability in gitpython (#1677)
|
diff --git a/e2e/poetry.lock b/e2e/poetry.lock
index 8631d58d..f7db8814 100644
--- a/e2e/poetry.lock
+++ b/e2e/poetry.lock
@@ -1 +1 @@
-# This file is automatically @generated by Poetry and should not be changed by hand.
+# This file is automatically @generated by Poetry 1.4.2 and should not be changed by hand.
@@ -420 +420 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -426,2 +426,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
diff --git a/jobs/cache_maintenance/poetry.lock b/jobs/cache_maintenance/poetry.lock
index b8c99a44..b051b2e9 100644
--- a/jobs/cache_maintenance/poetry.lock
+++ b/jobs/cache_maintenance/poetry.lock
@@ -877 +877 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -883,2 +883,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
diff --git a/jobs/mongodb_migration/poetry.lock b/jobs/mongodb_migration/poetry.lock
index b8c99a44..b051b2e9 100644
--- a/jobs/mongodb_migration/poetry.lock
+++ b/jobs/mongodb_migration/poetry.lock
@@ -877 +877 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -883,2 +883,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
diff --git a/libs/libapi/poetry.lock b/libs/libapi/poetry.lock
index 4910b9d0..8b6904f5 100644
--- a/libs/libapi/poetry.lock
+++ b/libs/libapi/poetry.lock
@@ -934 +934 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -940,2 +940,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
diff --git a/libs/libcommon/poetry.lock b/libs/libcommon/poetry.lock
index 6063c80d..1eb12b3c 100644
--- a/libs/libcommon/poetry.lock
+++ b/libs/libcommon/poetry.lock
@@ -877 +877 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -883,2 +883,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
diff --git a/services/admin/poetry.lock b/services/admin/poetry.lock
index 30469c08..51b6bd12 100644
--- a/services/admin/poetry.lock
+++ b/services/admin/poetry.lock
@@ -877 +877 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -883,2 +883,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
diff --git a/services/api/poetry.lock b/services/api/poetry.lock
index cb264642..65f6d085 100644
--- a/services/api/poetry.lock
+++ b/services/api/poetry.lock
@@ -923 +923 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -929,2 +929,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
diff --git a/services/rows/poetry.lock b/services/rows/poetry.lock
index d53ae174..e31f4e56 100644
--- a/services/rows/poetry.lock
+++ b/services/rows/poetry.lock
@@ -934 +934 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -940,2 +940,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
diff --git a/services/search/poetry.lock b/services/search/poetry.lock
index 2c7489e7..0dcd6e7d 100644
--- a/services/search/poetry.lock
+++ b/services/search/poetry.lock
@@ -1 +1 @@
-# This file is automatically @generated by Poetry and should not be changed by hand.
+# This file is automatically @generated by Poetry 1.4.2 and should not be changed by hand.
@@ -1800,0 +1801 @@ files = [
+ {file = "orjson-3.9.2-cp310-none-win32.whl", hash = "sha256:2ae61f5d544030a6379dbc23405df66fea0777c48a0216d2d83d3e08b69eb676"},
@@ -1809,0 +1811 @@ files = [
+ {file = "orjson-3.9.2-cp311-none-win32.whl", hash = "sha256:a9a7d618f99b2d67365f2b3a588686195cb6e16666cd5471da603a01315c17cc"},
@@ -1818,0 +1821 @@ files = [
+ {file = "orjson-3.9.2-cp37-none-win32.whl", hash = "sha256:373b7b2ad11975d143556fdbd2c27e1150b535d2c07e0b48dc434211ce557fe6"},
@@ -1827,0 +1831 @@ files = [
+ {file = "orjson-3.9.2-cp38-none-win32.whl", hash = "sha256:302d80198d8d5b658065627da3a356cbe5efa082b89b303f162f030c622e0a17"},
@@ -1836,0 +1841 @@ files = [
+ {file = "orjson-3.9.2-cp39-none-win32.whl", hash = "sha256:ba60f09d735f16593950c6adf033fbb526faa94d776925579a87b777db7d0838"},
@@ -2972,0 +2978 @@ files = [
+ {file = "soundfile-0.12.1-py2.py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:2dc3685bed7187c072a46ab4ffddd38cef7de9ae5eb05c03df2ad569cf4dacbc"},
diff --git a/services/worker/poetry.lock b/services/worker/poetry.lock
index 0794737b..8e9c72b5 100644
--- a/services/worker/poetry.lock
+++ b/services/worker/poetry.lock
@@ -1325 +1325 @@ name = "gitpython"
-version = "3.1.31"
+version = "3.1.32"
@@ -1331,2 +1331,2 @@ files = [
- {file = "GitPython-3.1.31-py3-none-any.whl", hash = "sha256:f04893614f6aa713a60cbbe1e6a97403ef633103cdd0ef5eb6efe0deb98dbe8d"},
- {file = "GitPython-3.1.31.tar.gz", hash = "sha256:8ce3bcf69adfdf7c7d503e78fd3b1c492af782d58893b650adb2ac8912ddd573"},
+ {file = "GitPython-3.1.32-py3-none-any.whl", hash = "sha256:e3d59b1c2c6ebb9dfa7a184daf3b6dd4914237e7488a1730a6d8f6f5d0b4187f"},
+ {file = "GitPython-3.1.32.tar.gz", hash = "sha256:8d9b8cb1e80b9735e8717c9362079d3ce4c6e5ddeebedd0361b228c3a67a62f6"},
|
|
602bbde0f263129638569010d910a3465f43cf6f
|
Andrea Francis Soria Jimenez
| 2023-08-11T19:33:38 |
Set cron schedule to default value (#1673)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 9cc593d0..724b7059 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -205,13 +204,0 @@ queueMetricsCollector:
-cacheMetricsCollector:
- action: "collect-cache-metrics"
- schedule: "*/10 * * * *"
- # every ten minutes first time, then it will be changed to default
- nodeSelector: {}
- resources:
- requests:
- cpu: 1
- limits:
- cpu: 1
- memory: "512Mi"
- tolerations: []
-
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index 397545aa..7905703e 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -164,13 +163,0 @@ queueMetricsCollector:
-cacheMetricsCollector:
- action: "collect-cache-metrics"
- schedule: "*/10 * * * *"
- # every ten minutes first time, then it will be changed to default
- nodeSelector: {}
- resources:
- requests:
- cpu: 1
- limits:
- cpu: 1
- memory: "512Mi"
- tolerations: []
-
|
|
7e53189b5ac538bdfb7018a536d1dca93b927872
|
Sylvain Lesage
| 2023-08-11T19:29:58 |
fix: 🐛 update the OpenAPI spec (#1667)
|
diff --git a/.spectral.yml b/.spectral.yml
new file mode 100644
index 00000000..1f74425c
--- /dev/null
+++ b/.spectral.yml
@@ -0,0 +1,3 @@
+extends: spectral:oas
+rules:
+ operation-tags: off
diff --git a/.vscode/monorepo.code-workspace b/.vscode/monorepo.code-workspace
index 6fe77b3d..d76454eb 100644
--- a/.vscode/monorepo.code-workspace
+++ b/.vscode/monorepo.code-workspace
@@ -70 +70,2 @@
- "python.linting.flake8Enabled": true
+ "python.linting.flake8Enabled": true,
+ "spectral.rulesetFile": ".spectral.yml"
@@ -75 +76,2 @@
- "ms-kubernetes-tools.vscode-kubernetes-tools"
+ "ms-kubernetes-tools.vscode-kubernetes-tools",
+ "stoplight.spectral"
diff --git a/chart/values.yaml b/chart/values.yaml
index fbffde0b..5e2bd89b 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -74 +73,0 @@ images:
-
@@ -90 +89 @@ secrets:
- parameters: { }
+ parameters: {}
@@ -214 +213 @@ optInOutUrlsScan:
- # the max concurrent request number
+ # the max concurrent request number
@@ -220 +219 @@ optInOutUrlsScan:
- # the number of grouped urls to be send in every request to spawning
+ # the number of grouped urls to be send in every request to spawning
@@ -248 +246,0 @@ cachedAssets:
-
@@ -266 +264 @@ duckDBIndex:
- # the time interval at which a downloaded index will be considered as expired and will be deleted
+ # the time interval at which a downloaded index will be considered as expired and will be deleted
@@ -327 +324,0 @@ backfill:
-
@@ -344 +340,0 @@ deleteIndexes:
-
@@ -358 +353,0 @@ queueMetricsCollector:
-
@@ -545,2 +540 @@ workers:
- -
- # name of the deployment
+ - # name of the deployment
diff --git a/docs/source/openapi.json b/docs/source/openapi.json
index a6c7c14b..c426cc06 100644
--- a/docs/source/openapi.json
+++ b/docs/source/openapi.json
@@ -2 +2 @@
- "openapi": "3.0.2",
+ "openapi": "3.1.0",
@@ -8 +8,2 @@
- "email": "[email protected]"
+ "email": "[email protected]",
+ "url": "https://github.com/huggingface/datasets-server/"
@@ -10 +11,5 @@
- "version": "1.0"
+ "version": "1.0",
+ "license": {
+ "name": "Apache 2.0",
+ "url": "https://www.apache.org/licenses/LICENSE-2.0"
+ }
@@ -11,0 +17,6 @@
+ "tags": [
+ {
+ "name": "datasets",
+ "description": "API to access datasets"
+ }
+ ],
@@ -22,29 +32,0 @@
- "schema": { "type": "string" },
- "examples": {
- "no-cache": { "summary": "No cache.", "value": "no-cache" },
- "max-age": { "summary": "Cache TTL.", "value": "max-age=120" }
- },
- "required": true
- },
- "Access-Control-Allow-Origin": {
- "description": "Indicates whether the response can be shared with requesting code from the given origin.",
- "schema": { "type": "string" },
- "example": "*",
- "required": true
- },
- "X-Error-Code-splits-401": {
- "description": "A string that identifies the underlying error for 401 on /splits.",
- "schema": {
- "type": "string",
- "enum": ["ExternalUnauthenticatedError"]
- },
- "examples": {
- "ExternalUnauthenticatedError": {
- "summary": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication.",
- "value": "ExternalUnauthenticatedError"
- }
- },
- "required": true
- },
- "X-Error-Code-splits-404": {
- "description": "A string that identifies the underlying error for 404 on /splits.",
@@ -52,6 +34 @@
- "type": "string",
- "enum": [
- "ExternalAuthenticatedError",
- "DatasetNotFoundError",
- "SplitsResponseNotFound"
- ]
+ "type": "string"
@@ -60,3 +37,3 @@
- "ExternalAuthenticatedError": {
- "summary": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials.",
- "value": "ExternalAuthenticatedError"
+ "no-cache": {
+ "summary": "No cache.",
+ "value": "no-cache"
@@ -64,7 +41,3 @@
- "DatasetNotFoundError": {
- "summary": "The dataset does not exist on the Hub.",
- "value": "DatasetNotFoundError"
- },
- "SplitsResponseNotFound": {
- "summary": "Not found.",
- "value": "SplitsResponseNotFound"
+ "max-age": {
+ "summary": "Cache TTL.",
+ "value": "max-age=120"
@@ -75,2 +48,2 @@
- "X-Error-Code-splits-422": {
- "description": "A string that identifies the underlying error for 422 on /splits.",
+ "Access-Control-Allow-Origin": {
+ "description": "Indicates whether the response can be shared with requesting code from the given origin.",
@@ -78,8 +51 @@
- "type": "string",
- "enum": ["MissingRequiredParameter"]
- },
- "examples": {
- "MissingRequiredParameter": {
- "summary": "Parameter 'dataset' is required",
- "value": "MissingRequiredParameter"
- }
+ "type": "string"
@@ -86,0 +53 @@
+ "example": "*",
@@ -89,2 +56,2 @@
- "X-Error-Code-splits-500": {
- "description": "A string that identifies the underlying error for 500 on /splits.",
+ "X-Error-Code-401": {
+ "description": "A string that identifies the underlying error for 401.",
@@ -92,5 +59,4 @@
- "type": "string",
- "enum": [
- "SplitsResponseNotReadyError",
- "SplitsNamesError",
- "UnexpectedError"
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/X-Error-Code-ExternalUnauthenticatedError"
+ }
@@ -99,28 +64,0 @@
- "examples": {
- "SplitsResponseNotReadyError": {
- "summary": "The server is busier than usual and the list of splits is not ready yet. Please retry later.",
- "value": "SplitsResponseNotReadyError"
- },
- "SplitsNamesError": {
- "summary": "Cannot get the split names for the dataset.",
- "value": "SplitsNamesError"
- },
- "UnexpectedError": {
- "summary": "Unexpected error.",
- "value": "UnexpectedError"
- }
- },
- "required": true
- },
- "X-Error-Code-first-rows-401": {
- "description": "A string that identifies the underlying error for 401 on /first-rows.",
- "schema": {
- "type": "string",
- "enum": ["ExternalUnauthenticatedError"]
- },
- "examples": {
- "ExternalUnauthenticatedError": {
- "summary": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication.",
- "value": "ExternalUnauthenticatedError"
- }
- },
@@ -129,2 +67,2 @@
- "X-Error-Code-first-rows-404": {
- "description": "A string that identifies the underlying error for 404 on /first-rows.",
+ "X-Error-Code-404": {
+ "description": "A string that identifies the underlying error for 404.",
@@ -132,7 +70,5 @@
- "type": "string",
- "enum": [
- "ExternalAuthenticatedError",
- "DatasetNotFoundError",
- "ConfigNotFoundError",
- "SplitNotFoundError",
- "FirstRowsResponseNotFound"
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/X-Error-Code-ExternalAuthenticatedError"
+ },
+ { "$ref": "#/components/schemas/X-Error-Code-ResponseNotFound" }
@@ -141,36 +76,0 @@
- "examples": {
- "ExternalAuthenticatedError": {
- "summary": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials.",
- "value": "ExternalAuthenticatedError"
- },
- "DatasetNotFoundError": {
- "summary": "The dataset does not exist on the Hub.",
- "value": "DatasetNotFoundError"
- },
- "ConfigNotFoundError": {
- "summary": "config yyy does not exist for dataset xxx",
- "value": "ConfigNotFoundError"
- },
- "SplitNotFoundError": {
- "summary": "The config or the split does not exist in the dataset",
- "value": "SplitNotFoundError"
- },
- "FirstRowsResponseNotFound": {
- "summary": "Not found.",
- "value": "FirstRowsResponseNotFound"
- }
- },
- "required": true
- },
- "X-Error-Code-first-rows-422": {
- "description": "A string that identifies the underlying error for 422 on /first-rows.",
- "schema": {
- "type": "string",
- "enum": ["MissingRequiredParameter"]
- },
- "examples": {
- "MissingRequiredParameter": {
- "summary": "Parameters 'dataset', 'config' and 'split' are required",
- "value": "MissingRequiredParameter"
- }
- },
@@ -179,2 +79,2 @@
- "X-Error-Code-first-rows-500": {
- "description": "A string that identifies the underlying error for 500 on /first-rows.",
+ "X-Error-Code-422": {
+ "description": "A string that identifies the underlying error for 422.",
@@ -182,9 +82,4 @@
- "type": "string",
- "enum": [
- "FirstRowsResponseNotReady",
- "InfoError",
- "FeaturesError",
- "StreamingRowsError",
- "NormalRowsError",
- "RowsPostProcessingError",
- "UnexpectedError"
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/X-Error-Code-MissingRequiredParameter"
+ }
@@ -193,44 +87,0 @@
- "examples": {
- "FirstRowsResponseNotReady": {
- "summary": "The list of the first rows is not ready yet. Please retry later.",
- "value": "FirstRowsResponseNotReady"
- },
- "InfoError": {
- "summary": "The info cannot be fetched for the config of the dataset.",
- "value": "InfoError"
- },
- "FeaturesError": {
- "summary": "Cannot extract the features (columns) for the split of the config of the dataset.",
- "value": "FeaturesError"
- },
- "StreamingRowsError": {
- "summary": "Cannot load the dataset split (in streaming mode) to extract the first rows.",
- "value": "StreamingRowsError"
- },
- "NormalRowsError": {
- "summary": "Cannot load the dataset split (in normal download mode) to extract the first rows.",
- "value": "NormalRowsError"
- },
- "RowsPostProcessingError": {
- "summary": "Server error while post-processing the split rows. Please report the issue.",
- "value": "RowsPostProcessingError"
- },
- "UnexpectedError": {
- "summary": "Unexpected error.",
- "value": "UnexpectedError"
- }
- },
- "required": true
- },
- "X-Error-Code-rows-401": {
- "description": "A string that identifies the underlying error for 401 on /rows.",
- "schema": {
- "type": "string",
- "enum": ["ExternalUnauthenticatedError"]
- },
- "examples": {
- "ExternalUnauthenticatedError": {
- "summary": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication.",
- "value": "ExternalUnauthenticatedError"
- }
- },
@@ -239,2 +90,2 @@
- "X-Error-Code-rows-404": {
- "description": "A string that identifies the underlying error for 404 on /rows.",
+ "X-Error-Code-500": {
+ "description": "A string that identifies the underlying error for 500. It's marked as required: false because the header can be missing on text-plain response.",
@@ -242,7 +93,5 @@
- "type": "string",
- "enum": [
- "ExternalAuthenticatedError",
- "DatasetNotFoundError",
- "ConfigNotFoundError",
- "SplitNotFoundError",
- "RowsResponseNotFound"
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/X-Error-Code-ResponseNotReadyError"
+ },
+ { "$ref": "#/components/schemas/X-Error-Code-UnexpectedError" }
@@ -251,23 +100 @@
- "examples": {
- "ExternalAuthenticatedError": {
- "summary": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials.",
- "value": "ExternalAuthenticatedError"
- },
- "DatasetNotFoundError": {
- "summary": "The dataset does not exist on the Hub.",
- "value": "DatasetNotFoundError"
- },
- "ConfigNotFoundError": {
- "summary": "config yyy does not exist for dataset xxx",
- "value": "ConfigNotFoundError"
- },
- "SplitNotFoundError": {
- "summary": "The config or the split does not exist in the dataset",
- "value": "SplitNotFoundError"
- },
- "RowsResponseNotFound": {
- "summary": "Not found.",
- "value": "RowsResponseNotFound"
- }
- },
- "required": true
+ "required": false
@@ -275,2 +102,2 @@
- "X-Error-Code-rows-422": {
- "description": "A string that identifies the underlying error for 422 on /rows.",
+ "X-Error-Code-500-first-rows": {
+ "description": "A string that identifies the underlying error for 500 on /first-rows. It's marked as required: false because the header can be missing on text-plain response.",
@@ -278,8 +105,7 @@
- "type": "string",
- "enum": ["MissingRequiredParameter"]
- },
- "examples": {
- "MissingRequiredParameter": {
- "summary": "Parameters 'dataset', 'config', 'split', 'offset' and 'length' are required",
- "value": "MissingRequiredParameter"
- }
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/X-Error-Code-ResponseNotReadyError"
+ },
+ { "$ref": "#/components/schemas/X-Error-Code-UnexpectedError" },
+ { "$ref": "#/components/schemas/X-Error-Code-StreamingRowsError" }
+ ]
@@ -287 +113 @@
- "required": true
+ "required": false
@@ -289,2 +115,2 @@
- "X-Error-Code-rows-500": {
- "description": "A string that identifies the underlying error for 500 on /first-rows.",
+ "X-Error-Code-500-is-valid": {
+ "description": "A string that identifies the underlying error for 500 on /is-valid. It's marked as required: false because the header can be missing on text-plain response.",
@@ -292,12 +118,3 @@
- "type": "string",
- "enum": ["RowsPostProcessingError", "UnexpectedError"]
- },
- "examples": {
- "RowsPostProcessingError": {
- "summary": "Server error while post-processing the split rows. Please report the issue.",
- "value": "RowsPostProcessingError"
- },
- "UnexpectedError": {
- "summary": "Unexpected error.",
- "value": "UnexpectedError"
- }
+ "oneOf": [
+ { "$ref": "#/components/schemas/X-Error-Code-UnexpectedError" }
+ ]
@@ -305 +122 @@
- "required": true
+ "required": false
@@ -307,2 +124,2 @@
- "X-Error-Code-valid-500": {
- "description": "A string that identifies the underlying error for 500 on /valid.",
+ "X-Error-Code-500-common": {
+ "description": "A string that identifies the underlying error for 500 on /parquet. It's marked as required: false because the header can be missing on text-plain response.",
@@ -310,8 +127,9 @@
- "type": "string",
- "enum": ["UnexpectedError"]
- },
- "examples": {
- "UnexpectedError": {
- "summary": "Unexpected error.",
- "value": "UnexpectedError"
- }
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/X-Error-Code-ResponseNotReadyError"
+ },
+ { "$ref": "#/components/schemas/X-Error-Code-UnexpectedError" },
+ {
+ "$ref": "#/components/schemas/X-Error-Code-ExternalFilesSizeRequestHTTPError"
+ }
+ ]
@@ -319 +137 @@
- "required": true
+ "required": false
@@ -321,2 +139,2 @@
- "X-Error-Code-is-valid-401": {
- "description": "A string that identifies the underlying error for 401 on /is-valid.",
+ "X-Error-Code-500-rows": {
+ "description": "A string that identifies the underlying error for 500 on /rows. It's marked as required: false because the header can be missing on text-plain response.",
@@ -324,8 +142,6 @@
- "type": "string",
- "enum": ["ExternalUnauthenticatedError"]
- },
- "examples": {
- "ExternalUnauthenticatedError": {
- "summary": "Cannot access the route. Please retry with authentication.",
- "value": "ExternalUnauthenticatedError"
- }
+ "oneOf": [
+ { "$ref": "#/components/schemas/X-Error-Code-UnexpectedError" },
+ {
+ "$ref": "#/components/schemas/X-Error-Code-RowsPostProcessingError"
+ }
+ ]
@@ -333 +149 @@
- "required": true
+ "required": false
@@ -335,2 +151,2 @@
- "X-Error-Code-is-valid-404": {
- "description": "A string that identifies the underlying error for 404 on /is-valid.",
+ "X-Error-Code-500-search": {
+ "description": "A string that identifies the underlying error for 500 on /search. It's marked as required: false because the header can be missing on text-plain response.",
@@ -338,8 +154,6 @@
- "type": "string",
- "enum": ["ExternalAuthenticatedError"]
- },
- "examples": {
- "ExternalAuthenticatedError": {
- "summary": "Cannot access the route with the current credentials. Please retry with other authentication credentials.",
- "value": "ExternalAuthenticatedError"
- }
+ "oneOf": [
+ { "$ref": "#/components/schemas/X-Error-Code-UnexpectedError" },
+ {
+ "$ref": "#/components/schemas/X-Error-Code-RowsPostProcessingError"
+ }
+ ]
@@ -347 +161 @@
- "required": true
+ "required": false
@@ -349,2 +163,2 @@
- "X-Error-Code-is-valid-422": {
- "description": "A string that identifies the underlying error for 422 on /is-valid.",
+ "X-Error-Code-500-valid": {
+ "description": "A string that identifies the underlying error for 500 on /valid. It's marked as required: false because the header can be missing on text-plain response.",
@@ -352,8 +166,3 @@
- "type": "string",
- "enum": ["MissingRequiredParameter"]
- },
- "examples": {
- "MissingRequiredParameter": {
- "summary": "Parameter 'dataset' is required",
- "value": "MissingRequiredParameter"
- }
+ "oneOf": [
+ { "$ref": "#/components/schemas/X-Error-Code-UnexpectedError" }
+ ]
@@ -361 +170 @@
- "required": true
+ "required": false
@@ -363,2 +172,2 @@
- "X-Error-Code-is-valid-500": {
- "description": "A string that identifies the underlying error for 500 on /is-valid.",
+ "X-Error-Code-501": {
+ "description": "A string that identifies the underlying error for 501.",
@@ -366,8 +175,8 @@
- "type": "string",
- "enum": ["UnexpectedError"]
- },
- "examples": {
- "UnexpectedError": {
- "summary": "Unexpected error.",
- "value": "UnexpectedError"
- }
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/X-Error-Code-DatasetInBlockListError"
+ },
+ {
+ "$ref": "#/components/schemas/X-Error-Code-DatasetWithTooManyConfigsError"
+ }
+ ]
@@ -382,0 +192,39 @@
+ "ConfigItem": {
+ "type": "object",
+ "required": ["dataset", "config"],
+ "properties": {
+ "dataset": {
+ "type": "string"
+ },
+ "config": {
+ "type": "string"
+ }
+ }
+ },
+ "ConfigItems": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ConfigItem"
+ }
+ },
+ "FailedConfigItem": {
+ "type": "object",
+ "required": ["dataset", "config", "error"],
+ "properties": {
+ "dataset": {
+ "type": "string"
+ },
+ "config": {
+ "type": "string"
+ },
+ "error": {
+ "type": "object"
+ }
+ }
+ },
+ "FailedConfigItems": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/FailedConfigItem"
+ }
+ },
@@ -389 +237,9 @@
- "items": { "$ref": "#/components/schemas/SplitItem" }
+ "items": {
+ "$ref": "#/components/schemas/SplitItem"
+ }
+ },
+ "pending": {
+ "$ref": "#/components/schemas/ConfigItems"
+ },
+ "failed": {
+ "$ref": "#/components/schemas/FailedConfigItems"
@@ -405,6 +260,0 @@
- },
- "num_bytes": {
- "type": "integer"
- },
- "num_examples": {
- "type": "integer"
@@ -450 +300,3 @@
- "items": { "$ref": "#/components/schemas/FeatureItem" }
+ "items": {
+ "$ref": "#/components/schemas/FeatureItem"
+ }
@@ -454 +306,3 @@
- "items": { "$ref": "#/components/schemas/FirstRowItem" }
+ "items": {
+ "$ref": "#/components/schemas/RowItem"
+ }
@@ -458 +312 @@
- "RowsResponse": {
+ "PaginatedResponse": {
@@ -460 +314 @@
- "required": ["features", "rows"],
+ "required": ["features", "rows", "num_total_rows"],
@@ -464 +318,3 @@
- "items": { "$ref": "#/components/schemas/FeatureItem" }
+ "items": {
+ "$ref": "#/components/schemas/FeatureItem"
+ }
@@ -468 +324,6 @@
- "items": { "$ref": "#/components/schemas/FirstRowItem" }
+ "items": {
+ "$ref": "#/components/schemas/RowItem"
+ }
+ },
+ "num_total_rows": {
+ "type": "integer"
@@ -489,4 +350,12 @@
- { "$ref": "#/components/schemas/ValueFeature" },
- { "$ref": "#/components/schemas/ClassLabelFeature" },
- { "$ref": "#/components/schemas/ArrayXDFeature" },
- { "$ref": "#/components/schemas/TranslationFeature" },
+ {
+ "$ref": "#/components/schemas/ValueFeature"
+ },
+ {
+ "$ref": "#/components/schemas/ClassLabelFeature"
+ },
+ {
+ "$ref": "#/components/schemas/ArrayXDFeature"
+ },
+ {
+ "$ref": "#/components/schemas/TranslationFeature"
+ },
@@ -517,5 +385,0 @@
- "id": {
- "type": "string",
- "nullable": true,
- "enum": [null]
- },
@@ -563,5 +426,0 @@
- "id": {
- "type": "string",
- "nullable": true,
- "enum": [null]
- },
@@ -572,3 +430,0 @@
- "num_classes": {
- "type": "integer"
- },
@@ -587,5 +442,0 @@
- "id": {
- "type": "string",
- "nullable": true,
- "enum": [null]
- },
@@ -609,5 +459,0 @@
- "id": {
- "type": "string",
- "nullable": true,
- "enum": [null]
- },
@@ -630,5 +475,0 @@
- "id": {
- "type": "string",
- "nullable": true,
- "enum": [null]
- },
@@ -654,5 +494,0 @@
- "id": {
- "type": "string",
- "nullable": true,
- "enum": [null]
- },
@@ -687,5 +522,0 @@
- "id": {
- "type": "string",
- "nullable": true,
- "enum": [null]
- },
@@ -711,5 +541,0 @@
- "id": {
- "type": "string",
- "nullable": true,
- "enum": [null]
- },
@@ -725 +551 @@
- "FirstRowItem": {
+ "RowItem": {
@@ -740 +566,3 @@
- "items": { "type": "string" }
+ "items": {
+ "type": "string"
+ }
@@ -746,7 +574,21 @@
- { "$ref": "#/components/schemas/ValueCell" },
- { "$ref": "#/components/schemas/ClassLabelCell" },
- { "$ref": "#/components/schemas/Array2DCell" },
- { "$ref": "#/components/schemas/Array3DCell" },
- { "$ref": "#/components/schemas/Array4DCell" },
- { "$ref": "#/components/schemas/Array5DCell" },
- { "$ref": "#/components/schemas/TranslationCell" },
+ {
+ "$ref": "#/components/schemas/ValueCell"
+ },
+ {
+ "$ref": "#/components/schemas/ClassLabelCell"
+ },
+ {
+ "$ref": "#/components/schemas/Array2DCell"
+ },
+ {
+ "$ref": "#/components/schemas/Array3DCell"
+ },
+ {
+ "$ref": "#/components/schemas/Array4DCell"
+ },
+ {
+ "$ref": "#/components/schemas/Array5DCell"
+ },
+ {
+ "$ref": "#/components/schemas/TranslationCell"
+ },
@@ -769,0 +612,3 @@
+ },
+ {
+ "$ref": "#/components/schemas/NullableImagesListCell"
@@ -775,4 +620,12 @@
- { "type": "boolean" },
- { "type": "integer" },
- { "type": "number" },
- { "type": "string" }
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "integer"
+ },
+ {
+ "type": "number"
+ },
+ {
+ "type": "string"
+ }
@@ -838,2 +691,6 @@
- { "$ref": "#/components/schemas/ListCell" },
- { "$ref": "#/components/schemas/DictionaryOfListsCell" }
+ {
+ "$ref": "#/components/schemas/ListCell"
+ },
+ {
+ "$ref": "#/components/schemas/DictionaryOfListsCell"
+ }
@@ -863,0 +721 @@
+ "required": ["src", "type"],
@@ -876,0 +735,16 @@
+ "type": "object",
+ "properties": {
+ "src": {
+ "type": "string",
+ "format": "uri"
+ },
+ "height": {
+ "type": "integer"
+ },
+ "width": {
+ "type": "integer"
+ }
+ },
+ "required": ["src", "height", "width"]
+ },
+ "NullableImagesListCell": {
@@ -879,8 +753,3 @@
- "type": "object",
- "properties": {
- "src": {
- "type": "string",
- "format": "uri"
- },
- "height": {
- "type": "integer"
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ImageCell"
@@ -888,2 +757,2 @@
- "width": {
- "type": "integer"
+ {
+ "type": "null"
@@ -891 +760 @@
- }
+ ]
@@ -896 +765 @@
- "required": ["preview", "viewer", "valid"],
+ "required": ["preview", "viewer"],
@@ -900 +769,3 @@
- "items": { "type": "string" }
+ "items": {
+ "type": "string"
+ }
@@ -904 +775,3 @@
- "items": { "type": "string" }
+ "items": {
+ "type": "string"
+ }
@@ -910 +783 @@
- "required": ["preview", "viewer"],
+ "required": ["preview", "viewer", "search"],
@@ -916,0 +790,21 @@
+ },
+ "search": {
+ "type": "boolean"
+ }
+ }
+ },
+ "PreviousJob": {
+ "type": "object",
+ "required": ["dataset", "config", "split", "kind"],
+ "properties": {
+ "dataset": {
+ "type": "string"
+ },
+ "kind": {
+ "type": "string"
+ },
+ "config": {
+ "type": "string"
+ },
+ "split": {
+ "type": ["string", "null"]
@@ -920 +814,7 @@
- "ParquetFilesResponse": {
+ "PreviousJobs": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PreviousJob"
+ }
+ },
+ "ParquetResponse": {
@@ -922 +822 @@
- "required": ["parquet_files"],
+ "required": ["parquet_files", "partial"],
@@ -926 +826,15 @@
- "items": { "$ref": "#/components/schemas/SplitHubFile" }
+ "items": {
+ "$ref": "#/components/schemas/SplitHubFile"
+ }
+ },
+ "features": {
+ "type": "object"
+ },
+ "pending": {
+ "$ref": "#/components/schemas/PreviousJobs"
+ },
+ "failed": {
+ "$ref": "#/components/schemas/PreviousJobs"
+ },
+ "partial": {
+ "$ref": "#/components/schemas/Partial"
@@ -953,0 +868,368 @@
+ },
+ "InfoResponse": {
+ "type": "object",
+ "required": ["dataset_info", "partial"],
+ "properties": {
+ "dataset_info": {
+ "type": "object",
+ "description": "A dump of the DatasetInfo object from the datasets library. See https://huggingface.co/docs/datasets/en/package_reference/main_classes#datasets.DatasetInfo. We don't describe the contents of these metadata for now."
+ },
+ "pending": {
+ "$ref": "#/components/schemas/PreviousJobs"
+ },
+ "failed": {
+ "$ref": "#/components/schemas/PreviousJobs"
+ },
+ "partial": {
+ "$ref": "#/components/schemas/Partial"
+ }
+ }
+ },
+ "Partial": {
+ "type": "boolean",
+ "description": "True means that the response has been computed on part of the dataset (typically the first 5GB). False means that the complete dataset was used."
+ },
+ "DatasetSize": {
+ "type": "object",
+ "required": [
+ "dataset",
+ "num_bytes_parquet_files",
+ "num_bytes_memory",
+ "num_rows"
+ ],
+ "properties": {
+ "dataset": {
+ "type": "string"
+ },
+ "num_bytes_original_files": {
+ "type": "integer"
+ },
+ "num_bytes_parquet_files": {
+ "type": "integer"
+ },
+ "num_bytes_memory": {
+ "type": "integer"
+ },
+ "num_rows": {
+ "type": "integer"
+ }
+ }
+ },
+ "ConfigSize": {
+ "type": "object",
+ "required": [
+ "dataset",
+ "config",
+ "num_bytes_parquet_files",
+ "num_bytes_memory",
+ "num_rows",
+ "num_columns"
+ ],
+ "properties": {
+ "dataset": {
+ "type": "string"
+ },
+ "config": {
+ "type": "string"
+ },
+ "num_bytes_original_files": {
+ "type": "integer"
+ },
+ "num_bytes_parquet_files": {
+ "type": "integer"
+ },
+ "num_bytes_memory": {
+ "type": "integer"
+ },
+ "num_rows": {
+ "type": "integer"
+ },
+ "num_columns": {
+ "type": "integer"
+ }
+ }
+ },
+ "SplitSize": {
+ "type": "object",
+ "required": [
+ "dataset",
+ "config",
+ "split",
+ "num_bytes_parquet_files",
+ "num_bytes_memory",
+ "num_rows",
+ "num_columns"
+ ],
+ "properties": {
+ "dataset": {
+ "type": "string"
+ },
+ "config": {
+ "type": "string"
+ },
+ "split": {
+ "type": "string"
+ },
+ "num_bytes_parquet_files": {
+ "type": "integer"
+ },
+ "num_bytes_memory": {
+ "type": "integer"
+ },
+ "num_rows": {
+ "type": "integer"
+ },
+ "num_columns": {
+ "type": "integer"
+ }
+ }
+ },
+ "SizeResponse": {
+ "type": "object",
+ "required": ["size", "partial"],
+ "properties": {
+ "size": {
+ "type": "object",
+ "required": ["splits"],
+ "properties": {
+ "dataset": {
+ "$ref": "#/components/schemas/DatasetSize"
+ },
+ "config": {
+ "$ref": "#/components/schemas/ConfigSize"
+ },
+ "configs": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ConfigSize"
+ }
+ },
+ "splits": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/SplitSize"
+ }
+ }
+ }
+ },
+ "pending": {
+ "$ref": "#/components/schemas/PreviousJobs"
+ },
+ "failed": {
+ "$ref": "#/components/schemas/PreviousJobs"
+ },
+ "partial": {
+ "$ref": "#/components/schemas/Partial"
+ }
+ }
+ },
+ "OptInOutUrlsCountResponse": {
+ "type": "object",
+ "required": [
+ "urls_columns",
+ "num_opt_in_urls",
+ "num_opt_out_urls",
+ "num_urls",
+ "num_scanned_rows",
+ "has_urls_columns"
+ ],
+ "properties": {
+ "urls_columns": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "num_opt_in_urls": {
+ "type": "integer"
+ },
+ "num_opt_out_urls": {
+ "type": "integer"
+ },
+ "num_urls": {
+ "type": "integer"
+ },
+ "num_scanned_rows": {
+ "type": "integer"
+ },
+ "has_urls_columns": {
+ "type": "boolean"
+ },
+ "full_scan": {
+ "type": ["boolean", "null"]
+ }
+ }
+ },
+ "ColumnType": {
+ "type": "string",
+ "enum": ["float", "int", "class_label"]
+ },
+ "Histogram": {
+ "type": "object",
+ "required": ["hist", "bin_edges"],
+ "properties": {
+ "hist": {
+ "type": "array",
+ "items": {
+ "type": "integer"
+ }
+ },
+ "bin_edges": {
+ "type": "array",
+ "items": {
+ "type": "number"
+ }
+ }
+ }
+ },
+ "NumericalStatisticsItem": {
+ "type": "object",
+ "required": [
+ "nan_count",
+ "nan_proportion",
+ "min",
+ "max",
+ "mean",
+ "median",
+ "std",
+ "histogram"
+ ],
+ "properties": {
+ "nan_count": {
+ "type": "integer"
+ },
+ "nan_proportion": {
+ "type": "number"
+ },
+ "min": {
+ "type": "number"
+ },
+ "max": {
+ "type": "number"
+ },
+ "mean": {
+ "type": "number"
+ },
+ "median": {
+ "type": "number"
+ },
+ "std": {
+ "type": "number"
+ },
+ "histogram": {
+ "$ref": "#/components/schemas/Histogram"
+ }
+ }
+ },
+ "CategoricalStatisticsItem": {
+ "type": "object",
+ "required": ["nan_count", "nan_proportion", "n_unique", "frequencies"],
+ "properties": {
+ "nan_count": {
+ "type": "integer"
+ },
+ "nan_proportion": {
+ "type": "number"
+ },
+ "n_unique": {
+ "type": "integer"
+ },
+ "frequencies": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "integer"
+ }
+ }
+ }
+ },
+ "StatisticsPerColumnItem": {
+ "type": "object",
+ "required": ["column_name", "column_type", "column_statistics"],
+ "properties": {
+ "column_name": {
+ "type": "string"
+ },
+ "column_type": {
+ "$ref": "#/components/schemas/ColumnType"
+ },
+ "column_statistics": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/NumericalStatisticsItem"
+ },
+ {
+ "$ref": "#/components/schemas/CategoricalStatisticsItem"
+ }
+ ]
+ }
+ }
+ },
+ "StatisticsResponse": {
+ "type": "object",
+ "required": ["statistics", "num_examples"],
+ "properties": {
+ "statistics": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/StatisticsPerColumnItem"
+ }
+ },
+ "num_examples": {
+ "type": "integer"
+ }
+ }
+ },
+ "X-Error-Code-DatasetInBlockListError": {
+ "type": "string",
+ "const": "DatasetInBlockListError",
+ "description": "The dataset is in the list of blocked datasets."
+ },
+ "X-Error-Code-DatasetWithTooManyConfigsError": {
+ "type": "string",
+ "const": "DatasetWithTooManyConfigsError",
+ "description": "The number of configs of a dataset exceeded the limit."
+ },
+ "X-Error-Code-ExternalAuthenticatedError": {
+ "type": "string",
+ "const": "ExternalAuthenticatedError",
+ "description": "Raised when the external authentication check failed while the user was authenticated. Even if the external authentication server returns 403 in that case, we return 404 because we don't know if the dataset exist or not. It's also coherent with how the Hugging Face Hub works."
+ },
+ "X-Error-Code-ExternalFilesSizeRequestHTTPError": {
+ "type": "string",
+ "const": "ExternalFilesSizeRequestHTTPError",
+ "description": "We failed to get the size of the external files."
+ },
+ "X-Error-Code-ExternalUnauthenticatedError": {
+ "type": "string",
+ "const": "ExternalUnauthenticatedError",
+ "description": "The external authentication check failed while the user was unauthenticated."
+ },
+ "X-Error-Code-ResponseNotFound": {
+ "type": "string",
+ "const": "ResponseNotFound",
+ "description": "Raised when the response has not been found."
+ },
+ "X-Error-Code-MissingRequiredParameter": {
+ "type": "string",
+ "const": "MissingRequiredParameter",
+ "description": "A required parameter is missing."
+ },
+ "X-Error-Code-ResponseNotReadyError": {
+ "type": "string",
+ "const": "ResponseNotReadyError",
+ "description": "The response has not been processed yet."
+ },
+ "X-Error-Code-RowsPostProcessingError": {
+ "type": "string",
+ "const": "RowsPostProcessingError",
+ "description": "The rows could not be post-processed successfully."
+ },
+ "X-Error-Code-StreamingRowsError": {
+ "type": "string",
+ "const": "StreamingRowsError",
+ "description": "The rows could not be fetched in streaming mode."
+ },
+ "X-Error-Code-UnexpectedError": {
+ "type": "string",
+ "const": "UnexpectedError",
+ "description": "The job runner raised an unexpected error."
@@ -969,18 +1251,406 @@
- }
- },
- "paths": {
- "/splits": {
- "get": {
- "summary": "List of splits",
- "description": "The list of splits of a dataset.",
- "externalDocs": {
- "description": "See Splits (Hub docs)",
- "url": "https://huggingface.co/docs/datasets-server/splits"
- },
- "operationId": "listSplits",
- "security": [
- {},
- {
- "HuggingFaceCookie": []
- },
- {
+ },
+ "examples": {
+ "InexistentConfigError": {
+ "summary": "The response is not found because the config does not exist.",
+ "description": "try with config=inexistent-config.",
+ "value": {
+ "error": "Not found."
+ }
+ },
+ "InexistentDatasetError": {
+ "summary": "The dataset does not exist.",
+ "description": "try with dataset=inexistent-dataset.",
+ "value": {
+ "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
+ }
+ },
+ "InexistentSplitError": {
+ "summary": "The response is not found because the split does not exist.",
+ "description": "try with split=inexistent-split.",
+ "value": {
+ "error": "Not found."
+ }
+ },
+ "AuthorizedPrivateDatasetError": {
+ "summary": "The dataset is private, and you are not authorized.",
+ "description": "try with dataset=severo/test_private.",
+ "value": {
+ "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
+ }
+ },
+ "UnauthorizedPrivateDatasetError": {
+ "summary": "The dataset is private, and you are authorized, but private datasets are not supported yet.",
+ "description": "try with dataset=severo/test_private.",
+ "value": {
+ "error": "Not found."
+ }
+ },
+ "UnauthorizedGatedDatasetError": {
+ "summary": "The dataset is public but gated, and you are not authenticated or authorized.",
+ "description": "try with dataset=severo/test_gated.",
+ "value": {
+ "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
+ }
+ },
+ "MissingDatasetParameterError": {
+ "summary": "The dataset parameter is missing.",
+ "description": "try without setting ?dataset",
+ "value": {
+ "error": "Parameter 'dataset' is required"
+ }
+ },
+ "EmptyDatasetParameterError": {
+ "summary": "The dataset parameter is empty.",
+ "description": "try with ?dataset=",
+ "value": {
+ "error": "Parameter 'dataset' is required"
+ }
+ },
+ "MissingDatasetConfigSplitParameterError": {
+ "summary": "One of the dataset, config or split parameters is missing.",
+ "description": "try without setting ?dataset",
+ "value": {
+ "error": "Parameters 'split', 'config' and 'dataset' are required"
+ }
+ },
+ "EmptyDatasetConfigSplitParameterError": {
+ "summary": "One of the dataset, config or split parameters is empty.",
+ "description": "try with ?dataset=",
+ "value": {
+ "error": "Parameters 'split', 'config' and 'dataset' are required"
+ }
+ },
+ "ResponseNotReadyError": {
+ "summary": "The response is not ready yet. You can retry later. The response header 'x-error-code' contains 'ResponseNotReady'.",
+ "description": "Create a new dataset and try immediately, before the response could be generated.",
+ "value": {
+ "error": "The server is busier than usual and the response is not ready yet. Please retry later."
+ }
+ },
+ "UnexpectedJsonError": {
+ "summary": "The server encountered an unexpected error",
+ "description": "This error indicates a bug in the code or a failure in the infrastructure. It can be reported to https://github.com/huggingface/datasets-server/issues.",
+ "value": {
+ "error": "Unexpected error."
+ }
+ },
+ "UnexpectedTextError": {
+ "summary": "The server encountered an unexpected error",
+ "description": "This error indicates a bug in the code or a failure in the infrastructure. It can be reported to https://github.com/huggingface/datasets-server/issues.",
+ "value": "Internal Server Error."
+ }
+ },
+ "parameters": {
+ "RequiredDataset": {
+ "name": "dataset",
+ "in": "query",
+ "description": "The identifier of the dataset on the Hub.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "examples": {
+ "glue": {
+ "summary": "A canonical dataset",
+ "value": "glue"
+ },
+ "Helsinki-NLP/tatoeba_mt": {
+ "summary": "A namespaced dataset",
+ "value": "Helsinki-NLP/tatoeba_mt"
+ }
+ }
+ },
+ "RequiredConfig": {
+ "name": "config",
+ "in": "query",
+ "description": "The dataset configuration (or subset).",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "examples": {
+ "cola": {
+ "summary": "A subset of the glue dataset",
+ "value": "cola"
+ },
+ "yangdong/ecqa": {
+ "summary": "The default configuration given by the 🤗 Datasets library",
+ "value": "yangdong--ecqa"
+ }
+ }
+ },
+ "RequiredSplit": {
+ "name": "split",
+ "in": "query",
+ "description": "The split name.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "examples": {
+ "train": {
+ "summary": "train split",
+ "value": "train"
+ },
+ "test": {
+ "summary": "test split",
+ "value": "test"
+ },
+ "validation": {
+ "summary": "validation split",
+ "value": "validation"
+ }
+ }
+ },
+ "OptionalConfig": {
+ "name": "config",
+ "in": "query",
+ "description": "The dataset configuration (or subset) on which to filter the response.",
+ "schema": {
+ "type": "string"
+ },
+ "examples": {
+ "cola": {
+ "summary": "A subset of the glue dataset",
+ "value": "cola"
+ },
+ "yangdong/ecqa": {
+ "summary": "The default configuration given by the 🤗 Datasets library",
+ "value": "yangdong--ecqa"
+ }
+ }
+ },
+ "OptionalSplit": {
+ "name": "split",
+ "in": "query",
+ "description": "The split name.",
+ "schema": {
+ "type": "string"
+ },
+ "examples": {
+ "train": {
+ "summary": "train split",
+ "value": "train"
+ },
+ "test": {
+ "summary": "test split",
+ "value": "test"
+ },
+ "validation": {
+ "summary": "validation split",
+ "value": "validation"
+ }
+ }
+ }
+ },
+ "responses": {
+ "Common401": {
+ "description": "If the external authentication step on the Hugging Face Hub failed, and no authentication mechanism has been provided. Retry with authentication.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-401"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "inexistent dataset, and not authenticated": {
+ "$ref": "#/components/examples/InexistentDatasetError"
+ },
+ "private dataset, and not authenticated or authorized": {
+ "$ref": "#/components/examples/UnauthorizedPrivateDatasetError"
+ }
+ }
+ }
+ }
+ },
+ "Dataset404": {
+ "description": "If the repository to download from cannot be found. This may be because it doesn't exist, or because it is set to `private` and you do not have access.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-404"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "inexistent dataset, while authenticated": {
+ "$ref": "#/components/examples/InexistentDatasetError"
+ },
+ "private dataset, while authenticated and authorized": {
+ "$ref": "#/components/examples/AuthorizedPrivateDatasetError"
+ },
+ "gated dataset, and not authenticated or authorized": {
+ "$ref": "#/components/examples/UnauthorizedGatedDatasetError"
+ }
+ }
+ }
+ }
+ },
+ "Dataset422": {
+ "description": "The `dataset` parameter has not been provided.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-422"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "missing dataset parameter": {
+ "$ref": "#/components/examples/MissingDatasetParameterError"
+ },
+ "empty dataset parameter": {
+ "$ref": "#/components/examples/EmptyDatasetParameterError"
+ }
+ }
+ }
+ }
+ },
+ "DatasetConfig404": {
+ "description": "If the repository to download from cannot be found. This may be because it doesn't exist, or because it is set to `private` and you do not have access.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-404"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "inexistent dataset, while authenticated": {
+ "$ref": "#/components/examples/InexistentDatasetError"
+ },
+ "private dataset, while authenticated and authorized": {
+ "$ref": "#/components/examples/AuthorizedPrivateDatasetError"
+ },
+ "gated dataset, and not authenticated or authorized": {
+ "$ref": "#/components/examples/UnauthorizedGatedDatasetError"
+ },
+ "inexistent config": {
+ "$ref": "#/components/examples/InexistentConfigError"
+ }
+ }
+ }
+ }
+ },
+ "DatasetConfigSplit404": {
+ "description": "If the repository to download from cannot be found, or if the config or split does not exist in the dataset. Note that this may be because the dataset doesn't exist, or because it is set to `private` and you do not have access.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-404"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "inexistent dataset, while authenticated": {
+ "$ref": "#/components/examples/InexistentDatasetError"
+ },
+ "private dataset, while authenticated and authorized": {
+ "$ref": "#/components/examples/AuthorizedPrivateDatasetError"
+ },
+ "gated dataset, and not authenticated or authorized": {
+ "$ref": "#/components/examples/UnauthorizedGatedDatasetError"
+ },
+ "inexistent config": {
+ "$ref": "#/components/examples/InexistentConfigError"
+ },
+ "inexistent split": {
+ "$ref": "#/components/examples/InexistentSplitError"
+ }
+ }
+ }
+ }
+ },
+ "DatasetConfigSplit422": {
+ "description": "Some of the `dataset`, `config`, or `split` parameters have not been provided or are invalid.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-422"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "missing required parameter": {
+ "$ref": "#/components/examples/MissingDatasetConfigSplitParameterError"
+ },
+ "empty required parameter": {
+ "$ref": "#/components/examples/EmptyDatasetConfigSplitParameterError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "paths": {
+ "/splits": {
+ "get": {
+ "summary": "List of splits",
+ "description": "The list of splits of a dataset.",
+ "externalDocs": {
+ "description": "See Splits (Hub docs)",
+ "url": "https://huggingface.co/docs/datasets-server/splits"
+ },
+ "operationId": "listSplits",
+ "security": [
+ {},
+ {
+ "HuggingFaceCookie": []
+ },
+ {
@@ -992,12 +1662,4 @@
- "name": "dataset",
- "in": "query",
- "description": "The identifier of the dataset on the Hub.",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "glue": { "summary": "a canonical dataset", "value": "glue" },
- "Helsinki-NLP/tatoeba_mt": {
- "summary": "a namespaced dataset",
- "value": "Helsinki-NLP/tatoeba_mt"
- }
- }
+ "$ref": "#/components/parameters/RequiredDataset"
+ },
+ {
+ "$ref": "#/components/parameters/OptionalConfig"
@@ -1010 +1672,3 @@
- "Cache-Control": { "$ref": "#/components/headers/Cache-Control" },
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
@@ -1021 +1685 @@
- "duorc": {
+ "all splits in a dataset": {
@@ -1022,0 +1687 @@
+ "description": "Try with https://datasets-server.huggingface.co/splits?dataset=duorc.",
@@ -1027,4 +1692,2 @@
- "config": "SelfRC",
- "split": "train",
- "num_bytes": 239852925,
- "num_examples": 60721
+ "config": "ParaphraseRC",
+ "split": "train"
@@ -1034,4 +1697,2 @@
- "config": "SelfRC",
- "split": "validation",
- "num_bytes": 51662575,
- "num_examples": 12961
+ "config": "ParaphraseRC",
+ "split": "validation"
@@ -1041,4 +1702,2 @@
- "config": "SelfRC",
- "split": "test",
- "num_bytes": 49142766,
- "num_examples": 12559
+ "config": "ParaphraseRC",
+ "split": "test"
@@ -1048,4 +1707,2 @@
- "config": "ParaphraseRC",
- "split": "train",
- "num_bytes": 496683105,
- "num_examples": 69524
+ "config": "SelfRC",
+ "split": "train"
@@ -1055,4 +1712,2 @@
- "config": "ParaphraseRC",
- "split": "validation",
- "num_bytes": 106510545,
- "num_examples": 15591
+ "config": "SelfRC",
+ "split": "validation"
@@ -1062,4 +1717,2 @@
- "config": "ParaphraseRC",
- "split": "test",
- "num_bytes": 115215816,
- "num_examples": 15857
+ "config": "SelfRC",
+ "split": "test"
@@ -1067 +1720,3 @@
- ]
+ ],
+ "pending": [],
+ "failed": []
@@ -1070,2 +1725,3 @@
- "emotion": {
- "summary": "emotion: one config, three splits",
+ "splits for a single config": {
+ "summary": "emotion has two configs. Setting config=unsplit only returns the splits for this config.",
+ "description": "Try with https://datasets-server.huggingface.co/splits?dataset=emotion&config=unsplit.",
@@ -1076,18 +1732,2 @@
- "config": "default",
- "split": "train",
- "num_bytes": 1741541,
- "num_examples": 16000
- },
- {
- "dataset": "emotion",
- "config": "default",
- "split": "validation",
- "num_bytes": 214699,
- "num_examples": 2000
- },
- {
- "dataset": "emotion",
- "config": "default",
- "split": "test",
- "num_bytes": 217177,
- "num_examples": 2000
+ "config": "unsplit",
+ "split": "train"
@@ -1103 +1743,10 @@
- "description": "If the external authentication step on the Hugging Face Hub failed, and no authentication mechanism has been provided. Retry with authentication.",
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/DatasetConfig404"
+ },
+ "422": {
+ "$ref": "#/components/responses/Dataset422"
+ },
+ "500": {
+ "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
@@ -1112 +1761 @@
- "$ref": "#/components/headers/X-Error-Code-splits-401"
+ "$ref": "#/components/headers/X-Error-Code-500"
@@ -1121,2 +1770,3 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist.",
+ "error in the dataset itself": {
+ "summary": "The dataset is empty, or a file is missing, or some other error that prevents the response to be created.",
+ "description": "Try with https://datasets-server.huggingface.co/splits?dataset=severo/empty",
@@ -1124 +1774,13 @@
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
+ "error": "The dataset is empty.",
+ "cause_exception": "EmptyDatasetError",
+ "cause_message": "The directory at hf://datasets/severo/empty@5db043c2aee5fe0f2118c134de45f7b2e3230fbc doesn't contain any data files",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/src/worker/job_runners/dataset/config_names.py\", line 56, in compute_config_names_response\n for config in sorted(get_dataset_config_names(path=dataset, use_auth_token=use_auth_token))\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/inspect.py\", line 351, in get_dataset_config_names\n dataset_module = dataset_module_factory(\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/load.py\", line 1486, in dataset_module_factory\n raise e1 from None\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/load.py\", line 1469, in dataset_module_factory\n return HubDatasetModuleFactoryWithoutScript(\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/load.py\", line 1032, in get_module\n else get_data_patterns(base_path, download_config=self.download_config)\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/data_files.py\", line 459, in get_data_patterns\n raise EmptyDatasetError(f\"The directory at {base_path} doesn't contain any data files\") from None\n",
+ "datasets.data_files.EmptyDatasetError: The directory at hf://datasets/severo/empty@5db043c2aee5fe0f2118c134de45f7b2e3230fbc doesn't contain any data files\n"
+ ]
@@ -1127,5 +1789,2 @@
- "gated-dataset": {
- "summary": "The dataset is gated.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
+ "response not ready": {
+ "$ref": "#/components/examples/ResponseNotReadyError"
@@ -1133,5 +1792,2 @@
- "private-dataset": {
- "summary": "The dataset is private.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
@@ -1140,8 +1795,0 @@
- }
- }
- },
- "404": {
- "description": "If the repository to download from cannot be found. This may be because it doesn't exist, or because it is set to `private` and you do not have access.",
- "headers": {
- "Cache-Control": {
- "$ref": "#/components/headers/Cache-Control"
@@ -1149,9 +1797 @@
- "Access-Control-Allow-Origin": {
- "$ref": "#/components/headers/Access-Control-Allow-Origin"
- },
- "X-Error-Code": {
- "$ref": "#/components/headers/X-Error-Code-splits-404"
- }
- },
- "content": {
- "application/json": {
+ "text/plain": {
@@ -1159 +1799 @@
- "$ref": "#/components/schemas/CustomError"
+ "$ref": "#/components/schemas/ServerErrorResponse"
@@ -1162,17 +1802,2 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "gated-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "private-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
@@ -1184,2 +1809,2 @@
- "422": {
- "description": "The `dataset` parameter has not been provided.",
+ "501": {
+ "description": "The server does not implement the feature.",
@@ -1194 +1819 @@
- "$ref": "#/components/headers/X-Error-Code-splits-422"
+ "$ref": "#/components/headers/X-Error-Code-501"
@@ -1203,92 +1828,6 @@
- "missing-parameter": {
- "summary": "The dataset parameter is missing.",
- "value": { "error": "Parameter 'dataset' is required" }
- },
- "empty-parameter": {
- "summary": "The dataset parameter is empty (?dataset=).",
- "value": { "error": "Parameter 'dataset' is required" }
- }
- }
- }
- }
- },
- "500": {
- "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
- "headers": {
- "Cache-Control": {
- "$ref": "#/components/headers/Cache-Control"
- },
- "Access-Control-Allow-Origin": {
- "$ref": "#/components/headers/Access-Control-Allow-Origin"
- },
- "X-Error-Code": {
- "$ref": "#/components/headers/X-Error-Code-splits-500"
- }
- },
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/CustomError"
- },
- "examples": {
- "SplitsNotFoundError": {
- "summary": "SplitsNotFoundError",
- "value": {
- "error": "Cannot get the split names for the dataset.",
- "cause_exception": "SplitsNotFoundError",
- "cause_message": "The split names could not be parsed from the dataset config.",
- "cause_traceback": [
- "Traceback (most recent call last):\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/inspect.py\", line 354, in get_dataset_config_info\n for split_generator in builder._split_generators(\n",
- "TypeError: _split_generators() missing 1 required positional argument: 'pipeline'\n",
- "\nThe above exception was the direct cause of the following exception:\n\n",
- "Traceback (most recent call last):\n",
- " File \"/src/services/worker/src/worker/responses/splits.py\", line 74, in get_splits_response\n split_full_names = get_dataset_split_full_names(dataset, hf_token)\n",
- " File \"/src/services/worker/src/worker/responses/splits.py\", line 35, in get_dataset_split_full_names\n return [\n",
- " File \"/src/services/worker/src/worker/responses/splits.py\", line 38, in <listcomp>\n for split in get_dataset_split_names(dataset, config, token=hf_token)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/inspect.py\", line 404, in get_dataset_split_names\n info = get_dataset_config_info(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/inspect.py\", line 359, in get_dataset_config_info\n raise SplitsNotFoundError(\"The split names could not be parsed from the dataset config.\") from err\n",
- "datasets.inspect.SplitsNotFoundError: The split names could not be parsed from the dataset config.\n"
- ]
- }
- },
- "FileNotFoundError": {
- "summary": "FileNotFoundError",
- "value": {
- "error": "Cannot get the split names for the dataset.",
- "cause_exception": "FileNotFoundError",
- "cause_message": "Couldn't find a dataset script at /src/services/worker/akhaliq/test/test.py or any data file in the same directory. Couldn't find 'akhaliq/test' on the Hugging Face Hub either: FileNotFoundError: The dataset repository at 'akhaliq/test' doesn't contain any data file.",
- "cause_traceback": [
- "Traceback (most recent call last):\n",
- " File \"/src/services/worker/src/worker/responses/splits.py\", line 74, in get_splits_response\n split_full_names = get_dataset_split_full_names(dataset, hf_token)\n",
- " File \"/src/services/worker/src/worker/responses/splits.py\", line 37, in get_dataset_split_full_names\n for config in get_dataset_config_names(dataset, token=hf_token)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/inspect.py\", line 289, in get_dataset_config_names\n dataset_module = dataset_module_factory(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/load.py\", line 1243, in dataset_module_factory\n raise FileNotFoundError(\n",
- "FileNotFoundError: Couldn't find a dataset script at /src/services/worker/akhaliq/test/test.py or any data file in the same directory. Couldn't find 'akhaliq/test' on the Hugging Face Hub either: FileNotFoundError: The dataset repository at 'akhaliq/test' doesn't contain any data file.\n"
- ]
- }
- },
- "not-ready": {
- "summary": "the response is not ready yet.",
- "value": {
- "error": "The server is busier than usual and the list of splits is not ready yet. Please retry later."
- }
- },
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Unexpected error."
- }
- }
- }
- },
- "text/plain": {
- "schema": {
- "$ref": "#/components/schemas/ServerErrorResponse"
- },
- "examples": {
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Internal Server Error"
- }
+ "too many configs in the dataset": {
+ "summary": "The dataset has too many configs. The server does not support more than 3,000 configs.",
+ "description": "Try with https://datasets-server.huggingface.co/splits?dataset=facebook/flores",
+ "value": {
+ "error": "The maximum number of configs allowed is 3000, dataset has 41617 configs."
+ }
@@ -1299,0 +1839,3 @@
+ },
+ "requestBody": {
+ "content": {}
@@ -1323,12 +1865 @@
- "name": "dataset",
- "in": "query",
- "description": "The identifier of the dataset on the Hub.",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "glue": { "summary": "a canonical dataset", "value": "glue" },
- "Helsinki-NLP/tatoeba_mt": {
- "summary": "a namespaced dataset",
- "value": "Helsinki-NLP/tatoeba_mt"
- }
- }
+ "$ref": "#/components/parameters/RequiredDataset"
@@ -1337,15 +1868 @@
- "name": "config",
- "in": "query",
- "description": "The dataset configuration (or subset).",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "cola": {
- "summary": "a subset of the glue dataset",
- "value": "cola"
- },
- "yangdong/ecqa": {
- "summary": "the default configuration given by the 🤗 Datasets library",
- "value": "yangdong--ecqa"
- }
- }
+ "$ref": "#/components/parameters/RequiredConfig"
@@ -1354,19 +1871 @@
- "name": "split",
- "in": "query",
- "description": "The split name.",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "train": {
- "summary": "train split",
- "value": "train"
- },
- "test": {
- "summary": "test split",
- "value": "test"
- },
- "validation": {
- "summary": "validation split",
- "value": "validation"
- }
- }
+ "$ref": "#/components/parameters/RequiredSplit"
@@ -1392,2 +1891,3 @@
- "imdb": {
- "summary": "text, and label column (only 3 rows are shown for brevity)",
+ "A simple dataset (imdb) with text and label": {
+ "summary": "Text, and label column. Only 3 rows are shown for brevity.",
+ "description": "Try with https://datasets-server.huggingface.co/first-rows?dataset=imdb&config=plain_text&split=train.",
@@ -1411 +1910,0 @@
- "num_classes": 2,
@@ -1441,8 +1939,0 @@
- },
- {
- "row_idx": 3,
- "row": {
- "text": "This film was probably inspired by Godard's Masculin, féminin and I urge you to see that film instead.<br /><br />The film has two strong elements and those are, (1) the realistic acting (2) the impressive, undeservedly good, photo. Apart from that, what strikes me most is the endless stream of silliness. Lena Nyman has to be most annoying actress in the world. She acts so stupid and with all the nudity in this film,...it's unattractive. Comparing to Godard's film, intellectuality has been replaced with stupidity. Without going too far on this subject, I would say that follows from the difference in ideals between the French and the Swedish society.<br /><br />A movie of its time, and place. 2/10.",
- "label": 0
- },
- "truncated_cells": []
@@ -1453,2 +1944,3 @@
- "truncated": {
- "summary": "truncated cells due to the response size (has a timestamp column)",
+ "Truncated cells": {
+ "summary": "Truncated cells due to the response size (has a timestamp column). Only 3 rows are shown for brevity.",
+ "description": "Try with https://datasets-server.huggingface.co/first-rows?dataset=ett&config=m2&split=test.",
@@ -1546,11 +2037,0 @@
- },
- {
- "row_idx": 3,
- "row": {
- "start": "2016-07-01T00:00:00",
- "target": "[38.6619987487793,38.222999572753906,37.34400177001953,37.124000549316406,37.124000549316406,36.9039",
- "feat_static_cat": [0],
- "feat_dynamic_real": "[[41.130001068115234,39.62200164794922,38.86800003051758,35.518001556396484,37.52799987792969,37.611",
- "item_id": "OT"
- },
- "truncated_cells": ["target", "feat_dynamic_real"]
@@ -1561,2 +2042,3 @@
- "image": {
- "summary": "a column with images (only 3 rows are shown for brevity)",
+ "Image column": {
+ "summary": "A column with images. Only 3 rows are shown for brevity.",
+ "description": "Try with https://datasets-server.huggingface.co/first-rows?dataset=huggan/horse2zebra&config=huggan--horse2zebra-aligned&split=train.",
@@ -1588 +2070 @@
- "url": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/0/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/0/imageA/image.jpg",
@@ -1593 +2075 @@
- "url": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/0/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/0/imageB/image.jpg",
@@ -1604 +2086 @@
- "url": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/1/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/1/imageA/image.jpg",
@@ -1609 +2091 @@
- "url": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/1/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/1/imageB/image.jpg",
@@ -1620,17 +2102 @@
- "url": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/2/imageA/image.jpg",
- "height": 256,
- "width": 256
- },
- "imageB": {
- "url": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/2/imageB/image.jpg",
- "height": 256,
- "width": 256
- }
- },
- "truncated_cells": []
- },
- {
- "row_idx": 3,
- "row": {
- "imageA": {
- "url": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/3/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/2/imageA/image.jpg",
@@ -1641 +2107 @@
- "url": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/3/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/2/imageB/image.jpg",
@@ -1651,2 +2117,3 @@
- "audio": {
- "summary": "a column with audio files (only 3 rows are shown for brevity)",
+ "Audio column": {
+ "summary": "A column with audio files. Only 3 rows are shown for brevity.",
+ "description": "Try with https://datasets-server.huggingface.co/first-rows?dataset=asapp%2Fslue&config=voxceleb&split=train.",
@@ -1654,2 +2121,2 @@
- "dataset": "mozilla-foundation/common_voice_9_0",
- "config": "en",
+ "dataset": "asapp/slue",
+ "config": "voxceleb",
@@ -1660 +2127 @@
- "name": "client_id",
+ "name": "id",
@@ -1668,8 +2134,0 @@
- "name": "path",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
- },
- {
- "feature_idx": 2,
@@ -1678 +2137 @@
- "sampling_rate": 48000,
+ "sampling_rate": 16000,
@@ -1683,26 +2142,2 @@
- "feature_idx": 3,
- "name": "sentence",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
- },
- {
- "feature_idx": 4,
- "name": "up_votes",
- "type": {
- "dtype": "int64",
- "_type": "Value"
- }
- },
- {
- "feature_idx": 5,
- "name": "down_votes",
- "type": {
- "dtype": "int64",
- "_type": "Value"
- }
- },
- {
- "feature_idx": 6,
- "name": "age",
+ "feature_idx": 2,
+ "name": "speaker_id",
@@ -1715,2 +2150,2 @@
- "feature_idx": 7,
- "name": "gender",
+ "feature_idx": 3,
+ "name": "normalized_text",
@@ -1723,2 +2158,2 @@
- "feature_idx": 8,
- "name": "accent",
+ "feature_idx": 4,
+ "name": "sentiment",
@@ -1731,2 +2166,2 @@
- "feature_idx": 9,
- "name": "locale",
+ "feature_idx": 5,
+ "name": "start_second",
@@ -1734 +2169 @@
- "dtype": "string",
+ "dtype": "float64",
@@ -1739,2 +2174,2 @@
- "feature_idx": 10,
- "name": "segment",
+ "feature_idx": 6,
+ "name": "end_second",
@@ -1742 +2177 @@
- "dtype": "string",
+ "dtype": "float64",
@@ -1751,2 +2186 @@
- "client_id": "04960d53cc851eeb6d93f21a09e09ab36fe16943acb226ced1211d7250ab2f1b9a1d655c1cc03d50006e396010851ad52d4c53f49dd77b080b01c4230704c68d",
- "path": null,
+ "id": "id10059_229vKIGbxrI_00001",
@@ -1755 +2189 @@
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/assets/mozilla-foundation/common_voice_9_0/--/en/train/0/audio/audio.mp3",
+ "src": "https://datasets-server.huggingface.co/assets/asapp/slue/--/voxceleb/train/0/audio/audio.mp3",
@@ -1759 +2193 @@
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/assets/mozilla-foundation/common_voice_9_0/--/en/train/0/audio/audio.wav",
+ "src": "https://datasets-server.huggingface.co/assets/asapp/slue/--/voxceleb/train/0/audio/audio.wav",
@@ -1763,8 +2197,5 @@
- "sentence": "Why does Melissandre look like she wants to consume Jon Snow on the ride up the wall?",
- "up_votes": 2,
- "down_votes": 0,
- "age": "fourties",
- "gender": "male",
- "accent": "United States English",
- "locale": "en",
- "segment": ""
+ "speaker_id": "id10059",
+ "normalized_text": "and i i don't believe in god no religion says yet i was",
+ "sentiment": "Neutral",
+ "start_second": 0,
+ "end_second": 4.24
@@ -1777,2 +2208 @@
- "client_id": "f9f1f96bae1390dfe61ff298abb90975c079e913c712d57d97307ed797469eac446abb149daaad24cacffcc24e1e3275fefeb97f977eb74ce2233e0e5c1d437e",
- "path": null,
+ "id": "id10059_229vKIGbxrI_00002",
@@ -1781 +2211 @@
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/assets/mozilla-foundation/common_voice_9_0/--/en/train/1/audio/audio.mp3",
+ "src": "https://datasets-server.huggingface.co/assets/asapp/slue/--/voxceleb/train/1/audio/audio.mp3",
@@ -1785 +2215 @@
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/assets/mozilla-foundation/common_voice_9_0/--/en/train/1/audio/audio.wav",
+ "src": "https://datasets-server.huggingface.co/assets/asapp/slue/--/voxceleb/train/1/audio/audio.wav",
@@ -1789,8 +2219,5 @@
- "sentence": "\"I'm getting them for twelve dollars a night.\"",
- "up_votes": 2,
- "down_votes": 0,
- "age": "",
- "gender": "",
- "accent": "",
- "locale": "en",
- "segment": ""
+ "speaker_id": "id10059",
+ "normalized_text": "the question because of my mother till i was fourteen when i thought about it when i emerged with",
+ "sentiment": "Neutral",
+ "start_second": 0,
+ "end_second": 5.8
@@ -1803,2 +2230 @@
- "client_id": "a6c7706a220eeea7ee3687c1122fe7ac17962d2449d25b6db37cc41cdaace442683e11945b6f581e73941c3083cd4eecfafc938840459cd8c571dae7774ee687",
- "path": null,
+ "id": "id10059_229vKIGbxrI_00003",
@@ -1807 +2233 @@
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/assets/mozilla-foundation/common_voice_9_0/--/en/train/2/audio/audio.mp3",
+ "src": "https://datasets-server.huggingface.co/assets/asapp/slue/--/voxceleb/train/2/audio/audio.mp3",
@@ -1811 +2237 @@
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/assets/mozilla-foundation/common_voice_9_0/--/en/train/2/audio/audio.wav",
+ "src": "https://datasets-server.huggingface.co/assets/asapp/slue/--/voxceleb/train/2/audio/audio.wav",
@@ -1815,8 +2241,5 @@
- "sentence": "Tower of strength",
- "up_votes": 2,
- "down_votes": 0,
- "age": "",
- "gender": "",
- "accent": "",
- "locale": "en",
- "segment": ""
+ "speaker_id": "id10059",
+ "normalized_text": "from my own culture things changed i i think about it a lot i value our",
+ "sentiment": "Neutral",
+ "start_second": 0,
+ "end_second": 5.67
@@ -1834 +2257,10 @@
- "description": "If the external authentication step on the Hugging Face Hub failed, and no authentication mechanism has been provided. Retry with authentication.",
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/DatasetConfigSplit404"
+ },
+ "422": {
+ "$ref": "#/components/responses/DatasetConfigSplit422"
+ },
+ "500": {
+ "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
@@ -1843 +2275 @@
- "$ref": "#/components/headers/X-Error-Code-first-rows-401"
+ "$ref": "#/components/headers/X-Error-Code-500-first-rows"
@@ -1852,2 +2284,3 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist.",
+ "error in the dataset itself": {
+ "summary": "An error while processing the dataset prevents the response to be created.",
+ "description": "Try with https://datasets-server.huggingface.co/first-rows?dataset=atomic&config=atomic&split=train",
@@ -1855 +2288,30 @@
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
+ "error": "Cannot load the dataset split (in streaming mode) to extract the first rows.",
+ "cause_exception": "FileNotFoundError",
+ "cause_message": "https://homes.cs.washington.edu/~msap/atomic/data/atomic_data.tgz",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 417, in _info\n await _file_info(\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 837, in _file_info\n r.raise_for_status()\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/aiohttp/client_reqrep.py\", line 1005, in raise_for_status\n raise ClientResponseError(\n",
+ "aiohttp.client_exceptions.ClientResponseError: 404, message='Not Found', url=URL('https://maartensap.com/atomic/data/atomic_data.tgz')\n",
+ "\nThe above exception was the direct cause of the following exception:\n\n",
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/src/worker/utils.py\", line 363, in get_rows_or_raise\n return get_rows(\n",
+ " File \"/src/services/worker/src/worker/utils.py\", line 305, in decorator\n return func(*args, **kwargs)\n",
+ " File \"/src/services/worker/src/worker/utils.py\", line 341, in get_rows\n rows_plus_one = list(itertools.islice(ds, rows_max_number + 1))\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/iterable_dataset.py\", line 981, in __iter__\n for key, example in ex_iterable:\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/iterable_dataset.py\", line 116, in __iter__\n yield from self.generate_examples_fn(**self.kwargs)\n",
+ " File \"/tmp/modules-cache/datasets_modules/datasets/atomic/c0f0ec7d10713c41dfc87f0cf17f936b122d22e19216051217c99134d38f6d7b/atomic.py\", line 123, in _generate_examples\n for path, f in files:\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 866, in __iter__\n yield from self.generator(*self.args, **self.kwargs)\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 917, in _iter_from_urlpath\n with xopen(urlpath, \"rb\", use_auth_token=use_auth_token) as f:\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 498, in xopen\n file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/core.py\", line 134, in open\n return self.__enter__()\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/core.py\", line 102, in __enter__\n f = self.fs.open(self.path, mode=mode)\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/spec.py\", line 1199, in open\n f = self._open(\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 356, in _open\n size = size or self.info(path, **kwargs)[\"size\"]\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/asyn.py\", line 115, in wrapper\n return sync(self.loop, func, *args, **kwargs)\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/asyn.py\", line 100, in sync\n raise return_result\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/asyn.py\", line 55, in _runner\n result[0] = await coro\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 430, in _info\n raise FileNotFoundError(url) from exc\n",
+ "FileNotFoundError: https://homes.cs.washington.edu/~msap/atomic/data/atomic_data.tgz\n"
+ ]
@@ -1858,5 +2320,2 @@
- "gated-dataset": {
- "summary": "The dataset is gated.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
+ "response not ready": {
+ "$ref": "#/components/examples/ResponseNotReadyError"
@@ -1864,5 +2323,12 @@
- "private-dataset": {
- "summary": "The dataset is private.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
@@ -1874,2 +2340,2 @@
- "404": {
- "description": "If the repository to download from cannot be found, or if the config or split does not exist in the dataset. Note that this may be because the dataset doesn't exist, or because it is set to `private` and you do not have access.",
+ "501": {
+ "description": "The server does not implement the feature.",
@@ -1884 +2350 @@
- "$ref": "#/components/headers/X-Error-Code-first-rows-404"
+ "$ref": "#/components/headers/X-Error-Code-501"
@@ -1892,28 +2358 @@
- "examples": {
- "inexistent-dataset": {
- "summary": "The dataset does not exist, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "gated-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "private-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "inexistent-config": {
- "summary": "The config does not exist in the dataset.",
- "value": { "error": "Not found." }
- },
- "inexistent-split": {
- "summary": "The soplit does not exist in the dataset.",
- "value": { "error": "Not found." }
- }
- }
+ "examples": {}
@@ -1921,0 +2361,17 @@
+ }
+ }
+ }
+ },
+ "/rows": {
+ "get": {
+ "summary": "A slice of rows of a split",
+ "description": "The list of rows of a dataset split at a given slice location (offset). Up to 100 rows are returned, use the length parameter to get less.",
+ "externalDocs": {
+ "description": "See rows (Hub docs)",
+ "url": "https://huggingface.co/docs/datasets-server/rows"
+ },
+ "operationId": "listRows",
+ "security": [
+ {},
+ {
+ "HuggingFaceCookie": []
@@ -1923,2 +2379,55 @@
- "422": {
- "description": "Some of the `dataset`, `config`, or `split` parameters have not been provided or are invalid.",
+ {
+ "HuggingFaceToken": []
+ }
+ ],
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/RequiredDataset"
+ },
+ {
+ "$ref": "#/components/parameters/RequiredConfig"
+ },
+ {
+ "$ref": "#/components/parameters/RequiredSplit"
+ },
+ {
+ "name": "offset",
+ "in": "query",
+ "description": "The offset of the slice.",
+ "schema": {
+ "type": "integer",
+ "default": 0,
+ "minimum": 0
+ },
+ "examples": {
+ "0": {
+ "summary": "from the beginning",
+ "value": 0
+ },
+ "100": {
+ "summary": "from the row at index 100",
+ "value": 100
+ }
+ }
+ },
+ {
+ "name": "length",
+ "in": "query",
+ "description": "The length of the slice",
+ "schema": {
+ "type": "integer",
+ "default": 100,
+ "minimum": 0,
+ "maximum": 100
+ },
+ "examples": {
+ "100": {
+ "summary": "a slice of 100 rows",
+ "value": 100
+ }
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The <a href='https://huggingface.co/docs/datasets/about_dataset_features'>features</a>, and the list of rows of the requested slice. Audio and bytes columns are not supported at the moment, and their content will be 'null'.",
@@ -1931,3 +2439,0 @@
- },
- "X-Error-Code": {
- "$ref": "#/components/headers/X-Error-Code-first-rows-422"
@@ -1939 +2445 @@
- "$ref": "#/components/schemas/CustomError"
+ "$ref": "#/components/schemas/PaginatedResponse"
@@ -1942,307 +2448,3 @@
- "missing-dataset": {
- "summary": "The dataset parameter is missing.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- },
- "missing-config": {
- "summary": "The config parameter is missing.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- },
- "missing-split": {
- "summary": "The split parameter is missing.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- },
- "empty-dataset": {
- "summary": "The dataset parameter is empty.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- },
- "empty-config": {
- "summary": "The config parameter is empty.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- },
- "empty-split": {
- "summary": "The split parameter is empty.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- }
- }
- }
- }
- },
- "500": {
- "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
- "headers": {
- "Cache-Control": {
- "$ref": "#/components/headers/Cache-Control"
- },
- "Access-Control-Allow-Origin": {
- "$ref": "#/components/headers/Access-Control-Allow-Origin"
- },
- "X-Error-Code": {
- "$ref": "#/components/headers/X-Error-Code-first-rows-500"
- }
- },
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/CustomError"
- },
- "examples": {
- "NonMatchingCheckError": {
- "summary": "NonMatchingCheckError",
- "value": {
- "error": "Cannot load the dataset split (in normal download mode) to extract the first rows.",
- "cause_exception": "NonMatchingChecksumError",
- "cause_message": "Checksums didn't match for dataset source files:\n['https://gitlab.com/bigirqu/ArCOV-19/-/archive/master/ArCOV-19-master.zip']",
- "cause_traceback": [
- "Traceback (most recent call last):\n",
- " File \"/src/services/worker/src/worker/responses/first_rows.py\", line 345, in get_first_rows_response\n rows = get_rows(\n",
- " File \"/src/services/worker/src/worker/utils.py\", line 123, in decorator\n return func(*args, **kwargs)\n",
- " File \"/src/services/worker/src/worker/responses/first_rows.py\", line 80, in get_rows\n rows_plus_one = list(itertools.islice(dataset, rows_max_number + 1))\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/iterable_dataset.py\", line 718, in __iter__\n for key, example in self._iter():\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/iterable_dataset.py\", line 708, in _iter\n yield from ex_iterable\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/iterable_dataset.py\", line 112, in __iter__\n yield from self.generate_examples_fn(**self.kwargs)\n",
- " File \"/root/.cache/huggingface/modules/datasets_modules/datasets/ar_cov19/818d9b774f4b70542b6807e6ddb6db32c916aafeba4fbdcd228ec79d21edaeab/ar_cov19.py\", line 131, in _generate_examples\n for fname in sorted(glob.glob(os.path.join(data_dir, \"ArCOV-19-master/dataset/all_tweets/2020-*\"))):\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/streaming.py\", line 67, in wrapper\n return function(*args, token=token, **kwargs)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 522, in xglob\n fs, *_ = fsspec.get_fs_token_paths(urlpath, storage_options=storage_options)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/core.py\", line 632, in get_fs_token_paths\n fs = filesystem(protocol, **inkwargs)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/registry.py\", line 262, in filesystem\n return cls(**storage_options)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/spec.py\", line 76, in __call__\n obj = super().__call__(*args, **kwargs)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/zip.py\", line 58, in __init__\n self.zip = zipfile.ZipFile(self.fo)\n",
- " File \"/usr/local/lib/python3.9/zipfile.py\", line 1257, in __init__\n self._RealGetContents()\n",
- " File \"/usr/local/lib/python3.9/zipfile.py\", line 1320, in _RealGetContents\n endrec = _EndRecData(fp)\n",
- " File \"/usr/local/lib/python3.9/zipfile.py\", line 263, in _EndRecData\n fpin.seek(0, 2)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 684, in seek\n raise ValueError(\"Cannot seek streaming HTTP file\")\n",
- "ValueError: Cannot seek streaming HTTP file\n",
- "\nDuring handling of the above exception, another exception occurred:\n\n",
- "Traceback (most recent call last):\n",
- " File \"/src/services/worker/src/worker/responses/first_rows.py\", line 355, in get_first_rows_response\n rows = get_rows(\n",
- " File \"/src/services/worker/src/worker/utils.py\", line 123, in decorator\n return func(*args, **kwargs)\n",
- " File \"/src/services/worker/src/worker/responses/first_rows.py\", line 68, in get_rows\n dataset = load_dataset(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/load.py\", line 1746, in load_dataset\n builder_instance.download_and_prepare(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py\", line 704, in download_and_prepare\n self._download_and_prepare(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py\", line 1227, in _download_and_prepare\n super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py\", line 775, in _download_and_prepare\n verify_checksums(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/utils/info_utils.py\", line 40, in verify_checksums\n raise NonMatchingChecksumError(error_msg + str(bad_urls))\n",
- "datasets.utils.info_utils.NonMatchingChecksumError: Checksums didn't match for dataset source files:\n['https://gitlab.com/bigirqu/ArCOV-19/-/archive/master/ArCOV-19-master.zip']\n"
- ]
- }
- },
- "FileNotFoundError": {
- "summary": "FileNotFoundError",
- "value": {
- "error": "Cannot load the dataset split (in normal download mode) to extract the first rows.",
- "cause_exception": "FileNotFoundError",
- "cause_message": "Couldn't find file at https://homes.cs.washington.edu/~msap/atomic/data/atomic_data.tgz",
- "cause_traceback": [
- "Traceback (most recent call last):\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 391, in _info\n await _file_info(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 772, in _file_info\n r.raise_for_status()\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/aiohttp/client_reqrep.py\", line 1004, in raise_for_status\n raise ClientResponseError(\n",
- "aiohttp.client_exceptions.ClientResponseError: 404, message='Not Found', url=URL('https://homes.cs.washington.edu/~msap/atomic/data/atomic_data.tgz')\n",
- "\nThe above exception was the direct cause of the following exception:\n\n",
- "Traceback (most recent call last):\n",
- " File \"/src/services/worker/src/worker/responses/first_rows.py\", line 345, in get_first_rows_response\n rows = get_rows(\n",
- " File \"/src/services/worker/src/worker/utils.py\", line 123, in decorator\n return func(*args, **kwargs)\n",
- " File \"/src/services/worker/src/worker/responses/first_rows.py\", line 80, in get_rows\n rows_plus_one = list(itertools.islice(dataset, rows_max_number + 1))\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/iterable_dataset.py\", line 718, in __iter__\n for key, example in self._iter():\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/iterable_dataset.py\", line 708, in _iter\n yield from ex_iterable\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/iterable_dataset.py\", line 112, in __iter__\n yield from self.generate_examples_fn(**self.kwargs)\n",
- " File \"/root/.cache/huggingface/modules/datasets_modules/datasets/atomic/c0f0ec7d10713c41dfc87f0cf17f936b122d22e19216051217c99134d38f6d7b/atomic.py\", line 123, in _generate_examples\n for path, f in files:\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 760, in __iter__\n yield from self.generator(*self.args, **self.kwargs)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 787, in _iter_from_urlpath\n with xopen(urlpath, \"rb\", token=token) as f:\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 453, in xopen\n file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/core.py\", line 141, in open\n out = self.__enter__()\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/core.py\", line 104, in __enter__\n f = self.fs.open(self.path, mode=mode)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/spec.py\", line 1037, in open\n f = self._open(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 340, in _open\n size = size or self.info(path, **kwargs)[\"size\"]\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/asyn.py\", line 86, in wrapper\n return sync(self.loop, func, *args, **kwargs)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/asyn.py\", line 66, in sync\n raise return_result\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/asyn.py\", line 26, in _runner\n result[0] = await coro\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/fsspec/implementations/http.py\", line 404, in _info\n raise FileNotFoundError(url) from exc\n",
- "FileNotFoundError: https://homes.cs.washington.edu/~msap/atomic/data/atomic_data.tgz\n",
- "\nDuring handling of the above exception, another exception occurred:\n\n",
- "Traceback (most recent call last):\n",
- " File \"/src/services/worker/src/worker/responses/first_rows.py\", line 355, in get_first_rows_response\n rows = get_rows(\n",
- " File \"/src/services/worker/src/worker/utils.py\", line 123, in decorator\n return func(*args, **kwargs)\n",
- " File \"/src/services/worker/src/worker/responses/first_rows.py\", line 68, in get_rows\n dataset = load_dataset(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/load.py\", line 1746, in load_dataset\n builder_instance.download_and_prepare(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py\", line 704, in download_and_prepare\n self._download_and_prepare(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py\", line 1227, in _download_and_prepare\n super()._download_and_prepare(dl_manager, verify_infos, check_duplicate_keys=verify_infos)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py\", line 771, in _download_and_prepare\n split_generators = self._split_generators(dl_manager, **split_generators_kwargs)\n",
- " File \"/root/.cache/huggingface/modules/datasets_modules/datasets/atomic/c0f0ec7d10713c41dfc87f0cf17f936b122d22e19216051217c99134d38f6d7b/atomic.py\", line 95, in _split_generators\n archive = dl_manager.download(my_urls)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/download_manager.py\", line 309, in download\n downloaded_path_or_paths = map_nested(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/utils/py_utils.py\", line 385, in map_nested\n return function(data_struct)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/download_manager.py\", line 335, in _download\n return cached_path(url_or_filename, download_config=download_config)\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/utils/file_utils.py\", line 185, in cached_path\n output_path = get_from_cache(\n",
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/utils/file_utils.py\", line 530, in get_from_cache\n raise FileNotFoundError(f\"Couldn't find file at {url}\")\n",
- "FileNotFoundError: Couldn't find file at https://homes.cs.washington.edu/~msap/atomic/data/atomic_data.tgz\n"
- ]
- }
- },
- "not-ready": {
- "summary": "the response is not ready yet.",
- "value": {
- "error": "The list of the first rows is not ready yet. Please retry later."
- }
- },
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Unexpected error."
- }
- }
- }
- },
- "text/plain": {
- "schema": {
- "$ref": "#/components/schemas/ServerErrorResponse"
- },
- "examples": {
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Internal Server Error"
- }
- }
- }
- }
- }
- }
- }
- }
- },
- "/rows": {
- "get": {
- "summary": "A slice of rows of a split",
- "description": "The list of rows of a dataset split at a given slice location (offset).",
- "externalDocs": {
- "description": "See rows (Hub docs)",
- "url": "https://huggingface.co/docs/datasets-server/rows"
- },
- "operationId": "listRows",
- "security": [
- {},
- {
- "HuggingFaceCookie": []
- },
- {
- "HuggingFaceToken": []
- }
- ],
- "parameters": [
- {
- "name": "dataset",
- "in": "query",
- "description": "The identifier of the dataset on the Hub.",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "glue": { "summary": "a canonical dataset", "value": "glue" },
- "Helsinki-NLP/tatoeba_mt": {
- "summary": "a namespaced dataset",
- "value": "Helsinki-NLP/tatoeba_mt"
- }
- }
- },
- {
- "name": "config",
- "in": "query",
- "description": "The dataset configuration (or subset).",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "cola": {
- "summary": "a subset of the glue dataset",
- "value": "cola"
- },
- "yangdong/ecqa": {
- "summary": "the default configuration given by the 🤗 Datasets library",
- "value": "yangdong--ecqa"
- }
- }
- },
- {
- "name": "split",
- "in": "query",
- "description": "The split name.",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "train": {
- "summary": "train split",
- "value": "train"
- },
- "test": {
- "summary": "test split",
- "value": "test"
- },
- "validation": {
- "summary": "validation split",
- "value": "validation"
- }
- }
- },
- {
- "name": "offset",
- "in": "query",
- "description": "The offset of the slice.",
- "default": 0,
- "minimum": 0,
- "schema": { "type": "integer" },
- "examples": {
- "0": {
- "summary": "from the beginning",
- "value": 0
- },
- "100": {
- "summary": "from the row at index 100",
- "value": 100
- }
- }
- },
- {
- "name": "length",
- "in": "query",
- "description": "The length of the slice",
- "default": 100,
- "minimum": 0,
- "maximum": 100,
- "schema": { "type": "integer" },
- "examples": {
- "100": {
- "summary": "a slice of 100 rows",
- "value": 100
- }
- }
- }
- ],
- "responses": {
- "200": {
- "description": "The <a href='https://huggingface.co/docs/datasets/about_dataset_features'>features</a>, and the list of rows of the requested slice.",
- "headers": {
- "Cache-Control": {
- "$ref": "#/components/headers/Cache-Control"
- },
- "Access-Control-Allow-Origin": {
- "$ref": "#/components/headers/Access-Control-Allow-Origin"
- }
- },
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/RowsResponse"
- },
- "examples": {
- "imdb": {
- "summary": "text, and label column (only 4 rows are shown for brevity)",
+ "A slice of a simple dataset (imdb)": {
+ "summary": "Get a slice of length 3 from row 234 (offset=234&length=3).",
+ "description": "Try with https://datasets-server.huggingface.co/rows?dataset=imdb&config=plain_text&split=train&offset=234&length=3.",
@@ -2254,4 +2456 @@
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
+ "type": { "dtype": "string", "_type": "Value" }
@@ -2263 +2461,0 @@
- "num_classes": 2,
@@ -2271,9 +2469 @@
- "row_idx": 0,
- "row": {
- "text": "I rented I AM CURIOUS-YELLOW from my video store because of all the controversy that surrounded it when it was first released in 1967. I also heard that at first it was seized by U.S. customs if it ever tried to enter this country, therefore being a fan of films considered \"controversial\" I really had to see this for myself.<br /><br />The plot is centered around a young Swedish drama student named Lena who wants to learn everything she can about life. In particular she wants to focus her attentions to making some sort of documentary on what the average Swede thought about certain political issues such as the Vietnam War and race issues in the United States. In between asking politicians and ordinary denizens of Stockholm about their opinions on politics, she has sex with her drama teacher, classmates, and married men.<br /><br />What kills me about I AM CURIOUS-YELLOW is that 40 years ago, this was considered pornographic. Really, the sex and nudity scenes are few and far between, even then it's not shot like some cheaply made porno. While my countrymen mind find it shocking, in reality sex and nudity are a major staple in Swedish cinema. Even Ingmar Bergman, arguably their answer to good old boy John Ford, had sex scenes in his films.<br /><br />I do commend the filmmakers for the fact that any sex shown in the film is shown for artistic purposes rather than just to shock people and make money to be shown in pornographic theaters in America. I AM CURIOUS-YELLOW is a good film for anyone wanting to study the meat and potatoes (no pun intended) of Swedish cinema. But really, this film doesn't have much of a plot.",
- "label": 0
- },
- "truncated_cells": []
- },
- {
- "row_idx": 1,
+ "row_idx": 234,
@@ -2281 +2471 @@
- "text": "\"I Am Curious: Yellow\" is a risible and pretentious steaming pile. It doesn't matter what one's political views are because this film can hardly be taken seriously on any level. As for the claim that frontal male nudity is an automatic NC-17, that isn't true. I've seen R-rated films with male nudity. Granted, they only offer some fleeting views, but where are the R-rated films with gaping vulvas and flapping labia? Nowhere, because they don't exist. The same goes for those crappy cable shows: schlongs swinging in the breeze but not a clitoris in sight. And those pretentious indie movies like The Brown Bunny, in which we're treated to the site of Vincent Gallo's throbbing johnson, but not a trace of pink visible on Chloe Sevigny. Before crying (or implying) \"double-standard\" in matters of nudity, the mentally obtuse should take into account one unavoidably obvious anatomical difference between men and women: there are no genitals on display when actresses appears nude, and the same cannot be said for a man. In fact, you generally won't see female genitals in an American film in anything short of porn or explicit erotica. This alleged double-standard is less a double standard than an admittedly depressing ability to come to terms culturally with the insides of women's bodies.",
+ "text": "Well, you know the rest! This has to be the worst movie I've seen in a long long time. I can only imagine that Stephanie Beaham had some bills to pay when taking on this role.<br /><br />The lead role is played by (to me) a complete unknown and I would imagine disappeared right back into obscurity right after this turkey.<br /><br />Bruce Lee led the martial arts charge in the early 70's and since then fight scenes have to be either martial arts based or at least brutal if using street fighting techniques. This movie uses fast cuts to show off the martial arts, however, even this can't disguise the fact that the lady doesn't know how to throw a punch. An average 8 year old boy would take her apart on this showing.<br /><br />Sorry, the only mystery on show here is how this didn't win the golden raspberry for its year.",
@@ -2287 +2477 @@
- "row_idx": 2,
+ "row_idx": 235,
@@ -2289 +2479 @@
- "text": "If only to avoid making this type of film in the future. This film is interesting as an experiment but tells no cogent story.<br /><br />One might feel virtuous for sitting thru it because it touches on so many IMPORTANT issues but it does so without any discernable motive. The viewer comes away with no new perspectives (unless one comes up with one while one's mind wanders, as it will invariably do during this pointless film).<br /><br />One might better spend one's time staring out a window at a tree growing.<br /><br />",
+ "text": "I'm in Iraq right now doing a job that gives plenty of time for watching movies. We also have access to plenty of pirated movies, this gem came along with 11 other movies, and this is easily the worst I've seen in a long time. I've seen a few other reviews that claim this movie doesn't take itself too seriously, but really, I think that's a cover up for the fact that its horrible. It's not tongue in cheek, the writers really thought they were improving on the movie Blade. This movie is just one notch above Vampire Assassin, which if you haven't seen, i recommend. At least that movie is so unbelievably bad that you'll laugh harder than you thought possible. This is right at that cusp of no redeeming qualities what so ever. from the bad acting, to cliché visual (ie opening credits), to the adobe premier special effects. they couldn't even get blanks for the guns, which may have to do with where the movie was filmed, but if you're going to use effects, make them close to accurate. as for the cast, it seems like they just went to a tae bo class and picked up the first not to ugly chick that walked out. Once again, like Ron Hall in Vampire Assassin, don't let stunt folk act, they can't. Also, the comment about this being a \"return of old vampire movies\"...no, it's not. This is exactly what all new vampire movies are about. Buffy the Vampire Slayer, Blade, Underworld, they're all about some super star fighting the vampires. This is the newest vampire genre, with bad blood, fake screams, and cheesy over acting. obviously anyone who wrote a good review about this is somehow connected to the movie, or friends of the cast. But what do I care, I paid 33 cents for it. Anyway, to wrap this up, someone in their first semester of film school decided to make a movie, I give them credit because it's better than I could do. Of course I also know I can't make movies so I don't try. I do know how to watch movies though. I work 12 hour nights, 6 days a week, I've seen several thousand in the year I've been out here and this was so bad that half way through i was hoping for a mortar attack.",
@@ -2295 +2485 @@
- "row_idx": 3,
+ "row_idx": 236,
@@ -2297 +2487 @@
- "text": "This film was probably inspired by Godard's Masculin, féminin and I urge you to see that film instead.<br /><br />The film has two strong elements and those are, (1) the realistic acting (2) the impressive, undeservedly good, photo. Apart from that, what strikes me most is the endless stream of silliness. Lena Nyman has to be most annoying actress in the world. She acts so stupid and with all the nudity in this film,...it's unattractive. Comparing to Godard's film, intellectuality has been replaced with stupidity. Without going too far on this subject, I would say that follows from the difference in ideals between the French and the Swedish society.<br /><br />A movie of its time, and place. 2/10.",
+ "text": "\"Valentine\" is another horror movie to add to the stalk and slash movie list (think \"Halloween\", \"Friday the 13th\", \"Scream\", and \"I Know What You Did Last Summer\"). It certainly isn't as good as those movies that I have listed about, but it's better than most of the ripoffs that came out after the first \"Friday the 13th\" film. One of those films was the 1981 Canadian made \"My Bloody Valentine\", which I hated alot. \"Valentine\" is a better film than that one, but it's not saying much. The plot: a nerdy young boy is teased and pranked by a couple of his classmates at the beginning of the film. Then the film moves years later when those classmates are all grown up, then they're picked off one-by-one. The killer is presumed to be the young boy now all grown up looking for revenge. But is it him? Or could it be somebody else? \"Valentine\" has an attractive cast which includes Denise Richards, David Boreanaz, Marley Shelton, Jessica Capshaw, and Katherine Heigl. They do what they can with the material they've got, but a lackluster script doesn't really do them any justice. There are some scary moments throughout, however. <br /><br />** (out of four)",
@@ -2302 +2492,2 @@
- ]
+ ],
+ "num_total_rows": 25000
@@ -2305,2 +2496,3 @@
- "image": {
- "summary": "a column with images (only 4 rows are shown for brevity)",
+ "A slice of an image dataset (huggan/horse2zebra)": {
+ "summary": "Get a slice of length 3 from row 234 (offset=234&length=3).",
+ "description": "Try with https://datasets-server.huggingface.co/rows?dataset=huggan/horse2zebra&config=huggan--horse2zebra-aligned&split=train&offset=234&length=3.",
@@ -2312,3 +2504 @@
- "type": {
- "_type": "Image"
- }
+ "type": { "_type": "Image" }
@@ -2319,3 +2509 @@
- "type": {
- "_type": "Image"
- }
+ "type": { "_type": "Image" }
@@ -2326,17 +2514 @@
- "row_idx": 0,
- "row": {
- "imageA": {
- "url": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/0/imageA/image.jpg",
- "height": 256,
- "width": 256
- },
- "imageB": {
- "url": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/0/imageB/image.jpg",
- "height": 256,
- "width": 256
- }
- },
- "truncated_cells": []
- },
- {
- "row_idx": 1,
+ "row_idx": 234,
@@ -2345 +2517 @@
- "url": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/1/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/234/imageA/image.jpg",
@@ -2350 +2522 @@
- "url": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/1/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/234/imageB/image.jpg",
@@ -2358 +2530 @@
- "row_idx": 2,
+ "row_idx": 235,
@@ -2361 +2533 @@
- "url": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/2/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/235/imageA/image.jpg",
@@ -2366 +2538 @@
- "url": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/2/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/235/imageB/image.jpg",
@@ -2374 +2546 @@
- "row_idx": 3,
+ "row_idx": 236,
@@ -2377 +2549 @@
- "url": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/3/imageA/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/236/imageA/image.jpg",
@@ -2382 +2554 @@
- "url": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/3/imageB/image.jpg",
+ "src": "https://datasets-server.huggingface.co/cached-assets/huggan/horse2zebra/--/huggan--horse2zebra-aligned/train/236/imageB/image.jpg",
@@ -2389 +2561,2 @@
- ]
+ ],
+ "num_total_rows": 1334
@@ -2392,2 +2565,3 @@
- "audio": {
- "summary": "a column with audio files (only 4 rows are shown for brevity)",
+ "Audio is not supported at the moment (example: asapp/slue)": {
+ "summary": "Get a slice of length 3 from row 234 (offset=234&length=3). The audio column is 'null'",
+ "description": "Try with https://datasets-server.huggingface.co/rows?dataset=asapp/slue&config=voxceleb&split=train&offset=234&length=3.",
@@ -2398,5 +2572,2 @@
- "name": "client_id",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
+ "name": "id",
+ "type": { "dtype": "string", "_type": "Value" }
@@ -2406,5 +2577,2 @@
- "name": "path",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
+ "name": "audio",
+ "type": { "sampling_rate": 16000, "_type": "Audio" }
@@ -2414,5 +2582,2 @@
- "name": "audio",
- "type": {
- "sampling_rate": 48000,
- "_type": "Audio"
- }
+ "name": "speaker_id",
+ "type": { "dtype": "string", "_type": "Value" }
@@ -2422,5 +2587,2 @@
- "name": "sentence",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
+ "name": "normalized_text",
+ "type": { "dtype": "string", "_type": "Value" }
@@ -2430,5 +2592,2 @@
- "name": "up_votes",
- "type": {
- "dtype": "int64",
- "_type": "Value"
- }
+ "name": "sentiment",
+ "type": { "dtype": "string", "_type": "Value" }
@@ -2438,5 +2597,2 @@
- "name": "down_votes",
- "type": {
- "dtype": "int64",
- "_type": "Value"
- }
+ "name": "start_second",
+ "type": { "dtype": "float64", "_type": "Value" }
@@ -2446,14 +2602,5 @@
- "name": "age",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
- },
- {
- "feature_idx": 7,
- "name": "gender",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
- },
+ "name": "end_second",
+ "type": { "dtype": "float64", "_type": "Value" }
+ }
+ ],
+ "rows": [
@@ -2461,6 +2608,11 @@
- "feature_idx": 8,
- "name": "accent",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
+ "row_idx": 234,
+ "row": {
+ "id": "id10080_Xp1eLGN_fHI_00006",
+ "audio": null,
+ "speaker_id": "id10080",
+ "normalized_text": "well i i wasn't boasting to what happened is that i it was it was a few years ago now i hit thirty i thought it's so mad that i don't want to reach into",
+ "sentiment": "Neutral",
+ "start_second": 0.0,
+ "end_second": 8.46
+ },
+ "truncated_cells": []
@@ -2469,6 +2621,11 @@
- "feature_idx": 9,
- "name": "locale",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
+ "row_idx": 235,
+ "row": {
+ "id": "id10080_Xp1eLGN_fHI_00007",
+ "audio": null,
+ "speaker_id": "id10080",
+ "normalized_text": "there's none of there's none of the kind i've had to survive in the world i've done that as a book and and a lot of people",
+ "sentiment": "Neutral",
+ "start_second": 0.0,
+ "end_second": 5.12
+ },
+ "truncated_cells": []
@@ -2477,6 +2634,310 @@
- "feature_idx": 10,
- "name": "segment",
- "type": {
- "dtype": "string",
- "_type": "Value"
- }
+ "row_idx": 236,
+ "row": {
+ "id": "id10080_Xp1eLGN_fHI_00008",
+ "audio": null,
+ "speaker_id": "id10080",
+ "normalized_text": "but what are the things you've learned and and and nobody told me at school stuff like you know how to achieve goals how to thrive when it's difficult how to what sort of",
+ "sentiment": "Neutral",
+ "start_second": 0.0,
+ "end_second": 8.85
+ },
+ "truncated_cells": []
+ }
+ ],
+ "num_total_rows": 5777
+ }
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "description": "If the repository to download from cannot be found, or if the config or split does not exist in the dataset. Note that this may be because the dataset doesn't exist, or because it is set to `private` and you do not have access.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-404"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "inexistent dataset, while authenticated": {
+ "$ref": "#/components/examples/InexistentDatasetError"
+ },
+ "private dataset, while authenticated and authorized": {
+ "$ref": "#/components/examples/AuthorizedPrivateDatasetError"
+ },
+ "gated dataset, and not authenticated or authorized": {
+ "$ref": "#/components/examples/UnauthorizedGatedDatasetError"
+ },
+ "inexistent config": {
+ "$ref": "#/components/examples/InexistentConfigError"
+ },
+ "inexistent split": {
+ "$ref": "#/components/examples/InexistentSplitError"
+ },
+ "error in the dataset itself": {
+ "summary": "An error while processing the dataset prevents the response to be created.",
+ "description": "Try with https://datasets-server.huggingface.co/rows?dataset=atomic&config=atomic&split=train. It's a bug, it should be a 500 error, see https://github.com/huggingface/datasets-server/issues/1661.",
+ "value": { "error": "Not found." }
+ }
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Some of the `dataset`, `config`, `split`, `offset` or `length` parameters have not been provided or are invalid.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-422"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "missing-dataset": {
+ "summary": "The dataset parameter is missing.",
+ "value": {
+ "error": "Parameters 'split', 'config' and 'dataset' are required"
+ }
+ },
+ "missing-config": {
+ "summary": "The config parameter is missing.",
+ "value": {
+ "error": "Parameters 'split', 'config' and 'dataset' are required"
+ }
+ },
+ "missing-split": {
+ "summary": "The split parameter is missing.",
+ "value": {
+ "error": "Parameters 'split', 'config' and 'dataset' are required"
+ }
+ },
+ "empty-dataset": {
+ "summary": "The dataset parameter is empty.",
+ "value": {
+ "error": "Parameters 'split', 'config' and 'dataset' are required"
+ }
+ },
+ "empty-config": {
+ "summary": "The config parameter is empty.",
+ "value": {
+ "error": "Parameters 'split', 'config' and 'dataset' are required"
+ }
+ },
+ "empty-split": {
+ "summary": "The split parameter is empty.",
+ "value": {
+ "error": "Parameters 'split', 'config' and 'dataset' are required"
+ }
+ },
+ "negative-offset": {
+ "summary": "The offset must be positive.",
+ "value": {
+ "error": "Offset must be positive"
+ }
+ },
+ "negative-length": {
+ "summary": "The length must be positive.",
+ "value": {
+ "error": "Length must be positive"
+ }
+ }
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "The server crashed, or the response couldn't be generated successfully due to an error in the dataset itself. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-500-rows"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
+ }
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "The server does not implement the feature.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-501"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {}
+ }
+ }
+ }
+ }
+ }
+ },
+ "/search": {
+ "get": {
+ "summary": "Full-text search in the text columns of a split",
+ "description": "Returns the rows matching the query, ordered by row index. Up to 100 rows are returned. The offset and length parameters allow to navigate the results.",
+ "externalDocs": {
+ "description": "See search (Hub docs). The doc is still missing for the endpoint, see https://github.com/huggingface/datasets-server/issues/1663.",
+ "url": "https://huggingface.co/docs/datasets-server/"
+ },
+ "operationId": "searchRows",
+ "security": [
+ {},
+ {
+ "HuggingFaceCookie": []
+ },
+ {
+ "HuggingFaceToken": []
+ }
+ ],
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/RequiredDataset"
+ },
+ {
+ "$ref": "#/components/parameters/RequiredConfig"
+ },
+ {
+ "$ref": "#/components/parameters/RequiredSplit"
+ },
+ {
+ "name": "query",
+ "in": "query",
+ "description": "The search query.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "examples": {
+ "dog": {
+ "summary": "search the rows that contain the text 'dog'",
+ "value": "dog"
+ }
+ }
+ },
+ {
+ "name": "offset",
+ "in": "query",
+ "description": "The offset of the returned rows.",
+ "schema": {
+ "type": "integer",
+ "default": 0,
+ "minimum": 0
+ },
+ "examples": {
+ "0": {
+ "summary": "from the beginning",
+ "value": 0
+ },
+ "100": {
+ "summary": "ignore the first 100 results",
+ "value": 100
+ }
+ }
+ },
+ {
+ "name": "length",
+ "in": "query",
+ "description": "The maximum number of returned rows",
+ "schema": {
+ "type": "integer",
+ "default": 100,
+ "minimum": 0,
+ "maximum": 100
+ },
+ "examples": {
+ "100": {
+ "summary": "up to 100 rows in the response",
+ "value": 100
+ }
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The <a href='https://huggingface.co/docs/datasets/about_dataset_features'>features</a>, and the list of rows that match the search query. The query will only be searched among the string columns. Audio and bytes columns are not supported at the moment, and their content will be 'null'.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaginatedResponse"
+ },
+ "examples": {
+ "A slice of a simple dataset (imdb)": {
+ "summary": "The first 3 rows that match the 'dog' search query (query=dog&length=3).",
+ "description": "Try with https://datasets-server.huggingface.co/search?dataset=imdb&config=plain_text&split=train&query=dog&length=3.",
+ "value": {
+ "features": [
+ {
+ "feature_idx": 0,
+ "name": "text",
+ "type": { "dtype": "string", "_type": "Value" }
+ },
+ {
+ "feature_idx": 1,
+ "name": "label",
+ "type": { "dtype": "int64", "_type": "Value" }
@@ -2487,24 +2948,377 @@
- "row_idx": 0,
- "row": {
- "client_id": "04960d53cc851eeb6d93f21a09e09ab36fe16943acb226ced1211d7250ab2f1b9a1d655c1cc03d50006e396010851ad52d4c53f49dd77b080b01c4230704c68d",
- "path": null,
- "audio": [
- {
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/cached-assets/mozilla-foundation/common_voice_9_0/--/en/train/0/audio/audio.mp3",
- "type": "audio/mpeg"
- },
- {
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/cached-assets/mozilla-foundation/common_voice_9_0/--/en/train/0/audio/audio.wav",
- "type": "audio/wav"
- }
- ],
- "sentence": "Why does Melissandre look like she wants to consume Jon Snow on the ride up the wall?",
- "up_votes": 2,
- "down_votes": 0,
- "age": "fourties",
- "gender": "male",
- "accent": "United States English",
- "locale": "en",
- "segment": ""
- },
- "truncated_cells": []
+ "row_idx": 27,
+ "row": {
+ "text": "Pedantic, overlong fabrication which attempts to chronicle the birth of the Federal Bureau of Investigations. Begins quite promisingly, with a still-relevant probe into an airplane explosion, however the melodrama involving James Stewart and wife Vera Miles just gets in the way (Miles had a habit of playing tepid wives under duress, and her frayed nerves arrive here right on schedule). Esteemed director Mervyn LeRoy helmed this adaptation of Don Whitehead's book, but despite the talent involved, the picture fails to make much of an impression. Best performance is turned in by Murray Hamilton as Stewart's partner, however most of the dialogue is ludicrous and the dogged pacing causes the movie to seem twice as long as it is. *1/2 from ****",
+ "label": 0
+ },
+ "truncated_cells": []
+ },
+ {
+ "row_idx": 51,
+ "row": {
+ "text": "The opening shot was the best thing about this movie, because it gave you hope that you would be seeing a passionate, well-crafted independent film. Damn that opening shot for filling me hope. As the \"film\" progressed in a slow, plodding manner, my thoughts were varied in relation to this \"film\": Was there too much butter in my popcorn? Did the actors have to PAY the director to be in this \"film\"? Did I get my ticket validated at the Box Office? Yes, dear reader. I saw this film in the Theatre! This would be the only exception I will make about seeing a film at home over a Movie Theatre, because at home you can TURN IT OFF. Were there any redeeming values? Peter Lemongelli as the standard college \"nerd\" had his moments, especially in a dog collar. Other than that this \"film\" went from trying to be a comedy, to a family drama to a spiritual uplifter. It succeeded on none of these fronts. Oh, and the girlfriend was realllllllllly bad. Her performance was the only comedy I found.",
+ "label": 0
+ },
+ "truncated_cells": []
+ },
+ {
+ "row_idx": 106,
+ "row": {
+ "text": "I saw this movie at the AFI Dallas festival. Most of the audience, including my wife, enjoyed this comedy-drama, but I didn't. It stars Lucas Haas (Brick, Alpha Dog), Molly Parker (Kissed, The Five Senses, Hollywoodland) and Adam Scott (First Snow, Art School Confidential). The director is Matt Bissonnette, who's married to Molly Parker. All three actors do a fine job in this movie about 3 friends, the marriage of two of them and infidelity involving the third. It all takes place at a lake house and it looks wonderful. The film wants to treat its subject as a comedy first and then a drama, and I thought it needed to be the other way around.",
+ "label": 0
+ },
+ "truncated_cells": []
+ }
+ ],
+ "num_total_rows": 624
+ }
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/DatasetConfigSplit404"
+ },
+ "422": {
+ "description": "Some of the `dataset`, `config`, `split`, `offset` or `length` parameters have not been provided or are invalid.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-422"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "missing-dataset": {
+ "summary": "The dataset parameter is missing.",
+ "value": {
+ "error": "Parameter 'dataset', 'config', 'split' and 'query' are required"
+ }
+ },
+ "missing-config": {
+ "summary": "The config parameter is missing.",
+ "value": {
+ "error": "Parameter 'dataset', 'config', 'split' and 'query' are required"
+ }
+ },
+ "missing-split": {
+ "summary": "The split parameter is missing.",
+ "value": {
+ "error": "Parameter 'dataset', 'config', 'split' and 'query' are required"
+ }
+ },
+ "missing-query": {
+ "summary": "The query parameter is missing.",
+ "value": {
+ "error": "Parameter 'dataset', 'config', 'split' and 'query' are required"
+ }
+ },
+ "empty-dataset": {
+ "summary": "The dataset parameter is empty.",
+ "value": {
+ "error": "Parameter 'dataset', 'config', 'split' and 'query' are required"
+ }
+ },
+ "empty-config": {
+ "summary": "The config parameter is empty.",
+ "value": {
+ "error": "Parameter 'dataset', 'config', 'split' and 'query' are required"
+ }
+ },
+ "empty-split": {
+ "summary": "The split parameter is empty.",
+ "value": {
+ "error": "Parameter 'dataset', 'config', 'split' and 'query' are required"
+ }
+ },
+ "empty-query": {
+ "summary": "The query parameter is empty.",
+ "value": {
+ "error": "Parameter 'dataset', 'config', 'split' and 'query' are required"
+ }
+ },
+ "negative-offset": {
+ "summary": "The offset must be positive.",
+ "value": {
+ "error": "Offset must be positive"
+ }
+ },
+ "negative-length": {
+ "summary": "The length must be positive.",
+ "value": {
+ "error": "Length must be positive"
+ }
+ }
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-500-search"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "error in the dataset itself": {
+ "summary": "An error while processing the dataset prevents the response to be created.",
+ "description": "Try with https://datasets-server.huggingface.co/search?dataset=atomic&config=atomic&split=train&query=dog",
+ "value": {
+ "error": "Couldn't get the size of external files in `_split_generators` because a request failed:\n404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\nPlease consider moving your data files in this dataset repository instead (e.g. inside a data/ folder).",
+ "cause_exception": "HTTPError",
+ "cause_message": "404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 506, in raise_if_too_big_from_external_data_files\n for i, size in enumerate(pool.imap_unordered(get_size, ext_data_files)):\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 870, in next\n raise value\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 125, in worker\n result = (True, func(*args, **kwds))\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 402, in _request_size\n response.raise_for_status()\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/requests/models.py\", line 1021, in raise_for_status\n raise HTTPError(http_error_msg, response=self)\n",
+ "requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\n"
+ ]
+ }
+ },
+ "response not ready": {
+ "$ref": "#/components/examples/ResponseNotReadyError"
+ },
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
+ }
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "The server does not implement the feature.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-501"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "blocked dataset": {
+ "summary": "The dataset is blocked manually on the server.",
+ "description": "Try with https://datasets-server.huggingface.co/search?dataset=echarlaix/vqa-lxmert&config=vqa&split=validation&query=test",
+ "value": {
+ "error": "The parquet conversion has been disabled for this dataset for now. Please open an issue in https://github.com/huggingface/datasets-server if you want this dataset to be supported."
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/parquet": {
+ "get": {
+ "summary": "List of parquet files",
+ "description": "The dataset is converted to the parquet format. The endpoint gives the list of the parquet files. The same split can have multiple parquet files, called shards. They are sorted by their shard index.",
+ "externalDocs": {
+ "description": "See Parquet (Hub docs)",
+ "url": "https://huggingface.co/docs/datasets-server/parquet"
+ },
+ "operationId": "listParquetFiles",
+ "security": [
+ {},
+ {
+ "HuggingFaceCookie": []
+ },
+ {
+ "HuggingFaceToken": []
+ }
+ ],
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/RequiredDataset"
+ },
+ {
+ "$ref": "#/components/parameters/OptionalConfig"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "A list of parquet files.</br>Beware: the response is not paginated.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ParquetResponse"
+ },
+ "examples": {
+ "duorc": {
+ "summary": "duorc: six parquet files, one per split",
+ "description": "Try with https://datasets-server.huggingface.co/parquet?dataset=duorc",
+ "value": {
+ "parquet_files": [
+ {
+ "dataset": "duorc",
+ "config": "ParaphraseRC",
+ "split": "test",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-test.parquet",
+ "filename": "duorc-test.parquet",
+ "size": 6136591
+ },
+ {
+ "dataset": "duorc",
+ "config": "ParaphraseRC",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-train.parquet",
+ "filename": "duorc-train.parquet",
+ "size": 26005668
+ },
+ {
+ "dataset": "duorc",
+ "config": "ParaphraseRC",
+ "split": "validation",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-validation.parquet",
+ "filename": "duorc-validation.parquet",
+ "size": 5566868
+ },
+ {
+ "dataset": "duorc",
+ "config": "SelfRC",
+ "split": "test",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-test.parquet",
+ "filename": "duorc-test.parquet",
+ "size": 3035736
+ },
+ {
+ "dataset": "duorc",
+ "config": "SelfRC",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-train.parquet",
+ "filename": "duorc-train.parquet",
+ "size": 14851720
+ },
+ {
+ "dataset": "duorc",
+ "config": "SelfRC",
+ "split": "validation",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-validation.parquet",
+ "filename": "duorc-validation.parquet",
+ "size": 3114390
+ }
+ ],
+ "pending": [],
+ "failed": [],
+ "partial": false
+ }
+ },
+ "duorc with ParaphraseRC config": {
+ "summary": "duorc: three parquet files for ParaphraseRC, one per split",
+ "description": "Try with https://datasets-server.huggingface.co/parquet?dataset=duorc&config=ParaphraseRC",
+ "value": {
+ "parquet_files": [
+ {
+ "dataset": "duorc",
+ "config": "ParaphraseRC",
+ "split": "test",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-test.parquet",
+ "filename": "duorc-test.parquet",
+ "size": 6136591
+ },
+ {
+ "dataset": "duorc",
+ "config": "ParaphraseRC",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-train.parquet",
+ "filename": "duorc-train.parquet",
+ "size": 26005668
+ },
+ {
+ "dataset": "duorc",
+ "config": "ParaphraseRC",
+ "split": "validation",
+ "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-validation.parquet",
+ "filename": "duorc-validation.parquet",
+ "size": 5566868
+ }
+ ],
+ "features": {
+ "plot_id": { "dtype": "string", "_type": "Value" },
+ "plot": { "dtype": "string", "_type": "Value" },
+ "title": { "dtype": "string", "_type": "Value" },
+ "question_id": { "dtype": "string", "_type": "Value" },
+ "question": { "dtype": "string", "_type": "Value" },
+ "answers": {
+ "feature": { "dtype": "string", "_type": "Value" },
+ "_type": "Sequence"
+ },
+ "no_answer": { "dtype": "bool", "_type": "Value" }
+ },
+ "partial": false
+ }
+ },
+ "sharded parquet files": {
+ "summary": "alexandrainst/da-wit: the parquet file for the train split is partitioned into 17 shards",
+ "description": "Try with https://datasets-server.huggingface.co/parquet?dataset=alexandrainst/da-wit",
+ "value": {
+ "parquet_files": [
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "test",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-test.parquet",
+ "filename": "parquet-test.parquet",
+ "size": 48684227
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00000-of-00017.parquet",
+ "filename": "parquet-train-00000-of-00017.parquet",
+ "size": 465549291
@@ -2513,24 +3327,6 @@
- "row_idx": 1,
- "row": {
- "client_id": "f9f1f96bae1390dfe61ff298abb90975c079e913c712d57d97307ed797469eac446abb149daaad24cacffcc24e1e3275fefeb97f977eb74ce2233e0e5c1d437e",
- "path": null,
- "audio": [
- {
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/cached-assets/mozilla-foundation/common_voice_9_0/--/en/train/1/audio/audio.mp3",
- "type": "audio/mpeg"
- },
- {
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/cached-assets/mozilla-foundation/common_voice_9_0/--/en/train/1/audio/audio.wav",
- "type": "audio/wav"
- }
- ],
- "sentence": "\"I'm getting them for twelve dollars a night.\"",
- "up_votes": 2,
- "down_votes": 0,
- "age": "",
- "gender": "",
- "accent": "",
- "locale": "en",
- "segment": ""
- },
- "truncated_cells": []
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00001-of-00017.parquet",
+ "filename": "parquet-train-00001-of-00017.parquet",
+ "size": 465701535
@@ -2539,24 +3335,126 @@
- "row_idx": 2,
- "row": {
- "client_id": "a6c7706a220eeea7ee3687c1122fe7ac17962d2449d25b6db37cc41cdaace442683e11945b6f581e73941c3083cd4eecfafc938840459cd8c571dae7774ee687",
- "path": null,
- "audio": [
- {
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/cached-assets/mozilla-foundation/common_voice_9_0/--/en/train/2/audio/audio.mp3",
- "type": "audio/mpeg"
- },
- {
- "src": "https://datasets-server.us.dev.moon.huggingface.tech/cached-assets/mozilla-foundation/common_voice_9_0/--/en/train/2/audio/audio.wav",
- "type": "audio/wav"
- }
- ],
- "sentence": "Tower of strength",
- "up_votes": 2,
- "down_votes": 0,
- "age": "",
- "gender": "",
- "accent": "",
- "locale": "en",
- "segment": ""
- },
- "truncated_cells": []
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00002-of-00017.parquet",
+ "filename": "parquet-train-00002-of-00017.parquet",
+ "size": 463857123
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00003-of-00017.parquet",
+ "filename": "parquet-train-00003-of-00017.parquet",
+ "size": 456197486
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00004-of-00017.parquet",
+ "filename": "parquet-train-00004-of-00017.parquet",
+ "size": 465412051
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00005-of-00017.parquet",
+ "filename": "parquet-train-00005-of-00017.parquet",
+ "size": 469114305
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00006-of-00017.parquet",
+ "filename": "parquet-train-00006-of-00017.parquet",
+ "size": 460338645
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00007-of-00017.parquet",
+ "filename": "parquet-train-00007-of-00017.parquet",
+ "size": 468309376
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00008-of-00017.parquet",
+ "filename": "parquet-train-00008-of-00017.parquet",
+ "size": 490063121
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00009-of-00017.parquet",
+ "filename": "parquet-train-00009-of-00017.parquet",
+ "size": 460462764
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00010-of-00017.parquet",
+ "filename": "parquet-train-00010-of-00017.parquet",
+ "size": 476525998
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00011-of-00017.parquet",
+ "filename": "parquet-train-00011-of-00017.parquet",
+ "size": 470327354
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00012-of-00017.parquet",
+ "filename": "parquet-train-00012-of-00017.parquet",
+ "size": 457138334
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00013-of-00017.parquet",
+ "filename": "parquet-train-00013-of-00017.parquet",
+ "size": 464485292
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00014-of-00017.parquet",
+ "filename": "parquet-train-00014-of-00017.parquet",
+ "size": 466549376
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00015-of-00017.parquet",
+ "filename": "parquet-train-00015-of-00017.parquet",
+ "size": 460452174
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "train",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00016-of-00017.parquet",
+ "filename": "parquet-train-00016-of-00017.parquet",
+ "size": 480583533
+ },
+ {
+ "dataset": "alexandrainst/da-wit",
+ "config": "alexandrainst--danish-wit",
+ "split": "val",
+ "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-val.parquet",
+ "filename": "parquet-val.parquet",
+ "size": 11434278
@@ -2564 +3462,21 @@
- ]
+ ],
+ "pending": [],
+ "failed": [],
+ "partial": false
+ }
+ },
+ "dataset where no parquet file could be created": {
+ "summary": "When the parquet files cannot be created for a configuration, it's listed in 'failed'.",
+ "description": "Try with https://datasets-server.huggingface.co/parquet?dataset=atomic",
+ "value": {
+ "parquet_files": [],
+ "pending": [],
+ "failed": [
+ {
+ "kind": "config-info",
+ "dataset": "atomic",
+ "config": "atomic",
+ "split": null
+ }
+ ],
+ "partial": false
@@ -2572 +3490,111 @@
- "description": "If the external authentication step on the Hugging Face Hub failed, and no authentication mechanism has been provided. Retry with authentication.",
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/DatasetConfig404"
+ },
+ "422": {
+ "$ref": "#/components/responses/Dataset422"
+ },
+ "500": {
+ "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-500-common"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "error in the dataset itself": {
+ "summary": "An error while processing the dataset prevents the response to be created.",
+ "description": "Try with https://datasets-server.huggingface.co/parquet?dataset=atomic&config=atomic",
+ "value": {
+ "error": "Couldn't get the size of external files in `_split_generators` because a request failed:\n404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\nPlease consider moving your data files in this dataset repository instead (e.g. inside a data/ folder).",
+ "cause_exception": "HTTPError",
+ "cause_message": "404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 506, in raise_if_too_big_from_external_data_files\n for i, size in enumerate(pool.imap_unordered(get_size, ext_data_files)):\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 870, in next\n raise value\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 125, in worker\n result = (True, func(*args, **kwds))\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 402, in _request_size\n response.raise_for_status()\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/requests/models.py\", line 1021, in raise_for_status\n raise HTTPError(http_error_msg, response=self)\n",
+ "requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\n"
+ ]
+ }
+ },
+ "response not ready": {
+ "$ref": "#/components/examples/ResponseNotReadyError"
+ },
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
+ }
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "The server does not implement the feature.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ },
+ "X-Error-Code": {
+ "$ref": "#/components/headers/X-Error-Code-501"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomError"
+ },
+ "examples": {
+ "blocked dataset": {
+ "summary": "The dataset is blocked manually on the server.",
+ "description": "Try with https://datasets-server.huggingface.co/parquet?dataset=echarlaix/vqa-lxmert&config=vqa",
+ "value": {
+ "error": "The parquet conversion has been disabled for this dataset for now. Please open an issue in https://github.com/huggingface/datasets-server if you want this dataset to be supported."
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/valid": {
+ "get": {
+ "summary": "Valid datasets",
+ "description": "The lists of the Hub datasets that work without an error, by type. It lists the datasets that have a Dataset Viewer (i.e. have been converted to Parquet format, and can be paginated) and the datasets that only have the Dataset Preview (the first 100 rows).",
+ "externalDocs": {
+ "description": "See Valid datasets (Hub docs)",
+ "url": "https://huggingface.co/docs/datasets-server/valid"
+ },
+ "operationId": "listValidDatasets",
+ "parameters": [],
+ "responses": {
+ "200": {
+ "description": "The valid datasets.",
@@ -2579,3 +3606,0 @@
- },
- "X-Error-Code": {
- "$ref": "#/components/headers/X-Error-Code-rows-401"
@@ -2587 +3612 @@
- "$ref": "#/components/schemas/CustomError"
+ "$ref": "#/components/schemas/ValidResponse"
@@ -2590,14 +3615,3 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
- },
- "gated-dataset": {
- "summary": "The dataset is gated.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
- },
- "private-dataset": {
- "summary": "The dataset is private.",
+ "an example of the response format (only kept the first values in each array for brevity)": {
+ "summary": "list of datasets",
+ "description": "Try with https://datasets-server.huggingface.co/valid",
@@ -2605 +3619,9 @@
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
+ "preview": [
+ "0n1xus/codexglue",
+ "0x7194633/rupile",
+ "AHussain0418/day2_data"
+ ],
+ "viewer": [
+ "0n1xus/pytorrent-standalone",
+ "51la5/keyword-extraction"
+ ]
@@ -2612,2 +3634,2 @@
- "404": {
- "description": "If the repository to download from cannot be found, or if the config or split does not exist in the dataset. Note that this may be because the dataset doesn't exist, or because it is set to `private` and you do not have access.",
+ "500": {
+ "description": "The server crashed.",
@@ -2622 +3644 @@
- "$ref": "#/components/headers/X-Error-Code-rows-404"
+ "$ref": "#/components/headers/X-Error-Code-500-valid"
@@ -2631,25 +3653,12 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "gated-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "private-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "inexistent-config": {
- "summary": "The config does not exist in the dataset.",
- "value": { "error": "Not found." }
- },
- "inexistent-split": {
- "summary": "The soplit does not exist in the dataset.",
- "value": { "error": "Not found." }
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
@@ -2659,0 +3669,17 @@
+ }
+ }
+ }
+ },
+ "/is-valid": {
+ "get": {
+ "summary": "Check if a dataset is valid",
+ "description": "Returns the capabilities of the dataset: show a preview of the 100 first rows, show the viewer for all the rows, search the rows. Use the optional config and split parameters to filter the response.",
+ "externalDocs": {
+ "description": "See Valid datasets (Hub docs)",
+ "url": "https://huggingface.co/docs/datasets-server/valid"
+ },
+ "operationId": "isValidDataset",
+ "security": [
+ {},
+ {
+ "HuggingFaceCookie": []
@@ -2661,2 +3687,18 @@
- "422": {
- "description": "Some of the `dataset`, `config`, `split`, `offset` or `length` parameters have not been provided or are invalid.",
+ {
+ "HuggingFaceToken": []
+ }
+ ],
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/RequiredDataset"
+ },
+ {
+ "$ref": "#/components/parameters/OptionalConfig"
+ },
+ {
+ "$ref": "#/components/parameters/OptionalSplit"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The capabilities of the dataset.",
@@ -2669,3 +3710,0 @@
- },
- "X-Error-Code": {
- "$ref": "#/components/headers/X-Error-Code-rows-422"
@@ -2677 +3716 @@
- "$ref": "#/components/schemas/CustomError"
+ "$ref": "#/components/schemas/IsValidResponse"
@@ -2680,20 +3719,3 @@
- "missing-dataset": {
- "summary": "The dataset parameter is missing.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- },
- "missing-config": {
- "summary": "The config parameter is missing.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- },
- "missing-split": {
- "summary": "The split parameter is missing.",
- "value": {
- "error": "Parameters 'split', 'config' and 'dataset' are required"
- }
- },
- "empty-dataset": {
- "summary": "The dataset parameter is empty.",
+ "all the capabilities": {
+ "summary": "valid dataset",
+ "description": "Try with https://datasets-server.huggingface.co/is-valid?dataset=glue",
@@ -2701 +3723,3 @@
- "error": "Parameters 'split', 'config' and 'dataset' are required"
+ "preview": true,
+ "viewer": true,
+ "search": true
@@ -2704,2 +3728,3 @@
- "empty-config": {
- "summary": "The config parameter is empty.",
+ "only preview": {
+ "summary": "dataset with only preview",
+ "description": "Try with https://datasets-server.huggingface.co/is-valid?dataset=ehartford/dolphin",
@@ -2707 +3732,3 @@
- "error": "Parameters 'split', 'config' and 'dataset' are required"
+ "preview": true,
+ "viewer": false,
+ "search": false
@@ -2710,2 +3737,3 @@
- "empty-split": {
- "summary": "The split parameter is empty.",
+ "no capabilities": {
+ "summary": "dataset with no capabilities",
+ "description": "Try with https://datasets-server.huggingface.co/is-valid?dataset=atomic",
@@ -2713 +3741,3 @@
- "error": "Parameters 'split', 'config' and 'dataset' are required"
+ "preview": false,
+ "viewer": false,
+ "search": false
@@ -2716,2 +3746,3 @@
- "negative-offset": {
- "summary": "The offset must be positive.",
+ "all the capabilities, for a config": {
+ "summary": "valid config",
+ "description": "Try with https://datasets-server.huggingface.co/is-valid?dataset=glue&config=ax",
@@ -2719 +3750,3 @@
- "error": "Offset must be positive"
+ "preview": true,
+ "viewer": true,
+ "search": true
@@ -2722,2 +3755,3 @@
- "negative-length": {
- "summary": "The length must be positive.",
+ "all the capabilities, for a split": {
+ "summary": "valid split",
+ "description": "Try with https://datasets-server.huggingface.co/is-valid?dataset=glue&config=ax&split=test",
@@ -2725 +3759,3 @@
- "error": "Length must be positive"
+ "preview": true,
+ "viewer": true,
+ "search": true
@@ -2731,0 +3768,9 @@
+ "401": {
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/Dataset404"
+ },
+ "422": {
+ "$ref": "#/components/responses/Dataset422"
+ },
@@ -2733 +3778 @@
- "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
+ "description": "The server crashed.",
@@ -2742 +3787 @@
- "$ref": "#/components/headers/X-Error-Code-rows-500"
+ "$ref": "#/components/headers/X-Error-Code-500-is-valid"
@@ -2751,11 +3796,2 @@
- "not-ready": {
- "summary": "the response is not ready yet.",
- "value": {
- "error": "The list of rows is not ready yet. Please retry later."
- }
- },
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Unexpected error."
- }
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
@@ -2770,5 +3806,2 @@
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Internal Server Error"
- }
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
@@ -2783 +3816 @@
- "/parquet": {
+ "/info": {
@@ -2785,2 +3818,2 @@
- "summary": "List of parquet files",
- "description": "The dataset is converted to the parquet format. The endpoint gives the list of the parquet files. The same split can have multiple parquet files, called shards. They are sorted by their shard index.",
+ "summary": "Get the metadata of a dataset.",
+ "description": "Returns the metadata of the dataset: description, homepage, features, etc. Use the optional config parameter to filter the response.",
@@ -2788,2 +3821,2 @@
- "description": "See Parquet (Hub docs)",
- "url": "https://huggingface.co/docs/datasets-server/parquet"
+ "description": "The response is a dump of the DatasetInfo object from the datasets library",
+ "url": "https://huggingface.co/docs/datasets/en/package_reference/main_classes#datasets.DatasetInfo"
@@ -2791 +3824 @@
- "operationId": "listParquetFiles",
+ "operationId": "getInfo",
@@ -2803,12 +3836 @@
- "name": "dataset",
- "in": "query",
- "description": "The identifier of the dataset on the Hub.",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "glue": { "summary": "a canonical dataset", "value": "glue" },
- "Helsinki-NLP/tatoeba_mt": {
- "summary": "a namespaced dataset",
- "value": "Helsinki-NLP/tatoeba_mt"
- }
- }
+ "$ref": "#/components/parameters/RequiredDataset"
@@ -2817,15 +3839 @@
- "name": "config",
- "in": "query",
- "description": "The dataset configuration (or subset).",
- "required": false,
- "schema": { "type": "string" },
- "examples": {
- "cola": {
- "summary": "a subset of the glue dataset",
- "value": "cola"
- },
- "yangdong/ecqa": {
- "summary": "the default configuration given by the 🤗 Datasets library",
- "value": "yangdong--ecqa"
- }
- }
+ "$ref": "#/components/parameters/OptionalConfig"
@@ -2836 +3844 @@
- "description": "A list of parquet files.</br>Beware: the response is not paginated.",
+ "description": "The metadata of the dataset.",
@@ -2838 +3846,3 @@
- "Cache-Control": { "$ref": "#/components/headers/Cache-Control" },
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
@@ -2846 +3856 @@
- "$ref": "#/components/schemas/ParquetFilesResponse"
+ "$ref": "#/components/schemas/InfoResponse"
@@ -2849,60 +3859,3 @@
- "duorc": {
- "summary": "duorc: six parquet files, one per split",
- "value": {
- "parquet_files": [
- {
- "dataset": "duorc",
- "config": "ParaphraseRC",
- "split": "test",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-test.parquet",
- "filename": "duorc-test.parquet",
- "size": 6136590
- },
- {
- "dataset": "duorc",
- "config": "ParaphraseRC",
- "split": "train",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-train.parquet",
- "filename": "duorc-train.parquet",
- "size": 26005667
- },
- {
- "dataset": "duorc",
- "config": "ParaphraseRC",
- "split": "validation",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-validation.parquet",
- "filename": "duorc-validation.parquet",
- "size": 5566867
- },
- {
- "dataset": "duorc",
- "config": "SelfRC",
- "split": "test",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-test.parquet",
- "filename": "duorc-test.parquet",
- "size": 3035735
- },
- {
- "dataset": "duorc",
- "config": "SelfRC",
- "split": "train",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-train.parquet",
- "filename": "duorc-train.parquet",
- "size": 14851719
- },
- {
- "dataset": "duorc",
- "config": "SelfRC",
- "split": "validation",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/SelfRC/duorc-validation.parquet",
- "filename": "duorc-validation.parquet",
- "size": 3114389
- }
- ],
- "pending": [],
- "failed": [],
- "partial": false
- }
- },
- "duorc with ParaphraseRC config": {
- "summary": "duorc: three parquet files for ParaphraseRC, one per split",
+ "dataset metadata": {
+ "summary": "metadata of a dataset. It's an object, with one key per config",
+ "description": "Try with https://datasets-server.huggingface.co/info?dataset=mnist",
@@ -2910,24 +3863,77 @@
- "parquet_files": [
- {
- "dataset": "duorc",
- "config": "ParaphraseRC",
- "split": "test",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-test.parquet",
- "filename": "duorc-test.parquet",
- "size": 6136590
- },
- {
- "dataset": "duorc",
- "config": "ParaphraseRC",
- "split": "train",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-train.parquet",
- "filename": "duorc-train.parquet",
- "size": 26005667
- },
- {
- "dataset": "duorc",
- "config": "ParaphraseRC",
- "split": "validation",
- "url": "https://huggingface.co/datasets/duorc/resolve/refs%2Fconvert%2Fparquet/ParaphraseRC/duorc-validation.parquet",
- "filename": "duorc-validation.parquet",
- "size": 5566867
+ "dataset_info": {
+ "mnist": {
+ "description": "The MNIST dataset consists of 70,000 28x28 black-and-white images in 10 classes (one for each digits), with 7,000\nimages per class. There are 60,000 training images and 10,000 test images.\n",
+ "citation": "@article{lecun2010mnist,\n title={MNIST handwritten digit database},\n author={LeCun, Yann and Cortes, Corinna and Burges, CJ},\n journal={ATT Labs [Online]. Available: http://yann.lecun.com/exdb/mnist},\n volume={2},\n year={2010}\n}\n",
+ "homepage": "http://yann.lecun.com/exdb/mnist/",
+ "license": "",
+ "features": {
+ "image": { "_type": "Image" },
+ "label": {
+ "names": [
+ "0",
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ "6",
+ "7",
+ "8",
+ "9"
+ ],
+ "_type": "ClassLabel"
+ }
+ },
+ "supervised_keys": {
+ "input": "image",
+ "output": "label"
+ },
+ "task_templates": [
+ {
+ "task": "image-classification",
+ "label_column": "label"
+ }
+ ],
+ "builder_name": "mnist",
+ "config_name": "mnist",
+ "version": {
+ "version_str": "1.0.0",
+ "major": 1,
+ "minor": 0,
+ "patch": 0
+ },
+ "splits": {
+ "train": {
+ "name": "train",
+ "num_bytes": 17471100,
+ "num_examples": 60000,
+ "dataset_name": "mnist"
+ },
+ "test": {
+ "name": "test",
+ "num_bytes": 2916482,
+ "num_examples": 10000,
+ "dataset_name": "mnist"
+ }
+ },
+ "download_checksums": {
+ "https://storage.googleapis.com/cvdf-datasets/mnist/train-images-idx3-ubyte.gz": {
+ "num_bytes": 9912422,
+ "checksum": null
+ },
+ "https://storage.googleapis.com/cvdf-datasets/mnist/train-labels-idx1-ubyte.gz": {
+ "num_bytes": 28881,
+ "checksum": null
+ },
+ "https://storage.googleapis.com/cvdf-datasets/mnist/t10k-images-idx3-ubyte.gz": {
+ "num_bytes": 1648877,
+ "checksum": null
+ },
+ "https://storage.googleapis.com/cvdf-datasets/mnist/t10k-labels-idx1-ubyte.gz": {
+ "num_bytes": 4542,
+ "checksum": null
+ }
+ },
+ "download_size": 11594722,
+ "dataset_size": 20387582,
+ "size_in_bytes": 31982304
@@ -2935 +3941 @@
- ],
+ },
@@ -2938,34 +3944 @@
- "partial": false,
- "features": {
- "plot_id": {
- "dtype": "string",
- "_type": "Value"
- },
- "plot": {
- "dtype": "string",
- "_type": "Value"
- },
- "title": {
- "dtype": "string",
- "_type": "Value"
- },
- "question_id": {
- "dtype": "string",
- "_type": "Value"
- },
- "question": {
- "dtype": "string",
- "_type": "Value"
- },
- "answers": {
- "feature": {
- "dtype": "string",
- "_type": "Value"
- },
- "_type": "Sequence"
- },
- "no_answer": {
- "dtype": "bool",
- "_type": "Value"
- }
- }
+ "partial": false
@@ -2974,2 +3947,3 @@
- "sharded": {
- "summary": "alexandrainst/da-wit: the parquet file for the train split is partitioned into 9 shards",
+ "config metadata": {
+ "summary": "metadata for a dataset config",
+ "description": "Try with https://datasets-server.huggingface.co/info?dataset=glue&config=ax",
@@ -2977,120 +3951,13 @@
- "parquet_files": [
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "test",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-test.parquet",
- "filename": "parquet-test.parquet",
- "size": 48684227
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00000-of-00017.parquet",
- "filename": "parquet-train-00000-of-00017.parquet",
- "size": 465549291
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00001-of-00017.parquet",
- "filename": "parquet-train-00001-of-00017.parquet",
- "size": 465701535
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00002-of-00017.parquet",
- "filename": "parquet-train-00002-of-00017.parquet",
- "size": 463857123
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00003-of-00017.parquet",
- "filename": "parquet-train-00003-of-00017.parquet",
- "size": 456197486
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00004-of-00017.parquet",
- "filename": "parquet-train-00004-of-00017.parquet",
- "size": 465412051
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00005-of-00017.parquet",
- "filename": "parquet-train-00005-of-00017.parquet",
- "size": 469114305
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00006-of-00017.parquet",
- "filename": "parquet-train-00006-of-00017.parquet",
- "size": 460338645
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00007-of-00017.parquet",
- "filename": "parquet-train-00007-of-00017.parquet",
- "size": 468309376
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00008-of-00017.parquet",
- "filename": "parquet-train-00008-of-00017.parquet",
- "size": 490063121
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00009-of-00017.parquet",
- "filename": "parquet-train-00009-of-00017.parquet",
- "size": 460462764
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00010-of-00017.parquet",
- "filename": "parquet-train-00010-of-00017.parquet",
- "size": 476525998
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00011-of-00017.parquet",
- "filename": "parquet-train-00011-of-00017.parquet",
- "size": 470327354
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00012-of-00017.parquet",
- "filename": "parquet-train-00012-of-00017.parquet",
- "size": 457138334
- },
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00013-of-00017.parquet",
- "filename": "parquet-train-00013-of-00017.parquet",
- "size": 464485292
+ "dataset_info": {
+ "description": "GLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n\n",
+ "citation": "\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n",
+ "homepage": "https://gluebenchmark.com/diagnostics",
+ "license": "",
+ "features": {
+ "premise": { "dtype": "string", "_type": "Value" },
+ "hypothesis": { "dtype": "string", "_type": "Value" },
+ "label": {
+ "names": ["entailment", "neutral", "contradiction"],
+ "_type": "ClassLabel"
+ },
+ "idx": { "dtype": "int32", "_type": "Value" }
@@ -3098,7 +3965,8 @@
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00014-of-00017.parquet",
- "filename": "parquet-train-00014-of-00017.parquet",
- "size": 466549376
+ "builder_name": "glue",
+ "config_name": "ax",
+ "version": {
+ "version_str": "1.0.0",
+ "description": "",
+ "major": 1,
+ "minor": 0,
+ "patch": 0
@@ -3106,7 +3974,7 @@
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00015-of-00017.parquet",
- "filename": "parquet-train-00015-of-00017.parquet",
- "size": 460452174
+ "splits": {
+ "test": {
+ "name": "test",
+ "num_bytes": 237694,
+ "num_examples": 1104,
+ "dataset_name": "glue"
+ }
@@ -3114,7 +3982,5 @@
- {
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "train",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-train-00016-of-00017.parquet",
- "filename": "parquet-train-00016-of-00017.parquet",
- "size": 480583533
+ "download_checksums": {
+ "https://dl.fbaipublicfiles.com/glue/data/AX.tsv": {
+ "num_bytes": 222257,
+ "checksum": null
+ }
@@ -3121,0 +3988,14 @@
+ "download_size": 222257,
+ "dataset_size": 237694,
+ "size_in_bytes": 459951
+ },
+ "partial": false
+ }
+ },
+ "dataset metadata with failed configs": {
+ "summary": "metadata of a dataset which has failed configs. The failed configs are listed in 'failed'.",
+ "description": "Try with https://datasets-server.huggingface.co/info?dataset=atomic",
+ "value": {
+ "dataset_info": {},
+ "pending": [],
+ "failed": [
@@ -3123,6 +4003,4 @@
- "dataset": "alexandrainst/da-wit",
- "config": "alexandrainst--danish-wit",
- "split": "val",
- "url": "https://huggingface.co/datasets/alexandrainst/da-wit/resolve/refs%2Fconvert%2Fparquet/alexandrainst--danish-wit/parquet-val.parquet",
- "filename": "parquet-val.parquet",
- "size": 11434278
+ "kind": "config-info",
+ "dataset": "atomic",
+ "config": "atomic",
+ "split": null
@@ -3131,2 +4008,0 @@
- "pending": [],
- "failed": [],
@@ -3141 +4017,10 @@
- "description": "If the external authentication step on the Hugging Face Hub failed, and no authentication mechanism has been provided. Retry with authentication.",
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/DatasetConfig404"
+ },
+ "422": {
+ "$ref": "#/components/responses/Dataset422"
+ },
+ "500": {
+ "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
@@ -3150 +4035 @@
- "$ref": "#/components/headers/X-Error-Code-splits-401"
+ "$ref": "#/components/headers/X-Error-Code-500-common"
@@ -3159,2 +4044,3 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist.",
+ "error in the dataset itself": {
+ "summary": "An error while processing the dataset prevents the response to be created.",
+ "description": "Try with https://datasets-server.huggingface.co/info?dataset=atomic&config=atomic",
@@ -3162 +4048,12 @@
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
+ "error": "Couldn't get the size of external files in `_split_generators` because a request failed:\n404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\nPlease consider moving your data files in this dataset repository instead (e.g. inside a data/ folder).",
+ "cause_exception": "HTTPError",
+ "cause_message": "404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 506, in raise_if_too_big_from_external_data_files\n for i, size in enumerate(pool.imap_unordered(get_size, ext_data_files)):\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 870, in next\n raise value\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 125, in worker\n result = (True, func(*args, **kwds))\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 402, in _request_size\n response.raise_for_status()\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/requests/models.py\", line 1021, in raise_for_status\n raise HTTPError(http_error_msg, response=self)\n",
+ "requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\n"
+ ]
@@ -3165,5 +4062,2 @@
- "gated-dataset": {
- "summary": "The dataset is gated.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
+ "response not ready": {
+ "$ref": "#/components/examples/ResponseNotReadyError"
@@ -3171,5 +4065,12 @@
- "private-dataset": {
- "summary": "The dataset is private.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
@@ -3181,2 +4082,2 @@
- "404": {
- "description": "If the repository to download from cannot be found. This may be because it doesn't exist, or because it is set to `private` and you do not have access.",
+ "501": {
+ "description": "The server does not implement the feature.",
@@ -3191 +4092 @@
- "$ref": "#/components/headers/X-Error-Code-splits-404"
+ "$ref": "#/components/headers/X-Error-Code-501"
@@ -3200,8 +4101,3 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "gated-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
+ "blocked dataset": {
+ "summary": "The dataset is blocked manually on the server.",
+ "description": "Try with https://datasets-server.huggingface.co/info?dataset=echarlaix/vqa-lxmert&config=vqa",
@@ -3209,7 +4105 @@
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "private-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
+ "error": "The parquet conversion has been disabled for this dataset for now. Please open an issue in https://github.com/huggingface/datasets-server if you want this dataset to be supported."
@@ -3220,0 +4111,17 @@
+ }
+ }
+ }
+ },
+ "/size": {
+ "get": {
+ "summary": "Get the size of a dataset.",
+ "description": "Returns the size (number of rows, storage) of the dataset. Use the optional config parameter to filter the response.",
+ "externalDocs": {
+ "description": "See size (Hub docs). The doc is still missing for the endpoint, see https://github.com/huggingface/datasets-server/issues/1664.",
+ "url": "https://huggingface.co/docs/datasets-server/"
+ },
+ "operationId": "getSize",
+ "security": [
+ {},
+ {
+ "HuggingFaceCookie": []
@@ -3222,2 +4129,15 @@
- "422": {
- "description": "The `dataset` parameter has not been provided.",
+ {
+ "HuggingFaceToken": []
+ }
+ ],
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/RequiredDataset"
+ },
+ {
+ "$ref": "#/components/parameters/OptionalConfig"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The size of the dataset.",
@@ -3230,3 +4149,0 @@
- },
- "X-Error-Code": {
- "$ref": "#/components/headers/X-Error-Code-splits-422"
@@ -3238 +4155 @@
- "$ref": "#/components/schemas/CustomError"
+ "$ref": "#/components/schemas/SizeResponse"
@@ -3241,3 +4158,77 @@
- "missing-parameter": {
- "summary": "The dataset parameter is missing.",
- "value": { "error": "Parameter 'dataset' is required" }
+ "dataset size": {
+ "summary": "size of a dataset.",
+ "description": "Try with https://datasets-server.huggingface.co/size?dataset=mnist",
+ "value": {
+ "size": {
+ "dataset": {
+ "dataset": "mnist",
+ "num_bytes_original_files": 11594722,
+ "num_bytes_parquet_files": 18157506,
+ "num_bytes_memory": 20387582,
+ "num_rows": 70000
+ },
+ "configs": [
+ {
+ "dataset": "mnist",
+ "config": "mnist",
+ "num_bytes_original_files": 11594722,
+ "num_bytes_parquet_files": 18157506,
+ "num_bytes_memory": 20387582,
+ "num_rows": 70000,
+ "num_columns": 2
+ }
+ ],
+ "splits": [
+ {
+ "dataset": "mnist",
+ "config": "mnist",
+ "split": "train",
+ "num_bytes_parquet_files": 15561616,
+ "num_bytes_memory": 17471100,
+ "num_rows": 60000,
+ "num_columns": 2
+ },
+ {
+ "dataset": "mnist",
+ "config": "mnist",
+ "split": "test",
+ "num_bytes_parquet_files": 2595890,
+ "num_bytes_memory": 2916482,
+ "num_rows": 10000,
+ "num_columns": 2
+ }
+ ]
+ },
+ "pending": [],
+ "failed": [],
+ "partial": false
+ }
+ },
+ "config size": {
+ "summary": "size of a dataset config",
+ "description": "Try with https://datasets-server.huggingface.co/size?dataset=glue&config=ax",
+ "value": {
+ "size": {
+ "config": {
+ "dataset": "glue",
+ "config": "ax",
+ "num_bytes_original_files": 222257,
+ "num_bytes_parquet_files": 80767,
+ "num_bytes_memory": 237694,
+ "num_rows": 1104,
+ "num_columns": 4
+ },
+ "splits": [
+ {
+ "dataset": "glue",
+ "config": "ax",
+ "split": "test",
+ "num_bytes_parquet_files": 80767,
+ "num_bytes_memory": 237694,
+ "num_rows": 1104,
+ "num_columns": 4
+ }
+ ]
+ },
+ "partial": false
+ }
@@ -3245,3 +4236,26 @@
- "empty-parameter": {
- "summary": "The dataset parameter is empty (?dataset=).",
- "value": { "error": "Parameter 'dataset' is required" }
+ "dataset size with failed configs": {
+ "summary": "size of a dataset which has failed configs. The failed configs are listed in 'failed'.",
+ "description": "Try with https://datasets-server.huggingface.co/size?dataset=atomic",
+ "value": {
+ "size": {
+ "dataset": {
+ "dataset": "atomic",
+ "num_bytes_original_files": 0,
+ "num_bytes_parquet_files": 0,
+ "num_bytes_memory": 0,
+ "num_rows": 0
+ },
+ "configs": [],
+ "splits": []
+ },
+ "pending": [],
+ "failed": [
+ {
+ "kind": "config-size",
+ "dataset": "atomic",
+ "config": "atomic",
+ "split": null
+ }
+ ],
+ "partial": false
+ }
@@ -3252,0 +4267,9 @@
+ "401": {
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/DatasetConfig404"
+ },
+ "422": {
+ "$ref": "#/components/responses/Dataset422"
+ },
@@ -3263 +4286 @@
- "$ref": "#/components/headers/X-Error-Code-splits-500"
+ "$ref": "#/components/headers/X-Error-Code-500-common"
@@ -3272,2 +4295,3 @@
- "not-ready": {
- "summary": "the response is not ready yet.",
+ "error in the dataset itself": {
+ "summary": "An error while processing the dataset prevents the response to be created.",
+ "description": "Try with https://datasets-server.huggingface.co/size?dataset=atomic&config=atomic",
@@ -3275 +4299,12 @@
- "error": "The server is busier than usual and the response is not ready yet. Please retry later."
+ "error": "Couldn't get the size of external files in `_split_generators` because a request failed:\n404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\nPlease consider moving your data files in this dataset repository instead (e.g. inside a data/ folder).",
+ "cause_exception": "HTTPError",
+ "cause_message": "404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 506, in raise_if_too_big_from_external_data_files\n for i, size in enumerate(pool.imap_unordered(get_size, ext_data_files)):\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 870, in next\n raise value\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 125, in worker\n result = (True, func(*args, **kwds))\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 402, in _request_size\n response.raise_for_status()\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/requests/models.py\", line 1021, in raise_for_status\n raise HTTPError(http_error_msg, response=self)\n",
+ "requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\n"
+ ]
@@ -3278,5 +4313,5 @@
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Unexpected error."
- }
+ "response not ready": {
+ "$ref": "#/components/examples/ResponseNotReadyError"
+ },
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
@@ -3291,53 +4326,2 @@
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Internal Server Error"
- }
- }
- }
- }
- }
- }
- }
- }
- },
- "/valid": {
- "get": {
- "summary": "Valid datasets",
- "description": "The lists of the Hub datasets that work without an error, by type. It lists the datasets that have a Dataset Viewer (i.e. have been converted to Parquet format, and can be paginated) and the datasets that only have the Dataset Preview (the first 100 rows).",
- "externalDocs": {
- "description": "See Valid datasets (Hub docs)",
- "url": "https://huggingface.co/docs/datasets-server/valid"
- },
- "operationId": "listValidDatasets",
- "parameters": [],
- "responses": {
- "200": {
- "description": "The valid datasets.",
- "headers": {
- "Cache-Control": {
- "$ref": "#/components/headers/Cache-Control"
- },
- "Access-Control-Allow-Origin": {
- "$ref": "#/components/headers/Access-Control-Allow-Origin"
- }
- },
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ValidResponse"
- },
- "examples": {
- "valid": {
- "summary": "list of datasets",
- "value": {
- "preview": [
- "0n1xus/codexglue",
- "0x7194633/rupile",
- "AHussain0418/day2_data"
- ],
- "viewer": [
- "0n1xus/pytorrent-standalone",
- "51la5/keyword-extraction"
- ]
- }
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
@@ -3349,2 +4333,2 @@
- "500": {
- "description": "The server crashed.",
+ "501": {
+ "description": "The server does not implement the feature.",
@@ -3359 +4343 @@
- "$ref": "#/components/headers/X-Error-Code-valid-500"
+ "$ref": "#/components/headers/X-Error-Code-501"
@@ -3368,15 +4352,3 @@
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Unexpected error."
- }
- }
- }
- },
- "text/plain": {
- "schema": {
- "$ref": "#/components/schemas/ServerErrorResponse"
- },
- "examples": {
- "internal": {
- "summary": "internal error",
+ "blocked dataset": {
+ "summary": "The dataset is blocked manually on the server.",
+ "description": "Try with https://datasets-server.huggingface.co/size?dataset=echarlaix/vqa-lxmert&config=vqa",
@@ -3384 +4356 @@
- "error": "Internal Server Error"
+ "error": "The parquet conversion has been disabled for this dataset for now. Please open an issue in https://github.com/huggingface/datasets-server if you want this dataset to be supported."
@@ -3394 +4366 @@
- "/is-valid": {
+ "/opt-in-out-urls": {
@@ -3396,2 +4368,2 @@
- "summary": "Check if a dataset is valid",
- "description": "Check if a dataset works without an error (for /splits and /first-rows).",
+ "summary": "Get the number of opted-in and opted-out image URLs in a dataset.",
+ "description": "Based on the API of spawning.ai, returns the number of image URLs that have been opted-in and opted-out. Use the optional config and splits parameters to filter the response. Only a sample of the rows is scanned, the first 100K rows at the moment.",
@@ -3399,2 +4371,2 @@
- "description": "See Valid datasets (Hub docs)",
- "url": "https://huggingface.co/docs/datasets-server/valid"
+ "description": "See spawning.io (Hub docs). The doc is still missing for the endpoint, see https://github.com/huggingface/datasets-server/issues/1664.",
+ "url": "https://huggingface.co/docs/datasets-server/"
@@ -3402 +4374 @@
- "operationId": "isValidDataset",
+ "operationId": "getOptInOutUrls",
@@ -3414,12 +4386,7 @@
- "name": "dataset",
- "in": "query",
- "description": "The identifier of the dataset on the Hub.",
- "required": true,
- "schema": { "type": "string" },
- "examples": {
- "glue": { "summary": "a canonical dataset", "value": "glue" },
- "Helsinki-NLP/tatoeba_mt": {
- "summary": "a namespaced dataset",
- "value": "Helsinki-NLP/tatoeba_mt"
- }
- }
+ "$ref": "#/components/parameters/RequiredDataset"
+ },
+ {
+ "$ref": "#/components/parameters/OptionalConfig"
+ },
+ {
+ "$ref": "#/components/parameters/OptionalSplit"
@@ -3430 +4397 @@
- "description": "The valid datasets.",
+ "description": "The number of opted-in and opted-out image URLS in the dataset.",
@@ -3442 +4409 @@
- "$ref": "#/components/schemas/IsValidResponse"
+ "$ref": "#/components/schemas/OptInOutUrlsCountResponse"
@@ -3445,2 +4412,3 @@
- "valid": {
- "summary": "valid dataset",
+ "number of URLS for a dataset": {
+ "summary": "number of URLs for a dataset.",
+ "description": "Try with https://datasets-server.huggingface.co/opt-in-out-urls?dataset=conceptual_captions",
@@ -3448,2 +4416,7 @@
- "viewer": true,
- "preview": true
+ "urls_columns": ["image_url"],
+ "has_urls_columns": true,
+ "num_opt_in_urls": 0,
+ "num_opt_out_urls": 54760,
+ "num_scanned_rows": 215840,
+ "num_urls": 215840,
+ "full_scan": false
@@ -3452,2 +4425,3 @@
- "preview": {
- "summary": "dataset with only preview",
+ "number of URLS for a config": {
+ "summary": "number of URLs for a config.",
+ "description": "Try with https://datasets-server.huggingface.co/opt-in-out-urls?dataset=conceptual_captions&config=labeled",
@@ -3455,2 +4429,7 @@
- "viewer": false,
- "preview": true
+ "urls_columns": ["image_url"],
+ "has_urls_columns": true,
+ "num_opt_in_urls": 0,
+ "num_opt_out_urls": 16579,
+ "num_scanned_rows": 100000,
+ "num_urls": 100000,
+ "full_scan": false
@@ -3459,2 +4438,3 @@
- "invalid": {
- "summary": "invalid dataset",
+ "number of URLS for a split": {
+ "summary": "number of URLs for a split.",
+ "description": "Try with https://datasets-server.huggingface.co/opt-in-out-urls?dataset=conceptual_captions&config=labeled&split=train",
@@ -3462,2 +4442,20 @@
- "viewer": false,
- "preview": false
+ "has_urls_columns": true,
+ "num_opt_in_urls": 0,
+ "num_opt_out_urls": 16579,
+ "num_scanned_rows": 100000,
+ "num_urls": 100000,
+ "urls_columns": ["image_url"],
+ "full_scan": false
+ }
+ },
+ "dataset that has no image URLs columns": {
+ "summary": "no image URLs columns: values are zero.",
+ "description": "Try with https://datasets-server.huggingface.co/opt-in-out-urls?dataset=mnist",
+ "value": {
+ "urls_columns": [],
+ "has_urls_columns": false,
+ "num_opt_in_urls": 0,
+ "num_opt_out_urls": 0,
+ "num_scanned_rows": 0,
+ "num_urls": 0,
+ "full_scan": false
@@ -3471 +4469,10 @@
- "description": "If the external authentication step on the Hugging Face Hub failed, and no authentication mechanism has been provided. Retry with authentication.",
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/DatasetConfigSplit404"
+ },
+ "422": {
+ "$ref": "#/components/responses/Dataset422"
+ },
+ "500": {
+ "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
@@ -3480 +4487 @@
- "$ref": "#/components/headers/X-Error-Code-is-valid-401"
+ "$ref": "#/components/headers/X-Error-Code-500"
@@ -3489,5 +4496,2 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
+ "response not ready": {
+ "$ref": "#/components/examples/ResponseNotReadyError"
@@ -3495,11 +4499,12 @@
- "gated-dataset": {
- "summary": "The dataset is gated.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
- },
- "private-dataset": {
- "summary": "The dataset is private.",
- "value": {
- "error": "The dataset does not exist, or is not accessible without authentication (private or gated). Please check the spelling of the dataset name or retry with authentication."
- }
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
@@ -3511,2 +4516,2 @@
- "404": {
- "description": "If the dataset cannot be found. This may be because it doesn't exist, or because it is set to `private` and you do not have access.",
+ "501": {
+ "description": "The server does not implement the feature.",
@@ -3521 +4526 @@
- "$ref": "#/components/headers/X-Error-Code-is-valid-404"
+ "$ref": "#/components/headers/X-Error-Code-501"
@@ -3528,0 +4534,52 @@
+ "examples": {}
+ }
+ }
+ }
+ }
+ }
+ },
+ "/statistics": {
+ "get": {
+ "summary": "Descriptive statistics of a split's columns",
+ "description": "Returns descriptive statistics, such as min, max, average, histogram, of the columns of a split.",
+ "externalDocs": {
+ "description": "See statistics (Hub docs). The doc is still missing for the endpoint, see https://github.com/huggingface/datasets-server/issues/1664.",
+ "url": "https://huggingface.co/docs/datasets-server/"
+ },
+ "operationId": "getStatistics",
+ "security": [
+ {},
+ {
+ "HuggingFaceCookie": []
+ },
+ {
+ "HuggingFaceToken": []
+ }
+ ],
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/RequiredDataset"
+ },
+ {
+ "$ref": "#/components/parameters/RequiredConfig"
+ },
+ {
+ "$ref": "#/components/parameters/RequiredSplit"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The descriptive statistics for the columns of the split.",
+ "headers": {
+ "Cache-Control": {
+ "$ref": "#/components/headers/Cache-Control"
+ },
+ "Access-Control-Allow-Origin": {
+ "$ref": "#/components/headers/Access-Control-Allow-Origin"
+ }
+ },
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StatisticsResponse"
+ },
@@ -3530,8 +4587,3 @@
- "inexistent-dataset": {
- "summary": "The dataset does not exist, while authentication was provided in the request.",
- "value": {
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
- }
- },
- "gated-dataset": {
- "summary": "The dataset is gated, while authentication was provided in the request.",
+ "A split (mstz/wine) with numeric columns": {
+ "summary": "Statistics on numeric columns.",
+ "description": "Try with https://datasets-server.huggingface.co/statistics?dataset=mstz/wine&config=wine&split=train.",
@@ -3539 +4591,265 @@
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
+ "num_examples": 6497,
+ "statistics": [
+ {
+ "column_name": "alcohol",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 8.0,
+ "max": 14.9,
+ "mean": 10.4918,
+ "median": 10.3,
+ "std": 1.19271,
+ "histogram": {
+ "hist": [
+ 40, 1133, 1662, 1156, 1092, 628, 569, 175, 41, 1
+ ],
+ "bin_edges": [
+ 8.0, 8.69, 9.38, 10.07, 10.76, 11.45, 12.14,
+ 12.83, 13.52, 14.21, 14.9
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "chlorides",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 0.009,
+ "max": 0.611,
+ "mean": 0.05603,
+ "median": 0.047,
+ "std": 0.03503,
+ "histogram": {
+ "hist": [5061, 1279, 92, 34, 8, 9, 10, 2, 0, 2],
+ "bin_edges": [
+ 0.009, 0.0692, 0.1294, 0.1896, 0.2498, 0.31,
+ 0.3702, 0.4304, 0.4906, 0.5508, 0.611
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "citric_acid",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 0.0,
+ "max": 1.66,
+ "mean": 0.31863,
+ "median": 0.31,
+ "std": 0.14532,
+ "histogram": {
+ "hist": [
+ 766, 3113, 2059, 420, 126, 5, 6, 1, 0, 1
+ ],
+ "bin_edges": [
+ 0.0, 0.166, 0.332, 0.498, 0.664, 0.83, 0.996,
+ 1.162, 1.328, 1.494, 1.66
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "density",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 0.98711,
+ "max": 1.03898,
+ "mean": 0.9947,
+ "median": 0.99489,
+ "std": 0.003,
+ "histogram": {
+ "hist": [1599, 3645, 1241, 9, 2, 0, 0, 0, 0, 1],
+ "bin_edges": [
+ 0.98711, 0.9923, 0.99748, 1.00267, 1.00786,
+ 1.01304, 1.01823, 1.02342, 1.02861, 1.03379,
+ 1.03898
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "fixed_acidity",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 3.8,
+ "max": 15.9,
+ "mean": 7.21531,
+ "median": 7.0,
+ "std": 1.29643,
+ "histogram": {
+ "hist": [
+ 63, 1151, 3248, 1339, 382, 177, 82, 41, 7, 7
+ ],
+ "bin_edges": [
+ 3.8, 5.01, 6.22, 7.43, 8.64, 9.85, 11.06, 12.27,
+ 13.48, 14.69, 15.9
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "free_sulfur_dioxide",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 1.0,
+ "max": 289.0,
+ "mean": 30.52532,
+ "median": 29.0,
+ "std": 17.7494,
+ "histogram": {
+ "hist": [3392, 2676, 401, 20, 6, 1, 0, 0, 0, 1],
+ "bin_edges": [
+ 1.0, 29.8, 58.6, 87.4, 116.2, 145.0, 173.8,
+ 202.6, 231.4, 260.2, 289.0
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "is_red",
+ "column_type": "class_label",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "n_unique": 2,
+ "frequencies": { "red": 1599, "white": 4898 }
+ }
+ },
+ {
+ "column_name": "pH",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 2.72,
+ "max": 4.01,
+ "mean": 3.2185,
+ "median": 3.21,
+ "std": 0.16079,
+ "histogram": {
+ "hist": [
+ 16, 334, 1233, 2111, 1663, 802, 263, 59, 12, 4
+ ],
+ "bin_edges": [
+ 2.72, 2.849, 2.978, 3.107, 3.236, 3.365, 3.494,
+ 3.623, 3.752, 3.881, 4.01
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "quality",
+ "column_type": "int",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 3,
+ "max": 9,
+ "mean": 5.81838,
+ "median": 6.0,
+ "std": 0.87326,
+ "histogram": {
+ "hist": [30, 216, 2138, 2836, 1079, 193, 5],
+ "bin_edges": [3, 4, 5, 6, 7, 8, 9, 9]
+ }
+ }
+ },
+ {
+ "column_name": "residual_sugar",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 0.6,
+ "max": 65.8,
+ "mean": 5.44324,
+ "median": 3.0,
+ "std": 4.7578,
+ "histogram": {
+ "hist": [4551, 1396, 533, 14, 2, 0, 0, 0, 0, 1],
+ "bin_edges": [
+ 0.6, 7.12, 13.64, 20.16, 26.68, 33.2, 39.72,
+ 46.24, 52.76, 59.28, 65.8
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "sulphates",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 0.22,
+ "max": 2.0,
+ "mean": 0.53127,
+ "median": 0.51,
+ "std": 0.14881,
+ "histogram": {
+ "hist": [
+ 1023, 3451, 1540, 382, 66, 21, 6, 4, 0, 4
+ ],
+ "bin_edges": [
+ 0.22, 0.398, 0.576, 0.754, 0.932, 1.11, 1.288,
+ 1.466, 1.644, 1.822, 2.0
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "total_sulfur_dioxide",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 6.0,
+ "max": 440.0,
+ "mean": 115.74457,
+ "median": 118.0,
+ "std": 56.52185,
+ "histogram": {
+ "hist": [
+ 1088, 979, 2049, 1514, 721, 134, 8, 2, 1, 1
+ ],
+ "bin_edges": [
+ 6.0, 49.4, 92.8, 136.2, 179.6, 223.0, 266.4,
+ 309.8, 353.2, 396.6, 440.0
+ ]
+ }
+ }
+ },
+ {
+ "column_name": "volatile_acidity",
+ "column_type": "float",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "min": 0.08,
+ "max": 1.58,
+ "mean": 0.33967,
+ "median": 0.29,
+ "std": 0.16464,
+ "histogram": {
+ "hist": [
+ 1580, 3002, 996, 606, 214, 70, 22, 4, 2, 1
+ ],
+ "bin_edges": [
+ 0.08, 0.23, 0.38, 0.53, 0.68, 0.83, 0.98, 1.13,
+ 1.28, 1.43, 1.58
+ ]
+ }
+ }
+ }
+ ]
@@ -3542,2 +4858,3 @@
- "private-dataset": {
- "summary": "The dataset is private, while authentication was provided in the request.",
+ "A split (mnist) with a label column": {
+ "summary": "Statistics on a class label column. The image column is not processed.",
+ "description": "Try with https://datasets-server.huggingface.co/statistics?dataset=mnist&config=mnist&split=train.",
@@ -3545 +4862,24 @@
- "error": "The dataset does not exist, or is not accessible with the current credentials (private or gated). Please check the spelling of the dataset name or retry with other authentication credentials."
+ "num_examples": 60000,
+ "statistics": [
+ {
+ "column_name": "label",
+ "column_type": "class_label",
+ "column_statistics": {
+ "nan_count": 0,
+ "nan_proportion": 0.0,
+ "n_unique": 10,
+ "frequencies": {
+ "0": 5923,
+ "1": 6742,
+ "2": 5958,
+ "3": 6131,
+ "4": 5842,
+ "5": 5421,
+ "6": 5918,
+ "7": 6265,
+ "8": 5851,
+ "9": 5949
+ }
+ }
+ }
+ ]
@@ -3551,0 +4892,6 @@
+ "401": {
+ "$ref": "#/components/responses/Common401"
+ },
+ "404": {
+ "$ref": "#/components/responses/DatasetConfigSplit404"
+ },
@@ -3553 +4899,4 @@
- "description": "The `dataset` parameter has not been provided.",
+ "$ref": "#/components/responses/DatasetConfigSplit422"
+ },
+ "500": {
+ "description": "The server crashed, the response still hasn't been generated (the process is asynchronous), or the response couldn't be generated successfully due to an error in the dataset itself. The client can retry after a time, in particular in the case of the response still being processed. If the error does not vanish, it's possibly due to a bug in the API software or in the dataset, and should be reported.",
@@ -3562 +4911 @@
- "$ref": "#/components/headers/X-Error-Code-is-valid-422"
+ "$ref": "#/components/headers/X-Error-Code-500-common"
@@ -3571,3 +4920,20 @@
- "missing-parameter": {
- "summary": "The dataset parameter is missing.",
- "value": { "error": "Parameter 'dataset' is required" }
+ "error in the dataset itself": {
+ "summary": "An error while processing the dataset prevents the response to be created.",
+ "description": "Try with https://datasets-server.huggingface.co/statistics?dataset=atomic&config=atomic&split=train",
+ "value": {
+ "error": "Couldn't get the size of external files in `_split_generators` because a request failed:\n404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\nPlease consider moving your data files in this dataset repository instead (e.g. inside a data/ folder).",
+ "cause_exception": "HTTPError",
+ "cause_message": "404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz",
+ "cause_traceback": [
+ "Traceback (most recent call last):\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 497, in _is_too_big_from_external_data_files\n for i, size in enumerate(pool.imap_unordered(get_size, ext_data_files)):\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 870, in next\n raise value\n",
+ " File \"/usr/local/lib/python3.9/multiprocessing/pool.py\", line 125, in worker\n result = (True, func(*args, **kwds))\n",
+ " File \"/src/services/worker/src/worker/job_runners/config/parquet_and_info.py\", line 396, in _request_size\n response.raise_for_status()\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/requests/models.py\", line 1021, in raise_for_status\n raise HTTPError(http_error_msg, response=self)\n",
+ "requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://maartensap.com/atomic/data/atomic_data.tgz\n"
+ ]
+ }
+ },
+ "response not ready": {
+ "$ref": "#/components/examples/ResponseNotReadyError"
@@ -3575,3 +4941,12 @@
- "empty-parameter": {
- "summary": "The dataset parameter is empty (?dataset=).",
- "value": { "error": "Parameter 'dataset' is required" }
+ "unexpected error": {
+ "$ref": "#/components/examples/UnexpectedJsonError"
+ }
+ }
+ },
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerErrorResponse"
+ },
+ "examples": {
+ "internal server error": {
+ "$ref": "#/components/examples/UnexpectedTextError"
@@ -3583,2 +4958,2 @@
- "500": {
- "description": "The server crashed.",
+ "501": {
+ "description": "The server does not implement the feature.",
@@ -3593 +4968 @@
- "$ref": "#/components/headers/X-Error-Code-is-valid-500"
+ "$ref": "#/components/headers/X-Error-Code-501"
@@ -3602,15 +4977,3 @@
- "internal": {
- "summary": "internal error",
- "value": {
- "error": "Unexpected error."
- }
- }
- }
- },
- "text/plain": {
- "schema": {
- "$ref": "#/components/schemas/ServerErrorResponse"
- },
- "examples": {
- "internal": {
- "summary": "internal error",
+ "blocked dataset": {
+ "summary": "The dataset is blocked manually on the server.",
+ "description": "Try with https://datasets-server.huggingface.co/statistics?dataset=echarlaix/vqa-lxmert&config=vqa&split=validation",
@@ -3618 +4981 @@
- "error": "Internal Server Error"
+ "error": "The parquet conversion has been disabled for this dataset for now. Please open an issue in https://github.com/huggingface/datasets-server if you want this dataset to be supported."
diff --git a/e2e/tests/test_12_splits.py b/e2e/tests/test_12_splits.py
index 26017ae7..504c560e 100644
--- a/e2e/tests/test_12_splits.py
+++ b/e2e/tests/test_12_splits.py
@@ -10 +10 @@ from .utils import get, get_openapi_body_example, poll, poll_splits, post_refres
- "status,name,dataset,error_code",
+ "status,name,dataset,config,error_code",
@@ -12,2 +12,2 @@ from .utils import get, get_openapi_body_example, poll, poll_splits, post_refres
- # (200, "duorc", "duorc", None),
- # (200, "emotion", "emotion", None),
+ # (200, "all splits in a dataset", "duorc", None, None),
+ # (200, "splits for a single config", "emotion", "unsplit", None)
@@ -16 +16 @@ from .utils import get, get_openapi_body_example, poll, poll_splits, post_refres
- "inexistent-dataset",
+ "inexistent dataset, and not authenticated",
@@ -17,0 +18 @@ from .utils import get, get_openapi_body_example, poll, poll_splits, post_refres
+ None,
@@ -23 +24 @@ from .utils import get, get_openapi_body_example, poll, poll_splits, post_refres
- # "severo/dummy_gated",
+ # "severo/dummy_gated", None,
@@ -29 +30 @@ from .utils import get, get_openapi_body_example, poll, poll_splits, post_refres
- # "severo/dummy_private",
+ # "severo/dummy_private", None,
@@ -32,5 +33,5 @@ from .utils import get, get_openapi_body_example, poll, poll_splits, post_refres
- (422, "empty-parameter", "", "MissingRequiredParameter"),
- (422, "missing-parameter", None, "MissingRequiredParameter"),
- # (500, "SplitsNotFoundError", "natural_questions", "SplitsNamesError"),
- # (500, "FileNotFoundError", "akhaliq/test", "SplitsNamesError"),
- # (500, "not-ready", "severo/fix-401", "SplitsResponseNotReady"),
+ (422, "missing dataset parameter", "", None, "MissingRequiredParameter"),
+ (422, "empty dataset parameter", None, None, "MissingRequiredParameter"),
+ # (500, "SplitsNotFoundError", "natural_questions", None, "SplitsNamesError"),
+ # (500, "FileNotFoundError", "akhaliq/test", None, "SplitsNamesError"),
+ # (500, "not-ready", "severo/fix-401", None, "SplitsResponseNotReady"),
@@ -40 +41 @@ from .utils import get, get_openapi_body_example, poll, poll_splits, post_refres
-def test_splits_using_openapi(status: int, name: str, dataset: str, error_code: str) -> None:
+def test_splits_using_openapi(status: int, name: str, dataset: str, config: str, error_code: str) -> None:
@@ -41,0 +43 @@ def test_splits_using_openapi(status: int, name: str, dataset: str, error_code:
+ config_query = f"&config={config}" if config else ""
@@ -43 +45 @@ def test_splits_using_openapi(status: int, name: str, dataset: str, error_code:
- if name == "empty-parameter":
+ if name == "empty dataset parameter":
@@ -45 +47 @@ def test_splits_using_openapi(status: int, name: str, dataset: str, error_code:
- elif name == "missing-parameter":
+ elif name == "missing dataset parameter":
@@ -50 +52,3 @@ def test_splits_using_openapi(status: int, name: str, dataset: str, error_code:
- r_splits = get(f"/splits?dataset={dataset}") if name == "not-ready" else poll_splits(dataset)
+ r_splits = (
+ get(f"/splits?dataset={dataset}{config_query}") if name == "not-ready" else poll_splits(dataset, config)
+ )
diff --git a/e2e/tests/test_13_first_rows.py b/e2e/tests/test_13_first_rows.py
index b59eb8a7..beda30f8 100644
--- a/e2e/tests/test_13_first_rows.py
+++ b/e2e/tests/test_13_first_rows.py
@@ -12 +11,0 @@ from .utils import (
- get,
@@ -30 +29 @@ def prepare_json(response: requests.Response) -> Any:
- "inexistent-dataset",
+ "inexistent dataset, and not authenticated",
@@ -36,6 +35,6 @@ def prepare_json(response: requests.Response) -> Any:
- (422, "missing-dataset", None, "plain_text", "train", "MissingRequiredParameter"),
- (422, "missing-config", "imdb", None, "train", "MissingRequiredParameter"),
- (422, "missing-split", "imdb", "plain_text", None, "MissingRequiredParameter"),
- (422, "empty-dataset", "", "plain_text", "train", "MissingRequiredParameter"),
- (422, "empty-config", "imdb", "", "train", "MissingRequiredParameter"),
- (422, "empty-split", "imdb", "plain_text", "", "MissingRequiredParameter"),
+ (422, "missing required parameter", None, "plain_text", "train", "MissingRequiredParameter"),
+ (422, "missing required parameter", "imdb", None, "train", "MissingRequiredParameter"),
+ (422, "missing required parameter", "imdb", "plain_text", None, "MissingRequiredParameter"),
+ (422, "empty required parameter", "", "plain_text", "train", "MissingRequiredParameter"),
+ (422, "empty required parameter", "imdb", "", "train", "MissingRequiredParameter"),
+ (422, "empty required parameter", "imdb", "plain_text", "", "MissingRequiredParameter"),
@@ -49 +48 @@ def test_first_rows(status: int, name: str, dataset: str, config: str, split: st
- if name.startswith("empty-"):
+ if name == "empty required parameter":
@@ -51 +50 @@ def test_first_rows(status: int, name: str, dataset: str, config: str, split: st
- elif name.startswith("missing-"):
+ elif name == "missing required parameter":
@@ -59,6 +58,2 @@ def test_first_rows(status: int, name: str, dataset: str, config: str, split: st
- poll_splits(dataset)
- if name == "not-ready":
- # poll the endpoint before the worker had the chance to process it
- r_rows = get(f"/first-rows?dataset={dataset}&config={config}&split={split}")
- else:
- r_rows = poll_first_rows(dataset, config, split)
+ poll_splits(dataset, config)
+ r_rows = poll_first_rows(dataset, config, split)
diff --git a/e2e/tests/utils.py b/e2e/tests/utils.py
index 22c1ef29..15e9b6a9 100644
--- a/e2e/tests/utils.py
+++ b/e2e/tests/utils.py
@@ -82,2 +82,3 @@ def poll_parquet(dataset: str, headers: Optional[Headers] = None) -> Response:
-def poll_splits(dataset: str, headers: Optional[Headers] = None) -> Response:
- return poll(f"/splits?dataset={dataset}", error_field="error", headers=headers)
+def poll_splits(dataset: str, config: Optional[str], headers: Optional[Headers] = None) -> Response:
+ config_query = f"&config={config}" if config else ""
+ return poll(f"/splits?dataset={dataset}{config_query}", error_field="error", headers=headers)
@@ -95,3 +96,21 @@ def get_openapi_body_example(path: str, status: int, example_name: str) -> Any:
- return openapi["paths"][path]["get"]["responses"][str(status)]["content"]["application/json"]["examples"][
- example_name
- ]["value"]
+ steps = [
+ "paths",
+ path,
+ "get",
+ "responses",
+ str(status),
+ "content",
+ "application/json",
+ "examples",
+ example_name,
+ "value",
+ ]
+ result = openapi
+ for step in steps:
+ if "$ref" in result:
+ new_steps = result["$ref"].split("/")[1:]
+ result = openapi
+ for new_step in new_steps:
+ result = result[new_step]
+ result = result[step]
+ return result
diff --git a/libs/libcommon/src/libcommon/exceptions.py b/libs/libcommon/src/libcommon/exceptions.py
index 5cb38fb3..fd4c17e9 100644
--- a/libs/libcommon/src/libcommon/exceptions.py
+++ b/libs/libcommon/src/libcommon/exceptions.py
@@ -142 +142 @@ class CacheDirectoryNotInitializedError(CacheableError):
- """Raised when the cache directory has not been initialized before job compute."""
+ """The cache directory has not been initialized before job compute."""
@@ -149 +149 @@ class ConfigNamesError(CacheableError):
- """Raised when the config names could not be fetched."""
+ """The config names could not be fetched."""
@@ -156 +156 @@ class CreateCommitError(CacheableError):
- """Raised when a commit could not be created on the Hub."""
+ """A commit could not be created on the Hub."""
@@ -163 +163 @@ class DatasetInBlockListError(CacheableError):
- """Raised when the dataset is in the list of blocked datasets."""
+ """The dataset is in the list of blocked datasets."""
@@ -170 +170 @@ class DatasetInfoHubRequestError(CacheableError):
- """Raised when the request to the Hub's dataset-info endpoint times out."""
+ """The request to the Hub's dataset-info endpoint times out."""
@@ -183 +183 @@ class DatasetManualDownloadError(CacheableError):
- """Raised when the dataset requires manual download."""
+ """The dataset requires manual download."""
@@ -190 +190 @@ class DatasetModuleNotInstalledError(CacheableError):
- """Raised when the dataset tries to import a module that is not installed."""
+ """The dataset tries to import a module that is not installed."""
@@ -197 +197 @@ class DatasetNotFoundError(CacheableError):
- """Raised when the dataset does not exist."""
+ """The dataset does not exist."""
@@ -210 +210 @@ class DatasetRevisionEmptyError(CacheableError):
- """Raised when the current git revision (branch, commit) could not be obtained."""
+ """The current git revision (branch, commit) could not be obtained."""
@@ -217 +217 @@ class DatasetRevisionNotFoundError(CacheableError):
- """Raised when the revision of a dataset repository does not exist."""
+ """The revision of a dataset repository does not exist."""
@@ -224 +224 @@ class DatasetWithTooManyConfigsError(CacheableError):
- """Raised when the number of configs of a dataset exceeded the limit."""
+ """The number of configs of a dataset exceeded the limit."""
@@ -231 +231 @@ class DatasetWithTooManyParquetFilesError(CacheableError):
- """Raised when the number of parquet files of a dataset is too big."""
+ """The number of parquet files of a dataset is too big."""
@@ -238 +238 @@ class DuckDBIndexFileNotFoundError(CacheableError):
- """Raised when no duckdb index file was found for split."""
+ """No duckdb index file was found for split."""
@@ -245 +245 @@ class DisabledViewerError(CacheableError):
- """Raised when the dataset viewer is disabled."""
+ """The dataset viewer is disabled."""
@@ -258 +258 @@ class EmptyDatasetError(CacheableError):
- """Raised when the dataset has no data."""
+ """The dataset has no data."""
@@ -265 +265 @@ class ExternalFilesSizeRequestConnectionError(CacheableError):
- """Raised when we failed to get the size of the external files."""
+ """We failed to get the size of the external files."""
@@ -272 +272 @@ class ExternalFilesSizeRequestError(CacheableError):
- """Raised when we failed to get the size of the external files."""
+ """We failed to get the size of the external files."""
@@ -279 +279 @@ class ExternalFilesSizeRequestHTTPError(CacheableError):
- """Raised when we failed to get the size of the external files."""
+ """We failed to get the size of the external files."""
@@ -286 +286 @@ class ExternalFilesSizeRequestTimeoutError(CacheableError):
- """Raised when we failed to get the size of the external files."""
+ """We failed to get the size of the external files."""
@@ -293 +293 @@ class ExternalServerError(CacheableError):
- """Raised when the spawning.ai server is not responding."""
+ """The spawning.ai server is not responding."""
@@ -300 +300 @@ class FeaturesError(CacheableError):
- """Raised when the features could not be fetched."""
+ """The features could not be fetched."""
@@ -307 +307 @@ class FileSystemError(CacheableError):
- """Raised when an error happen reading from File System."""
+ """An error happen reading from File System."""
@@ -314 +314 @@ class InfoError(CacheableError):
- """Raised when the info could not be fetched."""
+ """The info could not be fetched."""
@@ -321 +321 @@ class JobManagerCrashedError(CacheableError):
- """Raised when the job runner crashed and the job became a zombie."""
+ """The job runner crashed and the job became a zombie."""
@@ -334 +334 @@ class JobManagerExceededMaximumDurationError(CacheableError):
- """Raised when the job runner was killed because the job exceeded the maximum duration."""
+ """The job runner was killed because the job exceeded the maximum duration."""
@@ -347 +347 @@ class LockedDatasetTimeoutError(CacheableError):
- """Raised when a dataset is locked by another job."""
+ """A dataset is locked by another job."""
@@ -354 +354 @@ class MissingSpawningTokenError(CacheableError):
- """Raised when the spawning.ai token is not set."""
+ """The spawning.ai token is not set."""
@@ -361 +361 @@ class NormalRowsError(CacheableError):
- """Raised when the rows could not be fetched in normal mode."""
+ """The rows could not be fetched in normal mode."""
@@ -368 +368 @@ class NoIndexableColumnsError(CacheableError):
- """Raised when split does not have string columns to index."""
+ """The split does not have string columns to index."""
@@ -375 +375 @@ class NoSupportedFeaturesError(CacheableError):
- """Raised when dataset does not have any features which types are supported by a worker's processing pipeline."""
+ """The dataset does not have any features which types are supported by a worker's processing pipeline."""
@@ -382 +382 @@ class ParameterMissingError(CacheableError):
- """Raised when request is missing some parameter."""
+ """The request is missing some parameter."""
@@ -387 +387 @@ class ParameterMissingError(CacheableError):
- status_code=HTTPStatus.BAD_REQUEST,
+ status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
@@ -395 +395 @@ class ParquetResponseEmptyError(CacheableError):
- """Raised when no parquet files were found for split."""
+ """No parquet files were found for split."""
@@ -402 +402 @@ class PreviousStepFormatError(CacheableError):
- """Raised when the content of the previous step has not the expected format."""
+ """The content of the previous step has not the expected format."""
@@ -409 +409 @@ class PreviousStepStatusError(CacheableError):
- """Raised when the previous step gave an error. The job should not have been created."""
+ """The previous step gave an error. The job should not have been created."""
@@ -416 +416 @@ class ResponseAlreadyComputedError(CacheableError):
- """Raised when response has been already computed by another job runner."""
+ """The response has been already computed by another job runner."""
@@ -429 +429 @@ class RowsPostProcessingError(CacheableError):
- """Raised when the rows could not be post-processed successfully."""
+ """The rows could not be post-processed successfully."""
@@ -436 +436 @@ class SplitsNamesError(CacheableError):
- """Raised when the split names could not be fetched."""
+ """The split names could not be fetched."""
@@ -443 +443 @@ class SplitNamesFromStreamingError(CacheableError):
- """Raised when the split names could not be fetched."""
+ """The split names could not be fetched."""
@@ -450 +450 @@ class SplitNotFoundError(CacheableError):
- """Raised when the split does not exist."""
+ """The split does not exist."""
@@ -463 +463 @@ class SplitWithTooBigParquetError(CacheableError):
- """Raised when the split parquet size (sum of parquet sizes given) is too big."""
+ """The split parquet size (sum of parquet sizes given) is too big."""
@@ -470 +470 @@ class StreamingRowsError(CacheableError):
- """Raised when the rows could not be fetched in streaming mode."""
+ """The rows could not be fetched in streaming mode."""
@@ -477 +477 @@ class TooBigContentError(CacheableError):
- """Raised when content size in bytes is bigger than the supported value."""
+ """The content size in bytes is bigger than the supported value."""
@@ -490 +490 @@ class TooManyColumnsError(CacheableError):
- """Raised when the dataset exceeded the max number of columns."""
+ """The dataset exceeded the max number of columns."""
@@ -497 +497 @@ class UnexpectedError(CacheableError):
- """Raised when the job runner raised an unexpected error."""
+ """The job runner raised an unexpected error."""
@@ -511 +511 @@ class UnsupportedExternalFilesError(CacheableError):
- """Raised when we failed to get the size of the external files."""
+ """We failed to get the size of the external files."""
@@ -518 +518 @@ class StatisticsComputationError(CacheableError):
- """Raised in case of unexpected behaviour / errors during statistics computations."""
+ """An unexpected behavior or error occurred during statistics computations."""
diff --git a/libs/libcommon/src/libcommon/utils.py b/libs/libcommon/src/libcommon/utils.py
index 30f21d02..0f1711d7 100644
--- a/libs/libcommon/src/libcommon/utils.py
+++ b/libs/libcommon/src/libcommon/utils.py
@@ -78,0 +79,3 @@ class SplitHubFile(TypedDict):
+Row = Dict[str, Any]
+
+
@@ -81 +84 @@ class RowItem(TypedDict):
- row: Mapping[str, Any]
+ row: Row
@@ -85,3 +87,0 @@ class RowItem(TypedDict):
-Row = Dict[str, Any]
-
-
@@ -91 +91 @@ class FeatureItem(TypedDict):
- type: Row
+ type: Dict[str, Any]
@@ -96 +96 @@ class PaginatedResponse(TypedDict):
- rows: Any
+ rows: List[RowItem]
diff --git a/services/rows/src/rows/routes/rows.py b/services/rows/src/rows/routes/rows.py
index 30a83e95..9d871922 100644
--- a/services/rows/src/rows/routes/rows.py
+++ b/services/rows/src/rows/routes/rows.py
@@ -6 +6 @@ import random
-from typing import Any, List, Literal, Optional, Union
+from typing import List, Literal, Optional, Union
@@ -31,0 +32 @@ from libcommon.storage import StrPath
+from libcommon.utils import PaginatedResponse
@@ -60 +61 @@ def create_response(
-) -> Any:
+) -> PaginatedResponse:
@@ -65,3 +66,3 @@ def create_response(
- return {
- "features": to_features_list(features),
- "rows": to_rows_list(
+ return PaginatedResponse(
+ features=to_features_list(features),
+ rows=to_rows_list(
@@ -78,2 +79,2 @@ def create_response(
- "num_total_rows": num_total_rows,
- }
+ num_total_rows=num_total_rows,
+ )
diff --git a/services/worker/src/worker/dtos.py b/services/worker/src/worker/dtos.py
index d5fd3bde..3e23217a 100644
--- a/services/worker/src/worker/dtos.py
+++ b/services/worker/src/worker/dtos.py
@@ -5 +5 @@ from dataclasses import dataclass, field
-from typing import Any, Dict, List, Mapping, Optional, TypedDict
+from typing import Any, Dict, List, Mapping, Optional, TypedDict, Union
@@ -42,0 +43,8 @@ class SplitItem(ConfigItem):
+class FullConfigItem(DatasetItem):
+ config: str
+
+
+class FullSplitItem(FullConfigItem):
+ split: str
+
+
@@ -44 +52 @@ class SplitsList(TypedDict):
- splits: List[SplitItem]
+ splits: List[FullSplitItem]
@@ -47 +55 @@ class SplitsList(TypedDict):
-class FailedConfigItem(ConfigItem):
+class FailedConfigItem(FullConfigItem):
@@ -52,2 +60,2 @@ class DatasetSplitNamesResponse(TypedDict):
- splits: List[SplitItem]
- pending: List[ConfigItem]
+ splits: List[FullSplitItem]
+ pending: List[FullConfigItem]
@@ -57 +65,4 @@ class DatasetSplitNamesResponse(TypedDict):
-class PreviousJob(SplitItem):
+class PreviousJob(TypedDict):
+ dataset: str
+ config: Optional[str]
+ split: Optional[Union[str, None]]
@@ -61 +72 @@ class PreviousJob(SplitItem):
-class SplitFirstRowsResponse(SplitItem):
+class SplitFirstRowsResponse(FullSplitItem):
@@ -79 +90 @@ class OptInOutUrlsCountResponse(TypedDict):
- full_scan: Optional[bool]
+ full_scan: Union[bool, None]
@@ -139 +150,4 @@ class ConfigSize(TypedDict):
-class SplitSize(SplitItem):
+class SplitSize(TypedDict):
+ dataset: str
+ config: str
+ split: str
diff --git a/services/worker/src/worker/job_runners/config/split_names_from_info.py b/services/worker/src/worker/job_runners/config/split_names_from_info.py
index 6b97ce14..aa717225 100644
--- a/services/worker/src/worker/job_runners/config/split_names_from_info.py
+++ b/services/worker/src/worker/job_runners/config/split_names_from_info.py
@@ -14 +14 @@ from libcommon.simple_cache import get_previous_step_or_raise
-from worker.dtos import CompleteJobResult, JobRunnerInfo, SplitItem, SplitsList
+from worker.dtos import CompleteJobResult, FullSplitItem, JobRunnerInfo, SplitsList
@@ -48 +48 @@ def compute_split_names_from_info_response(dataset: str, config: str) -> SplitsL
- split_name_items: List[SplitItem] = [
+ split_name_items: List[FullSplitItem] = [
diff --git a/services/worker/src/worker/job_runners/config/split_names_from_streaming.py b/services/worker/src/worker/job_runners/config/split_names_from_streaming.py
index 174e182a..da52d7f8 100644
--- a/services/worker/src/worker/job_runners/config/split_names_from_streaming.py
+++ b/services/worker/src/worker/job_runners/config/split_names_from_streaming.py
@@ -20 +20 @@ from libcommon.exceptions import (
-from worker.dtos import CompleteJobResult, JobRunnerInfo, SplitItem, SplitsList
+from worker.dtos import CompleteJobResult, FullSplitItem, JobRunnerInfo, SplitsList
@@ -62 +62 @@ def compute_split_names_from_streaming_response(
- split_name_items: List[SplitItem] = [
+ split_name_items: List[FullSplitItem] = [
diff --git a/services/worker/src/worker/job_runners/dataset/split_names.py b/services/worker/src/worker/job_runners/dataset/split_names.py
index 06aa9222..aca1a59c 100644
--- a/services/worker/src/worker/job_runners/dataset/split_names.py
+++ b/services/worker/src/worker/job_runners/dataset/split_names.py
@@ -13 +12,0 @@ from worker.dtos import (
- ConfigItem,
@@ -15,0 +15,2 @@ from worker.dtos import (
+ FullConfigItem,
+ FullSplitItem,
@@ -17 +17,0 @@ from worker.dtos import (
- SplitItem,
@@ -51,2 +51,2 @@ def compute_dataset_split_names_response(dataset: str) -> Tuple[DatasetSplitName
- splits: List[SplitItem] = []
- pending: List[ConfigItem] = []
+ splits: List[FullSplitItem] = []
+ pending: List[FullConfigItem] = []
@@ -63 +63 @@ def compute_dataset_split_names_response(dataset: str) -> Tuple[DatasetSplitName
- pending.append(ConfigItem({"dataset": dataset, "config": config}))
+ pending.append(FullConfigItem({"dataset": dataset, "config": config}))
@@ -79 +79 @@ def compute_dataset_split_names_response(dataset: str) -> Tuple[DatasetSplitName
- SplitItem({"dataset": dataset, "config": config, "split": split_content["split"]})
+ FullSplitItem({"dataset": dataset, "config": config, "split": split_content["split"]})
diff --git a/services/worker/tests/job_runners/config/test_config_job_runner.py b/services/worker/tests/job_runners/config/test_config_job_runner.py
index 77a9ebec..57f60cd1 100644
--- a/services/worker/tests/job_runners/config/test_config_job_runner.py
+++ b/services/worker/tests/job_runners/config/test_config_job_runner.py
@@ -4,2 +3,0 @@
-from http import HTTPStatus
-
@@ -48 +45,0 @@ def test_failed_creation(test_processing_step: ProcessingStep, app_config: AppCo
- assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
diff --git a/services/worker/tests/job_runners/dataset/test_dataset_job_runner.py b/services/worker/tests/job_runners/dataset/test_dataset_job_runner.py
index 4fe427c9..a34f747b 100644
--- a/services/worker/tests/job_runners/dataset/test_dataset_job_runner.py
+++ b/services/worker/tests/job_runners/dataset/test_dataset_job_runner.py
@@ -4,2 +3,0 @@
-from http import HTTPStatus
-
@@ -49 +46,0 @@ def test_failed_creation(test_processing_step: ProcessingStep, app_config: AppCo
- assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
diff --git a/services/worker/tests/job_runners/split/test_split_job_runner.py b/services/worker/tests/job_runners/split/test_split_job_runner.py
index 2afde623..e6d6c4ea 100644
--- a/services/worker/tests/job_runners/split/test_split_job_runner.py
+++ b/services/worker/tests/job_runners/split/test_split_job_runner.py
@@ -4,2 +3,0 @@
-from http import HTTPStatus
-
@@ -49 +46,0 @@ def test_failed_creation(test_processing_step: ProcessingStep, app_config: AppCo
- assert exc_info.value.status_code == HTTPStatus.BAD_REQUEST
|
|
cf8042da9a2325a1d5706dbecded9b187d5cc8db
|
Sylvain Lesage
| 2023-08-11T18:18:04 |
feat: 🎸 move openapi.json to the docs (#1672)
|
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 3fbd1662..dc7b787e 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -14 +14 @@ on:
- - "chart/static-files/openapi.json"
+ - "docs/source/openapi.json"
@@ -25 +25 @@ on:
- - "chart/static-files/openapi.json"
+ - "docs/source/openapi.json"
diff --git a/.github/workflows/openapi-spec.yml b/.github/workflows/openapi-spec.yml
index 7de61309..4161aab7 100644
--- a/.github/workflows/openapi-spec.yml
+++ b/.github/workflows/openapi-spec.yml
@@ -11 +11 @@ on:
- - "chart/static-files/opanapi.json"
+ - "docs/source/openapi.json"
@@ -15 +15 @@ on:
- - "chart/static-files/opanapi.json"
+ - "docs/source/openapi.json"
@@ -47 +47 @@ jobs:
- poetry run python -m openapi_spec_validator ../chart/static-files/openapi.json
+ poetry run python -m openapi_spec_validator ../docs/source/openapi.json
diff --git a/chart/Chart.yaml b/chart/Chart.yaml
index e9a715a4..d6f9eb5c 100644
--- a/chart/Chart.yaml
+++ b/chart/Chart.yaml
@@ -21 +21 @@ type: application
-version: 1.16.1
+version: 1.16.2
diff --git a/chart/nginx-templates/default.conf.template b/chart/nginx-templates/default.conf.template
index 56886a2e..cf5278ae 100644
--- a/chart/nginx-templates/default.conf.template
+++ b/chart/nginx-templates/default.conf.template
@@ -29 +29 @@ server {
- alias /static-files/openapi.json;
+ return 307 https://raw.githubusercontent.com/huggingface/datasets-server/main/${OPENAPI_FILE};
diff --git a/chart/templates/reverse-proxy/_container.tpl b/chart/templates/reverse-proxy/_container.tpl
index 794208e7..8daf68c8 100644
--- a/chart/templates/reverse-proxy/_container.tpl
+++ b/chart/templates/reverse-proxy/_container.tpl
@@ -12,0 +13,2 @@
+ - name: OPENAPI_FILE
+ value: {{ .Values.reverseProxy.openapiFile | quote }}
@@ -36,4 +37,0 @@
- - name: static-files
- mountPath: /static-files
- mountPropagation: None
- readOnly: true
diff --git a/chart/templates/reverse-proxy/configMap.yaml b/chart/templates/reverse-proxy/configMap.yaml
index 603ff52c..88ec1fe1 100644
--- a/chart/templates/reverse-proxy/configMap.yaml
+++ b/chart/templates/reverse-proxy/configMap.yaml
@@ -15,2 +14,0 @@ data:
- openapi.json: |-
- {{ .Files.Get .Values.reverseProxy.openapiFile | nindent 4 }}
diff --git a/chart/templates/reverse-proxy/deployment.yaml b/chart/templates/reverse-proxy/deployment.yaml
index dd904666..cba61605 100644
--- a/chart/templates/reverse-proxy/deployment.yaml
+++ b/chart/templates/reverse-proxy/deployment.yaml
@@ -53,8 +52,0 @@ spec:
- - name: static-files
- configMap:
- name: "{{ include "name" . }}-reverse-proxy"
- defaultMode: 420
- optional: false
- items:
- - key: "openapi.json"
- path: "openapi.json"
diff --git a/chart/values.yaml b/chart/values.yaml
index 7e39215a..fbffde0b 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -171 +171 @@ worker:
- # the number of hearbeats a job must have missed to be considered a zombie job.
+ # the number of heartbeats a job must have missed to be considered a zombie job.
@@ -393 +393 @@ reverseProxy:
- openapiFile: "static-files/openapi.json"
+ openapiFile: "docs/source/openapi.json"
diff --git a/chart/static-files/openapi.json b/docs/source/openapi.json
similarity index 100%
rename from chart/static-files/openapi.json
rename to docs/source/openapi.json
diff --git a/e2e/tests/utils.py b/e2e/tests/utils.py
index b426b188..22c1ef29 100644
--- a/e2e/tests/utils.py
+++ b/e2e/tests/utils.py
@@ -92 +92 @@ def get_openapi_body_example(path: str, status: int, example_name: str) -> Any:
- openapi_filename = root / "chart" / "static-files" / "openapi.json"
+ openapi_filename = root / "docs" / "source" / "openapi.json"
diff --git a/services/reverse-proxy/README.md b/services/reverse-proxy/README.md
index f0881b1f..10763b36 100644
--- a/services/reverse-proxy/README.md
+++ b/services/reverse-proxy/README.md
@@ -17,0 +18,2 @@ It takes various environment variables, all of them are mandatory:
+- `CACHED_ASSETS_DIRECTORY`: the directory that contains the static cached assets, eg `/cached-assets`
+- `OPENAPI_FILE`: the path to the OpenAPI file, eg `docs/source/openapi.json`
@@ -29 +30,0 @@ The image requires three directories to be mounted (from volumes):
-- `/staticfiles` (read-only): the directory that contains the static files (`openapi.json`).
diff --git a/tools/docker-compose-datasets-server.yml b/tools/docker-compose-datasets-server.yml
index ad056681..60048ef1 100644
--- a/tools/docker-compose-datasets-server.yml
+++ b/tools/docker-compose-datasets-server.yml
@@ -10 +9,0 @@ services:
- - ../chart/static-files/openapi.json:/static-files/openapi.json:ro
@@ -15,0 +15 @@ services:
+ OPENAPI_FILE: ${OPENAPI_FILE-docs/source/openapi.json}
diff --git a/tools/docker-compose-dev-datasets-server.yml b/tools/docker-compose-dev-datasets-server.yml
index f2d798cb..0f736ae1 100644
--- a/tools/docker-compose-dev-datasets-server.yml
+++ b/tools/docker-compose-dev-datasets-server.yml
@@ -10 +9,0 @@ services:
- - ../chart/static-files/openapi.json:/static-files/openapi.json:ro
@@ -15,0 +15 @@ services:
+ OPENAPI_FILE: ${OPENAPI_FILE-docs/source/openapi.json}
|
|
7b51acfce7005839a50a113d561f526eeef043ad
|
Andrea Francis Soria Jimenez
| 2023-08-11T16:59:03 |
Incremental cache metrics (#1658)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 85f8182d..9cc593d0 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -160 +160 @@ cacheMaintenance:
- # ^ allowed values are {backfill, collect-metrics,skip}
+ # ^ allowed values are {backfill, collect-queue-metrics, collect-cache-metrics,skip}
@@ -192,2 +192,2 @@ backfill:
-metricsCollector:
- action: "collect-metrics"
+queueMetricsCollector:
+ action: "collect-queue-metrics"
@@ -204,0 +205,13 @@ metricsCollector:
+cacheMetricsCollector:
+ action: "collect-cache-metrics"
+ schedule: "*/10 * * * *"
+ # every ten minutes first time, then it will be changed to default
+ nodeSelector: {}
+ resources:
+ requests:
+ cpu: 1
+ limits:
+ cpu: 1
+ memory: "512Mi"
+ tolerations: []
+
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index 18e30b9d..397545aa 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -151,2 +151,2 @@ backfill:
-metricsCollector:
- action: "collect-metrics"
+queueMetricsCollector:
+ action: "collect-queue-metrics"
@@ -163,0 +164,13 @@ metricsCollector:
+cacheMetricsCollector:
+ action: "collect-cache-metrics"
+ schedule: "*/10 * * * *"
+ # every ten minutes first time, then it will be changed to default
+ nodeSelector: {}
+ resources:
+ requests:
+ cpu: 1
+ limits:
+ cpu: 1
+ memory: "512Mi"
+ tolerations: []
+
diff --git a/chart/templates/_common/_helpers.tpl b/chart/templates/_common/_helpers.tpl
index b71d65da..0502d52c 100644
--- a/chart/templates/_common/_helpers.tpl
+++ b/chart/templates/_common/_helpers.tpl
@@ -93 +93 @@ app.kubernetes.io/component: "{{ include "name" . }}-cache-maintenance"
-{{- define "labels.metricsCollector" -}}
+{{- define "labels.queueMetricsCollector" -}}
@@ -95 +95,6 @@ app.kubernetes.io/component: "{{ include "name" . }}-cache-maintenance"
-app.kubernetes.io/component: "{{ include "name" . }}-metrics-collector"
+app.kubernetes.io/component: "{{ include "name" . }}-queue-metrics-collector"
+{{- end -}}
+
+{{- define "labels.cacheMetricsCollector" -}}
+{{ include "hf.labels.commons" . }}
+app.kubernetes.io/component: "{{ include "name" . }}-cache-metrics-collector"
diff --git a/chart/templates/cron-jobs/cache-metrics-collector/_container.tpl b/chart/templates/cron-jobs/cache-metrics-collector/_container.tpl
new file mode 100644
index 00000000..54894e3f
--- /dev/null
+++ b/chart/templates/cron-jobs/cache-metrics-collector/_container.tpl
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+{{- define "containerCacheMetricsCollector" -}}
+- name: "{{ include "name" . }}-cache-metrics-collector"
+ image: {{ include "jobs.cacheMaintenance.image" . }}
+ imagePullPolicy: {{ .Values.images.pullPolicy }}
+ securityContext:
+ allowPrivilegeEscalation: false
+ resources: {{ toYaml .Values.cacheMetricsCollector.resources | nindent 4 }}
+ env:
+ {{ include "envLog" . | nindent 2 }}
+ {{ include "envCache" . | nindent 2 }}
+ {{ include "envQueue" . | nindent 2 }}
+ {{ include "envCommon" . | nindent 2 }}
+ {{ include "envMetrics" . | nindent 2 }}
+ - name: CACHE_MAINTENANCE_ACTION
+ value: {{ .Values.cacheMetricsCollector.action | quote }}
+{{- end -}}
diff --git a/chart/templates/cron-jobs/cache-metrics-collector/job.yaml b/chart/templates/cron-jobs/cache-metrics-collector/job.yaml
new file mode 100644
index 00000000..2b2d03e9
--- /dev/null
+++ b/chart/templates/cron-jobs/cache-metrics-collector/job.yaml
@@ -0,0 +1,25 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+{{- if and .Values.images.jobs.cacheMaintenance .Values.cacheMetricsCollector.enabled}}
+apiVersion: batch/v1
+kind: CronJob
+metadata:
+ labels: {{ include "labels.cacheMetricsCollector" . | nindent 4 }}
+ name: "{{ include "name" . }}-job-cache-metrics-collector"
+ namespace: {{ .Release.Namespace }}
+spec:
+ schedule: {{ .Values.cacheMetricsCollector.schedule | quote }}
+ jobTemplate:
+ spec:
+ ttlSecondsAfterFinished: 3600
+ template:
+ spec:
+ restartPolicy: OnFailure
+ {{- include "dnsConfig" . | nindent 10 }}
+ {{- include "image.imagePullSecrets" . | nindent 6 }}
+ nodeSelector: {{ toYaml .Values.cacheMetricsCollector.nodeSelector | nindent 12 }}
+ tolerations: {{ toYaml .Values.cacheMetricsCollector.tolerations | nindent 12 }}
+ containers: {{ include "containerCacheMetricsCollector" . | nindent 12 }}
+ securityContext: {{ include "securityContext" . | nindent 12 }}
+{{- end}}
diff --git a/chart/templates/cron-jobs/metrics-collector/job.yaml b/chart/templates/cron-jobs/metrics-collector/job.yaml
deleted file mode 100644
index 0e56996f..00000000
--- a/chart/templates/cron-jobs/metrics-collector/job.yaml
+++ /dev/null
@@ -1,25 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2022 The HuggingFace Authors.
-
-{{- if .Values.images.jobs.cacheMaintenance }}
-apiVersion: batch/v1
-kind: CronJob
-metadata:
- labels: {{ include "labels.metricsCollector" . | nindent 4 }}
- name: "{{ include "name" . }}-job-metrics-collector"
- namespace: {{ .Release.Namespace }}
-spec:
- schedule: {{ .Values.metricsCollector.schedule | quote }}
- jobTemplate:
- spec:
- ttlSecondsAfterFinished: 300
- template:
- spec:
- restartPolicy: OnFailure
- {{- include "dnsConfig" . | nindent 10 }}
- {{- include "image.imagePullSecrets" . | nindent 6 }}
- nodeSelector: {{ toYaml .Values.metricsCollector.nodeSelector | nindent 12 }}
- tolerations: {{ toYaml .Values.metricsCollector.tolerations | nindent 12 }}
- containers: {{ include "containerMetricsCollector" . | nindent 12 }}
- securityContext: {{ include "securityContext" . | nindent 12 }}
-{{- end}}
diff --git a/chart/templates/cron-jobs/metrics-collector/_container.tpl b/chart/templates/cron-jobs/queue-metrics-collector/_container.tpl
similarity index 67%
rename from chart/templates/cron-jobs/metrics-collector/_container.tpl
rename to chart/templates/cron-jobs/queue-metrics-collector/_container.tpl
index eb13d893..4b1d557b 100644
--- a/chart/templates/cron-jobs/metrics-collector/_container.tpl
+++ b/chart/templates/cron-jobs/queue-metrics-collector/_container.tpl
@@ -4,2 +4,2 @@
-{{- define "containerMetricsCollector" -}}
-- name: "{{ include "name" . }}-metrics-collector"
+{{- define "containerQueueMetricsCollector" -}}
+- name: "{{ include "name" . }}-queue-metrics-collector"
@@ -10 +10 @@
- resources: {{ toYaml .Values.metricsCollector.resources | nindent 4 }}
+ resources: {{ toYaml .Values.queueMetricsCollector.resources | nindent 4 }}
@@ -18 +18 @@
- value: {{ .Values.metricsCollector.action | quote }}
+ value: {{ .Values.queueMetricsCollector.action | quote }}
diff --git a/chart/templates/cron-jobs/queue-metrics-collector/job.yaml b/chart/templates/cron-jobs/queue-metrics-collector/job.yaml
new file mode 100644
index 00000000..1260d45a
--- /dev/null
+++ b/chart/templates/cron-jobs/queue-metrics-collector/job.yaml
@@ -0,0 +1,25 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2022 The HuggingFace Authors.
+
+{{- if and .Values.images.jobs.cacheMaintenance .Values.queueMetricsCollector.enabled}}
+apiVersion: batch/v1
+kind: CronJob
+metadata:
+ labels: {{ include "labels.queueMetricsCollector" . | nindent 4 }}
+ name: "{{ include "name" . }}-job-queue-metrics-collector"
+ namespace: {{ .Release.Namespace }}
+spec:
+ schedule: {{ .Values.queueMetricsCollector.schedule | quote }}
+ jobTemplate:
+ spec:
+ ttlSecondsAfterFinished: 300
+ template:
+ spec:
+ restartPolicy: OnFailure
+ {{- include "dnsConfig" . | nindent 10 }}
+ {{- include "image.imagePullSecrets" . | nindent 6 }}
+ nodeSelector: {{ toYaml .Values.queueMetricsCollector.nodeSelector | nindent 12 }}
+ tolerations: {{ toYaml .Values.queueMetricsCollector.tolerations | nindent 12 }}
+ containers: {{ include "containerQueueMetricsCollector" . | nindent 12 }}
+ securityContext: {{ include "securityContext" . | nindent 12 }}
+{{- end}}
diff --git a/chart/values.yaml b/chart/values.yaml
index 81cfd0cb..7e39215a 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -297 +297 @@ cacheMaintenance:
- # ^ allowed values are {skip,backfill,upgrade,collect-metrics}
+ # ^ allowed values are {skip,backfill,upgrade,collect-queue-metrics,collect-cache-metrics}
@@ -345,2 +345,3 @@ deleteIndexes:
-metricsCollector:
- action: "collect-metrics"
+queueMetricsCollector:
+ enabled: true
+ action: "collect-queue-metrics"
@@ -356,0 +358,13 @@ metricsCollector:
+
+cacheMetricsCollector:
+ enabled: true
+ action: "collect-cache-metrics"
+ schedule: "13 00 * * *"
+ nodeSelector: {}
+ resources:
+ requests:
+ cpu: 0
+ limits:
+ cpu: 0
+ tolerations: []
+
diff --git a/e2e/tests/test_31_admin_metrics.py b/e2e/tests/test_31_admin_metrics.py
index 5c753d5e..9503af49 100644
--- a/e2e/tests/test_31_admin_metrics.py
+++ b/e2e/tests/test_31_admin_metrics.py
@@ -34,3 +34 @@ def test_metrics() -> None:
- # the cache and queue metrics are computed by the background jobs. Here, in the e2e tests, we don't run them,
- # so we should not see any of these metrics.
-
+ # the queue metrics are computed by the background jobs. Here, in the e2e tests, we don't run them,
@@ -43,0 +42,3 @@ def test_metrics() -> None:
+
+ # the cache metrics are computed each time a job is processed
+ # they should exists at least for some of cache kinds
@@ -47 +48 @@ def test_metrics() -> None:
- assert not has_metric(
+ assert has_metric(
@@ -58 +59 @@ def test_metrics() -> None:
- ), f"assets_disk_usage - cache kind {cache_kind} found in {metrics}"
+ ), "assets_disk_usage"
diff --git a/jobs/cache_maintenance/src/cache_maintenance/cache_metrics.py b/jobs/cache_maintenance/src/cache_maintenance/cache_metrics.py
new file mode 100644
index 00000000..b325a70c
--- /dev/null
+++ b/jobs/cache_maintenance/src/cache_maintenance/cache_metrics.py
@@ -0,0 +1,29 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+
+from libcommon.simple_cache import (
+ CacheTotalMetricDocument,
+ get_responses_count_by_kind_status_and_error_code,
+)
+
+
+def collect_cache_metrics() -> None:
+ logging.info("collecting cache metrics")
+ for metric in get_responses_count_by_kind_status_and_error_code():
+ kind = metric["kind"]
+ http_status = metric["http_status"]
+ error_code = metric["error_code"]
+ new_total = metric["count"]
+
+ query_set = CacheTotalMetricDocument.objects(kind=kind, http_status=http_status, error_code=error_code)
+ current_metric = query_set.first()
+ if current_metric is not None:
+ current_total = current_metric.total
+ logging.info(
+ f"{kind=} {http_status=} {error_code=} current_total={current_total} new_total="
+ f"{new_total} difference={new_total-current_total}"
+ )
+ query_set.upsert_one(total=metric["count"])
+ logging.info("metrics have been collected")
diff --git a/jobs/cache_maintenance/src/cache_maintenance/main.py b/jobs/cache_maintenance/src/cache_maintenance/main.py
index b06fb7f7..5b17d7a1 100644
--- a/jobs/cache_maintenance/src/cache_maintenance/main.py
+++ b/jobs/cache_maintenance/src/cache_maintenance/main.py
@@ -17,0 +18 @@ from cache_maintenance.backfill import backfill_cache
+from cache_maintenance.cache_metrics import collect_cache_metrics
@@ -20 +21 @@ from cache_maintenance.delete_indexes import delete_indexes
-from cache_maintenance.metrics import collect_metrics
+from cache_maintenance.queue_metrics import collect_queue_metrics
@@ -26 +27 @@ def run_job() -> None:
- supported_actions = ["backfill", "collect-metrics", "delete-indexes", "skip"]
+ supported_actions = ["backfill", "collect-cache-metrics", "collect-queue-metrics", "delete-indexes", "skip"]
@@ -67,2 +68,4 @@ def run_job() -> None:
- elif action == "collect-metrics":
- collect_metrics(processing_graph=processing_graph)
+ elif action == "collect-queue-metrics":
+ collect_queue_metrics(processing_graph=processing_graph)
+ elif action == "collect-cache-metrics":
+ collect_cache_metrics()
diff --git a/jobs/cache_maintenance/src/cache_maintenance/metrics.py b/jobs/cache_maintenance/src/cache_maintenance/metrics.py
deleted file mode 100644
index 2aae8f11..00000000
--- a/jobs/cache_maintenance/src/cache_maintenance/metrics.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2022 The HuggingFace Authors.
-
-import logging
-
-from libcommon.metrics import CacheTotalMetricDocument, JobTotalMetricDocument
-from libcommon.processing_graph import ProcessingGraph
-from libcommon.queue import Queue
-from libcommon.simple_cache import get_responses_count_by_kind_status_and_error_code
-
-
-def collect_metrics(processing_graph: ProcessingGraph) -> None:
- logging.info("collecting jobs metrics")
- queue = Queue()
- for processing_step in processing_graph.get_processing_steps():
- for status, total in queue.get_jobs_count_by_status(job_type=processing_step.job_type).items():
- JobTotalMetricDocument.objects(queue=processing_step.job_type, status=status).upsert_one(total=total)
-
- logging.info("collecting cache metrics")
- for metric in get_responses_count_by_kind_status_and_error_code():
- CacheTotalMetricDocument.objects(
- kind=metric["kind"], http_status=metric["http_status"], error_code=metric["error_code"]
- ).upsert_one(total=metric["count"])
- logging.info("metrics have been collected")
diff --git a/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py b/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py
new file mode 100644
index 00000000..660445f9
--- /dev/null
+++ b/jobs/cache_maintenance/src/cache_maintenance/queue_metrics.py
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+
+from libcommon.metrics import JobTotalMetricDocument
+from libcommon.processing_graph import ProcessingGraph
+from libcommon.queue import Queue
+
+
+def collect_queue_metrics(processing_graph: ProcessingGraph) -> None:
+ logging.info("collecting jobs metrics")
+ queue = Queue()
+ for processing_step in processing_graph.get_processing_steps():
+ for status, total in queue.get_jobs_count_by_status(job_type=processing_step.job_type).items():
+ JobTotalMetricDocument.objects(queue=processing_step.job_type, status=status).upsert_one(total=total)
diff --git a/jobs/cache_maintenance/tests/test_collect_cache_metrics.py b/jobs/cache_maintenance/tests/test_collect_cache_metrics.py
new file mode 100644
index 00000000..238a035f
--- /dev/null
+++ b/jobs/cache_maintenance/tests/test_collect_cache_metrics.py
@@ -0,0 +1,37 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+from http import HTTPStatus
+
+from libcommon.simple_cache import CacheTotalMetricDocument, upsert_response
+
+from cache_maintenance.cache_metrics import collect_cache_metrics
+
+
+def test_collect_cache_metrics() -> None:
+ dataset = "test_dataset"
+ config = None
+ split = None
+ content = {"some": "content"}
+ kind = "kind"
+ upsert_response(
+ kind=kind,
+ dataset=dataset,
+ config=config,
+ split=split,
+ content=content,
+ http_status=HTTPStatus.OK,
+ )
+
+ collect_cache_metrics()
+
+ cache_metrics = CacheTotalMetricDocument.objects()
+ assert cache_metrics
+ assert len(cache_metrics) == 1
+
+ metric = cache_metrics.first()
+ assert metric is not None
+ assert metric.kind == kind
+ assert metric.error_code is None
+ assert metric.http_status == HTTPStatus.OK
+ assert metric.total == 1
diff --git a/jobs/cache_maintenance/tests/test_collect_metrics.py b/jobs/cache_maintenance/tests/test_collect_queue_metrics.py
similarity index 80%
rename from jobs/cache_maintenance/tests/test_collect_metrics.py
rename to jobs/cache_maintenance/tests/test_collect_queue_metrics.py
index 8811b02f..f8d3220e 100644
--- a/jobs/cache_maintenance/tests/test_collect_metrics.py
+++ b/jobs/cache_maintenance/tests/test_collect_queue_metrics.py
@@ -2 +2 @@
-# Copyright 2022 The HuggingFace Authors.
+# Copyright 2023 The HuggingFace Authors.
@@ -6 +6 @@ from http import HTTPStatus
-from libcommon.metrics import CacheTotalMetricDocument, JobTotalMetricDocument
+from libcommon.metrics import JobTotalMetricDocument
@@ -12 +12 @@ from libcommon.utils import Status
-from cache_maintenance.metrics import collect_metrics
+from cache_maintenance.queue_metrics import collect_queue_metrics
@@ -15 +15 @@ from cache_maintenance.metrics import collect_metrics
-def test_collect_metrics() -> None:
+def test_collect_queue_metrics() -> None:
@@ -44,5 +44 @@ def test_collect_metrics() -> None:
- collect_metrics(processing_graph=processing_graph)
-
- cache_metrics = CacheTotalMetricDocument.objects()
- assert cache_metrics
- assert len(cache_metrics) == 1
+ collect_queue_metrics(processing_graph=processing_graph)
diff --git a/jobs/mongodb_migration/src/mongodb_migration/collector.py b/jobs/mongodb_migration/src/mongodb_migration/collector.py
index 7430144b..e3278bb5 100644
--- a/jobs/mongodb_migration/src/mongodb_migration/collector.py
+++ b/jobs/mongodb_migration/src/mongodb_migration/collector.py
@@ -55,0 +56,3 @@ from mongodb_migration.migrations._20230705160600_queue_job_add_difficulty impor
+from mongodb_migration.migrations._20230811063600_cache_metrics_drop_collection import (
+ MigrationDropCacheMetricsCollection,
+)
@@ -247,0 +251 @@ class MigrationsCollector:
+ MigrationDropCacheMetricsCollection(version="20230811063600", description="drop cache metrics collection"),
diff --git a/jobs/mongodb_migration/src/mongodb_migration/migration.py b/jobs/mongodb_migration/src/mongodb_migration/migration.py
index 5175e640..b4e9fa77 100644
--- a/jobs/mongodb_migration/src/mongodb_migration/migration.py
+++ b/jobs/mongodb_migration/src/mongodb_migration/migration.py
@@ -8,0 +9 @@ from libcommon.constants import (
+ CACHE_METRICS_COLLECTION,
@@ -10 +10,0 @@ from libcommon.constants import (
- METRICS_COLLECTION_CACHE_TOTAL_METRIC,
@@ -72 +72 @@ class MetricsMigration(Migration):
- COLLECTION_CACHE_TOTAL_METRIC: str = METRICS_COLLECTION_CACHE_TOTAL_METRIC
+ COLLECTION_CACHE_TOTAL_METRIC: str = CACHE_METRICS_COLLECTION
diff --git a/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230811063600_cache_metrics_drop_collection.py b/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230811063600_cache_metrics_drop_collection.py
new file mode 100644
index 00000000..f025776b
--- /dev/null
+++ b/jobs/mongodb_migration/src/mongodb_migration/migrations/_20230811063600_cache_metrics_drop_collection.py
@@ -0,0 +1,29 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+
+from libcommon.constants import CACHE_METRICS_COLLECTION, METRICS_MONGOENGINE_ALIAS
+from mongoengine.connection import get_db
+
+from mongodb_migration.migration import IrreversibleMigrationError, Migration
+
+
+class MigrationDropCacheMetricsCollection(Migration):
+ def up(self) -> None:
+ # drop collection from metrics database, it will be recreated in cache database
+ logging.info(f"drop {CACHE_METRICS_COLLECTION} collection from {METRICS_MONGOENGINE_ALIAS}")
+
+ db = get_db(METRICS_MONGOENGINE_ALIAS)
+ db[CACHE_METRICS_COLLECTION].drop()
+
+ def down(self) -> None:
+ raise IrreversibleMigrationError("This migration does not support rollback")
+
+ def validate(self) -> None:
+ logging.info("check that collection does not exist")
+
+ db = get_db(METRICS_MONGOENGINE_ALIAS)
+ collections = db.list_collection_names() # type: ignore
+ if CACHE_METRICS_COLLECTION in collections:
+ raise ValueError(f"found collection with name {CACHE_METRICS_COLLECTION}")
diff --git a/jobs/mongodb_migration/tests/migrations/test_20230811063600_cache_metrics_drop_collection.py b/jobs/mongodb_migration/tests/migrations/test_20230811063600_cache_metrics_drop_collection.py
new file mode 100644
index 00000000..aac71e39
--- /dev/null
+++ b/jobs/mongodb_migration/tests/migrations/test_20230811063600_cache_metrics_drop_collection.py
@@ -0,0 +1,42 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+from libcommon.constants import CACHE_METRICS_COLLECTION, METRICS_MONGOENGINE_ALIAS
+from libcommon.resources import MongoResource
+from mongoengine.connection import get_db
+from pytest import raises
+
+from mongodb_migration.migration import IrreversibleMigrationError
+from mongodb_migration.migrations._20230811063600_cache_metrics_drop_collection import (
+ MigrationDropCacheMetricsCollection,
+)
+
+
+def test_drop_cache_metrics_collection(mongo_host: str) -> None:
+ with MongoResource(
+ database="test_drop_cache_metrics_collection", host=mongo_host, mongoengine_alias=METRICS_MONGOENGINE_ALIAS
+ ):
+ db = get_db(METRICS_MONGOENGINE_ALIAS)
+ db[CACHE_METRICS_COLLECTION].insert_many(
+ [
+ {
+ "kind": "kind",
+ "error_code": "UnexpectedError",
+ "http_status": 500,
+ "total": 1,
+ }
+ ]
+ )
+ assert db[CACHE_METRICS_COLLECTION].find_one({"kind": "kind"}) is not None
+ assert CACHE_METRICS_COLLECTION in db.list_collection_names() # type: ignore
+
+ migration = MigrationDropCacheMetricsCollection(
+ version="20230811063600", description="drop cache metrics collection"
+ )
+
+ migration.up()
+ assert db[CACHE_METRICS_COLLECTION].find_one({"kind": "kind"}) is None
+ assert CACHE_METRICS_COLLECTION not in db.list_collection_names() # type: ignore
+
+ with raises(IrreversibleMigrationError):
+ migration.down()
diff --git a/jobs/mongodb_migration/tests/test_deletion_migrations.py b/jobs/mongodb_migration/tests/test_deletion_migrations.py
index ba56516c..351a2247 100644
--- a/jobs/mongodb_migration/tests/test_deletion_migrations.py
+++ b/jobs/mongodb_migration/tests/test_deletion_migrations.py
@@ -5,0 +6 @@ from libcommon.constants import (
+ CACHE_METRICS_COLLECTION,
@@ -7 +7,0 @@ from libcommon.constants import (
- METRICS_COLLECTION_CACHE_TOTAL_METRIC,
@@ -92 +92 @@ def test_metrics_deletion_migration(mongo_host: str) -> None:
- db[METRICS_COLLECTION_CACHE_TOTAL_METRIC].insert_many([{"kind": cache_kind, "http_status": 400, "total": 0}])
+ db[CACHE_METRICS_COLLECTION].insert_many([{"kind": cache_kind, "http_status": 400, "total": 0}])
@@ -96 +96 @@ def test_metrics_deletion_migration(mongo_host: str) -> None:
- assert db[METRICS_COLLECTION_CACHE_TOTAL_METRIC].find_one(
+ assert db[CACHE_METRICS_COLLECTION].find_one(
@@ -111,3 +111 @@ def test_metrics_deletion_migration(mongo_host: str) -> None:
- assert not db[METRICS_COLLECTION_CACHE_TOTAL_METRIC].find_one(
- {"kind": cache_kind}
- ) # Ensure 0 records after deletion
+ assert not db[CACHE_METRICS_COLLECTION].find_one({"kind": cache_kind}) # Ensure 0 records after deletion
@@ -116 +114 @@ def test_metrics_deletion_migration(mongo_host: str) -> None:
- db[METRICS_COLLECTION_CACHE_TOTAL_METRIC].drop()
+ db[CACHE_METRICS_COLLECTION].drop()
diff --git a/libs/libcommon/src/libcommon/constants.py b/libs/libcommon/src/libcommon/constants.py
index a06be35d..5d7a7926 100644
--- a/libs/libcommon/src/libcommon/constants.py
+++ b/libs/libcommon/src/libcommon/constants.py
@@ -11 +11 @@ DUCKDB_INDEX_CACHE_APPNAME = "datasets_server_duckdb_index"
-METRICS_COLLECTION_CACHE_TOTAL_METRIC = "cacheTotalMetric"
+CACHE_METRICS_COLLECTION = "cacheTotalMetric"
diff --git a/libs/libcommon/src/libcommon/metrics.py b/libs/libcommon/src/libcommon/metrics.py
index b0833d61..520d2531 100644
--- a/libs/libcommon/src/libcommon/metrics.py
+++ b/libs/libcommon/src/libcommon/metrics.py
@@ -13 +12,0 @@ from libcommon.constants import (
- METRICS_COLLECTION_CACHE_TOTAL_METRIC,
@@ -63,26 +61,0 @@ class JobTotalMetricDocument(Document):
-class CacheTotalMetricDocument(Document):
- """Cache total metric in the mongoDB database, used to compute prometheus metrics.
-
- Args:
- kind (`str`): kind name
- http_status (`int`): cache http_status
- error_code (`str`): error code name
- total (`int`): total of jobs
- created_at (`datetime`): when the metric has been created.
- """
-
- id = ObjectIdField(db_field="_id", primary_key=True, default=ObjectId)
- kind = StringField(required=True)
- http_status = IntField(required=True)
- error_code = StringField()
- total = IntField(required=True, default=0)
- created_at = DateTimeField(default=get_datetime)
-
- meta = {
- "collection": METRICS_COLLECTION_CACHE_TOTAL_METRIC,
- "db_alias": METRICS_MONGOENGINE_ALIAS,
- "indexes": [("kind", "http_status", "error_code")],
- }
- objects = QuerySetManager["CacheTotalMetricDocument"]()
-
-
@@ -91 +63,0 @@ def _clean_metrics_database() -> None:
- CacheTotalMetricDocument.drop_collection() # type: ignore
diff --git a/libs/libcommon/src/libcommon/prometheus.py b/libs/libcommon/src/libcommon/prometheus.py
index 27fa882a..5c336bcc 100644
--- a/libs/libcommon/src/libcommon/prometheus.py
+++ b/libs/libcommon/src/libcommon/prometheus.py
@@ -19 +19,2 @@ from psutil import disk_usage
-from libcommon.metrics import CacheTotalMetricDocument, JobTotalMetricDocument
+from libcommon.metrics import JobTotalMetricDocument
+from libcommon.simple_cache import CacheTotalMetricDocument
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index 9a4d9ba5..1cd70304 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -39 +39,5 @@ from mongoengine.queryset.queryset import QuerySet
-from libcommon.constants import CACHE_COLLECTION_RESPONSES, CACHE_MONGOENGINE_ALIAS
+from libcommon.constants import (
+ CACHE_COLLECTION_RESPONSES,
+ CACHE_METRICS_COLLECTION,
+ CACHE_MONGOENGINE_ALIAS,
+)
@@ -117,0 +122,30 @@ class CachedResponseDocument(Document):
+DEFAULT_INCREASE_AMOUNT = 1
+DEFAULT_DECREASE_AMOUNT = -1
+
+
+class CacheTotalMetricDocument(Document):
+ """Cache total metric in the mongoDB database, used to compute prometheus metrics.
+
+ Args:
+ kind (`str`): kind name
+ http_status (`int`): cache http_status
+ error_code (`str`): error code name
+ total (`int`): total of jobs
+ created_at (`datetime`): when the metric has been created.
+ """
+
+ id = ObjectIdField(db_field="_id", primary_key=True, default=ObjectId)
+ kind = StringField(required=True)
+ http_status = IntField(required=True)
+ error_code = StringField()
+ total = IntField(required=True, default=0)
+ created_at = DateTimeField(default=get_datetime)
+
+ meta = {
+ "collection": CACHE_METRICS_COLLECTION,
+ "db_alias": CACHE_MONGOENGINE_ALIAS,
+ "indexes": [("kind", "http_status", "error_code")],
+ }
+ objects = QuerySetManager["CacheTotalMetricDocument"]()
+
+
@@ -129,0 +164,26 @@ class CacheEntryDoesNotExistError(DoesNotExist):
+def _update_metrics(kind: str, http_status: HTTPStatus, increase_by: int, error_code: Optional[str] = None) -> None:
+ CacheTotalMetricDocument.objects(kind=kind, http_status=http_status, error_code=error_code).upsert_one(
+ inc__total=increase_by
+ )
+
+
+def increase_metric(kind: str, http_status: HTTPStatus, error_code: Optional[str] = None) -> None:
+ CacheTotalMetricDocument.objects(kind=kind, http_status=http_status, error_code=error_code).upsert_one(
+ inc__total=DEFAULT_INCREASE_AMOUNT
+ )
+
+
+def decrease_metric(kind: str, http_status: HTTPStatus, error_code: Optional[str] = None) -> None:
+ CacheTotalMetricDocument.objects(kind=kind, http_status=http_status, error_code=error_code).upsert_one(
+ inc__total=DEFAULT_DECREASE_AMOUNT
+ )
+
+
+def decrease_metric_for_artifact(kind: str, dataset: str, config: Optional[str], split: Optional[str]) -> None:
+ try:
+ existing_cache = CachedResponseDocument.objects(kind=kind, dataset=dataset, config=config, split=split).get()
+ except DoesNotExist:
+ return
+ decrease_metric(kind=kind, http_status=existing_cache.http_status, error_code=existing_cache.error_code)
+
+
@@ -144,0 +205 @@ def upsert_response(
+ decrease_metric_for_artifact(kind=kind, dataset=dataset, config=config, split=split)
@@ -154,0 +216 @@ def upsert_response(
+ increase_metric(kind=kind, http_status=http_status, error_code=error_code)
@@ -186,0 +249 @@ def delete_response(
+ decrease_metric_for_artifact(kind=kind, dataset=dataset, config=config, split=split)
@@ -191 +254,4 @@ def delete_dataset_responses(dataset: str) -> Optional[int]:
- return CachedResponseDocument.objects(dataset=dataset).delete()
+ existing_cache = CachedResponseDocument.objects(dataset=dataset)
+ for cache in existing_cache:
+ decrease_metric(kind=cache.kind, http_status=cache.http_status, error_code=cache.error_code)
+ return existing_cache.delete()
@@ -816,0 +883 @@ def _clean_cache_database() -> None:
+ CacheTotalMetricDocument.drop_collection() # type: ignore
diff --git a/libs/libcommon/tests/test_prometheus.py b/libs/libcommon/tests/test_prometheus.py
index 59c6a524..821502e3 100644
--- a/libs/libcommon/tests/test_prometheus.py
+++ b/libs/libcommon/tests/test_prometheus.py
@@ -10 +10 @@ import pytest
-from libcommon.metrics import CacheTotalMetricDocument, JobTotalMetricDocument
+from libcommon.metrics import JobTotalMetricDocument
@@ -21 +21,2 @@ from libcommon.prometheus import (
-from libcommon.resources import MetricsMongoResource
+from libcommon.resources import CacheMongoResource, MetricsMongoResource
+from libcommon.simple_cache import CacheTotalMetricDocument
@@ -141 +142 @@ def get_metrics() -> Metrics:
-def test_cache_metrics(metrics_mongo_resource: MetricsMongoResource) -> None:
+def test_cache_metrics(cache_mongo_resource: CacheMongoResource) -> None:
diff --git a/libs/libcommon/tests/test_simple_cache.py b/libs/libcommon/tests/test_simple_cache.py
index 25b5b377..64688b4d 100644
--- a/libs/libcommon/tests/test_simple_cache.py
+++ b/libs/libcommon/tests/test_simple_cache.py
@@ -18,0 +19 @@ from libcommon.simple_cache import (
+ CacheTotalMetricDocument,
@@ -93,0 +95,6 @@ def test_insert_null_values() -> None:
+def assert_metric(http_status: HTTPStatus, error_code: Optional[str], kind: str, total: int) -> None:
+ metric = CacheTotalMetricDocument.objects(http_status=http_status, error_code=error_code, kind=kind).first()
+ assert metric is not None
+ assert metric.total == total
+
+
@@ -107,0 +115,2 @@ def test_upsert_response(config: Optional[str], split: Optional[str]) -> None:
+
+ assert CacheTotalMetricDocument.objects().count() == 0
@@ -128,0 +138,2 @@ def test_upsert_response(config: Optional[str], split: Optional[str]) -> None:
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind, total=1)
+
@@ -133,0 +145,2 @@ def test_upsert_response(config: Optional[str], split: Optional[str]) -> None:
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind, total=1)
+
@@ -139,0 +153,2 @@ def test_upsert_response(config: Optional[str], split: Optional[str]) -> None:
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind, total=2)
+
@@ -140,0 +156,3 @@ def test_upsert_response(config: Optional[str], split: Optional[str]) -> None:
+
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind, total=0)
+
@@ -158,0 +177,3 @@ def test_upsert_response(config: Optional[str], split: Optional[str]) -> None:
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind, total=0)
+ assert_metric(http_status=HTTPStatus.BAD_REQUEST, error_code=error_code, kind=kind, total=1)
+
@@ -177,0 +199,2 @@ def test_delete_response() -> None:
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind, total=2)
+
@@ -180,0 +204 @@ def test_delete_response() -> None:
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind, total=1)
@@ -195,0 +220,2 @@ def test_delete_dataset_responses() -> None:
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind_a, total=2)
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind_b, total=1)
@@ -199,0 +226,2 @@ def test_delete_dataset_responses() -> None:
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind_a, total=1)
+ assert_metric(http_status=HTTPStatus.OK, error_code=None, kind=kind_b, total=0)
|
|
8cf67846ac6a54d8e903b70af34d4f0b7d7c7a6f
|
Andrea Francis Soria Jimenez
| 2023-08-11T16:38:57 |
Adding temporaly StreamingRowsError to backfill (#1669)
|
diff --git a/libs/libcommon/src/libcommon/constants.py b/libs/libcommon/src/libcommon/constants.py
index 5add9c73..a06be35d 100644
--- a/libs/libcommon/src/libcommon/constants.py
+++ b/libs/libcommon/src/libcommon/constants.py
@@ -55 +55 @@ PARQUET_REVISION = "refs/convert/parquet"
-ERROR_CODES_TO_RETRY = "CreateCommitError,LockedDatasetTimeoutError"
+ERROR_CODES_TO_RETRY = "CreateCommitError,LockedDatasetTimeoutError,StreamingRowsError"
|
|
4c189b1cfb51dd19d7c448478d51d0dcf2db86d1
|
Albert Villanova del Moral
| 2023-08-10T14:51:04 |
Revert fix authentication with DownloadConfig (#1660)
|
diff --git a/services/worker/src/worker/job_runners/config/parquet_and_info.py b/services/worker/src/worker/job_runners/config/parquet_and_info.py
index d1f9713d..2bcb2b9b 100644
--- a/services/worker/src/worker/job_runners/config/parquet_and_info.py
+++ b/services/worker/src/worker/job_runners/config/parquet_and_info.py
@@ -1255 +1255 @@ def compute_config_parquet_and_info_response(
- download_config = DownloadConfig(delete_extracted=True, token=hf_token)
+ download_config = DownloadConfig(delete_extracted=True)
diff --git a/services/worker/src/worker/job_runners/config/split_names_from_streaming.py b/services/worker/src/worker/job_runners/config/split_names_from_streaming.py
index a327922d..174e182a 100644
--- a/services/worker/src/worker/job_runners/config/split_names_from_streaming.py
+++ b/services/worker/src/worker/job_runners/config/split_names_from_streaming.py
@@ -7 +7 @@ from typing import List, Optional
-from datasets import DownloadConfig, get_dataset_split_names
+from datasets import get_dataset_split_names
@@ -64,3 +64 @@ def compute_split_names_from_streaming_response(
- for split in get_dataset_split_names(
- path=dataset, config_name=config, download_config=DownloadConfig(token=hf_token)
- )
+ for split in get_dataset_split_names(path=dataset, config_name=config, token=hf_token)
diff --git a/services/worker/src/worker/job_runners/split/first_rows_from_streaming.py b/services/worker/src/worker/job_runners/split/first_rows_from_streaming.py
index 47ec8ca5..1b12989a 100644
--- a/services/worker/src/worker/job_runners/split/first_rows_from_streaming.py
+++ b/services/worker/src/worker/job_runners/split/first_rows_from_streaming.py
@@ -10 +9,0 @@ from datasets import (
- DownloadConfig,
@@ -151 +150 @@ def compute_first_rows_response(
- download_config=DownloadConfig(token=hf_token),
+ token=hf_token,
@@ -166 +164,0 @@ def compute_first_rows_response(
- download_config=DownloadConfig(token=hf_token),
diff --git a/services/worker/src/worker/utils.py b/services/worker/src/worker/utils.py
index 8706f9ff..17d4875c 100644
--- a/services/worker/src/worker/utils.py
+++ b/services/worker/src/worker/utils.py
@@ -224 +224 @@ def get_rows(
- download_config = DownloadConfig(delete_extracted=True, token=token)
+ download_config = DownloadConfig(delete_extracted=True)
|
|
5a938cbed2f63b1e5a3be3014cfea6e1816a19ce
|
Albert Villanova del Moral
| 2023-08-09T15:56:26 |
Update datasets to 2.14.4 (#1653)
|
diff --git a/front/admin_ui/poetry.lock b/front/admin_ui/poetry.lock
index 67c60823..8175cc67 100644
--- a/front/admin_ui/poetry.lock
+++ b/front/admin_ui/poetry.lock
@@ -529 +529 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -535,2 +535,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -1249 +1249 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
diff --git a/jobs/cache_maintenance/poetry.lock b/jobs/cache_maintenance/poetry.lock
index 68c240bb..b8c99a44 100644
--- a/jobs/cache_maintenance/poetry.lock
+++ b/jobs/cache_maintenance/poetry.lock
@@ -579 +579 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -585,2 +585,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -1027 +1027 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
diff --git a/jobs/mongodb_migration/poetry.lock b/jobs/mongodb_migration/poetry.lock
index 68c240bb..b8c99a44 100644
--- a/jobs/mongodb_migration/poetry.lock
+++ b/jobs/mongodb_migration/poetry.lock
@@ -579 +579 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -585,2 +585,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -1027 +1027 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
diff --git a/libs/libapi/poetry.lock b/libs/libapi/poetry.lock
index 7cda531f..4910b9d0 100644
--- a/libs/libapi/poetry.lock
+++ b/libs/libapi/poetry.lock
@@ -624 +624 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -630,2 +630,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -1084 +1084 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
diff --git a/libs/libcommon/poetry.lock b/libs/libcommon/poetry.lock
index fc4917e9..6063c80d 100644
--- a/libs/libcommon/poetry.lock
+++ b/libs/libcommon/poetry.lock
@@ -579 +579 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -585,2 +585,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -3014 +3014 @@ python-versions = "3.9.15"
-content-hash = "182da244596a37965e340ccc74e8d96962a671992e6386b48f9dd6f71de5d06f"
+content-hash = "773105f2f756f133cfc4e06a19d64ef578cc928ed3988327702dc1085a6e3562"
diff --git a/libs/libcommon/pyproject.toml b/libs/libcommon/pyproject.toml
index 8da0eb7e..3aab48b3 100644
--- a/libs/libcommon/pyproject.toml
+++ b/libs/libcommon/pyproject.toml
@@ -10 +10 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
diff --git a/services/admin/poetry.lock b/services/admin/poetry.lock
index f216681b..30469c08 100644
--- a/services/admin/poetry.lock
+++ b/services/admin/poetry.lock
@@ -579 +579 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -585,2 +585,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -1085 +1085 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
diff --git a/services/api/poetry.lock b/services/api/poetry.lock
index 868f4d75..cb264642 100644
--- a/services/api/poetry.lock
+++ b/services/api/poetry.lock
@@ -625 +625 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -631,2 +631,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -1175 +1175 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
diff --git a/services/rows/poetry.lock b/services/rows/poetry.lock
index f0f09307..d53ae174 100644
--- a/services/rows/poetry.lock
+++ b/services/rows/poetry.lock
@@ -624 +624 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -630,2 +630,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -1186 +1186 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
diff --git a/services/worker/poetry.lock b/services/worker/poetry.lock
index a40bd384..0794737b 100644
--- a/services/worker/poetry.lock
+++ b/services/worker/poetry.lock
@@ -910 +910 @@ name = "datasets"
-version = "2.14.3"
+version = "2.14.4"
@@ -916,2 +916,2 @@ files = [
- {file = "datasets-2.14.3-py3-none-any.whl", hash = "sha256:8da5868e55e7c1f0bf3356913a14a9926fe5eca66663691886b95bc9c9b065f0"},
- {file = "datasets-2.14.3.tar.gz", hash = "sha256:5fb20465a990cf7946f961884ba46fec19cdc95b1cd2cad2a7b87c8d183b02e1"},
+ {file = "datasets-2.14.4-py3-none-any.whl", hash = "sha256:29336bd316a7d827ccd4da2236596279b20ca2ac78f64c04c9483da7cbc2459b"},
+ {file = "datasets-2.14.4.tar.gz", hash = "sha256:ef29c2b5841de488cd343cfc26ab979bff77efa4d2285af51f1ad7db5c46a83b"},
@@ -1839 +1839 @@ appdirs = "^1.4.4"
-datasets = {version = "^2.14.3", extras = ["audio", "vision"]}
+datasets = {version = "^2.14.4", extras = ["audio", "vision"]}
|
|
4a70eba13cc7c17be613aad88450c713c51c059f
|
Sylvain Lesage
| 2023-08-08T18:45:45 |
fix: 🐛 TypeError: can't subtract offset-naive and offset-aware (#1651)
|
diff --git a/tools/stale.py b/tools/stale.py
index 50fb7b52..3dc5c7ff 100644
--- a/tools/stale.py
+++ b/tools/stale.py
@@ -10 +10 @@ Copied from https://github.com/huggingface/transformers
-from datetime import datetime as dt, timezone
+from datetime import datetime as dt
@@ -30 +30 @@ def main():
- now = dt.now(timezone.utc)
+ now = dt.utcnow()
|
|
4c0d3609ca2263ee5640b04602709f31b421f931
|
Albert Villanova del Moral
| 2023-08-08T15:20:31 |
Replace deprecated use_auth_token with token (#1578)
|
diff --git a/chart/static-files/openapi.json b/chart/static-files/openapi.json
index 378ae7c9..a6c7c14b 100644
--- a/chart/static-files/openapi.json
+++ b/chart/static-files/openapi.json
@@ -1248 +1248 @@
- " File \"/src/services/worker/src/worker/responses/splits.py\", line 38, in <listcomp>\n for split in get_dataset_split_names(dataset, config, use_auth_token=hf_token)\n",
+ " File \"/src/services/worker/src/worker/responses/splits.py\", line 38, in <listcomp>\n for split in get_dataset_split_names(dataset, config, token=hf_token)\n",
@@ -1264 +1264 @@
- " File \"/src/services/worker/src/worker/responses/splits.py\", line 37, in get_dataset_split_full_names\n for config in get_dataset_config_names(dataset, use_auth_token=hf_token)\n",
+ " File \"/src/services/worker/src/worker/responses/splits.py\", line 37, in get_dataset_split_full_names\n for config in get_dataset_config_names(dataset, token=hf_token)\n",
@@ -2016 +2016 @@
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/streaming.py\", line 67, in wrapper\n return function(*args, use_auth_token=use_auth_token, **kwargs)\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/streaming.py\", line 67, in wrapper\n return function(*args, token=token, **kwargs)\n",
@@ -2063 +2063 @@
- " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 787, in _iter_from_urlpath\n with xopen(urlpath, \"rb\", use_auth_token=use_auth_token) as f:\n",
+ " File \"/src/services/worker/.venv/lib/python3.9/site-packages/datasets/download/streaming_download_manager.py\", line 787, in _iter_from_urlpath\n with xopen(urlpath, \"rb\", token=token) as f:\n",
diff --git a/services/worker/src/worker/job_runners/config/parquet_and_info.py b/services/worker/src/worker/job_runners/config/parquet_and_info.py
index 206e04cf..d1f9713d 100644
--- a/services/worker/src/worker/job_runners/config/parquet_and_info.py
+++ b/services/worker/src/worker/job_runners/config/parquet_and_info.py
@@ -297,3 +297 @@ def raise_if_requires_manual_download(
- StreamingDownloadManager(
- base_path=builder.base_path, download_config=DownloadConfig(use_auth_token=hf_token)
- )
+ StreamingDownloadManager(base_path=builder.base_path, download_config=DownloadConfig(token=hf_token))
@@ -394 +392 @@ def _request_size(url: str, hf_token: Optional[str] = None) -> Optional[int]:
- headers = get_authentication_headers_for_url(url, use_auth_token=hf_token)
+ headers = get_authentication_headers_for_url(url, token=hf_token)
@@ -438 +436 @@ def _is_too_big_from_external_data_files(
- base_path=builder.base_path, download_config=DownloadConfig(use_auth_token=hf_token)
+ base_path=builder.base_path, download_config=DownloadConfig(token=hf_token)
@@ -883 +881 @@ def stream_convert_to_parquet(
- download_config=DownloadConfig(use_auth_token=builder.use_auth_token, storage_options=builder.storage_options),
+ download_config=DownloadConfig(token=builder.token, storage_options=builder.storage_options),
@@ -1263 +1261 @@ def compute_config_parquet_and_info_response(
- use_auth_token=hf_token,
+ token=hf_token,
diff --git a/services/worker/src/worker/job_runners/dataset/config_names.py b/services/worker/src/worker/job_runners/dataset/config_names.py
index 51b7a4e1..338bc440 100644
--- a/services/worker/src/worker/job_runners/dataset/config_names.py
+++ b/services/worker/src/worker/job_runners/dataset/config_names.py
@@ -5 +5 @@ import logging
-from typing import List, Optional, Union
+from typing import List, Optional
@@ -51 +50,0 @@ def compute_config_names_response(
- use_auth_token: Union[bool, str, None] = hf_token if hf_token is not None else False
@@ -56 +55 @@ def compute_config_names_response(
- for config in sorted(get_dataset_config_names(path=dataset, use_auth_token=use_auth_token))
+ for config in sorted(get_dataset_config_names(path=dataset, token=hf_token))
diff --git a/services/worker/src/worker/job_runners/split/first_rows_from_streaming.py b/services/worker/src/worker/job_runners/split/first_rows_from_streaming.py
index 546dc8f9..47ec8ca5 100644
--- a/services/worker/src/worker/job_runners/split/first_rows_from_streaming.py
+++ b/services/worker/src/worker/job_runners/split/first_rows_from_streaming.py
@@ -6 +6 @@ from pathlib import Path
-from typing import List, Optional, Union
+from typing import List, Optional
@@ -144 +143,0 @@ def compute_first_rows_response(
- use_auth_token: Union[bool, str, None] = hf_token if hf_token is not None else False
@@ -168 +167 @@ def compute_first_rows_response(
- use_auth_token=use_auth_token,
+ token=hf_token,
@@ -219 +218 @@ def compute_first_rows_response(
- use_auth_token=use_auth_token,
+ token=hf_token,
diff --git a/services/worker/src/worker/job_runners/split/opt_in_out_urls_scan_from_streaming.py b/services/worker/src/worker/job_runners/split/opt_in_out_urls_scan_from_streaming.py
index 2ccb4443..f6de5d33 100644
--- a/services/worker/src/worker/job_runners/split/opt_in_out_urls_scan_from_streaming.py
+++ b/services/worker/src/worker/job_runners/split/opt_in_out_urls_scan_from_streaming.py
@@ -7 +7 @@ from pathlib import Path
-from typing import Any, List, Optional, Tuple, Union
+from typing import Any, List, Optional, Tuple
@@ -154 +153,0 @@ def compute_opt_in_out_urls_scan_response(
- use_auth_token: Union[bool, str, None] = hf_token if hf_token is not None else False
@@ -176 +175 @@ def compute_opt_in_out_urls_scan_response(
- use_auth_token=use_auth_token,
+ token=hf_token,
@@ -210 +209 @@ def compute_opt_in_out_urls_scan_response(
- use_auth_token=use_auth_token,
+ token=hf_token,
diff --git a/services/worker/src/worker/utils.py b/services/worker/src/worker/utils.py
index 5fbd3443..8706f9ff 100644
--- a/services/worker/src/worker/utils.py
+++ b/services/worker/src/worker/utils.py
@@ -221 +221 @@ def get_rows(
- use_auth_token: Union[bool, str, None] = False,
+ token: Union[bool, str, None] = False,
@@ -224 +224 @@ def get_rows(
- download_config = DownloadConfig(delete_extracted=True, token=use_auth_token)
+ download_config = DownloadConfig(delete_extracted=True, token=token)
@@ -231 +231 @@ def get_rows(
- use_auth_token=use_auth_token,
+ token=token,
@@ -257 +257 @@ def get_rows_or_raise(
- use_auth_token: Union[bool, str, None],
+ token: Union[bool, str, None],
@@ -269 +269 @@ def get_rows_or_raise(
- use_auth_token=use_auth_token,
+ token=token,
@@ -294 +294 @@ def get_rows_or_raise(
- use_auth_token=use_auth_token,
+ token=token,
@@ -310 +310 @@ def get_parquet_file(url: str, fs: HTTPFileSystem, hf_token: Optional[str]) -> P
- headers = get_authentication_headers_for_url(url, use_auth_token=hf_token)
+ headers = get_authentication_headers_for_url(url, token=hf_token)
|
|
aeae747b89e596abab2e65250e78940cebf1c3e9
|
Andrea Francis Soria Jimenez
| 2023-08-08T13:57:02 |
feat: add search field to /is-valid (#1618)
|
diff --git a/e2e/tests/test_15_is_valid.py b/e2e/tests/test_15_is_valid.py
index 712b0cb4..007d9f0c 100644
--- a/e2e/tests/test_15_is_valid.py
+++ b/e2e/tests/test_15_is_valid.py
@@ -5 +5 @@ from .fixtures.hub import DatasetRepos
-from .utils import get
+from .utils import get, get_default_config_split
@@ -13,0 +14,8 @@ def test_is_valid_after_datasets_processed(hf_dataset_repos_csv_data: DatasetRep
+ config, split = get_default_config_split()
+
+ split_response = get(f"/is-valid?dataset={public}&config={config}&split={split}")
+ assert split_response.status_code == 200, f"{split_response.status_code} - {split_response.text}"
+
+ config_response = get(f"/is-valid?dataset={public}&config={config}")
+ assert config_response.status_code == 200, f"{config_response.status_code} - {config_response.text}"
+
diff --git a/libs/libcommon/src/libcommon/config.py b/libs/libcommon/src/libcommon/config.py
index 7db3fc80..56be859b 100644
--- a/libs/libcommon/src/libcommon/config.py
+++ b/libs/libcommon/src/libcommon/config.py
@@ -12,0 +13 @@ from libcommon.constants import (
+ PROCESSING_STEP_CONFIG_IS_VALID_VERSION,
@@ -31,0 +33 @@ from libcommon.constants import (
+ PROCESSING_STEP_SPLIT_IS_VALID_VERSION,
@@ -312,3 +314,3 @@ class ProcessingGraphConfig:
- "dataset-is-valid": {
- "input_type": "dataset",
- # special case: triggered by all the steps that have "enables_preview" or "enables_viewer"
+ "split-is-valid": {
+ "input_type": "split",
+ # special case: triggered by all the steps that have enables_preview/enables_viewer/enables_search
@@ -318,0 +321,20 @@ class ProcessingGraphConfig:
+ "split-duckdb-index",
+ ],
+ "job_runner_version": PROCESSING_STEP_SPLIT_IS_VALID_VERSION,
+ "difficulty": 20,
+ },
+ "config-is-valid": {
+ "input_type": "config",
+ "triggered_by": [
+ "config-split-names-from-streaming",
+ "config-split-names-from-info",
+ "split-is-valid",
+ ],
+ "job_runner_version": PROCESSING_STEP_CONFIG_IS_VALID_VERSION,
+ "difficulty": 20,
+ },
+ "dataset-is-valid": {
+ "input_type": "dataset",
+ "triggered_by": [
+ "dataset-config-names",
+ "config-is-valid",
@@ -363,0 +386 @@ class ProcessingGraphConfig:
+ "enables_search": True,
diff --git a/libs/libcommon/src/libcommon/constants.py b/libs/libcommon/src/libcommon/constants.py
index 0813a6d2..5add9c73 100644
--- a/libs/libcommon/src/libcommon/constants.py
+++ b/libs/libcommon/src/libcommon/constants.py
@@ -25,0 +26 @@ PROCESSING_STEP_CONFIG_INFO_VERSION = 2
+PROCESSING_STEP_CONFIG_IS_VALID_VERSION = 1
@@ -35 +36 @@ PROCESSING_STEP_DATASET_INFO_VERSION = 2
-PROCESSING_STEP_DATASET_IS_VALID_VERSION = 4
+PROCESSING_STEP_DATASET_IS_VALID_VERSION = 5
@@ -43,0 +45 @@ PROCESSING_STEP_SPLIT_IMAGE_URL_COLUMNS_VERSION = 1
+PROCESSING_STEP_SPLIT_IS_VALID_VERSION = 1
diff --git a/libs/libcommon/src/libcommon/processing_graph.py b/libs/libcommon/src/libcommon/processing_graph.py
index 0a04a70c..9d6d14cf 100644
--- a/libs/libcommon/src/libcommon/processing_graph.py
+++ b/libs/libcommon/src/libcommon/processing_graph.py
@@ -55,0 +56 @@ class ProcessingStepSpecification(TypedDict, total=False):
+ enables_search: Literal[True]
@@ -146,0 +148 @@ class ProcessingGraph:
+ _processing_steps_enables_search: List[ProcessingStep] = field(init=False)
@@ -192,0 +195 @@ class ProcessingGraph:
+ enables_search=specification.get("enables_search", False),
@@ -236,0 +240,5 @@ class ProcessingGraph:
+ self._processing_steps_enables_search = [
+ self._processing_steps[processing_step_name]
+ for (processing_step_name, required) in _nx_graph.nodes(data="enables_search")
+ if required
+ ]
@@ -412,0 +421,12 @@ class ProcessingGraph:
+ def get_processing_steps_enables_search(self) -> List[ProcessingStep]:
+ """
+ Get the processing steps that enable the dataset split search.
+
+ The returned processing steps are copies of the original ones, so that they can be modified without affecting
+ the original ones.
+
+ Returns:
+ List[ProcessingStep]: The list of processing steps that enable the dataset viewer
+ """
+ return copy_processing_steps_list(self._processing_steps_enables_search)
+
diff --git a/libs/libcommon/src/libcommon/simple_cache.py b/libs/libcommon/src/libcommon/simple_cache.py
index c99e8a00..9a4d9ba5 100644
--- a/libs/libcommon/src/libcommon/simple_cache.py
+++ b/libs/libcommon/src/libcommon/simple_cache.py
@@ -476,2 +476,9 @@ def get_valid_datasets(kind: str) -> Set[str]:
-def is_valid_for_kinds(dataset: str, kinds: List[str]) -> bool:
- return CachedResponseDocument.objects(dataset=dataset, kind__in=kinds, http_status=HTTPStatus.OK).count() > 0
+def has_any_successful_response(
+ kinds: List[str], dataset: str, config: Optional[str] = None, split: Optional[str] = None
+) -> bool:
+ return (
+ CachedResponseDocument.objects(
+ dataset=dataset, config=config, split=split, kind__in=kinds, http_status=HTTPStatus.OK
+ ).count()
+ > 0
+ )
diff --git a/libs/libcommon/tests/test_backfill_on_real_graph.py b/libs/libcommon/tests/test_backfill_on_real_graph.py
index 5cb1cf36..13cb97bb 100644
--- a/libs/libcommon/tests/test_backfill_on_real_graph.py
+++ b/libs/libcommon/tests/test_backfill_on_real_graph.py
@@ -158,0 +159,2 @@ def test_plan_job_creation_and_termination() -> None:
+ "config-is-valid,dataset,revision,config1",
+ "config-is-valid,dataset,revision,config2",
@@ -181 +183 @@ def test_plan_job_creation_and_termination() -> None:
- tasks=["CreateJobs,16"],
+ tasks=["CreateJobs,18"],
diff --git a/libs/libcommon/tests/test_processing_graph.py b/libs/libcommon/tests/test_processing_graph.py
index 57949655..c00cf7e4 100644
--- a/libs/libcommon/tests/test_processing_graph.py
+++ b/libs/libcommon/tests/test_processing_graph.py
@@ -75,0 +76 @@ def graph() -> ProcessingGraph:
+ "dataset-is-valid",
@@ -98,0 +100 @@ def graph() -> ProcessingGraph:
+ "config-is-valid",
@@ -110,0 +113 @@ def graph() -> ProcessingGraph:
+ "config-is-valid",
@@ -133 +136 @@ def graph() -> ProcessingGraph:
- ["dataset-is-valid", "split-image-url-columns"],
+ ["split-is-valid", "split-image-url-columns"],
@@ -139 +142 @@ def graph() -> ProcessingGraph:
- ["dataset-is-valid", "split-image-url-columns"],
+ ["split-is-valid", "split-image-url-columns"],
@@ -184 +187 @@ def graph() -> ProcessingGraph:
- ["dataset-is-valid", "dataset-size"],
+ ["split-is-valid", "dataset-size"],
@@ -198,3 +201,2 @@ def graph() -> ProcessingGraph:
- "config-size",
- "split-first-rows-from-parquet",
- "split-first-rows-from-streaming",
+ "config-is-valid",
+ "dataset-config-names",
@@ -212,0 +215,3 @@ def graph() -> ProcessingGraph:
+ "config-is-valid",
+ "split-is-valid",
+ "split-duckdb-index",
@@ -307 +312 @@ def graph() -> ProcessingGraph:
- [],
+ ["split-is-valid"],
@@ -351,0 +357,5 @@ def test_default_graph_enables_viewer(graph: ProcessingGraph) -> None:
+def test_default_graph_enables_search(graph: ProcessingGraph) -> None:
+ enables_search = ["split-duckdb-index"]
+ assert_lists_are_equal(graph.get_processing_steps_enables_search(), enables_search)
+
+
diff --git a/libs/libcommon/tests/test_simple_cache.py b/libs/libcommon/tests/test_simple_cache.py
index fe354769..25b5b377 100644
--- a/libs/libcommon/tests/test_simple_cache.py
+++ b/libs/libcommon/tests/test_simple_cache.py
@@ -34 +34 @@ from libcommon.simple_cache import (
- is_valid_for_kinds,
+ has_any_successful_response,
@@ -270,2 +270,2 @@ def test_get_valid_dataset_names_only_invalid_responses() -> None:
-def test_is_valid_for_kinds_empty() -> None:
- assert not is_valid_for_kinds(dataset="dataset", kinds=[])
+def test_has_any_successful_response_empty() -> None:
+ assert not has_any_successful_response(dataset="dataset", kinds=[])
@@ -274 +274 @@ def test_is_valid_for_kinds_empty() -> None:
-def test_is_valid_for_kinds_two_valid_datasets() -> None:
+def test_has_any_successful_response_two_valid_datasets() -> None:
@@ -281,4 +281,4 @@ def test_is_valid_for_kinds_two_valid_datasets() -> None:
- assert is_valid_for_kinds(dataset=dataset_a, kinds=[kind])
- assert is_valid_for_kinds(dataset=dataset_b, kinds=[kind])
- assert not is_valid_for_kinds(dataset=dataset_b, kinds=[other_kind])
- assert is_valid_for_kinds(dataset=dataset_b, kinds=[kind, other_kind])
+ assert has_any_successful_response(dataset=dataset_a, kinds=[kind])
+ assert has_any_successful_response(dataset=dataset_b, kinds=[kind])
+ assert not has_any_successful_response(dataset=dataset_b, kinds=[other_kind])
+ assert has_any_successful_response(dataset=dataset_b, kinds=[kind, other_kind])
@@ -287 +287 @@ def test_is_valid_for_kinds_two_valid_datasets() -> None:
-def test_is_valid_for_kinds_two_valid_kinds() -> None:
+def test_has_any_successful_response_two_valid_kinds() -> None:
@@ -293 +293 @@ def test_is_valid_for_kinds_two_valid_kinds() -> None:
- assert is_valid_for_kinds(dataset=dataset, kinds=[kind_a, kind_b])
+ assert has_any_successful_response(dataset=dataset, kinds=[kind_a, kind_b])
@@ -296,2 +296,3 @@ def test_is_valid_for_kinds_two_valid_kinds() -> None:
-def test_is_valid_for_kinds_at_least_one_valid_response() -> None:
- kind = "test_kind"
+def test_has_any_successful_response_at_least_one_valid_response() -> None:
+ kind_a = "test_kind_a"
+ kind_b = "test_kind_b"
@@ -299,3 +300,2 @@ def test_is_valid_for_kinds_at_least_one_valid_response() -> None:
- config_a = "test_config_a"
- config_b = "test_config_b"
- upsert_response(kind=kind, dataset=dataset, config=config_a, content={}, http_status=HTTPStatus.OK)
+ config = "test_config"
+ upsert_response(kind=kind_a, dataset=dataset, config=config, content={}, http_status=HTTPStatus.OK)
@@ -303 +303 @@ def test_is_valid_for_kinds_at_least_one_valid_response() -> None:
- kind=kind, dataset=dataset, config=config_b, content={}, http_status=HTTPStatus.INTERNAL_SERVER_ERROR
+ kind=kind_b, dataset=dataset, config=config, content={}, http_status=HTTPStatus.INTERNAL_SERVER_ERROR
@@ -305 +305 @@ def test_is_valid_for_kinds_at_least_one_valid_response() -> None:
- assert is_valid_for_kinds(dataset=dataset, kinds=[kind])
+ assert has_any_successful_response(dataset=dataset, config=config, kinds=[kind_a, kind_b])
@@ -308 +308 @@ def test_is_valid_for_kinds_at_least_one_valid_response() -> None:
-def test_is_valid_for_kinds_only_invalid_responses() -> None:
+def test_has_any_successful_response_only_invalid_responses() -> None:
@@ -319 +319 @@ def test_is_valid_for_kinds_only_invalid_responses() -> None:
- assert not is_valid_for_kinds(dataset=dataset, kinds=[kind])
+ assert not has_any_successful_response(dataset=dataset, kinds=[kind])
diff --git a/services/api/src/api/config.py b/services/api/src/api/config.py
index b38defd0..3521e8d1 100644
--- a/services/api/src/api/config.py
+++ b/services/api/src/api/config.py
@@ -79,0 +80,2 @@ class EndpointConfig:
+ "config": ["config-is-valid"],
+ "split": ["split-is-valid"],
diff --git a/services/api/tests/routes/test_endpoint.py b/services/api/tests/routes/test_endpoint.py
index aff251b6..2e1335c1 100644
--- a/services/api/tests/routes/test_endpoint.py
+++ b/services/api/tests/routes/test_endpoint.py
@@ -78,0 +79,10 @@ def test_endpoints_definition() -> None:
+ is_valid = definition["/is-valid"]
+ assert is_valid is not None
+ assert sorted(list(is_valid)) == ["config", "dataset", "split"]
+ assert is_valid["dataset"] is not None
+ assert is_valid["config"] is not None
+ assert is_valid["split"] is not None
+ assert len(is_valid["dataset"]) == 1 # Only has one processing step
+ assert len(is_valid["config"]) == 1 # Only has one processing step
+ assert len(is_valid["split"]) == 1 # Only has one processing step
+
diff --git a/services/worker/src/worker/dtos.py b/services/worker/src/worker/dtos.py
index 9ee8f203..d5fd3bde 100644
--- a/services/worker/src/worker/dtos.py
+++ b/services/worker/src/worker/dtos.py
@@ -172 +172 @@ class DatasetInfoResponse(TypedDict):
-class DatasetIsValidResponse(TypedDict):
+class IsValidResponse(TypedDict):
@@ -174,0 +175 @@ class DatasetIsValidResponse(TypedDict):
+ search: bool
diff --git a/services/worker/src/worker/job_runner_factory.py b/services/worker/src/worker/job_runner_factory.py
index 5fc6907d..5c79b92f 100644
--- a/services/worker/src/worker/job_runner_factory.py
+++ b/services/worker/src/worker/job_runner_factory.py
@@ -14,0 +15 @@ from worker.job_runners.config.info import ConfigInfoJobRunner
+from worker.job_runners.config.is_valid import ConfigIsValidJobRunner
@@ -47,0 +49 @@ from worker.job_runners.split.image_url_columns import SplitImageUrlColumnsJobRu
+from worker.job_runners.split.is_valid import SplitIsValidJobRunner
@@ -184,0 +187,13 @@ class JobRunnerFactory(BaseJobRunnerFactory):
+ if job_type == SplitIsValidJobRunner.get_job_type():
+ return SplitIsValidJobRunner(
+ job_info=job_info,
+ processing_step=processing_step,
+ processing_graph=self.processing_graph,
+ app_config=self.app_config,
+ )
+ if job_type == ConfigIsValidJobRunner.get_job_type():
+ return ConfigIsValidJobRunner(
+ job_info=job_info,
+ processing_step=processing_step,
+ app_config=self.app_config,
+ )
@@ -189 +203,0 @@ class JobRunnerFactory(BaseJobRunnerFactory):
- processing_graph=self.processing_graph,
@@ -252,0 +267,2 @@ class JobRunnerFactory(BaseJobRunnerFactory):
+ SplitIsValidJobRunner.get_job_type(),
+ ConfigIsValidJobRunner.get_job_type(),
diff --git a/services/worker/src/worker/job_runners/config/is_valid.py b/services/worker/src/worker/job_runners/config/is_valid.py
new file mode 100644
index 00000000..f69e1cc9
--- /dev/null
+++ b/services/worker/src/worker/job_runners/config/is_valid.py
@@ -0,0 +1,93 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+from http import HTTPStatus
+from typing import Tuple
+
+from libcommon.constants import PROCESSING_STEP_CONFIG_IS_VALID_VERSION
+from libcommon.exceptions import PreviousStepFormatError
+from libcommon.simple_cache import (
+ CacheEntryDoesNotExistError,
+ get_previous_step_or_raise,
+ get_response,
+)
+
+from worker.dtos import IsValidResponse, JobResult
+from worker.job_runners.config.config_job_runner import ConfigJobRunner
+
+
+def compute_is_valid_response(dataset: str, config: str) -> Tuple[IsValidResponse, float]:
+ """
+ Get the response of /is-valid for one specific dataset config on huggingface.co.
+
+ A dataset config is valid if any of the artifacts for any of the
+ steps is valid.
+ Args:
+ dataset (`str`):
+ A namespace (user or an organization) and a repo name separated
+ by a `/`.
+ config (`str`):
+ A configuration name.
+ Returns:
+ `Tuple[IsValidResponse, float]`: The response (viewer, preview, search) and the progress.
+ """
+ logging.info(f"get is-valid response for {dataset=} {config=}")
+
+ split_names_response = get_previous_step_or_raise(
+ kinds=["config-split-names-from-streaming", "config-split-names-from-info"],
+ dataset=dataset,
+ config=config,
+ )
+ content = split_names_response.response["content"]
+ if "splits" not in content:
+ raise PreviousStepFormatError("Previous step did not return the expected content: 'splits'.")
+
+ preview = False
+ viewer = False
+ search = False
+ try:
+ total = 0
+ pending = 0
+ for split_item in content["splits"]:
+ split = split_item["split"]
+ total += 1
+ try:
+ response = get_response(kind="split-is-valid", dataset=dataset, config=config, split=split)
+ except CacheEntryDoesNotExistError:
+ logging.debug("No response found in previous step for this dataset: 'split-is-valid'.")
+ pending += 1
+ continue
+ if response["http_status"] != HTTPStatus.OK:
+ logging.debug(f"Previous step gave an error: {response['http_status']}.")
+ continue
+ split_is_valid_content = response["content"]
+ preview = preview or split_is_valid_content["preview"]
+ viewer = viewer or split_is_valid_content["viewer"]
+ search = search or split_is_valid_content["search"]
+ except Exception as e:
+ raise PreviousStepFormatError("Previous step did not return the expected content.", e) from e
+
+ progress = (total - pending) / total if total else 1.0
+ return (
+ IsValidResponse(
+ preview=preview,
+ viewer=viewer,
+ search=search,
+ ),
+ progress,
+ )
+
+
+class ConfigIsValidJobRunner(ConfigJobRunner):
+ @staticmethod
+ def get_job_type() -> str:
+ return "config-is-valid"
+
+ @staticmethod
+ def get_job_runner_version() -> int:
+ return PROCESSING_STEP_CONFIG_IS_VALID_VERSION
+
+ def compute(self) -> JobResult:
+ response_content, progress = compute_is_valid_response(dataset=self.dataset, config=self.config)
+ return JobResult(response_content, progress=progress)
diff --git a/services/worker/src/worker/job_runners/dataset/is_valid.py b/services/worker/src/worker/job_runners/dataset/is_valid.py
index caf65b0a..40610419 100644
--- a/services/worker/src/worker/job_runners/dataset/is_valid.py
+++ b/services/worker/src/worker/job_runners/dataset/is_valid.py
@@ -2 +2 @@
-# Copyright 2022 The HuggingFace Authors.
+# Copyright 2023 The HuggingFace Authors.
@@ -4,0 +5,2 @@ import logging
+from http import HTTPStatus
+from typing import Tuple
@@ -7,3 +9,6 @@ from libcommon.constants import PROCESSING_STEP_DATASET_IS_VALID_VERSION
-from libcommon.processing_graph import ProcessingGraph, ProcessingStep
-from libcommon.simple_cache import is_valid_for_kinds
-from libcommon.utils import JobInfo
+from libcommon.exceptions import PreviousStepFormatError
+from libcommon.simple_cache import (
+ CacheEntryDoesNotExistError,
+ get_previous_step_or_raise,
+ get_response,
+)
@@ -11,2 +16 @@ from libcommon.utils import JobInfo
-from worker.config import AppConfig
-from worker.dtos import CompleteJobResult, DatasetIsValidResponse, JobResult
+from worker.dtos import IsValidResponse, JobResult
@@ -16 +20 @@ from worker.job_runners.dataset.dataset_job_runner import DatasetJobRunner
-def compute_is_valid_response(dataset: str, processing_graph: ProcessingGraph) -> DatasetIsValidResponse:
+def compute_is_valid_response(dataset: str) -> Tuple[IsValidResponse, float]:
@@ -29,3 +32,0 @@ def compute_is_valid_response(dataset: str, processing_graph: ProcessingGraph) -
- processing_graph (`ProcessingGraph`):
- The processing graph. In particular, it must provide the list of
- processing steps that enable the viewer and the preview.
@@ -33 +34 @@ def compute_is_valid_response(dataset: str, processing_graph: ProcessingGraph) -
- `DatasetIsValidResponse`: The response (viewer, preview).
+ `Tuple[IsValidResponse, float]`: The response (viewer, preview, search) and the progress.
@@ -35 +36 @@ def compute_is_valid_response(dataset: str, processing_graph: ProcessingGraph) -
- logging.info(f"get is-valid response for dataset={dataset}")
+ logging.info(f"get is-valid response for {dataset=}")
@@ -37,6 +38,29 @@ def compute_is_valid_response(dataset: str, processing_graph: ProcessingGraph) -
- viewer = is_valid_for_kinds(
- dataset=dataset, kinds=[step.cache_kind for step in processing_graph.get_processing_steps_enables_viewer()]
- )
- preview = is_valid_for_kinds(
- dataset=dataset, kinds=[step.cache_kind for step in processing_graph.get_processing_steps_enables_preview()]
- )
+ config_names_response = get_previous_step_or_raise(kinds=["dataset-config-names"], dataset=dataset)
+ content = config_names_response.response["content"]
+ if "config_names" not in content:
+ raise PreviousStepFormatError("Previous step did not return the expected content: 'config_names'.")
+
+ preview = False
+ viewer = False
+ search = False
+ try:
+ total = 0
+ pending = 0
+ for config_item in content["config_names"]:
+ config = config_item["config"]
+ total += 1
+ try:
+ response = get_response(kind="config-is-valid", dataset=dataset, config=config)
+ except CacheEntryDoesNotExistError:
+ logging.debug("No response found in previous step for this dataset: 'config-is-valid'.")
+ pending += 1
+ continue
+ if response["http_status"] != HTTPStatus.OK:
+ logging.debug(f"Previous step gave an error: {response['http_status']}.")
+ continue
+ config_is_valid_content = response["content"]
+ preview = preview or config_is_valid_content["preview"]
+ viewer = viewer or config_is_valid_content["viewer"]
+ search = search or config_is_valid_content["search"]
+ except Exception as e:
+ raise PreviousStepFormatError("Previous step did not return the expected content.", e) from e
@@ -44 +68,10 @@ def compute_is_valid_response(dataset: str, processing_graph: ProcessingGraph) -
- return DatasetIsValidResponse({"viewer": viewer, "preview": preview})
+ progress = (total - pending) / total if total else 1.0
+
+ return (
+ IsValidResponse(
+ preview=preview,
+ viewer=viewer,
+ search=search,
+ ),
+ progress,
+ )
@@ -56,14 +88,0 @@ class DatasetIsValidJobRunner(DatasetJobRunner):
- def __init__(
- self,
- job_info: JobInfo,
- app_config: AppConfig,
- processing_step: ProcessingStep,
- processing_graph: ProcessingGraph,
- ) -> None:
- super().__init__(
- job_info=job_info,
- app_config=app_config,
- processing_step=processing_step,
- )
- self.processing_graph = processing_graph
-
@@ -71,4 +90,2 @@ class DatasetIsValidJobRunner(DatasetJobRunner):
- if self.dataset is None:
- raise ValueError("dataset is required")
- response_content = compute_is_valid_response(dataset=self.dataset, processing_graph=self.processing_graph)
- return CompleteJobResult(response_content)
+ response_content, progress = compute_is_valid_response(dataset=self.dataset)
+ return JobResult(response_content, progress=progress)
diff --git a/services/worker/src/worker/job_runners/split/is_valid.py b/services/worker/src/worker/job_runners/split/is_valid.py
new file mode 100644
index 00000000..61baa4eb
--- /dev/null
+++ b/services/worker/src/worker/job_runners/split/is_valid.py
@@ -0,0 +1,90 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+import logging
+
+from libcommon.constants import PROCESSING_STEP_SPLIT_IS_VALID_VERSION
+from libcommon.processing_graph import ProcessingGraph, ProcessingStep
+from libcommon.simple_cache import has_any_successful_response
+from libcommon.utils import JobInfo
+
+from worker.config import AppConfig
+from worker.dtos import CompleteJobResult, IsValidResponse, JobResult
+from worker.job_runners.split.split_job_runner import SplitJobRunner
+
+
+def compute_is_valid_response(
+ dataset: str, config: str, split: str, processing_graph: ProcessingGraph
+) -> IsValidResponse:
+ """
+ Get the response of /is-valid for one specific dataset split on huggingface.co.
+
+
+ A dataset split is valid if any of the artifacts for any of the
+ steps is valid.
+ Args:
+ dataset (`str`):
+ A namespace (user or an organization) and a repo name separated
+ by a `/`.
+ config (`str`):
+ A configuration name.
+ split (`str`):
+ A split name.
+ processing_graph (`ProcessingGraph`):
+ The processing graph. In particular, it must provide the list of
+ processing steps that enable the viewer and the preview.
+ Returns:
+ `IsValidResponse`: The response (viewer, preview, search).
+ """
+ logging.info(f"get is-valid response for dataset={dataset}")
+
+ viewer = has_any_successful_response(
+ dataset=dataset,
+ config=config,
+ split=None,
+ kinds=[step.cache_kind for step in processing_graph.get_processing_steps_enables_viewer()],
+ )
+ preview = has_any_successful_response(
+ dataset=dataset,
+ config=config,
+ split=split,
+ kinds=[step.cache_kind for step in processing_graph.get_processing_steps_enables_preview()],
+ )
+ search = has_any_successful_response(
+ dataset=dataset,
+ config=config,
+ split=split,
+ kinds=[step.cache_kind for step in processing_graph.get_processing_steps_enables_search()],
+ )
+ return IsValidResponse(viewer=viewer, preview=preview, search=search)
+
+
+class SplitIsValidJobRunner(SplitJobRunner):
+ @staticmethod
+ def get_job_type() -> str:
+ return "split-is-valid"
+
+ @staticmethod
+ def get_job_runner_version() -> int:
+ return PROCESSING_STEP_SPLIT_IS_VALID_VERSION
+
+ def __init__(
+ self,
+ job_info: JobInfo,
+ app_config: AppConfig,
+ processing_step: ProcessingStep,
+ processing_graph: ProcessingGraph,
+ ) -> None:
+ super().__init__(
+ job_info=job_info,
+ app_config=app_config,
+ processing_step=processing_step,
+ )
+ self.processing_graph = processing_graph
+
+ def compute(self) -> JobResult:
+ return CompleteJobResult(
+ compute_is_valid_response(
+ dataset=self.dataset, config=self.config, split=self.split, processing_graph=self.processing_graph
+ )
+ )
diff --git a/services/worker/tests/job_runners/config/test_is_valid.py b/services/worker/tests/job_runners/config/test_is_valid.py
new file mode 100644
index 00000000..387d80b6
--- /dev/null
+++ b/services/worker/tests/job_runners/config/test_is_valid.py
@@ -0,0 +1,189 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+from http import HTTPStatus
+from typing import Any, Callable, List
+
+import pytest
+from libcommon.processing_graph import ProcessingGraph
+from libcommon.resources import CacheMongoResource, QueueMongoResource
+from libcommon.simple_cache import upsert_response
+from libcommon.utils import Priority
+
+from worker.config import AppConfig
+from worker.job_runners.config.is_valid import ConfigIsValidJobRunner
+
+from ..utils import UpstreamResponse
+
+
[email protected](autouse=True)
+def prepare_and_clean_mongo(app_config: AppConfig) -> None:
+ # prepare the database before each test, and clean it afterwards
+ pass
+
+
+GetJobRunner = Callable[[str, str, AppConfig], ConfigIsValidJobRunner]
+
+DATASET = "dataset"
+CONFIG = "config"
+SPLIT_1 = "split1"
+SPLIT_2 = "split2"
+
+UPSTREAM_RESPONSE_SPLIT_NAMES: UpstreamResponse = UpstreamResponse(
+ kind="config-split-names-from-streaming",
+ dataset=DATASET,
+ config=CONFIG,
+ http_status=HTTPStatus.OK,
+ content={
+ "splits": [
+ {"dataset": DATASET, "config": CONFIG, "split": SPLIT_1},
+ {"dataset": DATASET, "config": CONFIG, "split": SPLIT_2},
+ ]
+ },
+)
+UPSTREAM_RESPONSE_SPLIT_1_OK: UpstreamResponse = UpstreamResponse(
+ kind="split-is-valid",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT_1,
+ http_status=HTTPStatus.OK,
+ content={"viewer": True, "preview": True, "search": True},
+)
+UPSTREAM_RESPONSE_SPLIT_1_OK_VIEWER: UpstreamResponse = UpstreamResponse(
+ kind="split-is-valid",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT_1,
+ http_status=HTTPStatus.OK,
+ content={"viewer": True, "preview": False, "search": False},
+)
+UPSTREAM_RESPONSE_SPLIT_2_OK_SEARCH: UpstreamResponse = UpstreamResponse(
+ kind="split-is-valid",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT_2,
+ http_status=HTTPStatus.OK,
+ content={"viewer": False, "preview": False, "search": True},
+)
+UPSTREAM_RESPONSE_SPLIT_2_OK: UpstreamResponse = UpstreamResponse(
+ kind="split-is-valid",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT_2,
+ http_status=HTTPStatus.OK,
+ content={"viewer": True, "preview": True, "search": True},
+)
+UPSTREAM_RESPONSE_SPLIT_1_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="split-is-valid",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT_1,
+ http_status=HTTPStatus.INTERNAL_SERVER_ERROR,
+ content={},
+)
+UPSTREAM_RESPONSE_SPLIT_2_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="split-is-valid",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT_2,
+ http_status=HTTPStatus.INTERNAL_SERVER_ERROR,
+ content={},
+)
+EXPECTED_COMPLETED_ALL_FALSE = (
+ {"viewer": False, "preview": False, "search": False},
+ 1.0,
+)
+EXPECTED_ALL_MIXED = (
+ {"viewer": True, "preview": False, "search": True},
+ 1.0,
+)
+EXPECTED_COMPLETED_ALL_TRUE = (
+ {"viewer": True, "preview": True, "search": True},
+ 1.0,
+)
+EXPECTED_PENDING_ALL_TRUE = (
+ {"viewer": True, "preview": True, "search": True},
+ 0.5,
+)
+EXPECTED_PENDING_ALL_FALSE = (
+ {"viewer": False, "preview": False, "search": False},
+ 0.0,
+)
+
+
[email protected]
+def get_job_runner(
+ cache_mongo_resource: CacheMongoResource,
+ queue_mongo_resource: QueueMongoResource,
+) -> GetJobRunner:
+ def _get_job_runner(
+ dataset: str,
+ config: str,
+ app_config: AppConfig,
+ ) -> ConfigIsValidJobRunner:
+ processing_step_name = ConfigIsValidJobRunner.get_job_type()
+ processing_graph = ProcessingGraph(app_config.processing_graph.specification)
+ return ConfigIsValidJobRunner(
+ job_info={
+ "type": ConfigIsValidJobRunner.get_job_type(),
+ "params": {
+ "dataset": dataset,
+ "config": config,
+ "split": None,
+ "revision": "revision",
+ },
+ "job_id": "job_id",
+ "priority": Priority.NORMAL,
+ "difficulty": 20,
+ },
+ app_config=app_config,
+ processing_step=processing_graph.get_processing_step(processing_step_name),
+ )
+
+ return _get_job_runner
+
+
[email protected](
+ "upstream_responses,expected",
+ [
+ (
+ [
+ UPSTREAM_RESPONSE_SPLIT_1_OK,
+ UPSTREAM_RESPONSE_SPLIT_2_OK,
+ ],
+ EXPECTED_COMPLETED_ALL_TRUE,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_SPLIT_1_OK,
+ ],
+ EXPECTED_PENDING_ALL_TRUE,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_SPLIT_1_ERROR,
+ UPSTREAM_RESPONSE_SPLIT_2_ERROR,
+ ],
+ EXPECTED_COMPLETED_ALL_FALSE,
+ ),
+ ([UPSTREAM_RESPONSE_SPLIT_1_OK_VIEWER, UPSTREAM_RESPONSE_SPLIT_2_OK_SEARCH], EXPECTED_ALL_MIXED),
+ (
+ [],
+ EXPECTED_PENDING_ALL_FALSE,
+ ),
+ ],
+)
+def test_compute(
+ app_config: AppConfig,
+ get_job_runner: GetJobRunner,
+ upstream_responses: List[UpstreamResponse],
+ expected: Any,
+) -> None:
+ dataset, config = DATASET, CONFIG
+ upsert_response(**UPSTREAM_RESPONSE_SPLIT_NAMES)
+ for upstream_response in upstream_responses:
+ upsert_response(**upstream_response)
+ job_runner = get_job_runner(dataset, config, app_config)
+ compute_result = job_runner.compute()
+ assert compute_result.content == expected[0]
+ assert compute_result.progress == expected[1]
diff --git a/services/worker/tests/job_runners/dataset/test_is_valid.py b/services/worker/tests/job_runners/dataset/test_is_valid.py
index fc9a9d66..3244f5e5 100644
--- a/services/worker/tests/job_runners/dataset/test_is_valid.py
+++ b/services/worker/tests/job_runners/dataset/test_is_valid.py
@@ -2 +2 @@
-# Copyright 2022 The HuggingFace Authors.
+# Copyright 2023 The HuggingFace Authors.
@@ -27,0 +28,2 @@ DATASET = "dataset"
+CONFIG_1 = "config1"
+CONFIG_2 = "config2"
@@ -29,2 +31,10 @@ DATASET = "dataset"
-UPSTREAM_RESPONSE_CONFIG_SIZE: UpstreamResponse = UpstreamResponse(
- kind="config-size", dataset=DATASET, config="config", http_status=HTTPStatus.OK, content={}
+UPSTREAM_RESPONSE_CONFIG_NAMES: UpstreamResponse = UpstreamResponse(
+ kind="dataset-config-names",
+ dataset=DATASET,
+ http_status=HTTPStatus.OK,
+ content={
+ "config_names": [
+ {"dataset": DATASET, "config": CONFIG_1},
+ {"dataset": DATASET, "config": CONFIG_2},
+ ]
+ },
@@ -32,2 +42,2 @@ UPSTREAM_RESPONSE_CONFIG_SIZE: UpstreamResponse = UpstreamResponse(
-UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET: UpstreamResponse = UpstreamResponse(
- kind="split-first-rows-from-parquet",
+UPSTREAM_RESPONSE_CONFIG_1_OK: UpstreamResponse = UpstreamResponse(
+ kind="config-is-valid",
@@ -35,2 +45 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET: UpstreamResponse = UpstreamResp
- config="config",
- split="split",
+ config=CONFIG_1,
@@ -38 +47 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET: UpstreamResponse = UpstreamResp
- content={},
+ content={"viewer": True, "preview": True, "search": True},
@@ -40,2 +49,2 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET: UpstreamResponse = UpstreamResp
-UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING: UpstreamResponse = UpstreamResponse(
- kind="split-first-rows-from-streaming",
+UPSTREAM_RESPONSE_CONFIG_1_OK_VIEWER: UpstreamResponse = UpstreamResponse(
+ kind="config-is-valid",
@@ -43,2 +52 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING: UpstreamResponse = UpstreamRe
- config="config",
- split="split",
+ config=CONFIG_1,
@@ -46 +54 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING: UpstreamResponse = UpstreamRe
- content={},
+ content={"viewer": True, "preview": False, "search": False},
@@ -48,2 +56,13 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING: UpstreamResponse = UpstreamRe
-UPSTREAM_RESPONSE_CONFIG_SIZE_ERROR: UpstreamResponse = UpstreamResponse(
- kind="config-size", dataset=DATASET, config="config", http_status=HTTPStatus.INTERNAL_SERVER_ERROR, content={}
+UPSTREAM_RESPONSE_CONFIG_2_OK_SEARCH: UpstreamResponse = UpstreamResponse(
+ kind="config-is-valid",
+ dataset=DATASET,
+ config=CONFIG_2,
+ http_status=HTTPStatus.OK,
+ content={"viewer": False, "preview": False, "search": True},
+)
+UPSTREAM_RESPONSE_CONFIG_2_OK: UpstreamResponse = UpstreamResponse(
+ kind="config-is-valid",
+ dataset=DATASET,
+ config=CONFIG_2,
+ http_status=HTTPStatus.OK,
+ content={"viewer": True, "preview": True, "search": True},
@@ -51,2 +70,2 @@ UPSTREAM_RESPONSE_CONFIG_SIZE_ERROR: UpstreamResponse = UpstreamResponse(
-UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR: UpstreamResponse = UpstreamResponse(
- kind="split-first-rows-from-parquet",
+UPSTREAM_RESPONSE_CONFIG_1_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="config-is-valid",
@@ -54,2 +73 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR: UpstreamResponse = Upstre
- config="config",
- split="split",
+ config=CONFIG_1,
@@ -59,2 +77,2 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR: UpstreamResponse = Upstre
-UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING_ERROR: UpstreamResponse = UpstreamResponse(
- kind="split-first-rows-from-streaming",
+UPSTREAM_RESPONSE_CONFIG_2_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="config-is-valid",
@@ -62,2 +80 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING_ERROR: UpstreamResponse = Upst
- config="config",
- split="split",
+ config=CONFIG_2,
@@ -67,2 +84,2 @@ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING_ERROR: UpstreamResponse = Upst
-EXPECTED_ERROR = (
- {"viewer": False, "preview": False},
+EXPECTED_COMPLETED_ALL_FALSE = (
+ {"viewer": False, "preview": False, "search": False},
@@ -71,2 +88,2 @@ EXPECTED_ERROR = (
-EXPECTED_VIEWER_OK = (
- {"viewer": True, "preview": False},
+EXPECTED_ALL_MIXED = (
+ {"viewer": True, "preview": False, "search": True},
@@ -75,2 +92,2 @@ EXPECTED_VIEWER_OK = (
-EXPECTED_PREVIEW_OK = (
- {"viewer": False, "preview": True},
+EXPECTED_COMPLETED_ALL_TRUE = (
+ {"viewer": True, "preview": True, "search": True},
@@ -79,3 +96,7 @@ EXPECTED_PREVIEW_OK = (
-EXPECTED_BOTH_OK = (
- {"viewer": True, "preview": True},
- 1.0,
+EXPECTED_PENDING_ALL_TRUE = (
+ {"viewer": True, "preview": True, "search": True},
+ 0.5,
+)
+EXPECTED_PENDING_ALL_FALSE = (
+ {"viewer": False, "preview": False, "search": False},
+ 0.0,
@@ -101 +121,0 @@ def get_job_runner(
- "revision": "revision",
@@ -103,0 +124 @@ def get_job_runner(
+ "revision": "revision",
@@ -107 +128 @@ def get_job_runner(
- "difficulty": 50,
+ "difficulty": 20,
@@ -111 +131,0 @@ def get_job_runner(
- processing_graph=processing_graph,
@@ -122,11 +142,2 @@ def get_job_runner(
- UPSTREAM_RESPONSE_CONFIG_SIZE,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING,
- ],
- EXPECTED_BOTH_OK,
- ),
- (
- [
- UPSTREAM_RESPONSE_CONFIG_SIZE_ERROR,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING,
+ UPSTREAM_RESPONSE_CONFIG_1_OK,
+ UPSTREAM_RESPONSE_CONFIG_2_OK,
@@ -134 +145 @@ def get_job_runner(
- EXPECTED_PREVIEW_OK,
+ EXPECTED_COMPLETED_ALL_TRUE,
@@ -138,2 +149 @@ def get_job_runner(
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING,
+ UPSTREAM_RESPONSE_CONFIG_1_OK,
@@ -141 +151 @@ def get_job_runner(
- EXPECTED_PREVIEW_OK,
+ EXPECTED_PENDING_ALL_TRUE,
@@ -145,3 +155,2 @@ def get_job_runner(
- UPSTREAM_RESPONSE_CONFIG_SIZE,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING,
+ UPSTREAM_RESPONSE_CONFIG_1_ERROR,
+ UPSTREAM_RESPONSE_CONFIG_2_ERROR,
@@ -149,23 +158 @@ def get_job_runner(
- EXPECTED_BOTH_OK,
- ),
- (
- [
- UPSTREAM_RESPONSE_CONFIG_SIZE,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING_ERROR,
- ],
- EXPECTED_VIEWER_OK,
- ),
- (
- [
- UPSTREAM_RESPONSE_CONFIG_SIZE,
- ],
- EXPECTED_VIEWER_OK,
- ),
- (
- [
- UPSTREAM_RESPONSE_CONFIG_SIZE_ERROR,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR,
- UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING_ERROR,
- ],
- EXPECTED_ERROR,
+ EXPECTED_COMPLETED_ALL_FALSE,
@@ -172,0 +160 @@ def get_job_runner(
+ ([UPSTREAM_RESPONSE_CONFIG_1_OK_VIEWER, UPSTREAM_RESPONSE_CONFIG_2_OK_SEARCH], EXPECTED_ALL_MIXED),
@@ -175 +163 @@ def get_job_runner(
- EXPECTED_ERROR,
+ EXPECTED_PENDING_ALL_FALSE,
@@ -185,0 +174 @@ def test_compute(
+ upsert_response(**UPSTREAM_RESPONSE_CONFIG_NAMES)
@@ -192,7 +180,0 @@ def test_compute(
-
-
-def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> None:
- dataset = "doesnotexist"
- job_runner = get_job_runner(dataset, app_config)
- compute_result = job_runner.compute()
- assert compute_result.content == {"viewer": False, "preview": False}
diff --git a/services/worker/tests/job_runners/split/test_is_valid.py b/services/worker/tests/job_runners/split/test_is_valid.py
new file mode 100644
index 00000000..4a8dda8a
--- /dev/null
+++ b/services/worker/tests/job_runners/split/test_is_valid.py
@@ -0,0 +1,231 @@
+# SPDX-License-Identifier: Apache-2.0
+# Copyright 2023 The HuggingFace Authors.
+
+from http import HTTPStatus
+from typing import Any, Callable, List
+
+import pytest
+from libcommon.processing_graph import ProcessingGraph
+from libcommon.resources import CacheMongoResource, QueueMongoResource
+from libcommon.simple_cache import upsert_response
+from libcommon.utils import Priority
+
+from worker.config import AppConfig
+from worker.job_runners.split.is_valid import SplitIsValidJobRunner
+
+from ..utils import UpstreamResponse
+
+
[email protected](autouse=True)
+def prepare_and_clean_mongo(app_config: AppConfig) -> None:
+ # prepare the database before each test, and clean it afterwards
+ pass
+
+
+GetJobRunner = Callable[[str, str, str, AppConfig], SplitIsValidJobRunner]
+
+DATASET = "dataset"
+CONFIG = "config"
+SPLIT = "split"
+
+UPSTREAM_RESPONSE_CONFIG_SIZE: UpstreamResponse = UpstreamResponse(
+ kind="config-size", dataset=DATASET, config=CONFIG, http_status=HTTPStatus.OK, content={}
+)
+UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET: UpstreamResponse = UpstreamResponse(
+ kind="split-first-rows-from-parquet",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT,
+ http_status=HTTPStatus.OK,
+ content={},
+)
+UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING: UpstreamResponse = UpstreamResponse(
+ kind="split-first-rows-from-streaming",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT,
+ http_status=HTTPStatus.OK,
+ content={},
+)
+UPSTREAM_RESPONSE_SPLIT_DUCKDB_INDEX: UpstreamResponse = UpstreamResponse(
+ kind="split-duckdb-index",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT,
+ http_status=HTTPStatus.OK,
+ content={},
+)
+UPSTREAM_RESPONSE_CONFIG_SIZE_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="config-size", dataset=DATASET, config=CONFIG, http_status=HTTPStatus.INTERNAL_SERVER_ERROR, content={}
+)
+UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="split-first-rows-from-parquet",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT,
+ http_status=HTTPStatus.INTERNAL_SERVER_ERROR,
+ content={},
+)
+UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="split-first-rows-from-streaming",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT,
+ http_status=HTTPStatus.INTERNAL_SERVER_ERROR,
+ content={},
+)
+UPSTREAM_RESPONSE_SPLIT_DUCKDB_INDEX_ERROR: UpstreamResponse = UpstreamResponse(
+ kind="split-duckdb-index",
+ dataset=DATASET,
+ config=CONFIG,
+ split=SPLIT,
+ http_status=HTTPStatus.INTERNAL_SERVER_ERROR,
+ content={},
+)
+EXPECTED_ERROR = (
+ {"viewer": False, "preview": False, "search": False},
+ 1.0,
+)
+EXPECTED_VIEWER_OK = (
+ {"viewer": True, "preview": False, "search": False},
+ 1.0,
+)
+EXPECTED_PREVIEW_OK = (
+ {"viewer": False, "preview": True, "search": False},
+ 1.0,
+)
+EXPECTED_SEARCH_OK = (
+ {"viewer": False, "preview": False, "search": True},
+ 1.0,
+)
+EXPECTED_ALL_OK = (
+ {"viewer": True, "preview": True, "search": True},
+ 1.0,
+)
+
+
[email protected]
+def get_job_runner(
+ cache_mongo_resource: CacheMongoResource,
+ queue_mongo_resource: QueueMongoResource,
+) -> GetJobRunner:
+ def _get_job_runner(
+ dataset: str,
+ config: str,
+ split: str,
+ app_config: AppConfig,
+ ) -> SplitIsValidJobRunner:
+ processing_step_name = SplitIsValidJobRunner.get_job_type()
+ processing_graph = ProcessingGraph(app_config.processing_graph.specification)
+ return SplitIsValidJobRunner(
+ job_info={
+ "type": SplitIsValidJobRunner.get_job_type(),
+ "params": {
+ "dataset": dataset,
+ "config": config,
+ "split": split,
+ "revision": "revision",
+ },
+ "job_id": "job_id",
+ "priority": Priority.NORMAL,
+ "difficulty": 20,
+ },
+ app_config=app_config,
+ processing_step=processing_graph.get_processing_step(processing_step_name),
+ processing_graph=processing_graph,
+ )
+
+ return _get_job_runner
+
+
[email protected](
+ "upstream_responses,expected",
+ [
+ (
+ [
+ UPSTREAM_RESPONSE_CONFIG_SIZE,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING,
+ UPSTREAM_RESPONSE_SPLIT_DUCKDB_INDEX,
+ ],
+ EXPECTED_ALL_OK,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_CONFIG_SIZE_ERROR,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING,
+ ],
+ EXPECTED_PREVIEW_OK,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING,
+ ],
+ EXPECTED_PREVIEW_OK,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_CONFIG_SIZE,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING,
+ UPSTREAM_RESPONSE_SPLIT_DUCKDB_INDEX,
+ ],
+ EXPECTED_ALL_OK,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_CONFIG_SIZE,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING_ERROR,
+ ],
+ EXPECTED_VIEWER_OK,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_CONFIG_SIZE,
+ ],
+ EXPECTED_VIEWER_OK,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_SPLIT_DUCKDB_INDEX,
+ ],
+ EXPECTED_SEARCH_OK,
+ ),
+ (
+ [
+ UPSTREAM_RESPONSE_CONFIG_SIZE_ERROR,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_PARQUET_ERROR,
+ UPSTREAM_RESPONSE_SPLIT_FIRST_ROWS_FROM_STREAMING_ERROR,
+ UPSTREAM_RESPONSE_SPLIT_DUCKDB_INDEX_ERROR,
+ ],
+ EXPECTED_ERROR,
+ ),
+ (
+ [],
+ EXPECTED_ERROR,
+ ),
+ ],
+)
+def test_compute(
+ app_config: AppConfig,
+ get_job_runner: GetJobRunner,
+ upstream_responses: List[UpstreamResponse],
+ expected: Any,
+) -> None:
+ dataset, config, split = DATASET, CONFIG, SPLIT
+ for upstream_response in upstream_responses:
+ upsert_response(**upstream_response)
+ job_runner = get_job_runner(dataset, config, split, app_config)
+ compute_result = job_runner.compute()
+ assert compute_result.content == expected[0]
+ assert compute_result.progress == expected[1]
+
+
+def test_doesnotexist(app_config: AppConfig, get_job_runner: GetJobRunner) -> None:
+ dataset, config, split = "doesnotexist", "doesnotexist", "doesnotexist"
+ job_runner = get_job_runner(dataset, config, split, app_config)
+ compute_result = job_runner.compute()
+ assert compute_result.content == {"viewer": False, "preview": False, "search": False}
|
|
08c0a9ea165b272e5f98b15be35f6410dda9bbce
|
Sylvain Lesage
| 2023-08-08T03:31:11 |
fix: 🐛 add missing volume declaration (#1650)
|
diff --git a/chart/templates/worker/_deployment.yaml b/chart/templates/worker/_deployment.yaml
index e51a9852..2e95d9ca 100644
--- a/chart/templates/worker/_deployment.yaml
+++ b/chart/templates/worker/_deployment.yaml
@@ -39,0 +40 @@ spec:
+ {{ include "volumeParquetMetadata" . | nindent 8 }}
|
|
24611277c0c214025958f2682a65af42f18b4da9
|
Sylvain Lesage
| 2023-08-08T03:25:45 |
feat: 🎸 use EFS instead of NFS for parquet-metadata files (#1649)
|
diff --git a/chart/templates/_initContainers/_initContainerParquetMetadata.tpl b/chart/templates/_initContainers/_initContainerParquetMetadata.tpl
index 2473cff7..c7f218ad 100644
--- a/chart/templates/_initContainers/_initContainerParquetMetadata.tpl
+++ b/chart/templates/_initContainers/_initContainerParquetMetadata.tpl
@@ -14 +14 @@
- name: volume-nfs
+ name: volume-parquet-metadata
diff --git a/chart/templates/_initContainers/_initContainerParquetMetadataNew.tpl b/chart/templates/_initContainers/_initContainerParquetMetadataNew.tpl
deleted file mode 100644
index 8fe68431..00000000
--- a/chart/templates/_initContainers/_initContainerParquetMetadataNew.tpl
+++ /dev/null
@@ -1,21 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2023 The HuggingFace Authors.
-
-{{- define "initContainerParquetMetadataNew" -}}
-- name: prepare-parquet-metadata-new
- image: ubuntu:focal
- imagePullPolicy: {{ .Values.images.pullPolicy }}
- command: ["/bin/sh", "-c"]
- args:
- - chown {{ .Values.uid }}:{{ .Values.gid }} /mounted-path;
- volumeMounts:
- - mountPath: /mounted-path
- mountPropagation: None
- name: volume-parquet-metadata
- subPath: "{{ include "parquetMetadata.subpath" . }}"
- readOnly: false
- securityContext:
- runAsNonRoot: false
- runAsUser: 0
- runAsGroup: 0
-{{- end -}}
diff --git a/chart/templates/_volumeMounts/_volumeMountParquetMetadata.tpl b/chart/templates/_volumeMounts/_volumeMountParquetMetadata.tpl
index 1f0b92e1..11365946 100644
--- a/chart/templates/_volumeMounts/_volumeMountParquetMetadata.tpl
+++ b/chart/templates/_volumeMounts/_volumeMountParquetMetadata.tpl
@@ -7 +7 @@
- name: volume-nfs
+ name: volume-parquet-metadata
@@ -15 +15 @@
- name: volume-nfs
+ name: volume-parquet-metadata
diff --git a/chart/templates/_volumeMounts/_volumeMountParquetMetadataNew.tpl b/chart/templates/_volumeMounts/_volumeMountParquetMetadataNew.tpl
deleted file mode 100644
index fd84f864..00000000
--- a/chart/templates/_volumeMounts/_volumeMountParquetMetadataNew.tpl
+++ /dev/null
@@ -1,18 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2023 The HuggingFace Authors.
-
-{{- define "volumeMountParquetMetadataNewRO" -}}
-- mountPath: {{ .Values.parquetMetadata.storageDirectoryNew | quote }}
- mountPropagation: None
- name: volume-parquet-metadata
- subPath: "{{ include "parquetMetadata.subpath" . }}"
- readOnly: true
-{{- end -}}
-
-{{- define "volumeMountParquetMetadataNewRW" -}}
-- mountPath: {{ .Values.parquetMetadata.storageDirectoryNew | quote }}
- mountPropagation: None
- name: volume-parquet-metadata
- subPath: "{{ include "parquetMetadata.subpath" . }}"
- readOnly: false
-{{- end -}}
diff --git a/chart/templates/services/rows/deployment.yaml b/chart/templates/services/rows/deployment.yaml
index 65ac6c48..81b48fea 100644
--- a/chart/templates/services/rows/deployment.yaml
+++ b/chart/templates/services/rows/deployment.yaml
@@ -34,0 +35 @@ spec:
+ {{ include "volumeParquetMetadata" . | nindent 8 }}
diff --git a/chart/templates/storage-admin/_container.tpl b/chart/templates/storage-admin/_container.tpl
index f776e8ff..abd99be3 100644
--- a/chart/templates/storage-admin/_container.tpl
+++ b/chart/templates/storage-admin/_container.tpl
@@ -14 +13,0 @@
- {{ include "volumeMountParquetMetadataNewRW" . | nindent 2 }}
diff --git a/chart/templates/storage-admin/deployment.yaml b/chart/templates/storage-admin/deployment.yaml
index 4888334a..6e110c4d 100644
--- a/chart/templates/storage-admin/deployment.yaml
+++ b/chart/templates/storage-admin/deployment.yaml
@@ -26 +25,0 @@ spec:
- {{ include "initContainerParquetMetadataNew" . | nindent 8 }}
|
|
b31f64f438235993bce9a063ded64fabced8f8bc
|
Sylvain Lesage
| 2023-08-07T21:35:39 |
feat: 🎸 install latest version of rclone (#1648)
|
diff --git a/services/storage-admin/Dockerfile b/services/storage-admin/Dockerfile
index 5ef91acf..8b6892e4 100644
--- a/services/storage-admin/Dockerfile
+++ b/services/storage-admin/Dockerfile
@@ -7 +7 @@ RUN apt-get update \
- && DEBIAN_FRONTEND=noninteractive apt-get install -y rsync unzip wget curl rclone glances \
+ && DEBIAN_FRONTEND=noninteractive apt-get install -y rsync unzip wget curl glances \
@@ -8,0 +9 @@ RUN apt-get update \
+RUN curl https://rclone.org/install.sh | bash
|
|
824667a5d46f57133201049040977a8ab0c90318
|
Sylvain Lesage
| 2023-08-07T21:23:35 |
feat: 🎸 reduce the number of cpus for storage admin (#1647)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index ff56b467..85f8182d 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -213 +213 @@ storageAdmin:
- cpu: 8
+ cpu: 4
@@ -216 +216 @@ storageAdmin:
- cpu: 8
+ cpu: 4
|
|
cb6833d8f535a99322460b873b0febebca0c34e6
|
Sylvain Lesage
| 2023-08-07T21:11:08 |
fix: 🐛 fix the dockerfile (#1645)
|
diff --git a/services/storage-admin/Dockerfile b/services/storage-admin/Dockerfile
index 6057307b..5ef91acf 100644
--- a/services/storage-admin/Dockerfile
+++ b/services/storage-admin/Dockerfile
@@ -7 +7 @@ RUN apt-get update \
- && apt-get install -y rsync unzip wget curl rclone glances \
+ && DEBIAN_FRONTEND=noninteractive apt-get install -y rsync unzip wget curl rclone glances \
|
|
4d0a0ec6a250236828b51b02fb56cf6ff257f6f4
|
Sylvain Lesage
| 2023-08-07T20:53:03 |
feat: 🎸 use rclone on storage admin with multiple cores (#1644)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 8fc0cabe..ff56b467 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -213 +213 @@ storageAdmin:
- cpu: 1
+ cpu: 8
@@ -216 +216 @@ storageAdmin:
- cpu: 1
+ cpu: 8
diff --git a/services/storage-admin/Dockerfile b/services/storage-admin/Dockerfile
index 9c9faaca..6057307b 100644
--- a/services/storage-admin/Dockerfile
+++ b/services/storage-admin/Dockerfile
@@ -7 +7 @@ RUN apt-get update \
- && apt-get install -y rsync unzip wget curl \
+ && apt-get install -y rsync unzip wget curl rclone glances \
|
|
434ab85f13836b16ac370b00e80e03b46a532a52
|
Sylvain Lesage
| 2023-08-07T20:45:05 |
feat: 🎸 remove /admin/cancel-jobs/{job_type} (#1643)
|
diff --git a/libs/libcommon/src/libcommon/queue.py b/libs/libcommon/src/libcommon/queue.py
index a6512c63..25c1f43a 100644
--- a/libs/libcommon/src/libcommon/queue.py
+++ b/libs/libcommon/src/libcommon/queue.py
@@ -830,13 +829,0 @@ class Queue:
- def cancel_started_jobs(self, job_type: str) -> None:
- """Cancel all started jobs for a given type."""
- for job in JobDocument.objects(status=Status.STARTED.value, type=job_type):
- job.update(finished_at=get_datetime(), status=Status.CANCELLED)
- self.add_job(
- job_type=job.type,
- dataset=job.dataset,
- revision=job.revision,
- config=job.config,
- split=job.split,
- difficulty=job.difficulty,
- )
-
diff --git a/services/admin/README.md b/services/admin/README.md
index 71a362b8..ceecf6a6 100644
--- a/services/admin/README.md
+++ b/services/admin/README.md
@@ -49 +48,0 @@ The admin service provides endpoints:
-- `/cancel-jobs{processing_step}`: cancel all the started jobs for the processing step (stop the corresponding workers before!). It's a POST endpoint.:
diff --git a/services/admin/src/admin/app.py b/services/admin/src/admin/app.py
index df11c6f8..8f8cf8cc 100644
--- a/services/admin/src/admin/app.py
+++ b/services/admin/src/admin/app.py
@@ -26 +25,0 @@ from admin.routes.cache_reports_with_content import (
-from admin.routes.cancel_jobs import create_cancel_jobs_endpoint
@@ -163,10 +161,0 @@ def create_app() -> Starlette:
- Route(
- f"/cancel-jobs/{job_type}",
- endpoint=create_cancel_jobs_endpoint(
- job_type=job_type,
- external_auth_url=app_config.admin.external_auth_url,
- organization=app_config.admin.hf_organization,
- hf_timeout_seconds=app_config.admin.hf_timeout_seconds,
- ),
- methods=["POST"],
- ),
diff --git a/services/admin/src/admin/routes/cancel_jobs.py b/services/admin/src/admin/routes/cancel_jobs.py
deleted file mode 100644
index 69f533ef..00000000
--- a/services/admin/src/admin/routes/cancel_jobs.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-# Copyright 2022 The HuggingFace Authors.
-
-import logging
-from typing import Optional
-
-from libcommon.queue import Queue
-from starlette.requests import Request
-from starlette.responses import Response
-
-from admin.authentication import auth_check
-from admin.utils import (
- AdminCustomError,
- Endpoint,
- UnexpectedError,
- get_json_admin_error_response,
- get_json_ok_response,
-)
-
-
-def create_cancel_jobs_endpoint(
- job_type: str,
- external_auth_url: Optional[str] = None,
- organization: Optional[str] = None,
- hf_timeout_seconds: Optional[float] = None,
-) -> Endpoint:
- async def cancel_jobs_endpoint(request: Request) -> Response:
- try:
- logging.info(f"/cancel-jobs/{job_type}")
-
- # if auth_check fails, it will raise an exception that will be caught below
- auth_check(
- external_auth_url=external_auth_url,
- request=request,
- organization=organization,
- hf_timeout_seconds=hf_timeout_seconds,
- )
- Queue().cancel_started_jobs(job_type=job_type)
- return get_json_ok_response(
- {"status": "ok"},
- max_age=0,
- )
- except AdminCustomError as e:
- return get_json_admin_error_response(e, max_age=0)
- except Exception as e:
- return get_json_admin_error_response(UnexpectedError("Unexpected error.", e), max_age=0)
-
- return cancel_jobs_endpoint
|
|
e3110d0bda9cd308b16dbd3b12e0472f4738de31
|
Sylvain Lesage
| 2023-08-07T20:16:24 |
feat: 🎸 add RAM to the storage admin machine (#1642)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 1ce6961d..8fc0cabe 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -213,2 +213,2 @@ storageAdmin:
- cpu: 50m
- memory: "64Mi"
+ cpu: 1
+ memory: "4Gi"
@@ -217 +217 @@ storageAdmin:
- memory: "256Mi"
+ memory: "4Gi"
|
|
ceae9848e675b8bf9e79915af12eeac137cb7f8a
|
Sylvain Lesage
| 2023-08-07T20:10:14 |
Reduce ram for rows and search (#1641)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 50615012..1ce6961d 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -315 +315 @@ rows:
- memory: "7Gi"
+ memory: "6500Mi"
@@ -318 +318 @@ rows:
- memory: "7Gi"
+ memory: "6500Mi"
@@ -327 +327 @@ search:
- replicas: 12
+ replicas: 2
@@ -333 +333 @@ search:
- memory: "7Gi"
+ memory: "6500Mi"
@@ -336 +336 @@ search:
- memory: "7Gi"
+ memory: "6500Mi"
|
|
46de6aca64ee8b825915805fbf33eba196954227
|
Sylvain Lesage
| 2023-08-07T19:54:18 |
feat: 🎸 reduce RAM from 8 to 7GiB for rows and search services (#1640)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index c27fb119..50615012 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -315 +315 @@ rows:
- memory: "8Gi"
+ memory: "7Gi"
@@ -318 +318 @@ rows:
- memory: "8Gi"
+ memory: "7Gi"
@@ -333 +333 @@ search:
- memory: "8Gi"
+ memory: "7Gi"
@@ -336 +336 @@ search:
- memory: "8Gi"
+ memory: "7Gi"
|
|
2e147ee8e5d4bad397073abfe985274fee37b097
|
Sylvain Lesage
| 2023-08-07T19:48:10 |
refactor: 💡 change labels to lowercase programmatically (#1639)
|
diff --git a/tools/stale.py b/tools/stale.py
index 4071353b..50fb7b52 100644
--- a/tools/stale.py
+++ b/tools/stale.py
@@ -17,5 +17,5 @@ from github import Github
-LABELS_TO_EXEMPT_IN_LOWERCASE = [
- "p0",
- "p1",
- "p2"
-]
+LABELS_TO_EXEMPT_IN_LOWERCASE = [label.lower() for label in [
+ "P0",
+ "P1",
+ "P2"
+]]
|
|
82ab1f918422c1a7b76c2796265f78dc1f300d42
|
Sylvain Lesage
| 2023-08-07T19:31:44 |
feat: 🎸 reduce workers, and assign more RAM to /rows (#1638)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index dfb51464..c27fb119 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -315 +315 @@ rows:
- memory: "6Gi"
+ memory: "8Gi"
@@ -333 +333 @@ search:
- memory: "4Gi"
+ memory: "8Gi"
@@ -347 +347 @@ workers:
- replicas: 100
+ replicas: 24
@@ -364 +364 @@ workers:
- replicas: 25
+ replicas: 8
|
|
664692d9022ba4083c3cb1e19e252d6fef072fd8
|
Sylvain Lesage
| 2023-08-07T19:17:50 |
remove locks when finishing a job (#1637)
|
diff --git a/chart/templates/_env/_envWorker.tpl b/chart/templates/_env/_envWorker.tpl
index 1a3a08c6..d5401ff7 100644
--- a/chart/templates/_env/_envWorker.tpl
+++ b/chart/templates/_env/_envWorker.tpl
@@ -10,0 +11,2 @@
+- name: WORKER_KILL_LONG_JOB_INTERVAL_SECONDS
+ value: {{ .Values.worker.killLongJobIntervalSeconds | quote}}
diff --git a/chart/values.yaml b/chart/values.yaml
index fb164c9e..81cfd0cb 100644
--- a/chart/values.yaml
+++ b/chart/values.yaml
@@ -158,0 +159,2 @@ worker:
+ # the time interval at which the worker looks for long jobs to kill them
+ killLongJobIntervalSeconds: 60
diff --git a/libs/libcommon/src/libcommon/queue.py b/libs/libcommon/src/libcommon/queue.py
index d1b39250..a6512c63 100644
--- a/libs/libcommon/src/libcommon/queue.py
+++ b/libs/libcommon/src/libcommon/queue.py
@@ -346,0 +347,15 @@ class lock(contextlib.AbstractContextManager["lock"]):
+def release_locks(owner: str) -> None:
+ """
+ Release all locks owned by the given owner
+
+ Args:
+ owner (`str`): the current owner that holds the locks
+ """
+ Lock.objects(owner=owner).update(
+ write_concern={"w": "majority", "fsync": True},
+ read_concern={"level": "majority"},
+ owner=None,
+ updated_at=get_datetime(),
+ )
+
+
@@ -765 +780 @@ class Queue:
- The job is moved from the started state to the success or error state.
+ The job is moved from the started state to the success or error state. The existing locks are released.
@@ -784,0 +800 @@ class Queue:
+ release_locks(owner=job_id)
diff --git a/services/worker/README.md b/services/worker/README.md
index 8b4b430f..eadc62bb 100644
--- a/services/worker/README.md
+++ b/services/worker/README.md
@@ -18,0 +19 @@ Set environment variables to configure the worker.
+- `WORKER_KILL_LONG_JOB_INTERVAL_SECONDS`: the time interval at which the worker looks for long jobs to kill them. Defaults to `60` (1 minute).
@@ -20,0 +22 @@ Set environment variables to configure the worker.
+- `WORKER_MAX_JOB_DURATION_SECONDS`: the maximum duration allowed for a job to run. If the job runs longer, it is killed (see `WORKER_KILL_LONG_JOB_INTERVAL_SECONDS`). Defaults to `1200` (20 minutes).
diff --git a/services/worker/tests/conftest.py b/services/worker/tests/conftest.py
index 1a82ed4a..9e325e70 100644
--- a/services/worker/tests/conftest.py
+++ b/services/worker/tests/conftest.py
@@ -87 +87 @@ def set_env_vars(
- mp.setenv("WORKER_KILL_LONG_JOBS_INTERVAL_SECONDS", "1")
+ mp.setenv("WORKER_KILL_LONG_JOB_INTERVAL_SECONDS", "1")
diff --git a/tools/docker-compose-base.yml b/tools/docker-compose-base.yml
index 19ab22aa..52bb9a40 100644
--- a/tools/docker-compose-base.yml
+++ b/tools/docker-compose-base.yml
@@ -23,0 +24,2 @@ services:
+ WORKER_KILL_LONG_JOB_INTERVAL_SECONDS: ${WORKER_KILL_LONG_JOB_INTERVAL_SECONDS-60}
+ WORKER_KILL_ZOMBIES_INTERVAL_SECONDS: ${WORKER_KILL_ZOMBIES_INTERVAL_SECONDS-600}
@@ -25,0 +28 @@ services:
+ WORKER_MAX_MISSING_HEARTBEATS: ${WORKER_MAX_MISSING_HEARTBEATS-5}
diff --git a/tools/docker-compose-dev-base.yml b/tools/docker-compose-dev-base.yml
index 014f09ee..a4a02e69 100644
--- a/tools/docker-compose-dev-base.yml
+++ b/tools/docker-compose-dev-base.yml
@@ -23,0 +24,2 @@ services:
+ WORKER_KILL_LONG_JOB_INTERVAL_SECONDS: ${WORKER_KILL_LONG_JOB_INTERVAL_SECONDS-60}
+ WORKER_KILL_ZOMBIES_INTERVAL_SECONDS: ${WORKER_KILL_ZOMBIES_INTERVAL_SECONDS-600}
@@ -25,0 +28 @@ services:
+ WORKER_MAX_MISSING_HEARTBEATS: ${WORKER_MAX_MISSING_HEARTBEATS-5}
|
|
f07c09159d3304951c10062ddc485e315fb4c850
|
Sylvain Lesage
| 2023-08-07T16:32:29 |
ci: 🎡 fix the stale bot (#1635)
|
diff --git a/tools/stale.py b/tools/stale.py
index 9a2a0d04..4071353b 100644
--- a/tools/stale.py
+++ b/tools/stale.py
@@ -10 +10 @@ Copied from https://github.com/huggingface/transformers
-from datetime import datetime as dt
+from datetime import datetime as dt, timezone
@@ -13,0 +14 @@ from github import Github
+# ^ PyGithub - https://pygithub.readthedocs.io/en/stable/introduction.html
@@ -16,4 +17,4 @@ from github import Github
-LABELS_TO_EXEMPT = [
- "P0",
- "P1",
- "P2"
+LABELS_TO_EXEMPT_IN_LOWERCASE = [
+ "p0",
+ "p1",
+ "p2"
@@ -29 +30,7 @@ def main():
- comments = sorted([comment for comment in issue.get_comments()], key=lambda i: i.created_at, reverse=True)
+ now = dt.now(timezone.utc)
+ if (
+ (now - issue.created_at).days < 30
+ or any(label.name.lower() in LABELS_TO_EXEMPT_IN_LOWERCASE for label in issue.get_labels())
+ ):
+ continue
+ comments = sorted(list(issue.get_comments()), key=lambda i: i.created_at, reverse=True)
@@ -32,4 +39,3 @@ def main():
- last_comment is not None and last_comment.user.login == "github-actions[bot]"
- and (dt.utcnow() - issue.updated_at).days > 7
- and (dt.utcnow() - issue.created_at).days >= 30
- and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
+ last_comment is not None
+ and last_comment.user.login == "github-actions[bot]"
+ and (now - issue.updated_at).days > 7
@@ -37 +43 @@ def main():
- # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
+ # close issue since it has been 7 days of inactivity since bot mention
@@ -40,3 +46 @@ def main():
- (dt.utcnow() - issue.updated_at).days > 23
- and (dt.utcnow() - issue.created_at).days >= 30
- and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
+ (now - issue.updated_at).days > 23
@@ -44 +48 @@ def main():
- # print(f"Would add stale comment to {issue.number}")
+ #add stale comment
|
|
e3f1371876d621cd9551b1ce693bfda2f6439373
|
Andrea Francis Soria Jimenez
| 2023-08-04T20:08:38 |
Set default values for staging and prod (#1634)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index b9418f23..dfb51464 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -140 +140 @@ duckDBIndex:
- expiredTimeIntervalSeconds: 600
+ expiredTimeIntervalSeconds: 259_200 # 3 days
@@ -192,4 +191,0 @@ backfill:
-deleteIndexes:
- schedule: "*/10 * * * *"
- # every ten minutes
-
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index dc26a476..18e30b9d 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -151,12 +150,0 @@ backfill:
-deleteIndexes:
- schedule: "*/10 * * * *"
- # every ten minutes
- nodeSelector: {}
- resources:
- requests:
- cpu: 1
- limits:
- cpu: 1
- memory: "512Mi"
- tolerations: []
-
|
|
f94b48642a4aaad608807db49697743b03112d91
|
Andrea Francis Soria Jimenez
| 2023-08-04T19:53:17 |
Test reducing index interval time (#1633)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index 9aa9038c..b9418f23 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -140 +140 @@ duckDBIndex:
- expiredTimeIntervalSeconds: 259_200 # 3 days
+ expiredTimeIntervalSeconds: 600
|
|
310a27de55a2543d5590c44bdbb82bf60023b676
|
Andrea Francis Soria Jimenez
| 2023-08-04T17:45:28 |
Init only for delete-indexes action (#1632)
|
diff --git a/jobs/cache_maintenance/src/cache_maintenance/main.py b/jobs/cache_maintenance/src/cache_maintenance/main.py
index 29673e9c..b06fb7f7 100644
--- a/jobs/cache_maintenance/src/cache_maintenance/main.py
+++ b/jobs/cache_maintenance/src/cache_maintenance/main.py
@@ -36 +35,0 @@ def run_job() -> None:
- duckdb_index_cache_directory = init_duckdb_index_cache_dir(directory=job_config.duckdb.cache_directory)
@@ -70,0 +70 @@ def run_job() -> None:
+ duckdb_index_cache_directory = init_duckdb_index_cache_dir(directory=job_config.duckdb.cache_directory)
|
|
4f269086657c481622d7e6bf056dfa8cf197f8e8
|
Andrea Francis Soria Jimenez
| 2023-08-04T17:37:38 |
Fix delete indexes volume (#1631)
|
diff --git a/chart/templates/cron-jobs/delete-indexes/job.yaml b/chart/templates/cron-jobs/delete-indexes/job.yaml
index fc876dba..91b2adbd 100644
--- a/chart/templates/cron-jobs/delete-indexes/job.yaml
+++ b/chart/templates/cron-jobs/delete-indexes/job.yaml
@@ -25,4 +25,2 @@ spec:
- initContainers:
- {{ include "initContainerDuckDBIndex" . | nindent 8 }}
- volumes:
- {{ include "volumeDuckDBIndex" . | nindent 8 }}
+ initContainers: {{ include "initContainerDuckDBIndex" . | nindent 12 }}
+ volumes: {{ include "volumeDuckDBIndex" . | nindent 12 }}
|
|
a52f6ec59b3e2edde3f779ef706770a6af665792
|
Andrea Francis Soria Jimenez
| 2023-08-04T17:29:54 |
Fix container definition (#1630)
|
diff --git a/chart/templates/cron-jobs/backfill/job.yaml b/chart/templates/cron-jobs/backfill/job.yaml
index f04b3791..3e5595cc 100644
--- a/chart/templates/cron-jobs/backfill/job.yaml
+++ b/chart/templates/cron-jobs/backfill/job.yaml
@@ -25,4 +24,0 @@ spec:
- initContainers:
- {{ include "initContainerDuckDBIndex" . | nindent 8 }}
- volumes:
- {{ include "volumeDuckDBIndex" . | nindent 8 }}
diff --git a/chart/templates/cron-jobs/delete-indexes/job.yaml b/chart/templates/cron-jobs/delete-indexes/job.yaml
index 3bdd89a1..fc876dba 100644
--- a/chart/templates/cron-jobs/delete-indexes/job.yaml
+++ b/chart/templates/cron-jobs/delete-indexes/job.yaml
@@ -24,0 +25,4 @@ spec:
+ initContainers:
+ {{ include "initContainerDuckDBIndex" . | nindent 8 }}
+ volumes:
+ {{ include "volumeDuckDBIndex" . | nindent 8 }}
|
|
7e82822a069835f7bcf2122b5ed495ba936ee5a4
|
Andrea Francis Soria Jimenez
| 2023-08-04T17:24:08 |
Add duckdb volume (#1629)
|
diff --git a/chart/templates/cron-jobs/backfill/job.yaml b/chart/templates/cron-jobs/backfill/job.yaml
index 3e5595cc..f04b3791 100644
--- a/chart/templates/cron-jobs/backfill/job.yaml
+++ b/chart/templates/cron-jobs/backfill/job.yaml
@@ -24,0 +25,4 @@ spec:
+ initContainers:
+ {{ include "initContainerDuckDBIndex" . | nindent 8 }}
+ volumes:
+ {{ include "volumeDuckDBIndex" . | nindent 8 }}
|
|
f03e3ba57a709fab0caeb5d2b3d6449e7c506dc3
|
Rémy
| 2023-08-04T17:15:50 |
fix: unquoted env vars (#1628)
|
diff --git a/chart/templates/cron-jobs/delete-indexes/_container.tpl b/chart/templates/cron-jobs/delete-indexes/_container.tpl
index 801ad7a0..547bd1da 100644
--- a/chart/templates/cron-jobs/delete-indexes/_container.tpl
+++ b/chart/templates/cron-jobs/delete-indexes/_container.tpl
@@ -23 +23 @@
- value: {{ .Values.duckDBIndex.cacheDirectory}}
+ value: {{ .Values.duckDBIndex.cacheDirectory | quote }}
@@ -25 +25 @@
- value: {{ .Values.duckDBIndex.expiredTimeIntervalSeconds}}
+ value: {{ .Values.duckDBIndex.expiredTimeIntervalSeconds | quote }}
|
|
dde94aa51a56fe79874a2b5b3e79da5a7064d7e1
|
Andrea Francis Soria Jimenez
| 2023-08-04T17:00:26 |
Fix delete indexes job - fix cron (#1627)
|
diff --git a/chart/env/prod.yaml b/chart/env/prod.yaml
index e84fd7ed..9aa9038c 100644
--- a/chart/env/prod.yaml
+++ b/chart/env/prod.yaml
@@ -193 +193 @@ deleteIndexes:
- schedule: "*/10 * * * *"
+ schedule: "*/10 * * * *"
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index f27ea90b..dc26a476 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -152 +152 @@ deleteIndexes:
- schedule: "*/10 * * * *"
+ schedule: "*/10 * * * *"
|
|
58f81ae8ff63782e6bf1bfd33fd5bde3be2029b2
|
Andrea Francis Soria Jimenez
| 2023-08-04T16:52:56 |
Try to fix delete indexes job (#1626)
|
diff --git a/chart/Chart.yaml b/chart/Chart.yaml
index c0705ae7..e9a715a4 100644
--- a/chart/Chart.yaml
+++ b/chart/Chart.yaml
@@ -21 +21 @@ type: application
-version: 1.16.0
+version: 1.16.1
diff --git a/chart/env/staging.yaml b/chart/env/staging.yaml
index e1cf0e12..f27ea90b 100644
--- a/chart/env/staging.yaml
+++ b/chart/env/staging.yaml
@@ -153,0 +154,8 @@ deleteIndexes:
+ nodeSelector: {}
+ resources:
+ requests:
+ cpu: 1
+ limits:
+ cpu: 1
+ memory: "512Mi"
+ tolerations: []
diff --git a/chart/templates/cron-jobs/delete-indexes/_container.tpl b/chart/templates/cron-jobs/delete-indexes/_container.tpl
index de503196..801ad7a0 100644
--- a/chart/templates/cron-jobs/delete-indexes/_container.tpl
+++ b/chart/templates/cron-jobs/delete-indexes/_container.tpl
@@ -7,0 +8,2 @@
+ volumeMounts:
+ {{ include "volumeMountDuckDBIndexRW" . | nindent 2 }}
diff --git a/chart/templates/cron-jobs/delete-indexes/job.yaml b/chart/templates/cron-jobs/delete-indexes/job.yaml
index dc5dd496..3bdd89a1 100644
--- a/chart/templates/cron-jobs/delete-indexes/job.yaml
+++ b/chart/templates/cron-jobs/delete-indexes/job.yaml
@@ -18,0 +19 @@ spec:
+ {{- include "dnsConfig" . | nindent 10 }}
|
|
1217176a40c3f292afa0a6cb5b541c0a69aeea41
|
Andrea Francis Soria Jimenez
| 2023-08-04T16:31:29 |
Try to fix delete indexes job (#1625)
|
diff --git a/chart/templates/_common/_helpers.tpl b/chart/templates/_common/_helpers.tpl
index f710be22..b71d65da 100644
--- a/chart/templates/_common/_helpers.tpl
+++ b/chart/templates/_common/_helpers.tpl
@@ -105 +105 @@ app.kubernetes.io/component: "{{ include "name" . }}-backfill"
-app.kubernetes.io/component: "{{ include "name" . }}-deleteIndexes"
+app.kubernetes.io/component: "{{ include "name" . }}-delete-indexes"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.