| 44 | } |
| 45 | |
| 46 | func loadBackgroundFile(path string) (string, error) { |
| 47 | info, err := os.Stat(path) |
| 48 | if err != nil { |
| 49 | return "", fmt.Errorf("read background file %q: %w", path, err) |
| 50 | } |
| 51 | if info.IsDir() { |
| 52 | return "", fmt.Errorf("background file %q is a directory, not a file", path) |
| 53 | } |
| 54 | if info.Size() > maxBackgroundFileBytes { |
| 55 | return "", fmt.Errorf( |
| 56 | "background file %q is %d bytes, exceeding the maximum of %d bytes; please provide a smaller file", |
| 57 | path, info.Size(), maxBackgroundFileBytes, |
| 58 | ) |
| 59 | } |
| 60 | |
| 61 | raw, err := os.ReadFile(path) |
| 62 | if err != nil { |
| 63 | return "", fmt.Errorf("read background file %q: %w", path, err) |
| 64 | } |
| 65 | |
| 66 | cleaned := sanitizeMarkdown(string(raw)) |
| 67 | if cleaned == "" { |
| 68 | return "", fmt.Errorf("background file %q is empty after sanitisation", path) |
| 69 | } |
| 70 | |
| 71 | if strings.Contains(cleaned, backgroundOpenTag) || strings.Contains(cleaned, backgroundCloseTag) { |
| 72 | return "", fmt.Errorf( |
| 73 | "background file %q must not contain the reserved delimiters %q or %q", |
| 74 | path, backgroundOpenTag, backgroundCloseTag, |
| 75 | ) |
| 76 | } |
| 77 | |
| 78 | // Enforce the limits on the cleaned content only: the wrapper delimiters add |
| 79 | // overhead the user cannot control, so counting them would make the reported |
| 80 | // character count misleading. |
| 81 | if n := len([]rune(cleaned)); n > backgroundHardLimit { |
| 82 | return "", fmt.Errorf( |
| 83 | "background content is %d characters, exceeding the hard limit of %d (aborting)", |
| 84 | n, backgroundHardLimit, |
| 85 | ) |
| 86 | } else if n > backgroundSoftLimit { |
| 87 | fmt.Fprintf(os.Stderr, |
| 88 | "[ocr] --background-file content is %d characters, exceeding the recommended %d (continuing but review quality might be impacted)\n", |
| 89 | n, backgroundSoftLimit, |
| 90 | ) |
| 91 | } |
| 92 | |
| 93 | return backgroundOpenTag + "\n" + cleaned + "\n" + backgroundCloseTag, nil |
| 94 | } |
| 95 | |
| 96 | func sanitizeMarkdown(s string) string { |
| 97 | var b strings.Builder |