Skip to content

Commit

Permalink
Merge pull request #7 from boostcampaitech6/sanggi
Browse files Browse the repository at this point in the history
update: sakura theme
  • Loading branch information
Sanggi123 authored Mar 14, 2024
2 parents 9a1ea7a + 7849646 commit 5a72f64
Show file tree
Hide file tree
Showing 9 changed files with 1,153 additions and 159 deletions.
50 changes: 31 additions & 19 deletions MPA/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
from dependencies import load_model_tokenizer, get_model_tokenizer, load_poem_model_tokenizer, get_poem_model_tokenizer
from config import config
Expand All @@ -10,6 +11,10 @@

import time

import torch
import random


@asynccontextmanager
async def lifespan(app: FastAPI):

Expand All @@ -20,7 +25,8 @@ async def lifespan(app: FastAPI):
yield

app = FastAPI(lifespan=lifespan)
templates = Jinja2Templates(directory="templates") # HTML 파일이 위치한 디렉토리를 지정
templates = Jinja2Templates(directory="template") # HTML 파일이 위치한 디렉토리를 지정
app.mount("/static", StaticFiles(directory="template/static"), name="static")

@app.get("/", response_class=HTMLResponse)
async def get_first_page(request: Request):
Expand All @@ -43,15 +49,20 @@ async def show_result(request: Request, mood: str):

# input 데이터 전처리
inputs = tokenizer(mood, return_tensors="pt")
# 예측
outputs = model.generate(
**inputs,
num_beams=3,
num_return_sequences=3, # 반환할 시퀀스 수
do_sample=True
)
# 결과 디코딩
sentence = [tokenizer.decode(output, skip_special_tokens=True) for output in outputs]
# # 예측
# outputs = model.generate(
# **inputs,
# num_beams=6,
# num_return_sequences=3, # 반환할 시퀀스 수
# do_sample=True
# )
# #결과 디코딩
# sentence = [tokenizer.decode(output, skip_special_tokens=True) for output in outputs]

sentence =[]
for i in range(3):
output = model.generate(**inputs, do_sample=True)
sentence.append(tokenizer.decode(output[0], skip_special_tokens=True))

# 코드 실행 후 시간 측정
end_time = time.time()
Expand All @@ -60,7 +71,7 @@ async def show_result(request: Request, mood: str):
execution_time = end_time - start_time

logger.info("predict time : {}", execution_time)
logger.info("sentence : {}", sentence)
# logger.info("sentence : {}", sentence)

return templates.TemplateResponse("sentence_page.html", {"request": request, "mood": mood, 'sentence': sentence})

Expand Down Expand Up @@ -111,22 +122,23 @@ class MoodRequest(BaseModel):

@app.post("/reGenerate")
async def reGenerate(request: MoodRequest):

random_seed = random.randint(1, 10000)
torch.manual_seed(random_seed)

mood = request.mood

# 모델&토크나이저 load
model, tokenizer = get_model_tokenizer()

# input 데이터 전처리
inputs = tokenizer(mood, return_tensors="pt")

# 예측
outputs = model.generate(
**inputs,
num_beams=3,
num_return_sequences=3, # 반환할 시퀀스 수
do_sample=True
)
# 결과 디코딩
sentence = [tokenizer.decode(output, skip_special_tokens=True) for output in outputs]
sentence =[]
for i in range(3):
output = model.generate(**inputs, do_sample=True)
sentence.append(tokenizer.decode(output[0], skip_special_tokens=True))

return {"sentence": sentence}

