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
//! Types for RDFa (Resource Description Framework in Attributes)
//!
//! RDFa is a W3C standard for embedding structured data in HTML using attributes.
//! It provides semantic markup for web content with 62% desktop adoption.

use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// RDFa item representing a resource with properties
///
/// Corresponds to an element with `typeof` or `vocab` attribute.
/// Can contain nested items and multiple property values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct RdfaItem {
    /// The resource type(s) from typeof attribute
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub type_of: Option<Vec<String>>,

    /// The subject URI from about attribute
    #[serde(skip_serializing_if = "Option::is_none")]
    pub about: Option<String>,

    /// The vocabulary namespace
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vocab: Option<String>,

    /// Properties extracted from property attributes
    /// Key: property name, Value: array of property values
    #[serde(flatten)]
    pub properties: HashMap<String, Vec<RdfaValue>>,
}

/// Value of an RDFa property
///
/// Can be a literal text, URI reference, nested item, or typed literal
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RdfaValue {
    /// Nested RDFa item (must come first for untagged serde)
    Item(Box<RdfaItem>),

    /// Typed literal with datatype
    TypedLiteral { value: String, datatype: String },

    /// URI reference
    Resource(String),

    /// Literal text value
    Literal(String),
}

impl RdfaItem {
    /// Create a new empty RDFa item
    pub fn new() -> Self {
        Self {
            type_of: None,
            about: None,
            vocab: None,
            properties: HashMap::new(),
        }
    }

    /// Set the item type(s)
    pub fn with_type(mut self, types: Vec<String>) -> Self {
        self.type_of = Some(types);
        self
    }

    /// Set the vocab namespace
    pub fn with_vocab(mut self, vocab: String) -> Self {
        self.vocab = Some(vocab);
        self
    }

    /// Set the about URI
    pub fn with_about(mut self, about: String) -> Self {
        self.about = Some(about);
        self
    }

    /// Add a property value
    pub fn add_property(&mut self, name: String, value: RdfaValue) {
        self.properties.entry(name).or_default().push(value);
    }

    /// Convert to Python dictionary
    pub fn to_py_dict(&self, py: Python) -> Py<PyDict> {
        let dict = PyDict::new_bound(py);

        // Add type(s) - always as a list for consistency
        if let Some(ref types) = self.type_of {
            dict.set_item("type", types.clone()).unwrap();
        }

        // Add vocab
        if let Some(ref vocab) = self.vocab {
            dict.set_item("vocab", vocab).unwrap();
        }

        // Add about
        if let Some(ref about) = self.about {
            dict.set_item("about", about).unwrap();
        }

        // Add properties
        for (key, values) in &self.properties {
            if values.len() == 1 {
                // Single value - add directly
                dict.set_item(key, values[0].to_py_value(py)).unwrap();
            } else {
                // Multiple values - add as list
                let list = PyList::empty_bound(py);
                for value in values {
                    list.append(value.to_py_value(py)).unwrap();
                }
                dict.set_item(key, list).unwrap();
            }
        }

        dict.unbind()
    }
}

