DevOps/AWS

AWS S3와 연결하여 AWS Rekognition윌로 읎믞지 읞식 태귞 API 만듀Ʞ

567Rabbit 2024. 5. 28. 15:10

https://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/labels-detect-labels-image.html

 

읎믞지에서 레읎랔 감지 - Amazon Rekognition

Ʞ계 번역윌로 제공되는 번역입니닀. 제공된 번역곌 원볞 영얎의 낎용읎 상충하는 겜우에는 영얎 버전읎 우선합니닀. 읎믞지에서 레읎랔 감지 읎 DetectLabels작업을 사용하여 읎믞지에서 레읎랔 (

docs.aws.amazon.com

- 메뉎얌을 찞고한닀.

 

 

 

 

아래륌 찞고하여 버킷을 만든닀.

 

https://msdev-st.tistory.com/155

 

[AWS] S3 버킷 만듀Ʞ _ 슀토늬지 만듀얎서 사용하Ʞ

S3 ë²„í‚· ë§Œë“€êž° _ ìŠ€í† ëŠ¬ì§€ ë§Œë“€ì–Žì„œ ì‚¬ìš©í•˜êž°AWS의 S3란? Simple Storage Service의 앜자로 파음 서버의 역할을 하는 서비슀닀. 음반적읞 파음서버는 튞래픜읎 슝가핚에 따띌서 장비륌 슝섀하는 작

msdev-st.tistory.com

 

 

 

 

 

aws의 IAM에서,  AmazonRekognitionFullAcess 권한추가하Ʞ

 

 

 

 

 

 

 

serverless로 만든 폎더륌 vscode로 ì—°ë‹€.

 

 

 

 

 

버킷 만듀 때 사용한 읎늄을 넣윌멎 된닀.

 

 

 

 

 

app.py 작성

bash
ë‹«êž°
from flask import Flask from flask_restful import Api from resources.image import FileUploadResource app = Flask(__name__) api = Api(app) # 겜로와 늬소슀륌 연결한닀. api.add_resource( FileUploadResource , '/upload' ) if __name__ == '__main__' : ​​​​app.run()

 

 

 

 

 

resources 폮더 안에 image.py 작성

bash
ë‹«êž°
from flask_restful import Resource from flask import request from datetime import datetime import boto3 from config import Config class FileUploadResource(Resource) : ​​​​def post(self): ​​​​​​​​# 1. 큎띌읎얞튞로부터 데읎터륌 받아옚닀. ​​​​​​​​# 파음은 request.files 안에 있고, ​​​​​​​​# 텍슀튞는 request.form 안에 있닀. ​​​​​​​​if 'photo' not in request.files : ​​​​​​​​​​​​return {"result":"fail", "error":"파음을 업로드 하섞요."}, 400 ​​​​​​​​ ​​​​​​​​if 'content' not in request.form : ​​​​​​​​​​​​return {"result":"fail", "error":"낎용을 작성 하섞요."}, 400 ​​​​​​​​ ​​​​​​​​file = request.files.get('photo') ​​​​​​​​ ​​​​​​​​if 'image' not in file.content_type : ​​​​​​​​​​​​return {'result':'fail', ​​​​​​​​​​​​​​​​​​​​'error':'읎믞지 파음만 업로드 가능합니닀'}, 400 ​​​​​​​​ ​​​​​​​​print(file) ​​​​​​​​content = request.form['content'] ​​​​​​​​print(content) ​​​​​​​​# 파음을 s3에 업로드 핎알 하는데, ​​​​​​​​# 뚌저, 파음명은 유니크 핎알 한닀. ​​​​​​​​# 따띌서, 유니크한 파음명윌로 바꿔서 업로드 한닀. ​​​​​​​​# 현재시간곌 유저아읎디 등을 조합핎서 만든닀. ​​​​​​​​current_time = datetime.now() ​​​​​​​​file_name = current_time.isoformat().replace(':','_') + '.' + file.content_type.split('/')[-1] ​​​​​​​​print(file_name) ​​​​​​​​# 유저가 업로드한 파음명을, 낎가 만든 파음명윌로 바Ꟍ닀. ​​​​​​​​file.filename = file_name ​​​​​​​​# s3에 파음을 업로드한닀. ​​​​​​​​# aws의 서비슀듀을 파읎썬윔드로 작성 할 수 있는 ​​​​​​​​# boto3 띌읎람러늬륌 읎용핎서 윔드륌 작성한닀. ​​​​​​​​# ( 섀치는, $ pip install boto3 ) ​​​​​​​​client = boto3.client('s3' , ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​aws_access_key_id = Config.AWS_ACCESS_KEY, ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​aws_secret_access_key = Config.AWS_SECRET_ACCESS_KEY) ​​​​​​​​# ExtraArgs = {'ACL':'public-read','ContentType':'image/jpg'} 쀑요부분 ​​​​​​​​try : ​​​​​​​​​​​​client.upload_fileobj(file, ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​Config.S3_BUCKET, ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​file_name, ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ExtraArgs = {'ACL':'public-read', ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​'ContentType':file.content_type}) ​​​​​​​​except Exception as e: ​​​​​​​​​​​​return {"result":"fail", "error":str(e)}, 500 ​​​​​​​​return {"result":"success", "url":Config.S3_URL + file_name}

 

 

 

vscode cmd에서 섀치한닀.

bash
ë‹«êž°
pip install boto3

 

 

 

rekognition.py 작성

bash
ë‹«êž°
from flask import request from flask_restful import Resource from datetime import datetime import boto3 from config import Config class ObjectDetectionResource(Resource): ​​​​def post(self): ​​​​​​​​if 'photo' not in request.files : ​​​​​​​​​​​​return {"result":"fail", "error":"사진은 필수입니닀."}, 400 ​​​​​​​​ ​​​​​​​​file = request.files['photo'] ​​​​​​​​if 'image' not in file.content_type : ​​​​​​​​​​​​return {"result":"fail", "error":"읎믞지파음을 업로드 하섞요."}, 400 ​​​​​​​​ ​​​​​​​​current_time = datetime.now() ​​​​​​​​file_name = current_time.isoformat().replace(':','_') + '.jpg' ​​​​​​​​file.filename = file_name ​​​​​​​​# s3에 업로드 ​​​​​​​​# rekognition 서비슀륌 읎용하렀멎, ​​​​​​​​# 뚌저 s3에 읎믞지 파음을 업로드 핎놔알 한닀 ​​​​​​​​client = boto3.client('s3', ​​​​​​​​​​​​​​​​​​​​​aws_access_key_id = Config.AWS_ACCESS_KEY, ​​​​​​​​​​​​​​​​​​​​​aws_secret_access_key = Config.AWS_SECRET_ACCESS_KEY) ​​​​​​​​ ​​​​​​​​try : ​​​​​​​​​​​​client.upload_fileobj(file, ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​Config.S3_BUCKET, ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​file_name, ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ExtraArgs = {'ACL' : 'public-read', ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​'ContentType':'image/jpeg'}) ​​​​​​​​except Exception as e: ​​​​​​​​​​​​return {"result":"fail", "error":str(e)}, 500 ​​​​​​​​# 늬윔귞니션을 읎용 ​​​​​​​​label_list = self.detect_labels(file_name, Config.S3_BUCKET) ​​​​​​​​ ​​​​​​​​return {"result":"success", "lable": label_list} ​​​​ ​​​​def detect_labels(self, photo, bucket): ​​​​​​​​client = boto3.client('rekognition', ​​​​​​​​​​​​​​​​​​​​​'ap-northeast-2', ​​​​​​​​​​​​​​​​​​​​​aws_access_key_id = Config.AWS_ACCESS_KEY, ​​​​​​​​​​​​​​​​​​​​​aws_secret_access_key = Config.AWS_SECRET_ACCESS_KEY) ​​​​​​​​response = client.detect_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}}, ​​​​​​​​MaxLabels=10, ​​​​​​​​# Uncomment to use image properties and filtration settings ​​​​​​​​#Features=["GENERAL_LABELS", "IMAGE_PROPERTIES"], ​​​​​​​​#Settings={"GeneralLabels": {"LabelInclusionFilters":["Cat"]}, ​​​​​​​​# "ImageProperties": {"MaxDominantColors":10}} ​​​​​​​​) ​​​​​​​​print('Detected labels for ' + photo) ​​​​​​​​print() ​​​​​​​​print(response['Labels']) ​​​​​​​​label_list = [] ​​​​​​​​for label in response['Labels']: ​​​​​​​​​​​​print("Label: " + label['Name']) ​​​​​​​​​​​​label_list.append(label['Name']) ​​​​​​​​return label_list

 

 

 

 

 

 

사진 업로드 API 포슀튞맚 작성

 

 

 

 

 

send하고, s3 버킷에 듀얎가볎멎 아래처럌 사진을 send한 목록듀읎 뜬닀.

 

 

 

 

 

 

object detection API 포슀튞맚 작성하고 send하멎

 

 

 

 

 

vscode에서는 읎렇게 뜬닀.

 

 

 

 

 

 

 

.jpeg, .jpg 등의 타입 섀명 홈페읎지 링크읎닀.

 

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

 

Common MIME types - HTTP | MDN

This topic lists the most common MIME types with corresponding document types, ordered by their common extensions.

developer.mozilla.org