cooklang-import 0.9.7

A tool for importing recipes into Cooklang format
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
use super::{Extractor, ParsingContext};
use crate::model::Recipe;
use log::debug;
use scraper::{Html, Selector};
use std::collections::HashMap;

pub struct HtmlClassExtractor;

struct ClassMatchers {
    exact: HashMap<&'static str, Vec<&'static str>>,
    fuzzy: HashMap<&'static str, Vec<&'static str>>,
}

impl ClassMatchers {
    fn new() -> Self {
        let mut exact = HashMap::new();
        let mut fuzzy = HashMap::new();

        // WordPress Recipe Card (WPRM)
        exact.insert(
            "title",
            vec![
                "wprm-recipe-name",
                "tasty-recipes-title",
                "mv-create-title",
                "recipe-name",
                "recipe-title",
                "recipecardname",
                "recipe-card-title",
                "recipe-header-title",
                "wprp-recipe-title",
                "recipe_name",
                "recipe-content-title",
                "simple-recipe-pro-recipe-title",
                "recipe-callout-title",
                "wpzoom-recipe-card-title",
                "recipe-card__title",
                "wpupg-recipe-name",
                "recipe-card-title",
                "recipe-title-name",
                "recipess-recipe-title",
            ],
        );

        exact.insert(
            "description",
            vec![
                "wprm-recipe-summary",
                "recipe-summary",
                "recipe-description",
                "mv-create-description",
                "tasty-recipes-description",
                "recipe-card-summary",
                "wpzoom-recipe-summary",
                "recipe-summary-text",
                "recipe-intro",
                "recipe_description",
                "simple-recipe-pro-recipe-description",
                "recipe-callout-summary",
                "wpupg-recipe-summary",
                "recipe-card-description",
            ],
        );

        exact.insert(
            "ingredients",
            vec![
                "wprm-recipe-ingredients-container",
                "wprm-recipe-ingredient",
                "tasty-recipes-ingredients",
                "mv-create-ingredients",
                "recipe-ingredients",
                "recipe-ingredient-list",
                "recipe-card-ingredients",
                "wpzoom-recipe-ingredients",
                "recipe-ingredients-section",
                "simple-recipe-pro-recipe-ingredients",
                "recipe-callout-ingredients",
                "wpupg-recipe-ingredients",
                "recipe-card-ingredient-list",
                "recipe_ingredients",
                "recipess-ingredients-list",
                "structured-ingredients",
                "mpprecipe-ingredients",
                "recipe-content-ingredients",
                "recipe-ingredient-group",
            ],
        );

        exact.insert(
            "instructions",
            vec![
                "wprm-recipe-instructions-container",
                "wprm-recipe-instruction",
                "tasty-recipes-instructions",
                "mv-create-instructions",
                "recipe-instructions",
                "recipe-instruction-list",
                "recipe-card-instructions",
                "wpzoom-recipe-instructions",
                "recipe-instructions-section",
                "simple-recipe-pro-recipe-instructions",
                "recipe-callout-instructions",
                "wpupg-recipe-instructions",
                "recipe-card-instruction-list",
                "recipe_instructions",
                "recipess-instructions-list",
                "structured-instructions",
                "mpprecipe-instructions",
                "recipe-content-instructions",
                "recipe-instruction-group",
                "directions",
                "recipe-directions",
            ],
        );

        exact.insert(
            "prep_time",
            vec![
                "wprm-recipe-prep-time",
                "recipe-prep-time",
                "prep-time",
                "tasty-recipes-prep-time",
                "mv-create-time-prep",
                "recipe-card-prep-time",
                "wpzoom-recipe-prep-time",
                "recipe-prep_time",
                "simple-recipe-pro-prep-time",
                "wpupg-recipe-prep-time",
                "recipe-time-prep",
            ],
        );

        exact.insert(
            "cook_time",
            vec![
                "wprm-recipe-cook-time",
                "recipe-cook-time",
                "cook-time",
                "tasty-recipes-cook-time",
                "mv-create-time-active",
                "recipe-card-cook-time",
                "wpzoom-recipe-cook-time",
                "recipe-cook_time",
                "simple-recipe-pro-cook-time",
                "wpupg-recipe-cook-time",
                "recipe-time-cook",
            ],
        );

        exact.insert(
            "total_time",
            vec![
                "wprm-recipe-total-time",
                "recipe-total-time",
                "total-time",
                "tasty-recipes-total-time",
                "mv-create-time-total",
                "recipe-card-total-time",
                "wpzoom-recipe-total-time",
                "recipe-total_time",
                "simple-recipe-pro-total-time",
                "wpupg-recipe-total-time",
                "recipe-time-total",
            ],
        );

        exact.insert(
            "servings",
            vec![
                "wprm-recipe-servings",
                "recipe-yield",
                "recipe-servings",
                "tasty-recipes-yield",
                "mv-create-yield",
                "recipe-card-servings",
                "wpzoom-recipe-servings",
                "recipe-yield-value",
                "simple-recipe-pro-servings",
                "wpupg-recipe-servings",
                "recipe-card-yield",
                "recipeyield",
            ],
        );

        exact.insert(
            "notes",
            vec![
                "wprm-recipe-notes",
                "recipe-notes",
                "tasty-recipes-notes",
                "mv-create-notes",
                "recipe-card-notes",
                "wpzoom-recipe-notes",
                "recipe-tips",
                "simple-recipe-pro-notes",
                "wpupg-recipe-notes",
                "recipe-card-tips",
                "recipe-footnotes",
            ],
        );

        // Fuzzy matchers for fallback
        fuzzy.insert("title", vec!["recipe", "title", "name", "heading"]);

        fuzzy.insert("ingredients", vec!["ingredient"]);

        fuzzy.insert(
            "instructions",
            vec!["instruction", "direction", "method", "step"],
        );

        fuzzy.insert("description", vec!["summary", "description", "intro"]);

        ClassMatchers { exact, fuzzy }
    }

