| 64 | } |
| 65 | |
| 66 | func loadBackgroundFile(path string) (string, error) { |
| 67 | info, err := os.Stat(path) |
| 68 | if err != nil { |
| 69 | return "", fmt.Errorf("read background file %q: %w", path, err) |
| 70 | } |
| 71 | if info.IsDir() { |
| 72 | return "", fmt.Errorf("background file %q is a directory, not a file", path) |
| 73 | } |
| 74 | if info.Size() > maxBackgroundFileBytes { |
| 75 | return "", fmt.Errorf( |
| 76 | "background file %q is %d bytes, exceeding the maximum of %d bytes; please provide a smaller file", |
| 77 | path, info.Size(), maxBackgroundFileBytes, |
| 78 | ) |
| 79 | } |
| 80 | |
| 81 | raw, err := os.ReadFile(path) |
| 82 | if err != nil { |
| 83 | return "", fmt.Errorf("read background file %q: %w", path, err) |
| 84 | } |
| 85 | |
| 86 | cleaned := sanitizeMarkdown(string(raw)) |
| 87 | if cleaned == "" { |
| 88 | return "", fmt.Errorf("background file %q is empty after sanitisation", path) |
| 89 | } |
| 90 | |
| 91 | if strings.Contains(cleaned, backgroundOpenTag) || strings.Contains(cleaned, backgroundCloseTag) { |
| 92 | return "", fmt.Errorf( |
| 93 | "background file %q must not contain the reserved delimiters %q or %q", |
| 94 | path, backgroundOpenTag, backgroundCloseTag, |
| 95 | ) |
| 96 | } |
| 97 | |
| 98 | // Enforce the limits on the cleaned content only: the wrapper delimiters add |
| 99 | // overhead the user cannot control, so counting them would make the reported |
| 100 | // character count misleading. |
| 101 | if n := len([]rune(cleaned)); n > backgroundHardLimit { |
| 102 | return "", fmt.Errorf( |
| 103 | "background content is %d characters, exceeding the hard limit of %d (aborting)", |
| 104 | n, backgroundHardLimit, |
| 105 | ) |
| 106 | } else if n > backgroundSoftLimit { |
| 107 | fmt.Fprintf(os.Stderr, |
| 108 | "[ocr] --background-file content is %d characters, exceeding the recommended %d (continuing but review quality might be impacted)\n", |
| 109 | n, backgroundSoftLimit, |
| 110 | ) |
| 111 | } |
| 112 | |
| 113 | return backgroundOpenTag + "\n" + cleaned + "\n" + backgroundCloseTag, nil |
| 114 | } |
| 115 | |
| 116 | func sanitizeMarkdown(s string) string { |
| 117 | var b strings.Builder |