cooklang-import 0.7.0

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
use crate::extractors::{Extractor, ParsingContext};
use crate::model::Recipe;
use log::info;
use reqwest::Client;
use scraper::{ElementRef, Html, Node};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::env;
use std::error::Error;

const PROMPT: &str = r#"
You're an expert in finding recipe ingredients and instructions from messy texts.
Sometimes the text is not a recipe, in that case specify that in error field.
Given the text output only this JSON without any other characters:

{
  "ingredients": [<LIST OF INGREDIENTS HERE>],
  "instructions": [<LIST OF INSTRUCTIONS HERE>],
  "error": "<ERROR MESSAGE HERE IF NO RECIPE>"
}
"#;

const MODEL: &str = "gpt-4o-mini";

pub struct PlainTextLlmExtractor;

#[async_trait::async_trait]
impl Extractor for PlainTextLlmExtractor {
    fn parse(&self, context: &ParsingContext) -> Result<Recipe, Box<dyn std::error::Error>> {
        info!("Parsing with PlainTextLlmExtractor for {}", context.url);

        let document = &context.document;

        let texts = if env::var("PAGE_SCRIBER_URL").is_ok() {
            tokio::task::block_in_place(|| {
                tokio::runtime::Handle::current().block_on(fetch_inner_text(&context.url))
            })?
        } else {
            extract_inner_texts(document).join("\n")
        };

        let title = document
            .select(&scraper::Selector::parse("title").unwrap())
            .next()
            .map(|el| el.inner_html().trim().to_string())
            .unwrap_or_else(|| "Untitled Recipe".to_string());

        let json = tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current().block_on(fetch_json(texts))
        })?;

        if let Some(error) = json["error"].as_str() {
            if !error.is_empty() {
                return Err(error.into());
            }
        }

        let ingredients = json["ingredients"]
            .as_array()
            .unwrap_or(&Vec::new())
            .iter()
            .filter_map(|i| i.as_str().map(String::from))
            .collect::<Vec<String>>()
            .join("\n");

        let instructions = json["instructions"]
            .as_array()
            .unwrap_or(&Vec::new())
            .iter()
            .filter_map(|i| i.as_str().map(String::from))
            .collect::<Vec<String>>()
            .join(" ");

        // Combine into single content field
        let content = if !ingredients.is_empty() && !instructions.is_empty() {
            format!("{}\n\n{}", ingredients, instructions)
        } else if !ingredients.is_empty() {
            ingredients
        } else {
            instructions
        };

        Ok(Recipe {
            name: title,
            description: None,
            image: vec![],
            content,
            metadata: std::collections::HashMap::new(),
        })
    }
}

async fn fetch_inner_text(url: &str) -> Result<String, Box<dyn Error>> {
    let page_scriber_url = env::var("PAGE_SCRIBER_URL")?;
    let client = Client::new();
    let endpoint = format!("{page_scriber_url}/api/fetch-content");

    let response = client
        .post(&endpoint)
        .json(&ContentRequest {
            url: url.to_string(),
        })
        .send()
        .await?;

    // Check status code before attempting to parse JSON
    if !response.status().is_success() {
        return Err(format!(
            "Page scriber request failed with status: {}",
            response.status()
        )
        .into());
    }

    let content: ContentResponse = response.json().await?;

    Ok(content.content)
}

async fn fetch_json(texts: String) -> Result<Value, Box<dyn Error>> {
    let api_key = std::env::var("OPENAI_API_KEY")?;

    // For testing environment, return mock data
    if api_key == "test_key" {
        return Ok(serde_json::json!({
            "ingredients": "pasta\nsauce",
            "instructions": ["Cook pasta with sauce"],
            "error": ""
        }));
    }

    let response = reqwest::Client::new()
        .post("https://api.openai.com/v1/chat/completions")
        .header("Authorization", format!("Bearer {api_key}"))
        .json(&serde_json::json!({
            "model": MODEL,
            "messages": [
                {
                    "role": "system",
                    "content": PROMPT
                },
                {
                    "role": "user",
                    "content": texts
                }
            ]
        }))
        .send()
        .await?
        .json::<Value>()
        .await?;

    let content = response["choices"][0]["message"]["content"]
        .as_str()
        .ok_or("Failed to get response content")?;

    serde_json::from_str(content).map_err(|e| e.into())
}

fn extract_inner_texts(document: &Html) -> Vec<String> {
    let mut result = Vec::new();
    let root = document.root_element();
    extract_text_from_element(&root, &mut result);

    // Process the result to merge text between block markers
    let mut processed = Vec::new();
    let mut current_block = Vec::new();

    for text in result {
        match text.as_str() {
            "<BLOCK>" => {
                // Start a new block
                if !current_block.is_empty() {
                    let merged = current_block.join(" ").trim().to_string();
                    if !merged.is_empty() {
                        processed.push(merged);
                    }
                    current_block.clear();
                }
            }
            "</BLOCK>" => {
                // End the current block
                if !current_block.is_empty() {
                    let merged = current_block.join(" ").trim().to_string();
                    if !merged.is_empty() {
                        processed.push(merged);
                    }
                    current_block.clear();
                }
            }
            text => current_block.push(text.to_string()),
        }
    }

    // Handle any remaining text
    if !current_block.is_empty() {
        let merged = current_block.join(" ").trim().to_string();
        if !merged.is_empty() {
            processed.push(merged);
        }
    }

    // Remove any trailing empty lines
    while processed.last().is_some_and(|s| s.trim().is_empty()) {
        processed.pop();
    }

    processed
}

