공태현

Merge branch 'develop'

package-lock.json
/node_modules/
......@@ -25,4 +25,4 @@
[x] pront : 카운팅 기록 - 정지호
[x] pront : 홈페이지 디자인 - 정지호
[] 배포
[] PPT/발표 자료 준비
\ No newline at end of file
[] PPT/발표 자료 준비
......
const { json } = require('express/lib/response');
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name : {type : String, required : true, unique : true, },
password : {type : String, required : true, trim : true},
total_squart : {type : Number, default : 0},
today_squart : {type : Number, default : 0},
});
userSchema.methods.passwordCheck = function(password, cb) {
if (password === this.password)
cb(null, isMatch);
}
const User = mongoose.model('squartuser', userSchema )
module.exports = {User};
{
"name": "healthcare-with-webcam",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"repository": {
"type": "git",
"url": "http://khuhub.khu.ac.kr/2019102144/healthcare-with-webcam.git"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
"express-session": "^1.17.3",
"mongoose": "^6.3.4",
"mongoose-session": "0.0.4",
"ejs": "^3.1.8"
}
}
const express = require('express');
const ejs = require('ejs')
const app = express();
const port = 3000
app.set('port', port)
app.set('view engine', 'ejs')
app.engine('html',ejs.renderFile )
// model/user.js
const { User } = require('./model/User');
const mongoose = require('mongoose');
// db 연결을 위한 키 값 , 보안을 위해 최종 마스터 브런치에는 포함하지 않을 예정.
mongoose.connect('mongodb+srv://kongtae:ksas9825!%40@squartusers.e2ddc.mongodb.net/?retryWrites=true&w=majority')
.then(() => console.log('MongoDB connect!'))
.catch(err => console.log(err))
// 로그인 세션 : 로그인 정보 유지.
const express_session = require('express-session')
app.use(express_session({
secret : "@secret@number", // 암호화 키
resave : false,
saveUninitialized : false,
store:require('mongoose-session')(mongoose),
cookie : {maxAge : 60*60*24}
}))
app.get('/', (req,res) => {
console.log(req.session)
if (req.session.user)
{
app.set('views', __dirname + '/views/squatPage')
res.render('squat.html')
}
else
{
app.set('views', __dirname + '/views/mainPage')
res.render('main.html')
}
})
// 음성 소리 파일 전송
app.get('/sound/0.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/0.wav')
})
app.get('/sound/1.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/1.wav')
})
app.get('/sound/2.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/2.wav')
})
app.get('/sound/3.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/3.wav')
})
app.get('/sound/4.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/4.wav')
})
app.get('/sound/5.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/5.wav')
})
app.get('/sound/6.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/6.wav')
})
app.get('/sound/7.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/7.wav')
})
app.get('/sound/8.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/8.wav')
})
app.get('/sound/9.wav', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/9.wav')
})
app.get('/sound/bad.mp3', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/sound/bad.mp3')
})
//
// js 파일 전송.
app.get('/main.js', (req,res) => {
res.sendFile( __dirname + '/views/mainPage/main.js')
})
// css 파일 전송
app.get('/main.css', (req,res) => {
res.sendFile(__dirname + '/views/mainPage/main.css')
})
// js 파일 전송.
app.get('/squat.js', (req,res) => {
res.sendFile( __dirname + '/views/squatPage/squat.js')
})
// css 파일 전송
app.get('/squat.css', (req,res) => {
res.sendFile(__dirname + '/views/squatPage/squat.css')
})
app.get('/squat', (req,res) => {
if (req.session.user)
{
app.set('views', __dirname + '/views/squatPage')
res.render('squat.html')
}
else
{ // 로그인 안되어 있으면, 스쿼트 페이지 진입 불가.
app.set('views', __dirname + '/views/mainPage')
res.render('main.html')
}
})
app.listen(port, () => {
console.log(`Listening on ${port} port`);
})
// 유저 등록 및 로그인 API
// 등록 .
app.use(express.json())
app.post('/api/users/register', (req,res) => {
console.log(req.body)
const new_user = new User(req.body);
new_user.save((err, userInfo) => {
if (err)
{
var result = res.json({success : false, err})
return result
}
else
{
var result = res.status(200).json({success : true})
return result
}
})
})
// 로그인 .
app.post('/api/users/login', (req ,res) => {
console.log(req.body)
User.findOne({name : req.body.name}, (err, user) => {
if (!user) {
return res.json({
loginSuccess: false,
message : "이름이 일치하는 사용자가 없습니다 !",
})
}
else if (req.body.password === user.password) {
req.session.user = {
user_name : req.body.name,
user_password : req.body.password,
}
req.session.save()
console.log(req.session.user)
return res.json({
loginSuccess : true,
})
}
else {
return res.json({
loginSuccess : false,
message : "비밀번호가 일치하지 않습니다 !"
})
}
})
})
// 로그아웃
app.get('/api/users/logout', (req,res) => {
var session = req.session
if (session.user)
{
req.session.destroy(err => {
if (err) {
console.log(err)
return res.json({
logoutSuccess : false
})
}
else
{
console.log('로그아웃 완료')
return res.json({
logoutSuccess : true
})
}
})
// res.redirect('/');
}
else
{
console.log('로그인이 되어있지 않습니다.')
return res.json({
logoutSuccess : true,
})
}
})
app.get('/api/users/name', (req,res) => {
return res.json({
user : req.session.user
})
})
// 스쿼트 갯수 업데이트 API
app.post('/api/users/countupdate', (req,res) => {
var userName = req.body.name
var userCount = req.body.count
User.findOne({name : userName}, (err,userInfo) => {
if (err) res.json({success : false, err})
userInfo.today_squart = Number(userInfo.today_squart) + Number(userCount)
userInfo.total_squart = Number(userInfo.total_squart) + Number(userCount)
userInfo.save()
return res.json({
success : true,
today_squart : userInfo.today_squart,
total_squart : userInfo.total_squart
})
})
})
// 세션 저장 확인
app.get('/api/session', (req,res) => {
console.log(req.session.user)
return res.json({session :req.session})
})
@import url('https://fonts.googleapis.com/css2?family=Nanum+Pen+Script&display=swap');
@import url("https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800,900&display=swap");
@font-face {
font-family: 'BMJUA';
src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_one@1.0/BMJUA.woff') format('woff');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'BMEULJIRO';
src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_twelve@1.0/BMEULJIRO.woff') format('woff');
font-weight: normal;
font-style: normal;
}
.title {
font-size : 40px;
font-family: 'BMEULJIRO';
color : aliceblue;
margin-top: 10%;
margin-bottom: 20px;
text-align: center;
}
button {
margin: 10px;
margin-bottom: 30px;
}
input {
margin-top: 0px;
width: 300px;
height: 50px;
border: 1px solid aliceblue;
border-radius: 10px;
color: white;
background-color: #353535;
font-family: 'BMJUA';
font-size: 20px;
margin-block-end: 10px;
}
.w-btn {
position: relative;
border: none;
display: inline-block;
padding: 15px 30px;
border-radius: 15px;
font-family: "BMEULJIRO", sans-serif;
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
text-decoration: none;
font-weight: 600;
transition: 0.25s;
margin-bottom: 20px;
}
.w-btn-outline {
position: relative;
padding: 15px 30px;
border-radius: 15px;
font-family: "BMEULJIRO", sans-serif;
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
text-decoration: none;
font-weight: 600;
transition: 0.25s;
}
.w-btn-indigo {
background-color: aliceblue;
color: #2e2f30;
}
.w-btn-indigo-outline {
border: 3px solid aliceblue;
color: #2e2f30;
}
.w-btn-indigo-outline:hover {
color: #2e2f30;
background: aliceblue;
}
.font {
margin-right: 3px;
font-size: 20px;
color:aliceblue;
font-family: "BMEULJIRO";
}
.login_sign {
margin-top: 10px;
font-family: "BMJUA";
font-size: 20px;
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
width: 310px;
height: 50px;
color:black;
border-radius: 10px;
background-color: wheat;
border: none;
}
.flex-container{
display:inline-flex;
}
.flex-item{
width: 350px;
height:400px;
margin: 10px;
}
\ No newline at end of file
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Main Page</title>
<link rel="stylesheet" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body bgcolor= "#353535">
<div class="title">
🏋️‍♂️방구석 헬스 트레이너🏋️‍♀️
</div>
<center>
<div>
<input class="w-btn w-btn-indigo" type="button" value = "Squat Start" id = "moveSquart" onclick="moveSquartPage()"/>
</div>
<script type="text/javascript" src="./main.js"></script>
<div class="flex-container">
<div class="flex-item">
<div><input class="input" id = "name" value="👨‍🦲" type = "text"></div>
<div><input class="input" id = "password" value="🔑" type = "text"></div>
<div><button class="login_sign" type="submit" id = "button">로그인</button></div>
</div>
<div class="flex-item">
<div><input class="input" id = "register_name" value="👨‍🦲" type = "text"></div>
<div><input class="input" id = "register_password" value="🔑" type = "text"></div>
<div><button class="login_sign" type="submit" id = "register_button">회원가입</button></div>
</div>
</div>
</center>
</body>
</html>
\ No newline at end of file
function moveSquatPage()
{
location.href = "/squat";
}
$(document).ready(function(){
$('#button').click(function(){
let sendName = $('#name').val();
let sendPassword = $('#password').val();
let sendData = {
"name" : sendName,
"password" : sendPassword
}
$.ajax({
contentType : "application/json; charset=utf-8",
type : 'post',
url : 'api/users/login',
data : JSON.stringify(sendData),
dataType : 'JSON',
success : function(datas) {
if (datas.loginSuccess)
{
moveSquatPage()
}
else
{
alert(datas.message)
}
}
})
})
})
// 회원가입용
$(document).ready(function(){
$('#register_button').click(function(){
let sendName = $('#register_name').val();
let sendPassword = $('#register_password').val();
let sendData = {
"name" : sendName,
"password" : sendPassword
}
$.ajax({
contentType : "application/json; charset=utf-8",
type : 'post',
url : 'api/users/register',
data : JSON.stringify(sendData),
dataType : 'JSON',
success : function(datas) {
if (datas.success)
{
moveSquatPage()
}
else
{
alert("회원가입 실패 (이름 중복 의심)")
}
}
})
})
})
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
@import url("https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800,900&display=swap");
button {
margin: 10px;
margin-bottom: 20px;
}
.w-btn {
position: relative;
border: none;
display: inline-block;
padding: 15px 30px;
border-radius: 15px;
font-family: "paybooc-Light", sans-serif;
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
text-decoration: none;
font-weight: 600;
transition: 0.25s;
}
.w-btn-outline {
position: relative;
padding: 15px 30px;
border-radius: 15px;
font-family: "paybooc-Light", sans-serif;
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
text-decoration: none;
font-weight: 600;
transition: 0.25s;
}
.w-btn-indigo {
background-color: aliceblue;
color: #2e2f30;
}
.w-btn-indigo-outline {
border: 3px solid aliceblue;
color: #2e2f30;
}
.w-btn-indigo-outline:hover {
color: #2e2f30;
background: aliceblue;
}
.Title {
font-size : 100px;
font-family: fantasy;
color : aliceblue;
margin-top: 15%;
text-align: center;
}
.click_title {
font-size : 40px;
font-family: fantasy;
color : aliceblue;
margin-top: 40px;
margin-bottom: 20px;
text-align: center;
transition: 500ms;
}
.label-container {
visibility: hidden;
}
.hidden {
visibility: hidden;
}
.visible {
visibility: visible;
}
.circle {
margin: 20px;
width: 100px;
height: 100px;
background-color: aliceblue;
color: #2e2f30;
text-align: center;
border-radius: 50%;
line-height: 100px;
}
\ No newline at end of file
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="squat.css">
<title>Squat Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body bgcolor= "#353535">
<div id="title" class="Title">
Squat Page
<center>
<button class="w-btn w-btn-indigo" type="button" onclick="init()">WEBCAM START</button>
<button id = "savecount" class="w-btn w-btn-indigo" type="button" onclick="">스쿼트 횟수 저장</button>
<div>
<canvas id="canvas"></canvas>
<iframe
id="youtube"
class="hidden"
width="560" height="400"
src="https://www.youtube.com/embed/9WhpAVOSyl8?start=22"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>
</div>
<div id="counter" class="circle"></div>
</center>
</div>
<div id="label-container" class="label-container"></div>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.3.1/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@teachablemachine/pose@0.8/dist/teachablemachine-pose.min.js"></script>
<script src="./squat.js"></script>
</body>
</html>
// More API functions here:
// https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/pose
// the link to your model provided by Teachable Machine export panel
const URL = "https://teachablemachine.withgoogle.com/models/xymjZj4q-/"; // 임시 URI - stand , squart, bent(허리 굽은 자세) 학습.
let model, webcam, ctx, labelContainer, maxPredictions;
// 갯수 count
let count = 0;
var counter = document.getElementById("counter");
counter.textContent = count;
counter.className = "hidden";
async function init() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
var target = document.getElementById("youtube");
target.className = "visible";
var target2 = document.getElementById("title");
target2.className = "click_title";
counter.className = "circle";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// Note: the pose library adds a tmPose object to your window (window.tmPose)
model = await tmPose.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
// Convenience function to setup a webcam
const size = 400;
const flip = true; // whether to flip the webcam
webcam = new tmPose.Webcam(size, size, flip); // width, height, flip
await webcam.setup(); // request access to the webcam
await webcam.play();
webcam.style
window.requestAnimationFrame(loop);
// append/get elements to the DOM
const canvas = document.getElementById("canvas");
canvas.width = size; canvas.height = size;
ctx = canvas.getContext("2d");
labelContainer = document.getElementById("label-container");
for (let i = 0; i < maxPredictions; i++) { // and class labels
labelContainer.appendChild(document.createElement("div"));
}
}
async function loop(timestamp) {
webcam.update(); // update the webcam frame
await predict();
window.requestAnimationFrame(loop);
}
async function predict() {
// Prediction #1: run input through posenet
// estimatePose can take in an image, video or canvas html element
const { pose, posenetOutput } = await model.estimatePose(webcam.canvas);
// Prediction 2: run input through teachable machine classification model
const prediction = await model.predict(posenetOutput);
let status = "stand"
if (prediction[0].probability.toFixed(2) > 0.9) { // 서있는 상태
if (status == "squat"){ // 전에 스쿼트 상태였다면, 일어날 때 카운트를 하나 올려줘야 함.
count++;
var audio = new Audio('./sound/' + count%10 + '.wav');
audio.play();
counter.textContent = count;
console.log(count);
}
status = "stand"
} else if (prediction[1].probability.toFixed(2) == 1.00) { // 스쿼트 자세
status = "squat"
} else if (prediction[2].probability.toFixed(2) == 1.00) { // 굽은 자세(잘못된 케이스)
if (status == "squart" || status == "stand") { // 굽은 자세로 잘못 수행하면, 소리 나도록
var audio = new Audio('./sound/bad.mp3');
audio.play();
}
status = "bent"
}
for (let i = 0; i < maxPredictions; i++) {
const classPrediction =
prediction[i].className + ": " + prediction[i].probability.toFixed(2);
labelContainer.childNodes[i].innerHTML = classPrediction;
}
// finally draw the poses
drawPose(pose);
}
function drawPose(pose) {
if (webcam.canvas) {
ctx.drawImage(webcam.canvas, 0, 0);
// draw the keypoints and skeleton
if (pose) {
const minPartConfidence = 0.5;
tmPose.drawKeypoints(pose.keypoints, minPartConfidence, ctx);
tmPose.drawSkeleton(pose.keypoints, minPartConfidence, ctx);
}
}
}
// 사용자 정보 API
let userName = 0
$.get('/api/users/name', function(data) {
userName = data.user.user_name
console.log(data.user.user_name)
})
$(document).ready(function(){
$('#savecount').click(function(){
$.ajax({
contentType : "application/json; charset=utf-8",
type : 'get',
url : '/api/users/name',
dataType : 'JSON',
success : function(datas) {
let user_name = datas.user_name
$.ajax({
contentType : "application/json; charset=utf-8",
type : 'post',
url : '/api/users/countupdate',
dataType : 'JSON',
data : JSON.stringify({
"name" : userName,
"count" : count
}),
success : function(datas)
{
if (datas.success)
{
alert("저장 성공 !")
}
}
})
}
})
})
})