Skip to content

Commit

Permalink
Merge pull request #211 from tukcomCD2024/AIflask
Browse files Browse the repository at this point in the history
A iflask
  • Loading branch information
entellaKa authored May 18, 2024
2 parents 49e8916 + 1d1641c commit edb912b
Show file tree
Hide file tree
Showing 18 changed files with 104 additions and 43 deletions.
6 changes: 6 additions & 0 deletions AI/.idea/AI.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 13 additions & 4 deletions AI/.idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions AI/aiflask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import app as a

app = a.app
3 changes: 0 additions & 3 deletions AI/app.py

This file was deleted.

4 changes: 3 additions & 1 deletion AI/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from flask import Flask

app = Flask(__name__)


def create_app():
app = Flask(__name__)

if __name__ == "__main__":
app.run()
Expand Down
Binary file modified AI/app/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file modified AI/app/__pycache__/routes.cpython-39.pyc
Binary file not shown.
Binary file modified AI/app/controllers/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file modified AI/app/controllers/__pycache__/example_controllers.cpython-39.pyc
Binary file not shown.
7 changes: 2 additions & 5 deletions AI/app/controllers/example_controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
import_name=__name__,
url_prefix='/example')

ai = Blueprint(name='ai',
ai: Blueprint = Blueprint(name='ai',
import_name=__name__,
url_prefix='/ai')


@ai.route('/base64', methods=['POST'])
def draw() -> str:
def draw() -> Response:
return jsonify(auto_draw.AIbyBase64(json.loads(request.get_json())))


Expand All @@ -26,6 +26,3 @@ def drawByURL() -> str:
s = request.get_data()
l = json.loads(s)
return jsonify(auto_draw.AIbyURL(l))


String.format("https://ap-northeast-2.console.aws.amazon.com/s3/object/ai-icons?region=ap-northeast-2&bucketType=general&prefix=svg/{}/{}-outline.png", 이름, 이름)
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import io, base64
import os
from PIL import Image
import boto3
import requests
Expand All @@ -18,8 +17,7 @@ def downloadFromS3(bucket, key):
client = boto3.client('s3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name=AWS_DEFAULT_REGION
)
region_name=AWS_DEFAULT_REGION)

file_name = 'downLoad.png' # 다운될 이미지 이름
# bucket = 'mufi-photo' # 버켓 주소
Expand Down
30 changes: 30 additions & 0 deletions AI/app/services/ImagePreprocessing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from PIL import Image
import numpy as np

# 이미지를 흑백으로 변환
def convertMono(img: Image):
fn = lambda x: 255 if x > 0 else 0
img = img.convert('L').point(fn, mode='1')
return img


# 이미지 크기를 128*128로 변경 후 이미지를 배열화
def resizing(img):
img = img.resize((128, 128))
img = img.convert('RGB')
return img


# 이미지를 배열화
def imageToArray(img):
img = np.array(img)
img = np.expand_dims(img, axis=0)
return img


# 이미지를 AI에 맞게 전환
def imageProcessing(img: Image):
img = convertMono(img)
img = resizing(img)
img = imageToArray(img)
return img
Binary file modified AI/app/services/__pycache__/LoadImage.cpython-39.pyc
Binary file not shown.
Binary file modified AI/app/services/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file modified AI/app/services/__pycache__/auto_draw.cpython-39.pyc
Binary file not shown.
28 changes: 10 additions & 18 deletions AI/app/services/auto_draw.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
from keras.models import load_model
import numpy as np
import operator, os
from app.services.LoadImage import decodeFromJsonToImage, downloadFromS3, downloadFromURL
from app.services.ImageLoading import decodeFromJsonToImage, downloadFromS3, downloadFromURL
from app.services.ImagePreprocessing import imageProcessing

