Skip to content

Commit

Permalink
Merge pull request #3 from sparcs-kaist/dev
Browse files Browse the repository at this point in the history
Main branch update from Dev branch
  • Loading branch information
14KGun authored Jul 18, 2023
2 parents 7c8baf7 + fd0399d commit 60be669
Show file tree
Hide file tree
Showing 12 changed files with 303 additions and 16 deletions.
21 changes: 21 additions & 0 deletions .github/ISSUE_TEMPLATE/bug-report-template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
name: Bug report Template
about: Create a report to help us improve
title: "[Bug] bug-report title"
labels: "\U0001F631 bug"
assignees: ''

---

# Describe the bug
A clear and concise description of what the bug is.

# To Reproduce
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

# Screenshots
If applicable, add screenshots to help explain your problem.
18 changes: 18 additions & 0 deletions .github/ISSUE_TEMPLATE/issue-template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
name: Issue Template
about: Suggest an idea for this project
title: issue title
labels: ''
assignees: ''

---

# Summary <!-- 간단한 요약. -->

It implements ...

# Tasks <!-- 해야 할 태스크 체크리스트로 만들기 -->

- [ ] Task 1
- [ ] Task 2
- [ ] Task 3
9 changes: 9 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Summary <!-- PR 내용에 대한 간단한 요약 및 닫는 이슈 번호 표기. -->

It closes #issue_number

# Images or Screenshots <!-- PR 변경 사항에 대한 Screenshot이나 .gif 파일 -->

# Further Work <!-- PR 이후 개설할 이슈 목록 -->

- Do something...
53 changes: 53 additions & 0 deletions .github/workflows/create_release_tag.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
name: Create Release and Tag

on:
pull_request:
types:
- closed
branches:
- main

jobs:
if_merged:
if: github.event.pull_request.merged == true
name: Create Release and Tag
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Get previous tag-version
id: previous_tag
uses: WyriHaximus/github-action-get-previous-tag@v1
with:
fallback: 1.0.0

- name: Get next minor tag-version
id: minor_tag
uses: WyriHaximus/github-action-next-semvers@v1
with:
version: ${{ steps.previous_tag.outputs.tag }}

- name: Get current time
uses: josStorer/[email protected]
id: date
with:
format: YYYY-MM-DD
utcOffset: "+09:00"

- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ steps.minor_tag.outputs.v_patch }}
release_name: ${{ steps.minor_tag.outputs.v_patch }}
body: |
${{ steps.date.outputs.formattedTime }}
Github action released ${{ steps.minor_tag.outputs.v_patch }}
draft: false
prerelease: false
61 changes: 61 additions & 0 deletions .github/workflows/push_image_ecr.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
name: Push Prod Image to Amazon ECR

# when tagging action success
on:
workflow_run:
workflows: ["Create Release and Tag"]
types:
- completed

env:
AWS_REGION: ap-northeast-2

jobs:
if_workflow_success:
name: Build and Push
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}

steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Get previous tag-version
id: previous_tag
uses: WyriHaximus/github-action-get-previous-tag@v1
with:
fallback: 1.0.0

- name: Set Tag Version
id: tag
uses: actions/github-script@v4
with:
script: |
const tagVersion = "${{ steps.previous_tag.outputs.tag }}".replace('v', '')
core.setOutput('tag', tagVersion)
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}

- name: Login to AWS ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1

- name: Build and Push to AWS ECR
id: build_image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
IMAGE_TAG: ${{ steps.tag.outputs.tag }}
ECR_REPOSITORY: taxi-og-generator
run: |
docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:latest .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest
echo "Push image : $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG and latest"
43 changes: 43 additions & 0 deletions .github/workflows/push_image_ecr_dev.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: Push Dev Image to Amazon ECR
on:
pull_request:
types:
- closed
branches:
- dev

env:
AWS_REGION: ap-northeast-2

jobs:
if_merged:
if: github.event.pull_request.merged == true
name: Create Release and Tag
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}

- name: Login to AWS ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1

- name: Build and Push to AWS ECR
id: build_image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
ECR_REPOSITORY: taxi-og-generator
run: |
docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:dev .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:dev
echo "Push image : $ECR_REGISTRY/$ECR_REPOSITORY:dev"
Binary file removed graph.png
Binary file not shown.
Binary file added images/arrow.type1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/arrow.type2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/og.background.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes
114 changes: 98 additions & 16 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
from PIL import ImageFont, ImageDraw, Image
from io import BytesIO
from dotenv import load_dotenv
import datetime
import numpy as np
import requests
import locale
import cv2
import os

Expand All @@ -13,41 +15,121 @@
API_ROOM_INFO = os.environ["API_ROOM_INFO"] if "API_ROOM_INFO" in os.environ \
else "https://taxi.sparcs.org/api/rooms/publicInfo?id={}"

# init
# KST timezone setting -> is it working?
locale.setlocale(locale.LC_TIME, 'ko_KR.UTF-8')
timezone_kst = datetime.timezone(datetime.timedelta(hours = 9))

