Comments (2)
DetectLabels
から以下のエラーが返ってくる。
2021/03/30 05:14:00 operation error Rekognition: DetectLabels, https response error StatusCode: 400, RequestID: 0fca4ba2-30da-4d21-bc94-b456b41972cc, api error MissingAuthenticationTokenException: Missing Authentication Token
実行したコードは下記の通り。
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"log"
"os"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/rekognition"
"github.com/aws/aws-sdk-go-v2/service/rekognition/types"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/google/uuid"
)
var uploader *manager.Uploader
var rekognitionClient *rekognition.Client
//nolint:gochecknoinits
func init() {
region := os.Getenv("REGION")
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region))
if err != nil {
// TODO ここでエラーが発生した場合、致命的な問題が起きているのでちゃんとしたログを出すように改修する
log.Fatalln(err)
}
s3Client := s3.NewFromConfig(cfg)
uploader = manager.NewUploader(s3Client)
rekognitionOpt := rekognition.Options{Region: region}
rekognitionClient = rekognition.New(rekognitionOpt)
}
type RequestBody struct {
Image string `json:"image"`
}
type ResponseOkBody struct {
Labels interface{} `json:"labels"`
}
type ResponseErrorBody struct {
Message string `json:"message"`
}
func createApiGatewayV2Response(statusCode int, resBodyJson []byte) events.APIGatewayV2HTTPResponse {
res := events.APIGatewayV2HTTPResponse{
StatusCode: statusCode,
Headers: map[string]string{
"Content-Type": "application/json",
},
Body: string(resBodyJson),
IsBase64Encoded: false,
}
return res
}
func createErrorResponse(statusCode int, message string) events.APIGatewayV2HTTPResponse {
resBody := &ResponseErrorBody{Message: message}
resBodyJson, _ := json.Marshal(resBody)
res := events.APIGatewayV2HTTPResponse{
StatusCode: statusCode,
Headers: map[string]string{
"Content-Type": "application/json",
},
Body: string(resBodyJson),
IsBase64Encoded: false,
}
return res
}
func uploadToS3(
ctx context.Context,
uploader *manager.Uploader,
bucket string,
body *bytes.Buffer,
contentType string,
key string,
) error {
input := &s3.PutObjectInput{
Bucket: aws.String(bucket),
Body: body,
ContentType: aws.String(contentType),
Key: aws.String(key),
}
_, err := uploader.Upload(ctx, input)
if err != nil {
return err
}
return nil
}
func detectLabels(ctx context.Context, decodedImg []byte) (*rekognition.DetectLabelsOutput, error) {
// 画像解析
rekognitionImage := &types.Image{
Bytes: decodedImg,
}
// 何個までラベルを取得するかの設定、ラベルは信頼度が高い順に並んでいる
const maxLabels = int32(10)
// 信頼度の閾値、Confidenceがここで設定した値未満の場合、そのラベルはレスポンスに含まれない
const minConfidence = float32(85)
input := &rekognition.DetectLabelsInput{
Image: rekognitionImage,
MaxLabels: aws.Int32(maxLabels),
MinConfidence: aws.Float32(minConfidence),
}
output, err := rekognitionClient.DetectLabels(ctx, input)
if err != nil {
return nil, err
}
return output, nil
}
func Handler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
var reqBody RequestBody
if err := json.Unmarshal([]byte(req.Body), &reqBody); err != nil {
statusCode := 400
res := createErrorResponse(statusCode, "Bad Request")
return res, err
}
decodedImg, err := base64.StdEncoding.DecodeString(reqBody.Image)
if err != nil {
statusCode := 500
res := createErrorResponse(statusCode, "Failed Decode Base64 Image")
return res, err
}
uid, err := uuid.NewRandom()
if err != nil {
statusCode := 500
res := createErrorResponse(statusCode, "Failed Generate UUID")
return res, err
}
buffer := new(bytes.Buffer)
buffer.Write(decodedImg)
uploadKey := "tmp/" + uid.String() + ".jpg"
err = uploadToS3(
ctx,
uploader,
os.Getenv("TRIGGER_BUCKET_NAME"),
buffer,
"image/jpeg",
uploadKey,
)
if err != nil {
statusCode := 500
res := createErrorResponse(statusCode, "Failed Upload To S3")
return res, err
}
detectLabelsOutput, err := detectLabels(ctx, decodedImg)
if err != nil {
statusCode := 500
res := createErrorResponse(statusCode, "Failed recognition")
return res, err
}
resBody := &ResponseOkBody{Labels: detectLabelsOutput.Labels}
resBodyJson, _ := json.Marshal(resBody)
statusCode := 200
res := createApiGatewayV2Response(statusCode, resBodyJson)
return res, nil
}
func main() {
lambda.Start(Handler)
}
S3にはファイルはアップロードされているので、detectLabels
のみ何か問題がありそう。
すぐに解決出来なさそうなので、こちらは一旦保留にする。
from aws-rekognition-sandbox.
#4 (comment) は解決済。
aws-sdk-go-v2
に立てたissueのコメントで教えてもらったが、rekognition.New
は必ずクレデンシャルを要求するようなので、rekognition.NewFromConfig(cfg)
を使う事で解決出来た。
from aws-rekognition-sandbox.
Related Issues (14)
- S3にアップロードされたタイミングで画像が🐱の画像かどうかを判定するLambda関数の実装を行う
- テストコードを作成する HOT 5
- CI/CDの設定を追加する
- 他の画像フォーマットにも対応するように改修を行う
- 画像から顔の検出を行うAPIを実装する
- CI上でDockerを立ち上げているのをやめて、GitHubActionsのコンテナ内で完結するように改修する HOT 1
- Goのバージョンを1.17系に変更する HOT 1
- カバレッジレポートを送信出来るようにする HOT 1
- Docker上のgo testをリモートデバッグ出来るようにする
- リファクタリング(詳細は説明欄) HOT 1
- UseCaseのメソッドで異常が発生した際はエラーを返すようにする HOT 1
- Serverlessのバージョンを3系の最新に更新
- Goのバージョンを1.18系に変更する
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from aws-rekognition-sandbox.