fn extract_text_from_element(element: &ElementRef, result: &mut Vec<String>) {
    // Skip hidden elements and script/style tags
    if is_hidden(element) || should_skip_element(element) {
        return;
    }

    let tag_name = element.value().name().to_lowercase();

    // Handle special elements
    if tag_name == "br" {
        result.push("<BLOCK>".to_string());
        return;
    }

    for child in element.children() {
        match child.value() {
            Node::Text(text) => {
                let trimmed = normalize_whitespace(text);
                if !trimmed.is_empty() {
                    result.push(trimmed);
                }
            }
            Node::Element(_) => {
                if let Some(child_ref) = ElementRef::wrap(child) {
                    extract_text_from_element(&child_ref, result);
                }
            }
            _ => {}
        }
    }

    // Add newline after block elements
    if is_block_element(&tag_name) {
        result.push("</BLOCK>".to_string());
    }
}

fn is_hidden(element: &ElementRef) -> bool {
    element.value().attr("hidden").is_some()
        || element
            .value()
            .attr("style")
            .map(|s| s.contains("display: none") || s.contains("visibility: hidden"))
            .unwrap_or(false)
}

fn is_block_element(tag: &str) -> bool {
    matches!(
        tag,
        "address"
            | "article"
            | "aside"
            | "blockquote"
            | "canvas"
            | "dd"
            | "div"
            | "dl"
            | "dt"
            | "fieldset"
            | "figcaption"
            | "figure"
            | "footer"
            | "form"
            | "h1"
            | "h2"
            | "h3"
            | "h4"
            | "h5"
            | "h6"
            | "header"
            | "hr"
            | "li"
            | "main"
            | "nav"
            | "noscript"
            | "ol"
            | "p"
            | "pre"
            | "section"
            | "table"
            | "tfoot"
            | "tr"
            | "ul"
            | "video"
    )
}

fn normalize_whitespace(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

fn should_skip_element(element: &ElementRef) -> bool {
    let tag_name = element.value().name().to_lowercase();
    matches!(
        tag_name.as_str(),
        "script" | "style" | "noscript" | "iframe" | "canvas" | "svg"
    )
}

#[derive(Serialize)]
struct ContentRequest {
    url: String,
}

#[derive(Deserialize)]
struct ContentResponse {
    content: String,
}

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

    #[test]
    fn test_parse_success() {
        let html = "<html><body>Test</body></html>";
        let document = Html::parse_document(html);
        let context = ParsingContext {
            url: "http://example.com".to_string(),
            document,
            texts: None,
        };
        let extractor = PlainTextLlmExtractor;
        // Set up environment for test
        env::set_var("OPENAI_API_KEY", "test_key");

        tokio::runtime::Runtime::new().unwrap().block_on(async {
            let result = extractor.parse(&context);
            assert!(result.is_ok());
        });
    }

    #[test]
    fn test_parse() {
        // Set up environment for test
        env::set_var("OPENAI_API_KEY", "test_key");

        let html = r#"
            <html>
                <head><title>Test Recipe</title></head>
                <body>
                    <h1>Pasta Recipe</h1>
                    <p>Cook pasta with sauce</p>
                </body>
            </html>
        "#;

        let document = Html::parse_document(html);
        let context = ParsingContext {
            url: "http://example.com".to_string(),
            document,
            texts: None,
        };
        let extractor = PlainTextLlmExtractor;

        tokio::runtime::Runtime::new().unwrap().block_on(async {
            let result = extractor.parse(&context).unwrap();
            assert_eq!(result.name, "Test Recipe");
            assert!(!result.content.is_empty());
        });
    }

    #[test]
    fn test_extract_inner_text() {
        let html = r#"
            <html>
                <body>
                    <div>Hello</div>
                    <p>World</p>
                    <span>Test</span>
                </body>
            </html>
        "#;

        let document = Html::parse_document(html);
        let text = extract_inner_texts(&document);
        let joined = text.join(" ");
        assert_eq!(joined.trim(), "Hello World Test");
    }

    #[test]
    fn test_block_elements() {
        let html = r#"
            <div>Hello</div>
            <p>World</p>
            <span>Test</span>
        "#;
        let document = Html::parse_document(html);
        let texts = extract_inner_texts(&document);
        let joined = texts.join(" ");
        assert_eq!(joined.trim(), "Hello World Test");
    }

    #[test]
    fn test_hidden_elements() {
        let html = r#"
            <div>Visible</div>
            <div hidden>Hidden</div>
            <div style="display: none">Also Hidden</div>
        "#;
        let document = Html::parse_document(html);
        let texts = extract_inner_texts(&document);
        let joined = texts.join(" ");
        assert_eq!(joined.trim(), "Visible");
    }

    #[test]
    fn test_skip_script_elements() {
        let html = r#"
            <div>Visible content</div>
            <script>console.log('Skip this');</script>
            <style>body { color: red; }</style>
            <div>More content</div>
        "#;
        let document = Html::parse_document(html);
        let texts = extract_inner_texts(&document);
        let joined = texts.join(" ");
        assert_eq!(joined.trim(), "Visible content More content");
    }
}