This repository has been archived by the owner on Sep 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
108 lines (93 loc) · 2.09 KB
/
list.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package demo
import (
"embed"
"errors"
"math/rand"
"path/filepath"
"strings"
)
const dirName = "assets"
const demoNotice = `
**Please note, this is a pseudo response.**
**For genuine AI responses, you may want to set up your own instance following the instructions at
[proxoar/talk](https://github.com/proxoar/talk).**
`
//go:embed assets
var assets embed.FS
type Resource struct {
Name string
Text string
Audio []byte
}
type ResourcePool struct {
m map[string]Resource
list []Resource
}
func newResourcePool(list []Resource) *ResourcePool {
m := make(map[string]Resource, len(list))
for _, resource := range list {
m[resource.Text] = resource
}
return &ResourcePool{
m: m,
list: list,
}
}
func NewResourcePool() (*ResourcePool, error) {
entries, err := assets.ReadDir(dirName)
if err != nil {
return nil, err
}
var res []Resource
for _, entry := range entries {
if entry.IsDir() {
subDir := filepath.Join(dirName, entry.Name())
subEntries, err := assets.ReadDir(subDir)
if err != nil {
return nil, err
}
r := Resource{
Name: entry.Name(),
}
for _, subEntry := range subEntries {
fPath := filepath.Join(subDir, subEntry.Name())
if subEntry.Name() == "text.txt" {
text, err := assets.ReadFile(fPath)
if err != nil {
return nil, err
}
r.Text = string(text) + demoNotice
} else if strings.HasPrefix(subEntry.Name(), "audio") {
audio, err := assets.ReadFile(fPath)
if err != nil {
return nil, err
}
r.Audio = audio
} else {
return nil, errors.New("unknown resource: " + subEntry.Name())
}
}
res = append(res, r)
}
}
if len(res) == 0 {
return nil, errors.New("no resource was found")
}
return newResourcePool(res), nil
}
func (p ResourcePool) RandomResource() *Resource {
return &p.list[rand.Intn(len(p.list))]
}
func (p ResourcePool) FindAudioByTextOrRandom(text string) *Resource {
r, ok := p.m[text]
if ok {
return &r
}
return p.RandomResource()
}
func (p ResourcePool) List() []Resource {
return p.list[:]
}
func (p ResourcePool) Len() int {
return len(p.list)
}