Skip to content

Commit 20b80f1

Browse files
committed
feat: 텍스트 마스킹 후 업로드 기능으로 변경
1 parent 8cee367 commit 20b80f1

3 files changed

Lines changed: 40 additions & 19 deletions

File tree

.github/workflows/deploy.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,8 @@ jobs:
179179
task-definition: task-definition.json
180180
container-name: masking-service # Task Definition에 정의된 컨테이너 이름
181181
image: ${{ steps.build-image.outputs.image }}
182+
environment-variables: |
183+
S3_BUCKET_NAME=${{ secrets.S3_BUCKET_NAME }}
182184
183185
184186
- name: Deploy Amazon ECS task definition

masking-service/main.py

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import uvicorn
2-
from fastapi import FastAPI
3-
from pydantic import BaseModel
4-
import requests
2+
from fastapi import FastAPI, UploadFile, File, HTTPException
53
from io import BytesIO
64
from PIL import Image, ImageDraw
75
import easyocr
86
import numpy as np
7+
import boto3
8+
import os
9+
import uuid
910

1011
app=FastAPI(
1112
title="Image Masking Service",
@@ -16,8 +17,14 @@
1617
openapi_url="/mask/openapi.json"
1718
)
1819

19-
class ImageReq(BaseModel):
20-
image_url: str
20+
# Initialize S3 client
21+
s3_client = boto3.client(
22+
's3',
23+
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
24+
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
25+
region_name=os.getenv("AWS_REGION")
26+
)
27+
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")
2128

2229
reader = easyocr.Reader(['en', 'ko'])
2330

@@ -37,24 +44,35 @@ def mask_text(image: Image.Image) -> Image.Image:
3744

3845
return masked
3946

40-
@app.post("/mask/exec", summary="Mask text in image", description="Mask text in the given image URL.")
41-
async def mask_image(req: ImageReq):
47+
@app.post("/mask/exec", summary="Mask text in image and upload to S3", description="Upload an image, mask text, and upload the masked image to AWS S3.")
48+
async def mask_image(file: UploadFile = File(...)):
49+
if not S3_BUCKET_NAME:
50+
raise HTTPException(status_code=500, detail="S3_BUCKET_NAME environment variable not set.")
51+
4252
try:
43-
response = requests.get(req.image_url)
44-
response.raise_for_status()
45-
except requests.RequestException as e:
46-
return {"error": f"Failed to fetch image from URL: {e}"}
53+
contents = await file.read()
54+
img = Image.open(BytesIO(contents)).convert("RGB")
55+
except Exception as e:
56+
raise HTTPException(status_code=400, detail=f"Error reading image file: {e}")
4757

48-
# try:
49-
img = Image.open(BytesIO(response.content)).convert("RGB")
5058
masked_img = mask_text(img)
51-
# buffered = BytesIO()
52-
# masked_img.save(buffered, format="PNG")
53-
# img_str = "data:image/png;base64," + base64.b64encode(buffered.getvalue()).decode()
54-
# except Exception as e:
55-
# return {"error": f"Error processing image: {e}"}
5659

57-
return {"masked_image": "masking completed"}
60+
# Save masked image to a BytesIO object
61+
masked_img_buffer = BytesIO()
62+
masked_img.save(masked_img_buffer, format="PNG")
63+
masked_img_buffer.seek(0) # Rewind the buffer to the beginning
64+
65+
# Generate a unique filename for S3
66+
file_extension = file.filename.split(".")[-1] if "." in file.filename else "png"
67+
s3_filename = f"masked_images/{uuid.uuid4()}.{file_extension}"
68+
69+
try:
70+
s3_client.upload_fileobj(masked_img_buffer, S3_BUCKET_NAME, s3_filename)
71+
s3_url = f"https://{S3_BUCKET_NAME}.s3.amazonaws.com/{s3_filename}"
72+
except Exception as e:
73+
raise HTTPException(status_code=500, detail=f"Failed to upload masked image to S3: {e}")
74+
75+
return {"message": "Masking and upload completed successfully", "s3_url": s3_url}
5876

5977
@app.get("/health", summary="Health Check", description="Check if the service is running.")
6078
async def health_check():

masking-service/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ Pillow
99
httpx
1010
--extra-index-url https://download.pytorch.org/whl/cpu
1111
torch
12+
boto3

0 commit comments

Comments
 (0)