meta_oxide 0.1.1

Universal metadata extraction library supporting 13 formats (HTML Meta, Open Graph, Twitter Cards, JSON-LD, Microdata, Microformats, RDFa, Dublin Core, Web App Manifest, oEmbed, rel-links, Images, SEO) with 7 language bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
# Development Guide

Guide for contributing to and developing MetaOxide.

## Table of Contents

- [Development Setup]#development-setup
- [Project Structure]#project-structure
- [Building]#building
- [Testing]#testing
- [Adding New Microformats]#adding-new-microformats
- [Code Style]#code-style
- [Contributing]#contributing
- [Release Process]#release-process

---

## Development Setup

### Prerequisites

1. **Rust Toolchain**
   ```bash
   curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
   source $HOME/.cargo/env
   rustup update
   ```

2. **Python Development Environment**
   ```bash
   # Install Python 3.8+
   python3 --version

   # Create virtual environment
   python3 -m venv venv
   source venv/bin/activate  # On Windows: venv\Scripts\activate
   ```

3. **Maturin** (for Python bindings)
   ```bash
   pip install maturin
   ```

4. **Development Tools**
   ```bash
   # Rust formatter and linter
   rustup component add rustfmt clippy

   # Python tools
   pip install pytest black mypy ruff
   ```

### Clone and Setup

```bash
# Clone repository
git clone https://github.com/yourusername/meta_oxide.git
cd meta_oxide

# Install development dependencies
pip install -r requirements-dev.txt

# Build in development mode
maturin develop
```

---

## Project Structure

```
meta_oxide/
├── Cargo.toml              # Rust package configuration
├── pyproject.toml          # Python package configuration
├── README.md               # Project overview
├── LICENSE                 # License file
├── src/                    # Rust source code
│   ├── lib.rs              # Python bindings (PyO3)
│   ├── parser.rs           # HTML parser
│   ├── types.rs            # Data structures
│   ├── errors.rs           # Error types
│   └── extractors/         # Microformat extractors
│       ├── mod.rs          # Extractor module
│       ├── hcard.rs        # h-card extractor
│       ├── hentry.rs       # h-entry extractor
│       └── hevent.rs       # h-event extractor
├── tests/                  # Integration tests
│   ├── test_hcard.rs
│   ├── test_hentry.rs
│   └── test_hevent.rs
├── python/                 # Python-specific code
│   └── tests/              # Python tests
│       ├── test_hcard.py
│       ├── test_hentry.py
│       └── test_hevent.py
├── docs/                   # Documentation
│   ├── getting-started.md
│   ├── architecture.md
│   ├── api-reference.md
│   ├── examples.md
│   └── development.md
├── examples/               # Example code
│   ├── basic_usage.py
│   ├── rust_example.rs
│   └── web_scraper.py
└── benches/                # Benchmarks
    └── extraction_bench.rs
```

---

## Building

### Build Rust Library

```bash
# Debug build
cargo build

# Release build
cargo build --release

# Build and run tests
cargo test

# Build documentation
cargo doc --open
```

### Build Python Package

```bash
# Development build (with debug symbols)
maturin develop

# Release build
maturin build --release

# Build wheel
maturin build --release --out dist/

# Install from wheel
pip install dist/meta_oxide-*.whl
```

---

## Testing

### Rust Tests

```bash
# Run all tests
cargo test

# Run specific test
cargo test test_extract_hcard

# Run tests with output
cargo test -- --nocapture

# Run tests in specific module
cargo test extractors::hcard

# Run integration tests
cargo test --test '*'
```

### Python Tests

```bash
# Make sure package is built
maturin develop

# Run pytest
pytest python/tests/

# Run with coverage
pytest --cov=meta_oxide python/tests/

# Run specific test
pytest python/tests/test_hcard.py::test_basic_hcard
```

### Test Coverage

```bash
# Install tarpaulin
cargo install cargo-tarpaulin

# Generate coverage report
cargo tarpaulin --out Html --output-dir coverage/

# Open report
open coverage/index.html
```

---

## Adding New Microformats

### Step 1: Define the Type

Add a new struct in `src/types.rs`:

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HReview {
    pub name: Option<String>,
    pub rating: Option<String>,
    pub item: Option<String>,
    pub summary: Option<String>,
    pub reviewer: Option<Box<HCard>>,
    pub additional_properties: HashMap<String, Vec<String>>,
}