impl RdfaValue {
    /// Convert to Python value
    pub fn to_py_value(&self, py: Python) -> PyObject {
        match self {
            RdfaValue::Literal(s) => s.to_object(py),
            RdfaValue::Resource(uri) => uri.to_object(py),
            RdfaValue::Item(item) => item.to_py_dict(py).to_object(py),
            RdfaValue::TypedLiteral { value, datatype } => {
                let dict = PyDict::new_bound(py);
                dict.set_item("value", value).unwrap();
                dict.set_item("datatype", datatype).unwrap();
                dict.to_object(py)
            }
        }
    }
}

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

    #[test]
    fn test_rdfa_item_new() {
        let item = RdfaItem::new();
        assert!(item.type_of.is_none());
        assert!(item.about.is_none());
        assert!(item.vocab.is_none());
        assert!(item.properties.is_empty());
    }

    #[test]
    fn test_rdfa_item_default() {
        let item = RdfaItem::default();
        assert!(item.type_of.is_none());
        assert!(item.properties.is_empty());
    }

    #[test]
    fn test_rdfa_item_with_type() {
        let item = RdfaItem::new().with_type(vec!["https://schema.org/Person".to_string()]);
        assert_eq!(item.type_of, Some(vec!["https://schema.org/Person".to_string()]));
    }

    #[test]
    fn test_rdfa_item_with_vocab() {
        let item = RdfaItem::new().with_vocab("https://schema.org/".to_string());
        assert_eq!(item.vocab, Some("https://schema.org/".to_string()));
    }

    #[test]
    fn test_rdfa_item_with_about() {
        let item = RdfaItem::new().with_about("https://example.com/person/123".to_string());
        assert_eq!(item.about, Some("https://example.com/person/123".to_string()));
    }

    #[test]
    fn test_rdfa_item_add_property() {
        let mut item = RdfaItem::new();
        item.add_property("name".to_string(), RdfaValue::Literal("Jane Doe".to_string()));

        assert_eq!(item.properties.get("name").unwrap().len(), 1);
        match &item.properties.get("name").unwrap()[0] {
            RdfaValue::Literal(s) => assert_eq!(s, "Jane Doe"),
            _ => panic!("Expected literal value"),
        }
    }

    #[test]
    fn test_rdfa_item_multiple_properties() {
        let mut item = RdfaItem::new();
        item.add_property("telephone".to_string(), RdfaValue::Literal("555-1234".to_string()));
        item.add_property("telephone".to_string(), RdfaValue::Literal("555-5678".to_string()));

        assert_eq!(item.properties.get("telephone").unwrap().len(), 2);
    }

    #[test]
    fn test_rdfa_value_literal() {
        let value = RdfaValue::Literal("test".to_string());
        match value {
            RdfaValue::Literal(s) => assert_eq!(s, "test"),
            _ => panic!("Expected literal value"),
        }
    }

    #[test]
    fn test_rdfa_value_resource() {
        let value = RdfaValue::Resource("https://example.com".to_string());
        match value {
            RdfaValue::Resource(uri) => assert_eq!(uri, "https://example.com"),
            _ => panic!("Expected resource value"),
        }
    }

    #[test]
    fn test_rdfa_value_item() {
        let nested = RdfaItem::new();
        let value = RdfaValue::Item(Box::new(nested));
        match value {
            RdfaValue::Item(_) => {}
            _ => panic!("Expected item value"),
        }
    }

    #[test]
    fn test_rdfa_value_typed_literal() {
        let value = RdfaValue::TypedLiteral {
            value: "42".to_string(),
            datatype: "http://www.w3.org/2001/XMLSchema#integer".to_string(),
        };
        match value {
            RdfaValue::TypedLiteral { value, datatype } => {
                assert_eq!(value, "42");
                assert_eq!(datatype, "http://www.w3.org/2001/XMLSchema#integer");
            }
            _ => panic!("Expected typed literal"),
        }
    }

    #[test]
    fn test_rdfa_item_clone() {
        let mut item = RdfaItem::new().with_type(vec!["Person".to_string()]);
        item.add_property("name".to_string(), RdfaValue::Literal("Jane".to_string()));

        let cloned = item.clone();
        assert_eq!(item, cloned);
    }

    #[test]
    fn test_rdfa_item_partial_eq() {
        let mut item1 = RdfaItem::new().with_type(vec!["Person".to_string()]);
        item1.add_property("name".to_string(), RdfaValue::Literal("Jane".to_string()));

        let mut item2 = RdfaItem::new().with_type(vec!["Person".to_string()]);
        item2.add_property("name".to_string(), RdfaValue::Literal("Jane".to_string()));

        assert_eq!(item1, item2);
    }

    #[test]
    fn test_serde_serialize_deserialize() {
        let mut item = RdfaItem::new()
            .with_type(vec!["https://schema.org/Person".to_string()])
            .with_vocab("https://schema.org/".to_string())
            .with_about("https://example.com/jane".to_string());
        item.add_property("name".to_string(), RdfaValue::Literal("Jane Doe".to_string()));

        let json = serde_json::to_string(&item).unwrap();
        let deserialized: RdfaItem = serde_json::from_str(&json).unwrap();

        assert_eq!(item, deserialized);
    }

    #[test]
    fn test_serde_skip_none_fields() {
        let item = RdfaItem::new();
        let json = serde_json::to_value(&item).unwrap();

        // None fields should be skipped
        assert!(!json.as_object().unwrap().contains_key("type"));
        assert!(!json.as_object().unwrap().contains_key("vocab"));
        assert!(!json.as_object().unwrap().contains_key("about"));
    }

    #[test]
    fn test_serde_flatten_properties() {
        let mut item = RdfaItem::new();
        item.add_property("name".to_string(), RdfaValue::Literal("Jane".to_string()));

        let json = serde_json::to_value(&item).unwrap();
        let obj = json.as_object().unwrap();

        // Properties should be flattened into the root object
        assert!(obj.contains_key("name"));
    }

    #[test]
    fn test_to_py_dict_basic() {
        Python::with_gil(|py| {
            let mut item =
                RdfaItem::new().with_type(vec!["https://schema.org/Person".to_string()]);
            item.add_property("name".to_string(), RdfaValue::Literal("Jane Doe".to_string()));

            let py_dict = item.to_py_dict(py);
            let dict = py_dict.bind(py);

            assert!(dict.contains("type").unwrap());
            assert!(dict.contains("name").unwrap());
        });
    }

    #[test]
    fn test_to_py_dict_with_vocab() {
        Python::with_gil(|py| {
            let item = RdfaItem::new().with_vocab("https://schema.org/".to_string());

            let py_dict = item.to_py_dict(py);
            let dict = py_dict.bind(py);

            assert!(dict.contains("vocab").unwrap());
        });
    }

    #[test]
    fn test_to_py_dict_with_about() {
        Python::with_gil(|py| {
            let item = RdfaItem::new().with_about("https://example.com/jane".to_string());

            let py_dict = item.to_py_dict(py);
            let dict = py_dict.bind(py);

            assert!(dict.contains("about").unwrap());
        });
    }

    #[test]
    fn test_to_py_dict_multiple_values() {
        Python::with_gil(|py| {
            let mut item = RdfaItem::new();
            item.add_property("telephone".to_string(), RdfaValue::Literal("555-1234".to_string()));
            item.add_property("telephone".to_string(), RdfaValue::Literal("555-5678".to_string()));

            let py_dict = item.to_py_dict(py);
            let dict = py_dict.bind(py);

            assert!(dict.contains("telephone").unwrap());
            // Should be a list since there are multiple values
            let tel = dict.get_item("telephone").unwrap().unwrap();
            assert!(tel.is_instance_of::<PyList>());
        });
    }

    #[test]
    fn test_to_py_dict_nested_item() {
        Python::with_gil(|py| {
            let mut item = RdfaItem::new();
            let mut address =
                RdfaItem::new().with_type(vec!["https://schema.org/PostalAddress".to_string()]);
            address
                .add_property("streetAddress".to_string(), RdfaValue::Literal("123 Main".to_string()));

            item.add_property("address".to_string(), RdfaValue::Item(Box::new(address)));

            let py_dict = item.to_py_dict(py);
            let dict = py_dict.bind(py);

            assert!(dict.contains("address").unwrap());
            let address_val = dict.get_item("address").unwrap().unwrap();
            assert!(address_val.is_instance_of::<PyDict>());
        });
    }

    #[test]
    fn test_rdfa_value_to_py_literal() {
        Python::with_gil(|py| {
            let value = RdfaValue::Literal("test".to_string());
            let py_value = value.to_py_value(py);
            let py_str: String = py_value.extract(py).unwrap();
            assert_eq!(py_str, "test");
        });
    }

    #[test]
    fn test_rdfa_value_to_py_resource() {
        Python::with_gil(|py| {
            let value = RdfaValue::Resource("https://example.com".to_string());
            let py_value = value.to_py_value(py);
            let py_str: String = py_value.extract(py).unwrap();
            assert_eq!(py_str, "https://example.com");
        });
    }

    #[test]
    fn test_rdfa_value_to_py_typed_literal() {
        Python::with_gil(|py| {
            let value = RdfaValue::TypedLiteral {
                value: "42".to_string(),
                datatype: "xsd:integer".to_string(),
            };
            let py_value = value.to_py_value(py);
            let py_dict: Bound<PyDict> = py_value.extract(py).unwrap();
            assert!(py_dict.contains("value").unwrap());
            assert!(py_dict.contains("datatype").unwrap());
        });
    }

    #[test]
    fn test_rdfa_value_to_py_nested_item() {
        Python::with_gil(|py| {
            let item = RdfaItem::new().with_type(vec!["Person".to_string()]);
            let value = RdfaValue::Item(Box::new(item));
            let py_value = value.to_py_value(py);
            let py_dict: Bound<PyDict> = py_value.extract(py).unwrap();
            assert!(py_dict.contains("type").unwrap());
        });
    }
}