    fn find_by_class(&self, document: &Html, field: &str) -> Option<String> {
        // Try exact matches first
        if let Some(classes) = self.exact.get(field) {
            for class_name in classes {
                let selector_str = format!(".{class_name}");
                if let Ok(selector) = Selector::parse(&selector_str) {
                    let elements: Vec<_> = document.select(&selector).collect();
                    if !elements.is_empty() {
                        let text = elements
                            .iter()
                            .map(|el| el.text().collect::<Vec<_>>().join(" "))
                            .collect::<Vec<_>>()
                            .join("\n")
                            .trim()
                            .to_string();
                        if !text.is_empty() {
                            debug!("Found {} using exact class: {}", field, class_name);
                            return Some(text);
                        }
                    }
                };
            }
        }

        // Try fuzzy matches as fallback
        if let Some(patterns) = self.fuzzy.get(field) {
            for pattern in patterns {
                let selector_str = format!("[class*='{pattern}']");
                if let Ok(selector) = Selector::parse(&selector_str) {
                    let elements: Vec<_> = document.select(&selector).collect();
                    if !elements.is_empty() {
                        let text = elements
                            .iter()
                            .map(|el| el.text().collect::<Vec<_>>().join(" "))
                            .collect::<Vec<_>>()
                            .join("\n")
                            .trim()
                            .to_string();
                        if !text.is_empty() && text.len() < 5000 {
                            // Avoid grabbing entire page
                            debug!("Found {} using fuzzy class pattern: {}", field, pattern);
                            return Some(text);
                        }
                    }
                };
            }
        }

        None
    }