tags = 'airplane,apartment,apple,arm,arrow,axe,bag,baseball,basketball,bath,bed,bench,book,bottle,box,bread,broom,brush,bucket,bulb,cake,calendar,candle,candy,castle,chair,cherry,clock,cloud,coffee,coin,cookie,cup,cylinder,dice,dress,ear,earth,envelope,eraser,eye,finger,flag,flame,flask,flower,gamecontroller,ghost,gift,grape,hammer,heart,hospital,house,industry,injection,ladder,lake,leaf,leg,lightning,meat,megaphone,mic,money,monitor,mouse,mushroom,nail,nose,officebuilding,pants,peanut,pencil,police,pumpkin,rain,ribbon,rocket,ruler,school,shield,shirt,skirt,soccer,speaker,sprout,star,stethoscope,sun,swim,sword,television,tennis,tree,truck,umbrella,vehicle,volleyball,watch,wheel,windmill,zoom'.split(
',')


# 이미지 크기를 128*128로 변경
def resizing(image):
image = image.resize((128, 128))
image = image.convert('RGB')
image = np.array(image)
image = np.expand_dims(image, axis=0)
return image


# AI를 이용하여 유사한 이미지 출력
# AI를 이용하여 유사하다고 예상되는 이미지(이름) 출력
def getPredict(img):
saved_model = load_model(os.getcwd() + "/app/services/cnn1.h5")
pre = saved_model.predict(img)
return pre


# AI 결과를 정확도에 따라 오름차순으로 정렬
# AI 결과를 정확도에 따라 오름차 순으로 정렬
def resultByDesc(result):
x = {}
for i in range(len(result)):
Expand All @@ -34,15 +25,16 @@ def resultByDesc(result):
def getImageNameList(result):
names = []
for k, v in result:
print(k)
print(k,tags[k])
names.append(tags[k])
return names


def AI_process(image):
resized = resizing(image)
pre_result = getPredict(resized)
result2 = resultByDesc(pre_result[0])
return getImageNameList(result2)
imgData = imageProcessing(image)
predict = getPredict(imgData)
result = resultByDesc(predict[0])
return getImageNameList(result)


def AIbyBase64(json_data):
Expand Down
42 changes: 33 additions & 9 deletions AI/dockerfile
Original file line number Diff line number Diff line change
@@ -1,14 +1,38 @@
FROM python:3.8-slim
# NVIDIA CUDA 베이스 이미지 사용
FROM nvidia/cuda:11.2.2-cudnn8-runtime-ubuntu20.04

COPY . .
# 환경 변수 설정
ENV DEBIAN_FRONTEND=noninteractive

RUN pip3 install flask
RUN pip3 install tensorflow
RUN pip3 install pillow
RUN pip3 install boto3
# NVIDIA 패키지 리포지토리 추가 및 TensorRT 설치
RUN apt-get update && apt-get install -y gnupg2
RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/3bf863cc.pub && \
apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu2004/x86_64/7fa2af80.pub && \
sh -c 'echo "deb https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu2004/x86_64 /" > /etc/apt/sources.list.d/nvidia-ml.list' && \
apt-get update && apt-get install -y \
tzdata \
build-essential \
libhdf5-dev \
pkg-config \
python3 \
python3-pip \
libnvinfer8 \
libnvonnxparsers8 \
libnvparsers8 \
libnvinfer-plugin8 \
python3-libnvinfer-dev \
&& ln -fs /usr/share/zoneinfo/Asia/Seoul /etc/localtime \
&& dpkg-reconfigure --frontend noninteractive tzdata

WORKDIR .
# 작업 디렉토리 설정
WORKDIR /app

ENV FLASK_APP=app.py
# 애플리케이션 코드 복사
COPY . /app

CMD ["python3", "-m", "flask", "run","--host=0.0.0.0"]
# pip 업그레이드 및 패키지 설치
RUN pip3 install --upgrade pip
RUN pip3 install --no-cache-dir tensorflow gunicorn -r requirements.txt

# Gunicorn을 사용하여 Flask 애플리케이션 실행
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "aiflask:app"]
3 changes: 3 additions & 0 deletions AI/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
flask
pillow
boto3

0 comments on commit edb912b

Please sign in to comment.