-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
389 lines (276 loc) · 10.7 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package main
import (
"time"
"fmt"
"os"
"net/http"
"strings"
"encoding/json"
"bbb/bsky"
"bbb/bacalhau"
"bbb/s3uploader"
"bbb/gancho"
"bbb/helpers"
"github.com/joho/godotenv"
)
func uploadResultAndGetPublicURL(key, result string) (string, error) {
bucketName := os.Getenv("RESULTS_BUCKET")
uploader, err := s3uploader.NewS3Uploader(bucketName)
if err != nil {
fmt.Printf("Failed to initialize S3Uploader: %v", err)
return "", err
}
objectKey := key + ".txt"
content := []byte(result)
contentType := "text/plain"
publicURL, err := uploader.UploadFile(objectKey, content, contentType)
if err != nil {
fmt.Printf("Failed to upload file: %v", err)
return "", err
}
fmt.Printf("File uploaded successfully! Public publicURL: %s\n", publicURL)
return publicURL, nil
}
func dispatchClassificationJobAndPostReply(session *bsky.Session, notif bsky.Notification, imageURL string, isHotDogJob bool, isArbitraryClassJob bool, className string) {
bTest, bErr := bacalhau.GenerateClassificationJob(imageURL, isHotDogJob, className)
fmt.Println("bTest, bErr:", bTest, bErr)
result := bacalhau.CreateJob(bTest)
fmt.Println("Classification Job result:", result)
fmt.Println("JobID:", result.JobID)
fmt.Println("ExecutionID:", result.ExecutionID)
fmt.Println("Stdout:", result.Stdout)
splitStdoutStr := ">>> Results ID <<<"
classificationID := strings.TrimSpace(strings.Split(result.Stdout, splitStdoutStr)[1])
fmt.Println("classificationID:", classificationID)
objectStorageBaseURL := fmt.Sprintf("https://%s.s3.%s.amazonaws.com/", os.Getenv("S3_IMAGE_BUCKET"), os.Getenv("AWS_REGION"))
metadataFile, metadataErr := helpers.DownloadFile(objectStorageBaseURL + classificationID + ".json")
imageFile, imageErr := helpers.DownloadFile(objectStorageBaseURL + classificationID)
if metadataErr != nil {
fmt.Println("Could not retrieve result metadata:", metadataErr)
}
if imageErr != nil {
fmt.Println("Could not retrieve result image:", imageErr)
}
metadataStr := string(metadataFile)
var jsonObj map[string]interface{}
err := json.Unmarshal(metadataFile, &jsonObj)
if err != nil {
fmt.Printf("Error parsing JSON: %v\n", err)
return
}
analysisText := strings.Split(jsonObj["resultsText"].(string), "\n")[0]
classes := strings.Split( strings.Join( strings.Split( analysisText, " " )[3:], " " ), "," )
fmt.Println("metadataStr:", metadataStr)
fmt.Println("Analysis:", analysisText)
fmt.Println("Classes:", classes)
// fmt.Println("imageFile:", imageFile)
replyText := ""
if isHotDogJob == false {
replyText := fmt.Sprintf("Using the model '%s', ", os.Getenv("CLASSIFICATION_IMAGE"))
if len(classes) > 0 {
replyText += "I can see...\n\n"
for _, class := range classes {
replyText += fmt.Sprintf("%s\n", strings.TrimSpace(class))
}
replyText += "\n\n🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟\n\n"
} else {
replyText += "I can't detect anything in that image!\n\nSorry!"
}
} else {
for _, class := range classes {
replyText += fmt.Sprintf("%s\n", strings.TrimSpace(class))
}
}
// sendReply(session, notif, replyText)
sendReplyWithImage(session, notif, replyText, imageFile)
}
func dispatchBacalhauJobAndPostReply(session *bsky.Session, notif bsky.Notification, jobFileLink string) {
// Log start of the function
fmt.Println("Starting dispatchBacalhauJobAndPostReply...")
fmt.Println("Job file link:", jobFileLink)
// Step 1: Retrieve the job file
jobFile, jobFileErr := bacalhau.GetJobFileFromURL(jobFileLink)
if jobFileErr != nil {
fmt.Println("Could not get job file to dispatch job:", jobFileErr)
jobRetrievalErrTxt := fmt.Sprintf("Sorry! Something went wrong when trying to get your Job file 😔\n\nThe error that came back was %s\n\nPlease check your Job file and try again!", jobFileErr)
sendReply(session, notif, jobRetrievalErrTxt)
return
}
// Log successful retrieval of the job file
fmt.Println("Job file retrieved successfully:", jobFile)
// Step 2: Dispatch the job
fmt.Println("Dispatching job to Bacalhau...")
result := bacalhau.CreateJob(jobFile)
fmt.Println("Got here.")
// Check if the JobID is empty (failure case)
if result.JobID == "" {
replyText := "Sorry! Your Job failed to run! 😭\n\n" +
"This could be due to:\n\n" +
"1. Insufficient network capacity.\n" +
"2. Missing a node with matching requirements.\n" +
"3. Disallowed job configuration.\n" +
"4. Unexpected error on our end. We're keeping track of potential issues!"
sendReply(session, notif, replyText)
return
}
// Step 4: Log and check for JobID in result
fmt.Println("CreateJob result:", result)
if result.JobID == "" {
fmt.Println("CreateJob result does not contain a valid JobID.")
replyText := "Your Job failed to run! 😭\n\nWe couldn't retrieve a valid JobID."
sendReply(session, notif, replyText)
return
}
// Step 5: Determine the reply text based on ExecutionID and Stdout
var replyText string
if result.ExecutionID != "" && result.Stdout != "" {
var jobResultContent = result.Stdout
publicURL, uploadErr := uploadResultAndGetPublicURL(result.ExecutionID, jobResultContent)
if uploadErr != nil {
fmt.Println("Could not upload file to S3:", uploadErr)
os.Exit(1)
}
shortlink, slErr := gancho.GenerateShortURL(publicURL)
if slErr != nil {
shortlink = publicURL
}
// Successful execution
replyText = fmt.Sprintf(
"Your Bacalhau Job executed successfully 🥳🐟\n\n"+
"Job ID: %s\nExecution ID: %s\nOutput: %s\n\n"+
"🐟🐟🐟🐟🐟\n\n"+
"Explore more with Bacalhau! Check out our docs at https://docs.bacalhau.org",
result.JobID, result.ExecutionID, shortlink,
)
fmt.Println("Execution successful. Reply prepared:", replyText)
} else {
// Execution is incomplete or failed
replyText = fmt.Sprintf(
"Sorry! No results for your Bacalhau Job yet.\n\n"+
"Retrieve results using the Bacalhau CLI:\n\n"+
"1. Visit https://docs.bacalhau.org/getting-started/installation.\n"+
"2. Run `bacalhau job describe %s` to get results.",
result.JobID,
)
fmt.Println("Execution incomplete or failed. Reply prepared:", replyText)
// Optionally stop the job after a timeout
if result.JobID != "" {
fmt.Println("Stopping job with JobID:", result.JobID)
go bacalhau.StopJob(result.JobID, "The job ran too long for the Bacalhau Bot to tolerate.", true)
// bacalhau.StopJob(result.JobID, "The job ran too long for the Bacalhau Bot to tolerate.", true)
}
}
// Step 6: Send the reply
sendReply(session, notif, replyText)
}
func sendReplyWithImage(session *bsky.Session, notif bsky.Notification, replyText string, image []byte) {
fmt.Println("Preparing to send reply...")
var responseUri string
var err error
if os.Getenv("DRY_RUN") != "true"{
responseUri, err = bsky.ReplyToMentionWithImage(session.AccessJwt, notif, replyText, image, session.Did)
if err != nil {
fmt.Println("Error responding to mention:", err)
return
}
} else {
responseUri = "DRY_RUN_URI"
}
fmt.Println("Reply sent successfully. Response URI:", responseUri)
bsky.RecordResponse(responseUri)
}
// Helper to send replies
func sendReply(session *bsky.Session, notif bsky.Notification, replyText string) {
fmt.Println("Preparing to send reply...")
var responseUri string
var err error
if os.Getenv("DRY_RUN") != "true"{
responseUri, err = bsky.ReplyToMention(session.AccessJwt, notif, replyText, session.Did)
if err != nil {
fmt.Println("Error responding to mention:", err)
return
}
} else {
responseUri = "DRY_RUN_URI"
}
fmt.Println("Reply sent successfully. Response URI:", responseUri)
bsky.RecordResponse(responseUri)
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
// Respond with 200 OK and an empty body
w.WriteHeader(http.StatusOK)
}
func startHTTPServer() {
http.HandleFunc("/__gtg", healthCheckHandler)
port := ":8080" // Default port
if envPort := os.Getenv("PORT"); envPort != "" {
port = ":" + envPort
}
fmt.Printf("Starting HTTP server on port %s\n", port)
go func() {
if err := http.ListenAndServe(port, nil); err != nil {
fmt.Printf("HTTP server failed: %v\n", err)
}
}()
}
func main() {
// Load environment variables
err := godotenv.Load()
if err != nil {
fmt.Println("Could not find .env file. Continuing with existing environment variables.")
}
bsky.Username = os.Getenv("BLUESKY_USER")
bsky.Password = os.Getenv("BLUESKY_PASS")
if bsky.Username == "" || bsky.Password == "" {
fmt.Println("Missing environment variables. Please set BLUESKY_USER and BLUESKY_PASS.")
os.Exit(1)
}
bacalhau.BACALHAU_HOST = os.Getenv("BACALHAU_HOST")
fmt.Printf("Bacalhau Orchestrator Node IP: %s\n", bacalhau.BACALHAU_HOST)
// Authenticate with Bluesky API
session, err := bsky.Authenticate(bsky.Username, bsky.Password)
if err != nil {
fmt.Println("Authentication error:", err)
return
}
// bTest, bErr := bacalhau.GenerateClassificationJob("https://smt.codes/image.jpg")
// fmt.Println("bTest, bErr:", bTest, bErr)
startHTTPServer()
bsky.StartTime = time.Now()
// Poll notifications every 10 seconds
for {
fmt.Println("Fetching notifications...")
notifications, err := bsky.FetchNotifications(session.AccessJwt)
if err != nil {
fmt.Println("Error fetching notifications:", err)
time.Sleep(10 * time.Second)
os.Exit(1)
continue
}
for _, notif := range notifications {
// Process only "mention" notifications
isPostACommand, postComponents, commandType, className := bacalhau.CheckPostIsCommand(notif.Record.Text, bsky.Username)
if notif.Reason == "mention" && bsky.ShouldRespond(notif) && !bsky.HasResponded(notif.Uri) && isPostACommand {
fmt.Printf("Command detected: %s\n", notif.Record.Text)
acknowledgeJobRequest := "We got your job and we're running it now!\n\nYou should get results in a few seconds while we let it run, so hold tight and check your notifications!"
go sendReply(session, notif, acknowledgeJobRequest)
if commandType == "job_file" {
go dispatchBacalhauJobAndPostReply(session, notif, postComponents.Url)
}
if commandType == "classify_image" {
go dispatchClassificationJobAndPostReply(session, notif, notif.ImageURL, false, false, className)
}
if commandType == "hotdog" {
go dispatchClassificationJobAndPostReply(session, notif, notif.ImageURL, true, false, className)
}
if commandType == "arbitraryClass" {
go dispatchClassificationJobAndPostReply(session, notif, notif.ImageURL, true, true, className)
}
// dispatchBacalhauJobAndPostReply(session, notif, postComponents.Url)
fmt.Printf("Dipatched jobs and responses to mention: %s\n", notif.Record.Text)
bsky.RecordResponse(notif.Uri) // Record the original mention
}
}
time.Sleep(10 * time.Second)
}
}