impl HReview {
    pub fn to_py_dict(&self, py: Python) -> Py<PyDict> {
        let dict = PyDict::new_bound(py);

        if let Some(name) = &self.name {
            dict.set_item("name", name).unwrap();
        }
        if let Some(rating) = &self.rating {
            dict.set_item("rating", rating).unwrap();
        }
        // ... add other fields

        dict.into()
    }
}
```

### Step 2: Create Extractor

Create `src/extractors/hreview.rs`:

```rust
use crate::errors::{MicroformatError, Result};
use crate::types::HReview;
use scraper::{Html, Selector};
use std::collections::HashMap;

pub fn extract(html: &str, _base_url: Option<&str>) -> Result<Vec<HReview>> {
    let document = Html::parse_document(html);
    let mut reviews = Vec::new();

    let selector = Selector::parse(".h-review")
        .map_err(|e| MicroformatError::ParseError(e.to_string()))?;

    for element in document.select(&selector) {
        let mut review = HReview {
            name: None,
            rating: None,
            item: None,
            summary: None,
            reviewer: None,
            additional_properties: HashMap::new(),
        };

        // Extract properties
        if let Ok(name_sel) = Selector::parse(".p-name") {
            if let Some(name_elem) = element.select(&name_sel).next() {
                review.name = Some(name_elem.text().collect::<String>().trim().to_string());
            }
        }

        // ... extract other properties

        reviews.push(review);
    }

    Ok(reviews)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_hreview() {
        let html = r#"
            <div class="h-review">
                <span class="p-name">Great Product</span>
                <span class="p-rating">5</span>
            </div>
        "#;

        let reviews = extract(html, None).unwrap();
        assert_eq!(reviews.len(), 1);
        assert_eq!(reviews[0].name, Some("Great Product".to_string()));
        assert_eq!(reviews[0].rating, Some("5".to_string()));
    }
}
```

### Step 3: Update Module

Add to `src/extractors/mod.rs`:

```rust
pub mod hreview;
pub use hreview::extract as extract_hreview;
```

### Step 4: Add Python Binding

Add to `src/lib.rs`:

```rust
#[pyfunction]
fn extract_hreview(html: &str, base_url: Option<&str>) -> PyResult<Vec<PyObject>> {
    Python::with_gil(|py| {
        let reviews = extractors::hreview::extract(html, base_url)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;

        Ok(reviews.iter().map(|review| review.to_py_dict(py).into()).collect())
    })
}

#[pymodule]
fn meta_oxide(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(extract_microformats, m)?)?;
    m.add_function(wrap_pyfunction!(extract_hcard, m)?)?;
    m.add_function(wrap_pyfunction!(extract_hentry, m)?)?;
    m.add_function(wrap_pyfunction!(extract_hevent, m)?)?;
    m.add_function(wrap_pyfunction!(extract_hreview, m)?)?;  // Add this
    m.add("__version__", env!("CARGO_PKG_VERSION"))?;
    Ok(())
}
```

### Step 5: Add Tests

Create `python/tests/test_hreview.py`:

```python
import meta_oxide

def test_extract_hreview():
    html = """
    <div class="h-review">
        <span class="p-name">Great Product</span>
        <span class="p-rating">5</span>
    </div>
    """

    reviews = meta_oxide.extract_hreview(html)
    assert len(reviews) == 1
    assert reviews[0]['name'] == 'Great Product'
    assert reviews[0]['rating'] == '5'
```

### Step 6: Update Documentation

1. Add entry to `docs/api-reference.md`
2. Add example to `docs/examples.md`
3. Update README.md supported formats list

---

## Code Style

### Rust

Follow Rust conventions and use the formatter:

```bash
# Format code
cargo fmt

# Check formatting
cargo fmt -- --check

# Run clippy
cargo clippy -- -D warnings

# Fix clippy suggestions
cargo clippy --fix
```

**Style Guidelines:**
- Use 4 spaces for indentation
- Maximum line length: 100 characters
- Use descriptive variable names
- Add documentation comments for public APIs
- Use `Result<T, E>` for functions that can fail

**Example:**
```rust
/// Extract h-card microformats from HTML
///
/// # Arguments
///
/// * `html` - HTML string to parse
/// * `base_url` - Optional base URL for resolving relative URLs
///
/// # Returns
///
/// Vector of extracted h-cards
///
/// # Errors
///
/// Returns `MicroformatError` if parsing fails
pub fn extract(html: &str, base_url: Option<&str>) -> Result<Vec<HCard>> {
    // Implementation
}
```

### Python

Follow PEP 8 and use the formatter:

```bash
# Format with black
black python/

# Lint with ruff
ruff check python/

