This repository has been archived by the owner on Jun 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathmain.go
188 lines (156 loc) · 4.62 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
dapr "github.com/dapr/go-sdk/client"
"github.com/dapr/go-sdk/service/common"
daprd "github.com/dapr/go-sdk/service/grpc"
"github.com/pkg/errors"
)
const (
languageDefault = "en"
secretStoreName = "pipeline-secrets"
secretStoreKey = "Azure:CognitiveAPIKey"
)
var (
logger = log.New(os.Stdout, "", 0)
serviceAddress = getEnvVar("ADDRESS", ":60005")
apiToken = getEnvVar("API_TOKEN", "")
apiDomain = getEnvVar("API_DOMAIN", "tweet-sentiment")
apiURL = fmt.Sprintf("https://%s.cognitiveservices.azure.com/text/analytics/v3.0/sentiment", apiDomain)
)
func main() {
// create serving server
s, err := daprd.NewService(serviceAddress)
if err != nil {
log.Fatalf("failed to start the server: %v", err)
}
// add handler to the service
s.AddServiceInvocationHandler("sentiment", sentimentHandler)
// start the server to handle incoming events
log.Printf("starting server at %s...", serviceAddress)
if err := s.Start(); err != nil {
log.Fatalf("server error: %v", err)
}
}
func sentimentHandler(ctx context.Context, in *common.InvocationEvent) (out *common.Content, err error) {
logger.Printf("Processing: %s", in.Data)
var req map[string]string
if err := json.Unmarshal(in.Data, &req); err != nil {
return nil, errors.Wrapf(err, "error deserializing data: %s", in.Data)
}
score, err := getSentiment(ctx, req["language"], req["text"])
if err != nil {
logger.Printf("error scoring sentiment: %v", err)
return nil, errors.Wrapf(err, "error scoring sentiment: %s", in.Data)
}
b, err := json.Marshal(score)
if err != nil {
return nil, errors.Wrapf(err, "error serializing score: %v", score)
}
logger.Printf("Processed: %s", b)
return &common.Content{
ContentType: "application/json",
Data: b,
}, nil
}
// SentimentScore represents sentiment result
type SentimentScore struct {
Sentiment string `json:"sentiment"`
Confidence float64 `json:"confidence"`
}
func getSentiment(ctx context.Context, lang, text string) (out *SentimentScore, err error) {
if text == "" {
return nil, errors.New("text required")
}
if lang == "" {
lang = languageDefault
}
if apiToken == "" {
apiToken = getSecret(secretStoreName, secretStoreKey)
}
r := fmt.Sprintf(`{
"documents": [{
"language": "%s",
"id": "1",
"text": "%s"
}]
}`, lang, text)
req, err := http.NewRequest(http.MethodPost, apiURL, bytes.NewBuffer([]byte(r)))
if err != nil {
return nil, errors.Wrapf(err, "error creating request from: %v", r)
}
req = req.WithContext(ctx)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Ocp-Apim-Subscription-Key", apiToken)
client := http.Client{Timeout: time.Second * 5}
res, err := client.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "error posting to: %s", apiURL)
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("invalid API response status: %d", res.StatusCode)
}
defer res.Body.Close()
// dump, _ := httputil.DumpResponse(res, true)
// logger.Printf("response: %s", dump)
var rez struct {
Documents []struct {
Sentiment string `json:"sentiment"`
Scores struct {
Positive float64 `json:"positive"`
Neutral float64 `json:"neutral"`
Negative float64 `json:"negative"`
Mixed float64 `json:"mixed"`
} `json:"confidenceScores"`
} `json:"documents"`
}
if err := json.NewDecoder(res.Body).Decode(&rez); err != nil {
return nil, errors.Wrap(err, "error decoding API response")
}
if len(rez.Documents) != 1 {
return nil, errors.Wrapf(err, "invalid response, expected 1 document, got %d", len(rez.Documents))
}
doc := rez.Documents[0]
out = &SentimentScore{
Sentiment: doc.Sentiment,
}
switch out.Sentiment {
case "positive":
out.Confidence = rez.Documents[0].Scores.Positive
case "negative":
out.Confidence = rez.Documents[0].Scores.Negative
case "neutral":
out.Confidence = rez.Documents[0].Scores.Neutral
case "mixed":
out.Confidence = rez.Documents[0].Scores.Mixed
default:
return nil, fmt.Errorf("invalid sentiment: %s", out.Sentiment)
}
return
}
func getEnvVar(key, fallbackValue string) string {
if val, ok := os.LookupEnv(key); ok {
return strings.TrimSpace(val)
}
return fallbackValue
}
func getSecret(store, key string) string {
// try to find it in Dapr secret store
c, err := dapr.NewClient()
if err != nil {
logger.Fatal("unable to create Dapr client")
}
if m, err := c.GetSecret(context.Background(), store, key, map[string]string{}); err == nil {
return m[key]
}
logger.Fatalf("no item found in Dapr secret store for %s", key)
return ""
}