Expand Down
75 changes: 75 additions & 0 deletions MPA/template/keyword_page.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>오늘의 시</title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700&display=swap" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" type="text/css" href="./static/css/style.css">
</head>
<body class="bg-gray-100">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(window).load(function () {
$('body').sakura();
});
</script>
<div class="min-h-screen flex items-center justify-center">
<div class="bg-white p-8 rounded-lg shadow-lg max-w-md w-full">
<h1 class="text-2xl font-bold mb-4">오늘의 기분은?</h1>
<p class="mb-4">오늘 하루 어떠셨나요?</p>
<p class="mb-4 font-semibold">오늘의 감정을 선택해 보세요!</p>
<form id="moodForm" action="/submit_keyword" method="post">
<div class="mb-4">
<label class="inline-flex items-center">
<input type="radio" name="mood" value="행복하다" class="form-radio h-5 w-5 text-blue-600" onchange="checkSelection()">
<span class="ml-2">행복하다</span>
</label>
</div>
<div class="mb-4">
<label class="inline-flex items-center">
<input type="radio" name="mood" value="슬프다" class="form-radio h-5 w-5 text-blue-600" onchange="checkSelection()">
<span class="ml-2">슬프다</span>
</label>
</div>
<div class="mb-4">
<label class="inline-flex items-center">
<input type="radio" name="mood" value="화나다" class="form-radio h-5 w-5 text-blue-600" onchange="checkSelection()">
<span class="ml-2">화나다</span>
</label>
</div>
<div class="mb-4">
<label class="inline-flex items-center">
<input type="radio" name="mood" value="지루하다" class="form-radio h-5 w-5 text-blue-600" onchange="checkSelection()">
<span class="ml-2">지루하다</span>
</label>
</div>
<div class="mb-6">
<label class="inline-flex items-center">
<input type="radio" name="mood" value="놀라다" class="form-radio h-5 w-5 text-blue-600" onchange="checkSelection()">
<span class="ml-2">놀라다</span>
</label>
</div>
<button type="submit" id="submitButton" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700 focus:outline-none w-full" disabled>선택완료</button>
</form>
</div>
</div>
<script>
// 라디오 버튼 선택 확인
function checkSelection() {
const submitButton = document.getElementById('submitButton');
const radios = document.forms['moodForm'].elements['mood'];
let isSelected = false;
for(let i = 0; i < radios.length; i++) {
if(radios[i].checked) isSelected = true;
}
submitButton.disabled = !isSelected; //
}

