Added S3 backup of images generated
This commit is contained in:
@ -5,7 +5,9 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/replicate/replicate-go"
|
||||
@ -99,6 +101,26 @@ func ReplicateImageGeneration(prompt string) (*bytes.Buffer, error) {
|
||||
return nil, imgReadErr
|
||||
}
|
||||
|
||||
// Save image to a temporary file
|
||||
tmpfile, err := os.CreateTemp("", "image.*.jpg")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
|
||||
if _, err := tmpfile.Write(imageBytes); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := tmpfile.Close(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Upload the image to S3
|
||||
_, uploadErr := UploadToS3(tmpfile.Name())
|
||||
if uploadErr != nil {
|
||||
log.Printf("Failed to upload image to S3: %v", uploadErr)
|
||||
}
|
||||
|
||||
imageFile := bytes.NewBuffer(imageBytes)
|
||||
return imageFile, nil
|
||||
}
|
||||
|
53
lib/s3.go
Normal file
53
lib/s3.go
Normal file
@ -0,0 +1,53 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/s3/s3manager"
|
||||
)
|
||||
|
||||
func UploadToS3(filePath string) (*s3manager.UploadOutput, error) {
|
||||
bucket := os.Getenv("BUCKET_NAME")
|
||||
if bucket == "" {
|
||||
fmt.Println("No S3 bucket specified, skipping upload.")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
endpoint := os.Getenv("AWS_ENDPOINT_URL_S3")
|
||||
accessKeyID := os.Getenv("AWS_ACCESS_KEY_ID")
|
||||
secretAccessKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
|
||||
|
||||
sess, err := session.NewSession(&aws.Config{
|
||||
Credentials: credentials.NewStaticCredentials(
|
||||
accessKeyID,
|
||||
secretAccessKey,
|
||||
"",
|
||||
),
|
||||
Endpoint: aws.String(endpoint),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create session, %v", err)
|
||||
}
|
||||
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file, %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
uploader := s3manager.NewUploader(sess)
|
||||
result, err := uploader.Upload(&s3manager.UploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(filePath),
|
||||
Body: file,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to upload file, %v", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
Reference in New Issue
Block a user