# Type check with mypy
mypy python/
```

---

## Benchmarking

### Create Benchmark

Create `benches/extraction_bench.rs`:

```rust
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use meta_oxide::extractors::extract_hcard;

fn bench_hcard_extraction(c: &mut Criterion) {
    let html = r#"
        <div class="h-card">
            <span class="p-name">John Doe</span>
            <a class="u-url" href="https://example.com">Website</a>
        </div>
    "#;

    c.bench_function("extract_hcard", |b| {
        b.iter(|| extract_hcard(black_box(html), None))
    });
}

criterion_group!(benches, bench_hcard_extraction);
criterion_main!(benches);
```

### Run Benchmarks

```bash
# Run all benchmarks
cargo bench

# Run specific benchmark
cargo bench extract_hcard

# Generate HTML report
cargo bench -- --save-baseline my_baseline
```

---

## Contributing

### Workflow

1. **Fork the repository**
   ```bash
   # On GitHub, click "Fork"
   git clone https://github.com/yourusername/meta_oxide.git
   ```

2. **Create a branch**
   ```bash
   git checkout -b feature/my-new-feature
   ```

3. **Make changes**
   - Write code
   - Add tests
   - Update documentation

4. **Run tests and linters**
   ```bash
   cargo test
   cargo fmt
   cargo clippy
   pytest python/tests/
   ```

5. **Commit changes**
   ```bash
   git add .
   git commit -m "Add new feature: description"
   ```

6. **Push and create PR**
   ```bash
   git push origin feature/my-new-feature
   # Create pull request on GitHub
   ```

### Commit Message Format

Use conventional commits:

```
type(scope): short description

Longer description if needed

Fixes #123
```

**Types:**
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `test`: Test changes
- `refactor`: Code refactoring
- `perf`: Performance improvement
- `chore`: Maintenance tasks

**Examples:**
```
feat(extractors): add h-review support
fix(parser): handle nested microformats correctly
docs(api): update h-card examples
test(hentry): add test for author extraction
```

---

## Release Process

### Version Bumping

1. Update version in `Cargo.toml`
2. Update `CHANGELOG.md`
3. Create git tag

```bash
# Bump version
# Edit Cargo.toml: version = "0.1.0"

# Update changelog
# Edit CHANGELOG.md

# Commit
git add Cargo.toml CHANGELOG.md
git commit -m "chore: bump version to 0.2.0"

# Tag
git tag -a v0.1.0 -m "Release v0.1.0"
git push origin v0.1.0
```

### Publishing to PyPI

```bash
# Build wheels for multiple platforms
maturin build --release

# Publish to PyPI
maturin publish --username __token__ --password $PYPI_TOKEN
```

### Publishing to crates.io

```bash
# Login
cargo login

# Publish
cargo publish
```

---

## Debugging

### Debug Rust Code

```bash
# Build with debug symbols
cargo build

# Run with debugger (lldb on macOS, gdb on Linux)
rust-lldb target/debug/meta_oxide
```

### Debug Python Bindings

```python
import meta_oxide
import pdb

html = "..."

# Set breakpoint
pdb.set_trace()
result = meta_oxide.extract_hcard(html)
```

### Enable Logging

Add to `Cargo.toml`:

```toml
[dependencies]
env_logger = "0.11"
log = "0.4"
```

Use in code:

```rust
use log::{debug, info, warn, error};

info!("Parsing HTML document");
debug!("Found {} elements", elements.len());
```

Run with logging:

```bash
RUST_LOG=debug cargo test
```

---

## IDE Setup

### VS Code

Recommended extensions:
- rust-analyzer
- Python
- Even Better TOML
- CodeLLDB (for debugging)

Settings (`.vscode/settings.json`):

```json
{
    "rust-analyzer.check.command": "clippy",
    "python.linting.enabled": true,
    "python.linting.ruffEnabled": true,
    "python.formatting.provider": "black",
    "[rust]": {
        "editor.defaultFormatter": "rust-lang.rust-analyzer",
        "editor.formatOnSave": true
    }
}
```

### PyCharm / IntelliJ IDEA

1. Install Rust plugin
2. Configure Python interpreter
3. Enable "Format on save"

---

## Resources

- [Rust Book]https://doc.rust-lang.org/book/
- [PyO3 Guide]https://pyo3.rs/
- [Microformats Wiki]http://microformats.org/wiki/
- [scraper Documentation]https://docs.rs/scraper/

---

## Getting Help

- Open an issue on GitHub
- Join discussions
- Check existing documentation
- Read the code (it's well-commented!)