    fn extract_list_items(&self, document: &Html, field: &str) -> Vec<String> {
        let mut items = Vec::new();

        // Try to find container first
        if let Some(classes) = self.exact.get(field) {
            for class_name in classes {
                let selector_str = format!(".{class_name}");
                if let Ok(selector) = Selector::parse(&selector_str) {
                    for container in document.select(&selector) {
                        // Look for list items within container
                        if let Ok(li_selector) = Selector::parse("li") {
                            for li in container.select(&li_selector) {
                                let text =
                                    li.text().collect::<Vec<_>>().join(" ").trim().to_string();
                                if !text.is_empty() {
                                    items.push(text);
                                }
                            }
                        }

                        // If no list items, try div or p elements
                        if items.is_empty() {
                            for selector_str in &["div", "p", "span"] {
                                if let Ok(item_selector) = Selector::parse(selector_str) {
                                    for item in container.select(&item_selector) {
                                        let text = item
                                            .text()
                                            .collect::<Vec<_>>()
                                            .join(" ")
                                            .trim()
                                            .to_string();
                                        if !text.is_empty() && text.len() > 5 && text.len() < 500 {
                                            items.push(text);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if !items.is_empty() {
                        debug!(
                            "Found {} {} using class: {}",
                            items.len(),
                            field,
                            class_name
                        );
                        return items;
                    }
                };
            }
        }

        items
    }

    /// Extract instructions with section headers preserved
    fn extract_instructions_with_sections(&self, document: &Html) -> Vec<String> {
        let mut items = Vec::new();

        // Try WPRM instruction groups first (they have explicit section headers)
        if let Ok(group_selector) = Selector::parse(".wprm-recipe-instruction-group") {
            let groups: Vec<_> = document.select(&group_selector).collect();
            if !groups.is_empty() {
                for group in groups {
                    // Extract section header
                    if let Ok(header_selector) = Selector::parse(".wprm-recipe-group-name") {
                        if let Some(header) = group.select(&header_selector).next() {
                            let header_text = header
                                .text()
                                .collect::<Vec<_>>()
                                .join(" ")
                                .trim()
                                .to_string();
                            if !header_text.is_empty() {
                                // Add section header as markdown heading
                                items.push(format!("## {}", header_text.trim_end_matches(':')));
                            }
                        }
                    }

                    // Extract list items within this group
                    if let Ok(li_selector) = Selector::parse("li") {
                        for li in group.select(&li_selector) {
                            let text = li.text().collect::<Vec<_>>().join(" ").trim().to_string();
                            if !text.is_empty() {
                                items.push(text);
                            }
                        }
                    }
                }

                if !items.is_empty() {
                    debug!(
                        "Found {} instructions with sections using WPRM groups",
                        items.len()
                    );
                    return items;
                }
            }
        }

        // Try other instruction group patterns
        for group_class in &[
            "recipe-instruction-group",
            "tasty-recipes-instruction-group",
            "mv-create-instruction-group",
        ] {
            if let Ok(group_selector) = Selector::parse(&format!(".{group_class}")) {
                let groups: Vec<_> = document.select(&group_selector).collect();
                if !groups.is_empty() {
                    for group in groups {
                        // Try to find a header (h3, h4, or specific class)
                        for header_tag in &["h3", "h4", ".group-name", ".section-name"] {
                            if let Ok(header_selector) = Selector::parse(header_tag) {
                                if let Some(header) = group.select(&header_selector).next() {
                                    let header_text = header
                                        .text()
                                        .collect::<Vec<_>>()
                                        .join(" ")
                                        .trim()
                                        .to_string();
                                    if !header_text.is_empty() && header_text.len() < 100 {
                                        items.push(format!(
                                            "## {}",
                                            header_text.trim_end_matches(':')
                                        ));
                                        break;
                                    }
                                }
                            }
                        }

                        // Extract list items within this group
                        if let Ok(li_selector) = Selector::parse("li") {
                            for li in group.select(&li_selector) {
                                let text =
                                    li.text().collect::<Vec<_>>().join(" ").trim().to_string();
                                if !text.is_empty() {
                                    items.push(text);
                                }
                            }
                        }
                    }

                    if !items.is_empty() {
                        debug!(
                            "Found {} instructions with sections using {}",
                            items.len(),
                            group_class
                        );
                        return items;
                    }
                }
            }
        }

        // Fall back to regular extraction without sections
        self.extract_list_items(document, "instructions")
    }
}

impl Extractor for HtmlClassExtractor {
    fn parse(&self, context: &ParsingContext) -> Result<Recipe, Box<dyn std::error::Error>> {
        debug!("Attempting to extract recipe using HTML class matchers");

        let matchers = ClassMatchers::new();
        let mut metadata = HashMap::new();
        let mut name = String::new();
        let mut description = None;

        // Extract title
        if let Some(title) = matchers.find_by_class(&context.document, "title") {
            name = title;
        } else {
            // Try h1 or h2 as fallback
            if let Ok(selector) = Selector::parse("h1, h2") {
                if let Some(element) = context.document.select(&selector).next() {
                    name = element
                        .text()
                        .collect::<Vec<_>>()
                        .join(" ")
                        .trim()
                        .to_string();
                }
            }
        }

        // Extract description
        if let Some(desc) = matchers.find_by_class(&context.document, "description") {
            description = Some(desc);
        }

        // Extract ingredients
        let ingredients = matchers.extract_list_items(&context.document, "ingredients");

        // Extract instructions (with section headers preserved)
        let instructions_list = matchers.extract_instructions_with_sections(&context.document);

        // Extract metadata
        if let Some(prep_time) = matchers.find_by_class(&context.document, "prep_time") {
            metadata.insert("prep_time".to_string(), prep_time);
        }

        if let Some(cook_time) = matchers.find_by_class(&context.document, "cook_time") {
            metadata.insert("cook_time".to_string(), cook_time);
        }

        if let Some(total_time) = matchers.find_by_class(&context.document, "total_time") {
            metadata.insert("total_time".to_string(), total_time);
        }

        if let Some(servings) = matchers.find_by_class(&context.document, "servings") {
            metadata.insert("servings".to_string(), servings);
        }

        if let Some(notes) = matchers.find_by_class(&context.document, "notes") {
            metadata.insert("notes".to_string(), notes);
        }

        // Add source URL to metadata
        metadata.insert("source_url".to_string(), context.url.clone());

        // Validation
        if name.is_empty() {
            return Err("Could not extract recipe title from HTML".into());
        }

        if ingredients.is_empty() && instructions_list.is_empty() {
            return Err("Could not extract recipe content from HTML".into());
        }

        // Convert instructions list to single string with paragraph breaks
        let instructions = if !instructions_list.is_empty() {
            instructions_list.join("\n\n")
        } else {
            String::new()
        };

        debug!("Successfully extracted recipe using HTML class matchers");
        debug!("Recipe name: {}", name);
        debug!("Ingredients count: {}", ingredients.len());
        debug!("Instructions count: {}", instructions_list.len());

        Ok(Recipe {
            name,
            description,
            image: Vec::new(),
            ingredients,
            instructions,
            metadata,
        })
    }
}