{"id":31956281,"url":"https://github.com/davanstrien/datasets-server-py","last_synced_at":"2026-07-17T06:36:27.382Z","repository":{"id":303335892,"uuid":"1012645462","full_name":"davanstrien/datasets-server-py","owner":"davanstrien","description":null,"archived":false,"fork":false,"pushed_at":"2026-01-12T16:03:17.000Z","size":511,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-07-17T06:36:05.185Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/davanstrien.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-07-02T16:45:57.000Z","updated_at":"2026-01-12T16:02:49.000Z","dependencies_parsed_at":null,"dependency_job_id":"bc9f2a22-b8ff-47d1-a876-15035ea74cdd","html_url":"https://github.com/davanstrien/datasets-server-py","commit_stats":null,"previous_names":["davanstrien/datasets-server-py"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/davanstrien/datasets-server-py","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davanstrien%2Fdatasets-server-py","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davanstrien%2Fdatasets-server-py/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davanstrien%2Fdatasets-server-py/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davanstrien%2Fdatasets-server-py/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/davanstrien","download_url":"https://codeload.github.com/davanstrien/datasets-server-py/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davanstrien%2Fdatasets-server-py/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35571461,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-17T02:00:06.162Z","response_time":116,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-10-14T14:48:18.252Z","updated_at":"2026-07-17T06:36:27.374Z","avatar_url":"https://github.com/davanstrien.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Datasets Server Python Client\n\nA Python client library for the Hugging Face Datasets Viewer API with both synchronous and asynchronous support.\n\n## Features\n\n- 🔄 **Sync/Async Support**: Choose between synchronous and asynchronous clients based on your needs\n- 🔍 **Full API Coverage**: Access all Datasets Viewer API endpoints with a Pythonic interface\n- 🎯 **Type Safety**: Pydantic models for all API responses ensure type safety and validation\n- 🚀 **High Performance**: Async support enables efficient concurrent operations\n- 🔐 **Authentication**: Seamless integration with Hugging Face authentication tokens\n- 📊 **Rich Data Access**: Preview datasets, search content, filter rows, and analyze statistics without downloading\n- 🤖 **CLI for Agents**: Command-line interface with JSON output, designed for AI agents and automation\n\n## Command-Line Interface\n\nThe package includes a CLI (`dv`) designed for quick dataset exploration and AI agent integration:\n\n```bash\n# Check if a dataset is viewable\n$ dv is-valid fka/awesome-chatgpt-prompts\n{\"viewer\": true, \"preview\": true, \"search\": true, \"filter\": true, \"statistics\": true}\n\n# List available splits\n$ dv splits fka/awesome-chatgpt-prompts\n[{\"dataset\": \"fka/awesome-chatgpt-prompts\", \"config\": \"default\", \"split\": \"train\"}]\n\n# Sample random rows\n$ dv sample fka/awesome-chatgpt-prompts -n 3 -c default -s train\n{\"features\": [...], \"rows\": [...], \"num_rows_total\": 170, ...}\n\n# Search for content\n$ dv search fka/awesome-chatgpt-prompts \"python\" -c default -s train\n{\"features\": [...], \"rows\": [...], ...}\n```\n\n### Available Commands\n\n| Command | Description |\n|---------|-------------|\n| `dv is-valid \u003cdataset\u003e` | Check dataset validity and feature availability |\n| `dv info \u003cdataset\u003e` | Get dataset metadata |\n| `dv splits \u003cdataset\u003e` | List available configs/splits |\n| `dv size \u003cdataset\u003e` | Get dataset size information |\n| `dv parquet \u003cdataset\u003e` | List parquet file URLs (for DuckDB/pandas bulk access) |\n| `dv preview \u003cdataset\u003e` | Get first ~100 rows |\n| `dv sample \u003cdataset\u003e -n N` | Get random sample (max 100 rows) |\n| `dv search \u003cdataset\u003e \u003cquery\u003e` | Search for matching rows |\n| `dv stats \u003cdataset\u003e -c \u003cconfig\u003e -s \u003csplit\u003e` | Get column statistics |\n\n### Agent-Friendly Design\n\nThe CLI outputs JSON by default, making it easy to integrate with AI agents and automation tools like [Hugging Face Skills](https://github.com/huggingface/skills):\n\n```bash\n# Pipe to jq for processing\n$ dv splits my-dataset | jq '.[0].config'\n\"default\"\n\n# Check exit codes (0=success, 1=error)\n$ dv is-valid nonexistent/dataset; echo \"Exit: $?\"\n{\"error\": \"DatasetNotFoundError\", \"message\": \"...\"}\nExit: 1\n\n# For bulk data access, get parquet URLs and use DuckDB/pandas\n$ dv parquet my-dataset | jq '.[].url'\n```\n\n\u003e **Note**: The Datasets Viewer API is designed for dataset exploration (previewing a few rows), not bulk data access. For heavy data processing, use `dv parquet` to get file URLs and process with DuckDB or pandas directly.\n\n## Installation\n\nInstall directly from GitHub:\n\n```bash\n# Using pip\npip install git+https://github.com/davanstrien/datasets-server-py.git\n\n# Using UV (recommended)\nuv pip install git+https://github.com/davanstrien/datasets-server-py.git\n```\n\nFor development:\n\n```bash\ngit clone https://github.com/davanstrien/datasets-server-py\ncd datasets-server-py\nuv pip install -e \".[dev]\"\n```\n\n## Quick Start\n\n### Synchronous Usage\n\n```python\nfrom datasets_server import DatasetsServerClient\n\n# Initialize client (uses HF token from environment if available)\nclient = DatasetsServerClient()\n\n# Check dataset validity\nvalidity = client.is_valid(\"stanfordnlp/imdb\")\nif validity.preview:\n    # Preview first rows\n    rows = client.preview(\"stanfordnlp/imdb\")\n    print(f\"Dataset has {len(rows.rows)} preview rows\")\n    \n# Search within a dataset\nif validity.search:\n    results = client.search(\n        dataset=\"stanfordnlp/imdb\",\n        query=\"amazing movie\",\n        config=\"plain_text\",\n        split=\"train\",\n        length=5\n    )\n    print(f\"Found {results.num_rows_total} matches\")\n```\n\n### Asynchronous Usage\n\n```python\nimport asyncio\nfrom datasets_server import AsyncDatasetsServerClient\n\nasync def explore_datasets():\n    async with AsyncDatasetsServerClient() as client:\n        # Check multiple datasets concurrently\n        datasets = [\"SetFit/ag_news\", \"stanfordnlp/imdb\", \"davanstrien/haiku_dpo\"]\n        tasks = [client.is_valid(ds) for ds in datasets]\n        validities = await asyncio.gather(*tasks)\n        \n        for dataset, validity in zip(datasets, validities):\n            print(f\"{dataset}: preview={validity.preview}, search={validity.search}\")\n\nasyncio.run(explore_datasets())\n```\n\n## API Reference\n\n### Client Initialization\n\nBoth clients accept the same parameters:\n\n```python\nclient = DatasetsServerClient(\n    token=\"your-hf-token\",  # Optional: defaults to cached token\n    endpoint=\"https://custom-endpoint\",  # Optional: custom API endpoint\n    timeout=30.0  # Optional: request timeout in seconds\n)\n```\n\n### Available Methods\n\nAll methods are available in both sync and async versions:\n\n#### Dataset Validation\n- `is_valid(dataset)` - Check if a dataset is valid and which features are available\n\n#### Dataset Information\n- `list_splits(dataset)` - List all configurations and splits\n- `get_info(dataset, config=None)` - Get detailed dataset information\n- `get_size(dataset)` - Get dataset size information\n- `list_parquet_files(dataset)` - List available Parquet files\n\n#### Data Access\n- `preview(dataset, config=None, split=None)` - Preview first 100 rows\n- `get_rows(dataset, config, split, offset=0, length=100)` - Get rows with pagination\n- `iter_rows(dataset, config, split, batch_size=100)` - Iterate through all rows\n- `sample_rows(dataset, config, split, n_samples, seed=None, max_requests=None)` - Get random sample of rows\n\n#### Search and Filter\n- `search(dataset, query, config, split, offset=0, length=100)` - Search text in dataset\n- `filter(dataset, where, config, split, orderby=None, offset=0, length=100)` - Filter with SQL-like conditions\n\n#### Statistics\n- `get_statistics(dataset, config, split)` - Get statistical information about dataset columns\n\n## Examples\n\n### Explore a Dataset\n\n```python\nfrom datasets_server import DatasetsServerClient\n\nclient = DatasetsServerClient()\n\n# Get basic information\ninfo = client.get_info(\"SetFit/ag_news\")\nprint(f\"Description: {info.dataset_info.get('description', 'N/A')}\")\n\n# List available splits\nsplits = client.list_splits(\"SetFit/ag_news\")\nfor split in splits:\n    print(f\"Config: {split.config}, Split: {split.split}\")\n\n# Get dataset statistics\nstats = client.get_statistics(\"SetFit/ag_news\", config=\"default\", split=\"train\")\nprint(f\"Number of examples: {stats.num_examples:,}\")\n```\n\n### Filter Dataset Rows\n\n```python\n# Filter for positive reviews (label = 1)\nfiltered = client.filter(\n    dataset=\"stanfordnlp/imdb\",\n    config=\"plain_text\",\n    split=\"train\",\n    where='\"label\" = 1',\n    length=10\n)\n\nfor row in filtered.rows:\n    print(f\"Label: {row['row']['label']}, Text preview: {row['row']['text'][:100]}...\")\n```\n\n### Sample Random Rows\n\n```python\n# Get a random sample of rows\nsample = client.sample_rows(\n    dataset=\"stanfordnlp/imdb\",\n    config=\"plain_text\",\n    split=\"train\",\n    n_samples=10,\n    seed=42  # For reproducibility\n)\n\nfor row in sample.rows:\n    text_preview = row[\"row\"][\"text\"][:100] + \"...\"\n    label = \"positive\" if row[\"row\"][\"label\"] == 1 else \"negative\"\n    print(f\"{label}: {text_preview}\")\n\n# API-efficient sampling with max_requests\n# Limits API calls for large datasets\nefficient_sample = client.sample_rows(\n    dataset=\"stanfordnlp/imdb\",\n    config=\"plain_text\",\n    split=\"train\",\n    n_samples=50,\n    seed=42,\n    max_requests=5  # Use at most 5 API calls\n)\n# Note: max_requests trades randomness for API efficiency\n```\n\n### Concurrent Operations with Async\n\n```python\nimport asyncio\nfrom datasets_server import AsyncDatasetsServerClient\n\nasync def analyze_datasets(dataset_list):\n    async with AsyncDatasetsServerClient() as client:\n        # Get info for all datasets concurrently\n        tasks = [client.get_info(ds) for ds in dataset_list]\n        results = await asyncio.gather(*tasks, return_exceptions=True)\n        \n        for dataset, result in zip(dataset_list, results):\n            if isinstance(result, Exception):\n                print(f\"{dataset}: Error - {result}\")\n            else:\n                print(f\"{dataset}: {result.dataset_info.get('num_rows', 'Unknown')} rows\")\n\nasyncio.run(analyze_datasets([\"SetFit/ag_news\", \"stanfordnlp/imdb\", \"librarian-bots/dataset_cards_with_metadata\"]))\n```\n\n## Error Handling\n\nThe client includes custom exceptions for better error handling:\n\n```python\nfrom datasets_server import (\n    DatasetsServerClient,\n    DatasetNotFoundError,\n    DatasetServerError\n)\n\nclient = DatasetsServerClient()\n\ntry:\n    validity = client.is_valid(\"non-existent-dataset\")\nexcept DatasetNotFoundError as e:\n    print(f\"Dataset not found: {e}\")\nexcept DatasetServerError as e:\n    print(f\"API error: {e}\")\n```\n\n## Development\n\n### Setup Development Environment\n\n```bash\n# Clone the repository\ngit clone https://github.com/davanstrien/datasets-server-py\ncd datasets-server-py\n\n# Install UV\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Create virtual environment and install dependencies\nuv venv\nsource .venv/bin/activate\nuv pip install -e \".[dev,examples]\"\n```\n\n### Running Tests\n\n```bash\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=datasets_server\n\n# Run only async tests\npytest tests/test_async_client.py\n```\n\n### Code Quality\n\n```bash\n# Format code\nruff format src/ tests/\n\n# Lint code\nruff check src/ tests/\n\n# Type checking\nmypy src/\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the Apache License 2.0 - see the LICENSE file for details.\n\n## Acknowledgments\n\n- Built to work seamlessly with the [Hugging Face Hub](https://huggingface.co/)\n- Inspired by the design patterns of [huggingface_hub](https://github.com/huggingface/huggingface_hub)\n\n## Links\n\n- [Hugging Face Datasets Viewer Documentation](https://huggingface.co/docs/dataset-viewer)\n- [Issue Tracker](https://github.com/davanstrien/datasets-server-py/issues)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavanstrien%2Fdatasets-server-py","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdavanstrien%2Fdatasets-server-py","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavanstrien%2Fdatasets-server-py/lists"}