summaryrefslogtreecommitdiff
path: root/internal/comic/image_validation.go
blob: 475cb9621bf476620b315517e55452c96b5eab1a (plain)
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
package comic

import (
	"bytes"
	"context"
	"fmt"
	"os/exec"
	"strings"
)

var imageLeakMarkers = []string{
	"mandatory language rule",
	"this is a bulgarian comic book",
	"bulgarian comic book",
	"mandatory panel layout",
	"mandatory speech bubbles",
	"ultra-realistic rendering",
	"final lock",
	"photorealism",
	"character & setting reference",
	"this is a text-free character gallery page",
	"story page",
	"gallery page",
	"back cover",
	"cover lines",
	"story teaser",
	"story ending hint",
	"art style:",
	"no panel grid",
	"no speech bubbles",
	"no text of any kind",
}

var validateImagePromptLeakageFn = validateImagePromptLeakage

func validateImagePromptLeakage(ctx context.Context, outputFile, label string) error {
	if ctx == nil {
		ctx = context.Background()
	}

	tesseractPath, err := exec.LookPath("tesseract")
	if err != nil {
		return nil
	}

	cmd := exec.CommandContext(ctx, tesseractPath, outputFile, "stdout", "-l", "eng", "--psm", "11")
	var out bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &bytes.Buffer{}
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("%s OCR failed: %w", label, err)
	}

	ocr := strings.ToLower(out.String())
	if marker, ok := findImageLeakMarker(ocr); ok {
		return fmt.Errorf("%s contains prompt leakage marker %q", label, marker)
	}
	return nil
}

func findImageLeakMarker(text string) (string, bool) {
	for _, marker := range imageLeakMarkers {
		if strings.Contains(text, marker) {
			return marker, true
		}
	}
	return "", false
}