Metadata-Version: 2.3
Name: yosoi
Version: 0.0.1a11
Summary: AI-Powered Selector Discovery - Discover once, scrape forever
License: 
         
         Apache License
         Version 2.0, January 2004
         http://www.apache.org/licenses/
         
         TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
         
         1. Definitions.
         
         "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
         
         "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
         
         "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
         
         "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
         
         "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
         
         "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
         
         "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
         
         "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
         
         "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
         
         "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
         
         2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
         
         3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
         
         4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
         
             You must give any other recipients of the Work or Derivative Works a copy of this License; and
             You must cause any modified files to carry prominent notices stating that You changed the files; and
             You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
             If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
         
         You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
         
         5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
         
         6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
         
         7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
         
         8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
         
         9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
         
         END OF TERMS AND CONDITIONS
         
         Copyright [yyyy] [name of copyright owner]
         
         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
         You may obtain a copy of the License at
         
             http://www.apache.org/licenses/LICENSE-2.0
         
         Unless required by applicable law or agreed to in writing, software
         distributed under the License is distributed on an "AS IS" BASIS,
         WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         See the License for the specific language governing permissions and
         limitations under the License.
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Dist: beautifulsoup4>=4.12
Requires-Dist: brotli>=1.1
Requires-Dist: click>=8.2.1
Requires-Dist: dateparser>=1.3
Requires-Dist: httpx>=0.28.1
Requires-Dist: logfire>=4.16
Requires-Dist: lxml>=6.0.2
Requires-Dist: parsel>=1.9
Requires-Dist: pydantic>=2
Requires-Dist: pydantic-ai>=0.0.16
Requires-Dist: python-dotenv>=1.2.1
Requires-Dist: rich>=14.2
Requires-Dist: rich-click>=1.9.7
Requires-Dist: taskiq>=0.12.1
Requires-Dist: tenacity>=9.1.4
Requires-Dist: openpyxl>=3.1 ; extra == 'tabular'
Requires-Dist: pandas>=2 ; extra == 'tabular'
Requires-Dist: pyarrow>=14 ; extra == 'tabular'
Requires-Python: >=3.10
Project-URL: Changelog, https://github.com/CascadingLabs/Yosoi/blob/main/CHANGELOG.md
Project-URL: Homepage, https://cascadinglabs.com/yosoi/
Project-URL: Issues, https://github.com/CascadingLabs/Yosoi/issues
Project-URL: Repository, https://github.com/CascadingLabs/Yosoi
Provides-Extra: tabular
Description-Content-Type: text/markdown

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.18713573.svg)](https://doi.org/10.5281/zenodo.18713573)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
[![Actions status](https://github.com/CascadingLabs/Yosoi/actions/workflows/CI.yaml/badge.svg)](https://github.com/CascadingLabs/Yosoi/actions)
[![image](https://img.shields.io/pypi/pyversions/yosoi.svg)](https://pypi.python.org/pypi/yosoi)
[![image](https://img.shields.io/pypi/v/yosoi.svg)](https://pypi.python.org/pypi/yosoi)
[![codecov](https://codecov.io/gh/CascadingLabs/Yosoi/graph/badge.svg?token=DFDI574EEA)](https://codecov.io/gh/CascadingLabs/Yosoi)
<!-- [![image](https://img.shields.io/pypi/l/yosoi.svg)](https://pypi.python.org/pypi/yosoi) -->

# Yosoi - AI-Powered CSS Selector Discover

> **Discover CSS selectors once with AI, scrape forever with BeautifulSoup**

Give Yosoi a URL, and it uses AI to automatically discover the best CSS selectors for extracting headlines, authors, dates, body text, and related content. Discovery takes 3 seconds and costs $0.001 per domain — then scrape thousands of articles for free with BeautifulSoup.

**Key Benefits:**
- **Fast**: 3 seconds to discover selectors per domain
- **Cheap**: $0.001 per domain (one-time cost)
- **Accurate**: Validates selectors before saving
- **Reusable**: Discover once, use forever
- **Production-Ready**: Type-safe, linted, tested

## Quick Start

### Installation

```bash
# Clone the repository
git clone <your-repo>
cd yosoi

# Install dependencies (using uv)
uv sync

# For development tools
uv sync --group dev
```

### Configuration

Create a `.env` file (see `env.example`):

```bash
# Set keys for whichever providers you want to use
GROQ_KEY=your_groq_api_key_here           # groq/...
GEMINI_KEY=your_gemini_api_key_here       # gemini/...
OPENAI_KEY=your_openai_api_key_here       # openai/...
CEREBRAS_KEY=your_cerebras_api_key_here   # cerebras/...
OPENROUTER_KEY=your_openrouter_key_here  # openrouter/...

# Optional: Observability
LOGFIRE_TOKEN=your_logfire_token_here     # For Logfire tracing
```

**Get API Keys:**
- Groq (Free): https://console.groq.com/keys
- Gemini: https://aistudio.google.com/app/apikey
- OpenRouter (Free tier available): https://openrouter.ai/keys
- Logfire (Optional): https://logfire.pydantic.dev

> Some Free models from OpenRouter require configuration of your [Privacy Settings](https://openrouter.ai/settings/privacy) to allow training on your data.

### Basic Usage

```bash
# Process a single URL (uses GROQ_KEY or GEMINI_KEY from .env)
uv run yosoi --url https://example.com/article

# Specify model explicitly with -m provider/model-name
uv run yosoi -m groq/llama-3.3-70b-versatile --url https://example.com/article
uv run yosoi -m gemini/gemini-2.0-flash --url https://example.com/article
uv run yosoi -m openai/gpt-4o --url https://example.com/article
uv run yosoi -m openrouter/gpt-oss --url https://example.com/article

# Process multiple URLs from a file
uv run yosoi -m groq/llama-3.3-70b-versatile --file urls.txt

# Force re-discovery
uv run yosoi --url https://example.com --force

# Show summary of all saved selectors
uv run yosoi --summary

# Enable debug mode (saves extracted HTML)
uv run yosoi --url https://example.com --debug
```

### URLs File Format

Create `urls.txt` with one URL per line:

```text
https://example.com/article1
https://example.com/article2
# Comments are allowed
https://example.com/article3
```

Or use JSON format (`urls.json`):

```json
[
  {"url": "https://example.com/article1"},
  {"url": "https://example.com/article2"}
]
```

## Project Structure

```
.
├── .yosoi/                        # Hidden runtime directory
│   └── selectors/                 # Persisted selector snapshots
├── yosoi/                         # Main package
│   ├── __init__.py
│   ├── __main__.py
│   ├── cli.py                     # CLI entry point & argument parsing
│   ├── core/                      # Core pipeline logic
│   │   ├── pipeline.py            # SelectorDiscoveryPipeline orchestrator
│   │   ├── cleaning/
│   │   │   └── cleaner.py         # HTML noise removal
│   │   ├── discovery/
│   │   │   ├── agent.py           # pydantic-ai agent definition
│   │   │   └── config.py          # Model / provider configuration
│   │   ├── extraction/
│   │   │   └── extractor.py       # Relevant HTML extraction
│   │   ├── fetcher/
│   │   │   ├── base.py            # Abstract fetcher interface
│   │   │   ├── simple.py          # httpx-based fetcher
│   │   │   ├── playwright.py      # Playwright fetcher (JS-heavy sites)
│   │   │   └── smart.py           # Auto-selects fetcher strategy
│   │   └── verification/
│   │       └── verifier.py        # CSS selector verification
│   ├── models/                    # Pydantic data models
│   │   ├── selectors.py           # SelectorSet & field models
│   │   └── results.py             # Pipeline result types
│   ├── storage/                   # Persistence layer
│   │   ├── persistence.py         # JSON read/write for selectors
│   │   ├── tracking.py            # Domain-level tracking & stats
│   │   └── debug.py               # Debug HTML snapshot storage
│   ├── outputs/                   # Output formatters
│   │   ├── json.py                # JSON report formatter
│   │   ├── markdown.py            # Markdown / Rich table output
│   │   └── utils.py               # Shared output helpers
│   ├── prompts/                   # LLM prompt templates (markdown)
│   │   ├── discovery_system.md
│   │   └── discovery_user.md
│   └── utils/                     # Shared utilities
│       ├── exceptions.py          # Custom exception hierarchy
│       ├── files.py               # File-path helpers
│       ├── headers.py             # HTTP header rotation
│       ├── logging.py             # Structured logging setup
│       ├── prompts.py             # Prompt loader utility
│       └── retry.py               # Retry / back-off helpers
├── tests/
│   ├── conftest.py
│   ├── integration/
│   │   ├── test_pipeline.py       # End-to-end pipeline tests
│   │   └── test_snapshots.py      # Selector snapshot regression tests
│   └── unit/
│       ├── test_discovery_bs4.py
│       ├── test_pipeline.py
│       └── test_pydantic_flow.py
├── pyproject.toml                 # Project config & dependencies
├── env.example                    # API key template
└── urls.txt                       # Example URL list
```

## How It Works

### Phase 1: Smart HTML Extraction
```
Full HTML (2MB)
  ↓
Remove noise (scripts, styles, nav, footer)
  ↓
Find main content (<article>, <main>, .content)
  ↓
Extract ~30k chars of relevant HTML
  ↓
Send to AI
```

### Phase 2: AI Analysis
```
AI reads actual HTML structure
  ↓
Finds real class names & IDs
  ↓
Returns up to 3 selectors per field:
  - Primary (most specific)
  - Fallback (reliable backup)
  - Tertiary (generic)
```

### Phase 3: Validation
```
Test each selector on the actual page
  ↓
Find first working selector per field
  ↓
Mark which priority worked (primary/fallback/tertiary)
  ↓
Save validated selectors to JSON
```

## Output Format

Selectors are saved as JSON files in the `.yosoi/selectors/` directory:

```json
{
  "headline": {
    "primary": "h1.article-title",
    "fallback": "h1",
    "tertiary": "h2"
  },
  "author": {
    "primary": "a[href*='/author/']",
    "fallback": ".byline",
    "tertiary": "NA"
  },
  "date": {
    "primary": "time.published-date",
    "fallback": "time",
    "tertiary": ".date"
  },
  "body_text": {
    "primary": "article.content p",
    "fallback": "article p",
    "tertiary": "p"
  },
  "related_content": {
    "primary": "aside.related a",
    "fallback": ".sidebar a",
    "tertiary": "NA"
  }
}
```

## Using Discovered Selectors

Once selectors are discovered, use them with standard BeautifulSoup:

```python
from yosoi.storage.persistence import SelectorStorage
from bs4 import BeautifulSoup
import requests

# Load discovered selectors
storage = SelectorStorage()
selectors = storage.load_selectors('example.com')

# Scrape using the selectors (fast & free!)
url = 'https://example.com/another-article'
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')

# Extract data using validated selectors
headline_selector = selectors['headline']['primary']
headline = soup.select_one(headline_selector)
if headline:
    print(f"Headline: {headline.get_text(strip=True)}")

# Extract body text
body_selector = selectors['body_text']['primary']
paragraphs = soup.select(body_selector)
body_text = '\n\n'.join(p.get_text(strip=True) for p in paragraphs)
print(f"\nBody:\n{body_text}")
```

### Using as a Library

```python
from yosoi.core.pipeline import SelectorDiscoveryPipeline
import os

# Initialize with your preferred provider
pipeline = SelectorDiscoveryPipeline(
    ai_api_key=os.getenv('GROQ_KEY'),
    model_name='llama-3.3-70b-versatile',
    provider='groq'
)

# Process a URL
success = pipeline.process_url('https://example.com/article')

# Process multiple URLs
urls = ['https://example.com/article1', 'https://example.com/article2']
pipeline.process_urls(urls, force=False)

# Show summary
pipeline.show_summary()
```

## Supported AI Models

Use `-m provider/model-name` to select any model explicitly. The API key is read from the corresponding environment variable.

| Provider | `-m` prefix | Env key | Example model |
|----------|-------------|---------|---------------|
| Groq | `groq/` | `GROQ_KEY` | `llama-3.3-70b-versatile` |
| Google Gemini | `gemini/` | `GEMINI_KEY` | `gemini-2.0-flash` |
| OpenAI | `openai/` | `OPENAI_KEY` | `gpt-4o` |
| Cerebras | `cerebras/` | `CEREBRAS_KEY` | `llama-3.3-70b` |
| OpenRouter | `openrouter/` | `OPENROUTER_KEY` | `gpt-oss` |

If `-m` is not provided, Yosoi auto-detects: uses Groq if `GROQ_KEY` is set, otherwise Gemini.

## Observability with Logfire

Yosoi integrates with [Logfire](https://logfire.pydantic.dev) for comprehensive observability:

**What's Tracked:**
- Request/response traces for each URL
- AI model calls and responses
- Selector validation results
- Performance metrics
- Error tracking

**Enable Logfire:**
1. Sign up at https://logfire.pydantic.dev
2. Get your token
3. Add `LOGFIRE_TOKEN=your_token` to `.env`
4. Run your discovery process
5. View traces in Logfire dashboard

## Features

**AI-Powered** - Uses Groq/Gemini to read HTML and find selectors
**Cheap** - $0.001 per domain
**Verified** - Tests each selector on the live page before saving
**Organized** - Clean JSON output per domain
**Rich CLI** - Nice terminal output with progress indicators
**Type-Safe** - Full type hints with mypy checking
**Observable** - Integrated with Logfire for tracing
**Production-Ready** - Linted, formatted, and tested

## Troubleshooting

### AI Returns All "NA"
**Cause**: Site has poor semantic HTML or heavy JavaScript rendering
**Solution**:
- Check if site requires JavaScript (use debug mode: `--debug`)
- Review extracted HTML in `debug_html/` directory
- Use the Playwright fetcher for JavaScript-heavy sites (`SmartFetcher` selects it automatically)
- If the site explicitly fails, re-run with `--force` after verifying the page loads in a browser

### Selectors Don't Work
**Cause**: Site structure changed or uses dynamic content
**Solution**:
- Re-run with `--force` to re-discover selectors
- Check if site requires authentication
- Verify selectors with `--debug` mode

### API Key Errors
**Problem**: `GROQ_KEY` or `GEMINI_KEY` not found
**Solution**:
- Ensure `.env` file exists in project root
- Verify key is correctly formatted (no quotes needed)
- Check key has not expired at provider's dashboard

### HTTP Errors (403, 429, 500)
- **403 Forbidden**: Site blocks scrapers - may need different User-Agent
- **429 Too Many Requests**: Rate limited - add delays between requests
- **5xx Server Error**: Server issue - Yosoi will skip retries automatically

### Import Errors
**Problem**: `ModuleNotFoundError` for pydantic_ai, logfire, etc.
**Solution**:
```bash
# Reinstall dependencies
uv sync

# If still failing, try clean install
rm -rf .venv
uv sync
```

## Best Practices

### For Reliable Scraping

1. **Test on multiple pages**: Validate selectors work across different articles
2. **Use fallback selectors**: Always have primary/fallback/tertiary
3. **Monitor changes**: Re-discover periodically (sites change)
4. **Handle missing data**: Not all fields exist on all pages

### For Better AI Results

1. **Use debug mode first**: Check what HTML is being sent to AI
2. **Prefer semantic HTML**: Sites with `<article>`, `<time>`, etc. work best
3. **Avoid paywalled sites**: Content behind login walls won't work
4. **Check rate limits**: Respect site's `robots.txt` and rate limits

### For Production Use

1. **Cache selectors**: Store and reuse for same domain
2. **Add error handling**: Sites can change or go down
3. **Use Logfire**: Monitor success rates and failures
4. **Set timeouts**: Don't let requests hang indefinitely

## Limitations / Future Developments

- **JavaScript-rendered content**: Not visible in raw HTML (maybe a future development)
- **Paywalled sites**: Cannot access content behind logins
- **Dynamic selectors**: Sites that change class names frequently
- **Rate limits**: Some sites may block or rate-limit requests

## Citation

If you use **yosoi** in your research or project, please cite it using the metadata provided in the `CITATION.cff` file.

### BibTeX
If you are using LaTeX, you can use the following entry:

```bibtex
@software{Berg_yosoi_2026,
author = {Berg, Andrew and Miles, Houston and Mefford, Braeden and Wang, Mia},
license = {Apache-2.0},
month = feb,
title = {{yosoi}},
url = {https://github.com/CascadingLabs/Yosoi},
version = {0.0.1-alpha6},
year = {2026}
}
```