# initialization
app = FastAPI()
fontTitle = ImageFont.truetype("fonts/NanumSquare_acEB.ttf", 60)
fontDate = ImageFont.truetype("fonts/NanumSquare_acB.ttf", 30)
colorWhite = (255, 255, 255, 1)
images = {
"background": cv2.imread("images/og.background.png"),
"default": cv2.imread("images/og.default.png"),
"arrow.type1": cv2.imread("images/arrow.type1.png"),
"arrow.type2": cv2.imread("images/arrow.type2.png"),
}
fonts = {
"type1": {
"title": ImageFont.truetype("fonts/NanumSquare_acEB.ttf", 96),
"date": ImageFont.truetype("fonts/NanumSquare_acEB.ttf", 48),
"name": ImageFont.truetype("fonts/NanumSquare_acR.ttf", 48),
},
"type2": {
"title": ImageFont.truetype("fonts/NanumSquare_acEB.ttf", 72),
"date": ImageFont.truetype("fonts/NanumSquare_acEB.ttf", 40),
"name": ImageFont.truetype("fonts/NanumSquare_acR.ttf", 40),
},
}
colors = {
"purple": (110, 54, 120, 1),
"black": (50, 50, 50, 1),
}

def date2text(date):
date = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f%z").astimezone(timezone_kst)
return "{}년 {}월 {}일 {}요일 {} {}".format(
date.year,
date.month,
date.day,
["월", "화", "수", "목", "금", "토", "일"][date.weekday()],
"오전" if date.strftime("%p") == "AM" else "오후",
date.strftime("%-I:%M"),
)

def predictWidth(draw, text, font):
width, _ = draw.textsize(text, font=font)
return width

def defaultImage():
img = cv2.imread("graph.back.png")
res, im_png = cv2.imencode(".png", img)
_, im_png = cv2.imencode(".png", images["default"])
return StreamingResponse(BytesIO(im_png.tobytes()), media_type="image/png")

@app.get("/{roomId}")
async def mainHandler(roomId: str = "647ac989fe1dbfb2b9408ff9"):
async def mainHandler(roomId: str):
try:
# if roomId ends with .png, remove it
if roomId.endswith(".png"): roomId = roomId[:-4]

# get room information
res = requests.get(API_ROOM_INFO.format(roomId))
if res.status_code != 200:
raise ValueError("mainHandler : Invalid roomId")
roomInfo = res.json()

# convert room information to text
text = {
"from": roomInfo["from"]["koName"],
"to": roomInfo["to"]["koName"],
"date": date2text(roomInfo["time"]),
"name": roomInfo["name"],
}

# load background image
img = Image.fromarray(cv2.imread("graph.png"))
draw = ImageDraw.Draw(img, 'RGBA')
img_og = Image.fromarray(images["background"])
draw = ImageDraw.Draw(img_og, 'RGBA')

# select draw type
# if location text width is less than 784, use type1
# else, use type2
draw_type = "type1" if predictWidth(draw, text["from"] + text["to"], fonts["type1"]["title"]) <= 784 else "type2"

# draw Location
draw.text((50, 50), '{} → {}'.format(roomInfo["from"]["koName"], roomInfo["to"]["koName"]), font=fontTitle, fill=colorWhite)
# draw location
draw.text((52, 52), text["from"], font=fonts[draw_type]["title"], fill=colors["purple"])
widthFrom = predictWidth(draw, text["from"], fonts[draw_type]["title"])
draw.text(
(52 + 20 + 96 + widthFrom, 52) if draw_type == "type1" else (172, 166),
text["to"],
font=fonts[draw_type]["title"], fill=colors["purple"]
)

# draw Date
draw.text((50, 150), '{}'.format(roomInfo["time"]), font=fontDate, fill=colorWhite)
# draw arrow
img_arrow = Image.fromarray(images["arrow.{}".format(draw_type)]).convert('RGBA')
img_og.paste(
img_arrow,
(52 + 10 + widthFrom, 52) if draw_type == "type1" else (52, 160)
)

# draw Name
draw.text((50, 200), '{}'.format(roomInfo["name"]), font=fontDate, fill=colorWhite)
# draw date
draw.text(
(52, 189) if draw_type == "type1" else (52, 280), text["date"],
font=fonts[draw_type]["date"],
fill=colors["black"]
)

# ellipsis if name has long width
if predictWidth(draw, text["name"], fonts[draw_type]["name"]) > 700:
while predictWidth(draw, text["name"] + "...", fonts[draw_type]["name"]) > 700:
text["name"] = text["name"][:-1]
text["name"] += "..."

# draw name
draw.text((52, 392) if draw_type == "type1" else (52, 401),
text["name"],
font=fonts[draw_type]["name"],
fill=colors["black"]
)

# convert to png image
res, img_png = cv2.imencode(".png", np.array(img))
res, img_png = cv2.imencode(".png", np.array(img_og))

# response
return StreamingResponse(BytesIO(img_png.tobytes()), media_type="image/png")
Expand Down

0 comments on commit 60be669

Please sign in to comment.