// 함수 초기 상태 확인
document.addEventListener('DOMContentLoaded', checkSelection);
</script>
<script src="./static/js/sakura.js"></script>
</body>
</html>
33 changes: 10 additions & 23 deletions MPA/templates/output_page.html → MPA/template/output_page.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,15 @@
<title>오늘의 시</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700&display=swap" rel="stylesheet">
<style>
.content-container {
max-width: 80%;
margin: auto;
}
.image-placeholder {
background-color: #E5E7EB;
display: flex;
align-items: center;
justify-content: center;
color: #9CA3AF;
font-size: 1.5rem;
aspect-ratio: 1 / 1;
width: 100%;
}
.poem-container {
display: flex;
flex-direction: column;
justify-content: space-between;
}
</style>
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
</head>
<body class="bg-white text-gray-800">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(window).load(function () {
$('body').sakura();
});
</script>
<div class="container mx-auto p-4">
<h1 class="text-2xl font-semibold text-center mb-6">당신의 오늘과 어울리는 시</h1>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 content-container">
Expand All @@ -40,18 +26,19 @@ <h1 class="text-2xl font-semibold text-center mb-6">당신의 오늘과 어울
<div class="border rounded-lg p-4 poem-container">
<div>
<h2 class="text-xl font-semibold mb-4">생성된 시</h2>
<pre class="text-gray-600">{{ poem }}...</pre>
<pre class="text-black-900 poem-font">{{ poem }}...</pre>
</div>
</div>
</div>
<div class="flex justify-center gap-4 mb-4">
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
<button id="saveButton" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
이미지와 시 저장
</button>
<button class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded" onclick="window.location.href = '/';">
메인으로 돌아가기
</button>
</div>
</div>
<script src="/static/js/sakura.js"></script>
</body>
</html>
11 changes: 11 additions & 0 deletions MPA/template/result_page.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!-- result_page.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Result Page</title>
</head>
<body>
<h1>You selected: {{ quote }}</h1>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
<title>오늘의 시</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Noto Sans KR', sans-serif;
}
</style>
<link rel="stylesheet" type="text/css" href="/static/css/style.css">
</head>
<body class="bg-gray-100">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(window).load(function () {
$('body').sakura();
});
</script>
<div class="min-h-screen flex items-center justify-center">
<div class="max-w-lg mx-auto my-10 p-6 bg-white shadow-lg rounded-lg">
<h2 class="text-2xl font-bold mb-4">#2. 문장 선택 페이지</h2>
Expand All @@ -24,15 +26,15 @@ <h3 class="text-xl mb-2">마음에 드는 구절은?</h3>
<form id="sentenceForm" action="/submit_sentence" method="post">
<div class="mb-4">
<div class="flex items-center mb-2">
<input id="sentence1" type="radio" name="sentence" value="{{ sentence[0] | e }}" class="mr-2" onchange="checkSelection()">
<input id="sentence1" type="radio" name="sentence" value="{{ sentence[0] | e }}" class="form-radio mr-2" onchange="checkSelection()">
<label for="sentence1" class="text-gray-700">{{ sentence[0] }}</label>
</div>
<div class="flex items-center mb-2">
<input id="sentence2" type="radio" name="sentence" value="{{ sentence[1] | e }}" class="mr-2" onchange="checkSelection()">
<input id="sentence2" type="radio" name="sentence" value="{{ sentence[1] | e }}" class="form-radio mr-2" onchange="checkSelection()">
<label for="sentence2" class="text-gray-700">{{ sentence[1] }}</label>
</div>
<div class="flex items-center mb-2">
<input id="sentence3" type="radio" name="sentence" value="{{ sentence[2] | e }}" class="mr-2" onchange="checkSelection()">
<input id="sentence3" type="radio" name="sentence" value="{{ sentence[2] | e }}" class="form-radio mr-2" onchange="checkSelection()">
<label for="sentence3" class="text-gray-700">{{ sentence[2] }}</label>
</div>
</div>
Expand All @@ -46,48 +48,48 @@ <h3 class="text-xl mb-2">마음에 드는 구절은?</h3>
</form>
</div>
</div>
<script>
// 라디오 버튼 선택 확인
function checkSelection() {
const submitButton = document.getElementById('submitButton');
const radios = document.forms['sentenceForm'].elements['sentence'];
let isSelected = false;
for(let i = 0; i < radios.length; i++) {
if(radios[i].checked) isSelected = true;
<script>
// 라디오 버튼 선택 확인
function checkSelection() {
const submitButton = document.getElementById('submitButton');
const radios = document.forms['sentenceForm'].elements['sentence'];
let isSelected = false;
for(let i = 0; i < radios.length; i++) {
if(radios[i].checked) isSelected = true;
}
submitButton.disabled = !isSelected;
}
submitButton.disabled = !isSelected;
}
// 함수 초기 상태 확인
document.addEventListener('DOMContentLoaded', checkSelection);
// 함수 초기 상태 확인
document.addEventListener('DOMContentLoaded', checkSelection);

function reGenerate() {
fetch('/reGenerate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
mood: '{{ mood | tojson}}'
function reGenerate() {
fetch('/reGenerate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
mood: '{{ mood | tojson}}'
})
})
.then(response => response.json())
.then(data => {
updateSentences(data.sentence);
})
})
.then(response => response.json())
.then(data => {
updateSentences(data.sentence);
})
.catch((error) => {
console.error('Error:', error)
});
}
.catch((error) => {
console.error('Error:', error)
});
}

function updateSentences(sentence) {
for (let i = 0; i < sentence.length; i++) {
document.getElementById(`sentence${i+1}`).value = sentence[i];
document.querySelector(`label[for=sentence${i+1}]`).textContent = sentence[i];
function updateSentences(sentence) {
for (let i = 0; i < sentence.length; i++) {
document.getElementById(`sentence${i+1}`).value = sentence[i];
document.querySelector(`label[for=sentence${i+1}]`).textContent = sentence[i];
}
}
}

// 함수 초기 상태 확인
document.getElementById("reButton").addEventListener('click', reGenerate);
</script>
document.getElementById("reButton").addEventListener('click', reGenerate);
</script>
<script src="/static/js/sakura.js"></script>
</body>
</html>
Loading

0 comments on commit 5a72f64

Please sign in to comment.