-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
89 lines (72 loc) · 1.89 KB
/
main.go
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
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"github.com/junte/stable-diffusion-prompt-parser/src/parser"
)
type Output struct {
Evaluated *parser.ParsedPrompt `json:"evaluated"`
Beautified string `json:"beautified"`
Cleaned string `json:"cleaned"`
}
func toIndentedJson(output *Output, prefix string, indent string) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
encoder.SetIndent(prefix, indent)
// intialize slices to get rid of nulls in json
if output.Evaluated.Tags == nil {
output.Evaluated.Tags = make([]*parser.PromptTag, 0)
}
if output.Evaluated.Hypernets == nil {
output.Evaluated.Hypernets = make([]*parser.PromptModel, 0)
}
if output.Evaluated.Loras == nil {
output.Evaluated.Loras = make([]*parser.PromptModel, 0)
}
err := encoder.Encode(output)
return bytes.TrimRight(buffer.Bytes(), "\n"), err
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
var input string
for scanner.Scan() {
line := scanner.Text()
if len(line) > 0 {
input += line + " "
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
parser := parser.NewPromptParser()
parsed, err := parser.ParsePrompt(input)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
beautified, err := parser.BeautifyPrompt(input)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
regex := regexp.MustCompile(`,? ?<[^>]*>,? ?`)
cleaned := regex.ReplaceAllString(beautified, ", ")
output := Output{
Evaluated: parsed,
Beautified: beautified,
Cleaned: strings.Trim(cleaned, ", "),
}
marshalled, err := toIndentedJson(&output, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
fmt.Fprintln(os.Stdout, string(marshalled))
}