이민호

clean code

Showing 70 changed files with 948 additions and 8 deletions
This diff is collapsed. Click to expand it.
1 +{
2 + "name": "screensaver",
3 + "version": "0.0.0",
4 + "private": true,
5 + "scripts": {
6 + "start": "node ./bin/www"
7 + },
8 + "dependencies": {
9 + "@tensorflow-models/blazeface": "0.0.5",
10 + "atob": "^2.1.2",
11 + "aws-sdk": "^2.791.0",
12 + "cookie-parser": "~1.4.4",
13 + "debug": "~2.6.9",
14 + "ejs": "~2.6.1",
15 + "express": "~4.16.1",
16 + "http-errors": "^1.6.3",
17 + "morgan": "~1.9.1",
18 + "multer": "^1.4.2",
19 + "python-shell": "^2.0.3"
20 + }
21 +}
...@@ -61,8 +61,6 @@ ...@@ -61,8 +61,6 @@
61 <footer class="align-center"> 61 <footer class="align-center">
62 <form action="/use" method="post"> 62 <form action="/use" method="post">
63 <input type="hidden" name="landing" id="landing" value="true" /> 63 <input type="hidden" name="landing" id="landing" value="true" />
64 - <!-- <label for="type">Password (4 characters minimum):</label>
65 - <input type='password' name='type' id='type' minlength="4" required/> -->
66 <input type='hidden' name="collection" id='collection' value="<%= collection %>" > 64 <input type='hidden' name="collection" id='collection' value="<%= collection %>" >
67 <select name="type" id="type" class="button alt"> 65 <select name="type" id="type" class="button alt">
68 <option value="Desktop">바탕화면</option> 66 <option value="Desktop">바탕화면</option>
......
1 +config.json
...\ No newline at end of file ...\ No newline at end of file
1 +var createError = require("http-errors");
2 +var express = require("express");
3 +var path = require("path");
4 +var cookieParser = require("cookie-parser");
5 +var logger = require("morgan");
6 +
7 +var indexRouter = require("./routes/index");
8 +var registerRouter = require("./routes/register");
9 +var useRouter = require("./routes/use");
10 +
11 +var app = express();
12 +
13 +// view engine setup
14 +app.set("views", path.join(__dirname, "views"));
15 +app.set("view engine", "ejs");
16 +
17 +app.use(logger("dev"));
18 +app.use(express.json({limit : "50mb"}));
19 +app.use(express.urlencoded({ limit:"50mb",extended: true }));
20 +app.use(cookieParser());
21 +app.use(express.static(path.join(__dirname, "public")));
22 +
23 +app.use("/", indexRouter);
24 +app.use("/register", registerRouter);
25 +app.use("/use", useRouter);
26 +
27 +// catch 404 and forward to error handler
28 +app.use(function (req, res, next) {
29 + next(createError(404));
30 +});
31 +
32 +// error handler
33 +app.use(function (err, req, res, next) {
34 + // set locals, only providing error in development
35 + res.locals.message = err.message;
36 + res.locals.error = req.app.get("env") === "development" ? err : {};
37 +
38 + // render the error page
39 + res.status(err.status || 500);
40 + res.render("error");
41 +});
42 +
43 +module.exports = app;
1 +#!/usr/bin/env node
2 +
3 +/**
4 + * Module dependencies.
5 + */
6 +
7 +var app = require("../app");
8 +var debug = require("debug")("screensaver:server");
9 +var http = require("http");
10 +const fs = require("fs");
11 +const path = require("path");
12 +const HTTPS = require("https");
13 +const domain = "www.screensaver.ml";
14 +const sslport = 23023;
15 +
16 +try {
17 + const option = {
18 + ca: fs.readFileSync("/etc/letsencrypt/live/" + domain + "/fullchain.pem"),
19 + key: fs
20 + .readFileSync(
21 + path.resolve(
22 + process.cwd(),
23 + "/etc/letsencrypt/live/" + domain + "/privkey.pem"
24 + ),
25 + "utf8"
26 + )
27 + .toString(),
28 + cert: fs
29 + .readFileSync(
30 + path.resolve(
31 + process.cwd(),
32 + "/etc/letsencrypt/live/" + domain + "/cert.pem"
33 + ),
34 + "utf8"
35 + )
36 + .toString(),
37 + };
38 +
39 + HTTPS.createServer(option, app).listen(sslport, () => {
40 + console.log(`[HTTPS] Server is started on port ${sslport}`);
41 + });
42 +} catch (error) {
43 + console.log(
44 + "[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다."
45 + );
46 + console.log(error);
47 +}
48 +
49 +/**
50 + * Get port from environment and store in Express.
51 + */
52 +
53 +var port = normalizePort(process.env.PORT || "3000");
54 +app.set("port", port);
55 +
56 +/**
57 + * Create HTTP server.
58 + */
59 +
60 +var server = http.createServer(app);
61 +
62 +/**
63 + * Listen on provided port, on all network interfaces.
64 + */
65 +
66 +server.listen(port);
67 +server.on("error", onError);
68 +server.on("listening", onListening);
69 +
70 +/**
71 + * Normalize a port into a number, string, or false.
72 + */
73 +
74 +function normalizePort(val) {
75 + var port = parseInt(val, 10);
76 +
77 + if (isNaN(port)) {
78 + // named pipe
79 + return val;
80 + }
81 +
82 + if (port >= 0) {
83 + // port number
84 + return port;
85 + }
86 +
87 + return false;
88 +}
89 +
90 +/**
91 + * Event listener for HTTP server "error" event.
92 + */
93 +
94 +function onError(error) {
95 + if (error.syscall !== "listen") {
96 + throw error;
97 + }
98 +
99 + var bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
100 +
101 + // handle specific listen errors with friendly messages
102 + switch (error.code) {
103 + case "EACCES":
104 + console.error(bind + " requires elevated privileges");
105 + process.exit(1);
106 + break;
107 + case "EADDRINUSE":
108 + console.error(bind + " is already in use");
109 + process.exit(1);
110 + break;
111 + default:
112 + throw error;
113 + }
114 +}
115 +
116 +/**
117 + * Event listener for HTTP server "listening" event.
118 + */
119 +
120 +function onListening() {
121 + var addr = server.address();
122 + var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
123 + debug("Listening on " + bind);
124 +}
No preview for this file type
This diff could not be displayed because it is too large.
1 +aws_setup.js
...\ No newline at end of file ...\ No newline at end of file
1 +/**
2 + * @license
3 + * Copyright 2019 Google LLC. All Rights Reserved.
4 + * Licensed under the Apache License, Version 2.0 (the "License");
5 + * you may not use this file except in compliance with the License.
6 + * You may obtain a copy of the License at
7 + *
8 + * https://www.apache.org/licenses/LICENSE-2.0
9 + *
10 + * Unless required by applicable law or agreed to in writing, software
11 + * distributed under the License is distributed on an "AS IS" BASIS,
12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 + * See the License for the specific language governing permissions and
14 + * limitations under the License.
15 + * =============================================================================
16 + */
17 +
18 +
19 +// tfjsWasm.setWasmPath('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@latest/dist/tfjs-backend-wasm.wasm');
20 +
21 +
22 +
23 +const stats = new Stats();
24 +stats.showPanel(0);
25 +document.body.prepend(stats.domElement);
26 +
27 +let model, ctx, videoWidth, videoHeight, video, canvas;
28 +let face_frame_count;
29 +face_frame_count = 0
30 +
31 +const state = {
32 + backend: 'webgl'
33 +};
34 +
35 +// const gui = new dat.GUI();
36 +// gui.add(state, 'backend', ['wasm', 'webgl', 'cpu']).onChange(async backend => {
37 +// await tf.setBackend(backend);
38 +// });
39 +
40 +async function setupCamera() {
41 + video = document.getElementById('video');
42 +
43 + const stream = await navigator.mediaDevices.getUserMedia({
44 + 'audio': false,
45 + 'video': { facingMode: 'user' },
46 + });
47 + video.srcObject = stream;
48 +
49 + return new Promise((resolve) => {
50 + video.onloadedmetadata = () => {
51 + resolve(video);
52 + };
53 + });
54 +}
55 +
56 +async function AWS_req(img_byte){
57 + let element = document.getElementById('method');
58 + console.log(element.value)
59 + let collection = document.getElementById('collection');
60 +
61 + var rekognition = new AWS.Rekognition();
62 + var params = {
63 + CollectionId: "6jj2",
64 + FaceMatchThreshold: 95,
65 + Image: {
66 + Bytes : img_byte
67 + },
68 + MaxFaces: 5
69 + };
70 + post_data = {
71 + "type" : element.value,
72 + "landing": "false",
73 + "image":img_byte,
74 + "collection" :collection.value
75 + }
76 + console.log(img_byte)
77 + redirectPost("/use",post_data)
78 + // rekognition.searchFacesByImage(params, function(err, data){
79 + // if (err) {
80 + // console.log(err, err.stack); // an error occurred
81 + // alert("AWS Not configured. Check /pubilc/javascripts/aws_setup.js");
82 + // // window.location.href = '/';
83 + // }
84 +
85 + // else console.log(data); // successful response
86 + // if (data.FaceMatches.length>0){
87 + // post_data = {
88 + // "result": true,
89 + // "type" : element.value,
90 + // "landing": "false",
91 + // "image":img_byte
92 + // }
93 + // // redirectPost("/use",post_data)
94 + // }
95 + // else{
96 + // post_data = {
97 + // "result": false,
98 + // "type" : element.value,
99 + // "landing": "false",
100 + // "image":img_byte
101 + // }
102 + // console.log('me!')
103 + // // redirectPost("/use",post_data)
104 + // }
105 +
106 +
107 + // }
108 + // )
109 +
110 +}
111 +
112 +const renderPrediction = async () => {
113 + stats.begin();
114 +
115 + const returnTensors = false;
116 + const flipHorizontal = true;
117 + const annotateBoxes = true;
118 + const predictions = await model.estimateFaces(
119 + video, returnTensors, flipHorizontal, annotateBoxes);
120 +
121 + if (predictions.length > 0) {
122 + face_frame_count += 1;
123 + ctx.clearRect(0, 0, canvas.width, canvas.height);
124 +
125 + for (let i = 0; i < predictions.length; i++) {
126 + if (returnTensors) {
127 + predictions[i].topLeft = predictions[i].topLeft.arraySync();
128 + predictions[i].bottomRight = predictions[i].bottomRight.arraySync();
129 + if (annotateBoxes) {
130 + predictions[i].landmarks = predictions[i].landmarks.arraySync();
131 + }
132 + }
133 +
134 + const start = predictions[i].topLeft;
135 + const end = predictions[i].bottomRight;
136 + // console.log(start)
137 + // console.log(end)
138 + const size = [end[0] - start[0], end[1] - start[1]];
139 + ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
140 + // ctx.fillRect(start[0], start[1], size[0], size[1]);
141 +
142 + if (annotateBoxes) {
143 + const landmarks = predictions[i].landmarks;
144 +
145 + ctx.fillStyle = "blue";
146 + for (let j = 0; j < landmarks.length; j++) {
147 + const x = landmarks[j][0];
148 + const y = landmarks[j][1];
149 + ctx.fillRect(x, y, 5, 5);
150 + }
151 + }
152 + }
153 + }
154 +
155 + stats.end();
156 + if(face_frame_count > 100){
157 + onClick()
158 + face_frame_count = 0
159 + }
160 + requestAnimationFrame(renderPrediction);
161 +};
162 +function onClick(){
163 + canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
164 + var dataURL = canvas.toDataURL();
165 + enc_data = atob(dataURL.split("data:image/png;base64,")[1])
166 + // console.log(enc_data)
167 + var length = enc_data.length;
168 + imageBytes = new ArrayBuffer(length);
169 + var ua = new Uint8Array(imageBytes);
170 + for (var i = 0; i < length; i++) {
171 + ua[i] = enc_data.charCodeAt(i);
172 + }
173 + // console.log(ua)
174 + AWS_req(dataURL)
175 +
176 +}
177 +const setupPage = async () => {
178 + await tf.setBackend(state.backend);
179 + await setupCamera();
180 + video.play();
181 +
182 + videoWidth = video.videoWidth;
183 + videoHeight = video.videoHeight;
184 + video.width = videoWidth;
185 + video.height = videoHeight;
186 +
187 + canvas = document.getElementById('output');
188 + canvas.width = videoWidth;
189 + canvas.height = videoHeight;
190 + ctx = canvas.getContext('2d');
191 + ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
192 +
193 + model = await blazeface.load();
194 +
195 + renderPrediction();
196 +};
197 +
198 +function redirectPost(url, data) {
199 + var form = document.createElement('form');
200 + document.body.appendChild(form);
201 + form.method = 'post';
202 + form.action = url;
203 + for (var name in data) {
204 + var input = document.createElement('input');
205 + input.type = 'hidden';
206 + input.name = name;
207 + input.value = data[name];
208 + form.appendChild(input);
209 + }
210 + form.submit();
211 +}
212 +
213 +setupPage();
This diff is collapsed. Click to expand it.
1 +/* jquery.scrollex v0.2.1 | (c) @ajlkn | github.com/ajlkn/jquery.scrollex | MIT licensed */
2 +!function(t){function e(t,e,n){return"string"==typeof t&&("%"==t.slice(-1)?t=parseInt(t.substring(0,t.length-1))/100*e:"vh"==t.slice(-2)?t=parseInt(t.substring(0,t.length-2))/100*n:"px"==t.slice(-2)&&(t=parseInt(t.substring(0,t.length-2)))),t}var n=t(window),i=1,o={};n.on("scroll",function(){var e=n.scrollTop();t.map(o,function(t){window.clearTimeout(t.timeoutId),t.timeoutId=window.setTimeout(function(){t.handler(e)},t.options.delay)})}).on("load",function(){n.trigger("scroll")}),jQuery.fn.scrollex=function(l){var s=t(this);if(0==this.length)return s;if(this.length>1){for(var r=0;r<this.length;r++)t(this[r]).scrollex(l);return s}if(s.data("_scrollexId"))return s;var a,u,h,c,p;switch(a=i++,u=jQuery.extend({top:0,bottom:0,delay:0,mode:"default",enter:null,leave:null,initialize:null,terminate:null,scroll:null},l),u.mode){case"top":h=function(t,e,n,i,o){return t>=i&&o>=t};break;case"bottom":h=function(t,e,n,i,o){return n>=i&&o>=n};break;case"middle":h=function(t,e,n,i,o){return e>=i&&o>=e};break;case"top-only":h=function(t,e,n,i,o){return i>=t&&n>=i};break;case"bottom-only":h=function(t,e,n,i,o){return n>=o&&o>=t};break;default:case"default":h=function(t,e,n,i,o){return n>=i&&o>=t}}return c=function(t){var i,o,l,s,r,a,u=this.state,h=!1,c=this.$element.offset();i=n.height(),o=t+i/2,l=t+i,s=this.$element.outerHeight(),r=c.top+e(this.options.top,s,i),a=c.top+s-e(this.options.bottom,s,i),h=this.test(t,o,l,r,a),h!=u&&(this.state=h,h?this.options.enter&&this.options.enter.apply(this.element):this.options.leave&&this.options.leave.apply(this.element)),this.options.scroll&&this.options.scroll.apply(this.element,[(o-r)/(a-r)])},p={id:a,options:u,test:h,handler:c,state:null,element:this,$element:s,timeoutId:null},o[a]=p,s.data("_scrollexId",p.id),p.options.initialize&&p.options.initialize.apply(this),s},jQuery.fn.unscrollex=function(){var e=t(this);if(0==this.length)return e;if(this.length>1){for(var n=0;n<this.length;n++)t(this[n]).unscrollex();return e}var i,l;return(i=e.data("_scrollexId"))?(l=o[i],window.clearTimeout(l.timeoutId),delete o[i],e.removeData("_scrollexId"),l.options.terminate&&l.options.terminate.apply(this),e):e}}(jQuery);
...\ No newline at end of file ...\ No newline at end of file
1 +/*
2 + Hielo by TEMPLATED
3 + templated.co @templatedco
4 + Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
5 +*/
6 +
7 +var settings = {
8 +
9 + banner: {
10 +
11 + // Indicators (= the clickable dots at the bottom).
12 + indicators: true,
13 +
14 + // Transition speed (in ms)
15 + // For timing purposes only. It *must* match the transition speed of "#banner > article".
16 + speed: 1500,
17 +
18 + // Transition delay (in ms)
19 + delay: 5000,
20 +
21 + // Parallax intensity (between 0 and 1; higher = more intense, lower = less intense; 0 = off)
22 + parallax: 0.25
23 +
24 + }
25 +
26 +};
27 +
28 +(function($) {
29 +
30 + skel.breakpoints({
31 + xlarge: '(max-width: 1680px)',
32 + large: '(max-width: 1280px)',
33 + medium: '(max-width: 980px)',
34 + small: '(max-width: 736px)',
35 + xsmall: '(max-width: 480px)'
36 + });
37 +
38 + /**
39 + * Applies parallax scrolling to an element's background image.
40 + * @return {jQuery} jQuery object.
41 + */
42 + $.fn._parallax = (skel.vars.browser == 'ie' || skel.vars.mobile) ? function() { return $(this) } : function(intensity) {
43 +
44 + var $window = $(window),
45 + $this = $(this);
46 +
47 + if (this.length == 0 || intensity === 0)
48 + return $this;
49 +
50 + if (this.length > 1) {
51 +
52 + for (var i=0; i < this.length; i++)
53 + $(this[i])._parallax(intensity);
54 +
55 + return $this;
56 +
57 + }
58 +
59 + if (!intensity)
60 + intensity = 0.25;
61 +
62 + $this.each(function() {
63 +
64 + var $t = $(this),
65 + on, off;
66 +
67 + on = function() {
68 +
69 + $t.css('background-position', 'center 100%, center 100%, center 0px');
70 +
71 + $window
72 + .on('scroll._parallax', function() {
73 +
74 + var pos = parseInt($window.scrollTop()) - parseInt($t.position().top);
75 +
76 + $t.css('background-position', 'center ' + (pos * (-1 * intensity)) + 'px');
77 +
78 + });
79 +
80 + };
81 +
82 + off = function() {
83 +
84 + $t
85 + .css('background-position', '');
86 +
87 + $window
88 + .off('scroll._parallax');
89 +
90 + };
91 +
92 + skel.on('change', function() {
93 +
94 + if (skel.breakpoint('medium').active)
95 + (off)();
96 + else
97 + (on)();
98 +
99 + });
100 +
101 + });
102 +
103 + $window
104 + .off('load._parallax resize._parallax')
105 + .on('load._parallax resize._parallax', function() {
106 + $window.trigger('scroll');
107 + });
108 +
109 + return $(this);
110 +
111 + };
112 +
113 + /**
114 + * Custom banner slider for Slate.
115 + * @return {jQuery} jQuery object.
116 + */
117 + $.fn._slider = function(options) {
118 +
119 + var $window = $(window),
120 + $this = $(this);
121 +
122 + if (this.length == 0)
123 + return $this;
124 +
125 + if (this.length > 1) {
126 +
127 + for (var i=0; i < this.length; i++)
128 + $(this[i])._slider(options);
129 +
130 + return $this;
131 +
132 + }
133 +
134 + // Vars.
135 + var current = 0, pos = 0, lastPos = 0,
136 + slides = [], indicators = [],
137 + $indicators,
138 + $slides = $this.children('article'),
139 + intervalId,
140 + isLocked = false,
141 + i = 0;
142 +
143 + // Turn off indicators if we only have one slide.
144 + if ($slides.length == 1)
145 + options.indicators = false;
146 +
147 + // Functions.
148 + $this._switchTo = function(x, stop) {
149 +
150 + if (isLocked || pos == x)
151 + return;
152 +
153 + isLocked = true;
154 +
155 + if (stop)
156 + window.clearInterval(intervalId);
157 +
158 + // Update positions.
159 + lastPos = pos;
160 + pos = x;
161 +
162 + // Hide last slide.
163 + slides[lastPos].removeClass('top');
164 +
165 + if (options.indicators)
166 + indicators[lastPos].removeClass('visible');
167 +
168 + // Show new slide.
169 + slides[pos].addClass('visible').addClass('top');
170 +
171 + if (options.indicators)
172 + indicators[pos].addClass('visible');
173 +
174 + // Finish hiding last slide after a short delay.
175 + window.setTimeout(function() {
176 +
177 + slides[lastPos].addClass('instant').removeClass('visible');
178 +
179 + window.setTimeout(function() {
180 +
181 + slides[lastPos].removeClass('instant');
182 + isLocked = false;
183 +
184 + }, 100);
185 +
186 + }, options.speed);
187 +
188 + };
189 +
190 + // Indicators.
191 + if (options.indicators)
192 + $indicators = $('<ul class="indicators"></ul>').appendTo($this);
193 +
194 + // Slides.
195 + $slides
196 + .each(function() {
197 +
198 + var $slide = $(this),
199 + $img = $slide.find('img');
200 +
201 + // Slide.
202 + $slide
203 + .css('background-image', 'url("' + $img.attr('src') + '")')
204 + .css('background-position', ($slide.data('position') ? $slide.data('position') : 'center'));
205 +
206 + // Add to slides.
207 + slides.push($slide);
208 +
209 + // Indicators.
210 + if (options.indicators) {
211 +
212 + var $indicator_li = $('<li>' + i + '</li>').appendTo($indicators);
213 +
214 + // Indicator.
215 + $indicator_li
216 + .data('index', i)
217 + .on('click', function() {
218 + $this._switchTo($(this).data('index'), true);
219 + });
220 +
221 + // Add to indicators.
222 + indicators.push($indicator_li);
223 +
224 + }
225 +
226 + i++;
227 +
228 + })
229 + ._parallax(options.parallax);
230 +
231 + // Initial slide.
232 + slides[pos].addClass('visible').addClass('top');
233 +
234 + if (options.indicators)
235 + indicators[pos].addClass('visible');
236 +
237 + // Bail if we only have a single slide.
238 + if (slides.length == 1)
239 + return;
240 +
241 + // Main loop.
242 + intervalId = window.setInterval(function() {
243 +
244 + current++;
245 +
246 + if (current >= slides.length)
247 + current = 0;
248 +
249 + $this._switchTo(current);
250 +
251 + }, options.delay);
252 +
253 + };
254 +
255 + $(function() {
256 +
257 + var $window = $(window),
258 + $body = $('body'),
259 + $header = $('#header'),
260 + $banner = $('.banner');
261 +
262 + // Disable animations/transitions until the page has loaded.
263 + $body.addClass('is-loading');
264 +
265 + $window.on('load', function() {
266 + window.setTimeout(function() {
267 + $body.removeClass('is-loading');
268 + }, 100);
269 + });
270 +
271 + // Prioritize "important" elements on medium.
272 + skel.on('+medium -medium', function() {
273 + $.prioritize(
274 + '.important\\28 medium\\29',
275 + skel.breakpoint('medium').active
276 + );
277 + });
278 +
279 + // Banner.
280 + $banner._slider(settings.banner);
281 +
282 + // Menu.
283 + $('#menu')
284 + .append('<a href="#menu" class="close"></a>')
285 + .appendTo($body)
286 + .panel({
287 + delay: 500,
288 + hideOnClick: true,
289 + hideOnSwipe: true,
290 + resetScroll: true,
291 + resetForms: true,
292 + side: 'right'
293 + });
294 +
295 + // Header.
296 + if (skel.vars.IEVersion < 9)
297 + $header.removeClass('alt');
298 +
299 + if ($banner.length > 0
300 + && $header.hasClass('alt')) {
301 +
302 + $window.on('resize', function() { $window.trigger('scroll'); });
303 +
304 + $banner.scrollex({
305 + bottom: $header.outerHeight(),
306 + terminate: function() { $header.removeClass('alt'); },
307 + enter: function() { $header.addClass('alt'); },
308 + leave: function() { $header.removeClass('alt'); $header.addClass('reveal'); }
309 + });
310 +
311 + }
312 +
313 + });
314 +
315 +})(jQuery);
...\ No newline at end of file ...\ No newline at end of file
1 +/* skel.js v3.0.2-dev | (c) skel.io | MIT licensed */
2 +var skel=function(){"use strict";var t={breakpointIds:null,events:{},isInit:!1,obj:{attachments:{},breakpoints:{},head:null,states:{}},sd:"/",state:null,stateHandlers:{},stateId:"",vars:{},DOMReady:null,indexOf:null,isArray:null,iterate:null,matchesMedia:null,extend:function(e,n){t.iterate(n,function(i){t.isArray(n[i])?(t.isArray(e[i])||(e[i]=[]),t.extend(e[i],n[i])):"object"==typeof n[i]?("object"!=typeof e[i]&&(e[i]={}),t.extend(e[i],n[i])):e[i]=n[i]})},newStyle:function(t){var e=document.createElement("style");return e.type="text/css",e.innerHTML=t,e},_canUse:null,canUse:function(e){t._canUse||(t._canUse=document.createElement("div"));var n=t._canUse.style,i=e.charAt(0).toUpperCase()+e.slice(1);return e in n||"Moz"+i in n||"Webkit"+i in n||"O"+i in n||"ms"+i in n},on:function(e,n){var i=e.split(/[\s]+/);return t.iterate(i,function(e){var a=i[e];if(t.isInit){if("init"==a)return void n();if("change"==a)n();else{var r=a.charAt(0);if("+"==r||"!"==r){var o=a.substring(1);if(o in t.obj.breakpoints)if("+"==r&&t.obj.breakpoints[o].active)n();else if("!"==r&&!t.obj.breakpoints[o].active)return void n()}}}t.events[a]||(t.events[a]=[]),t.events[a].push(n)}),t},trigger:function(e){if(t.events[e]&&0!=t.events[e].length)return t.iterate(t.events[e],function(n){t.events[e][n]()}),t},breakpoint:function(e){return t.obj.breakpoints[e]},breakpoints:function(e){function n(t,e){this.name=this.id=t,this.media=e,this.active=!1,this.wasActive=!1}return n.prototype.matches=function(){return t.matchesMedia(this.media)},n.prototype.sync=function(){this.wasActive=this.active,this.active=this.matches()},t.iterate(e,function(i){t.obj.breakpoints[i]=new n(i,e[i])}),window.setTimeout(function(){t.poll()},0),t},addStateHandler:function(e,n){t.stateHandlers[e]=n},callStateHandler:function(e){var n=t.stateHandlers[e]();t.iterate(n,function(e){t.state.attachments.push(n[e])})},changeState:function(e){t.iterate(t.obj.breakpoints,function(e){t.obj.breakpoints[e].sync()}),t.vars.lastStateId=t.stateId,t.stateId=e,t.breakpointIds=t.stateId===t.sd?[]:t.stateId.substring(1).split(t.sd),t.obj.states[t.stateId]?t.state=t.obj.states[t.stateId]:(t.obj.states[t.stateId]={attachments:[]},t.state=t.obj.states[t.stateId],t.iterate(t.stateHandlers,t.callStateHandler)),t.detachAll(t.state.attachments),t.attachAll(t.state.attachments),t.vars.stateId=t.stateId,t.vars.state=t.state,t.trigger("change"),t.iterate(t.obj.breakpoints,function(e){t.obj.breakpoints[e].active?t.obj.breakpoints[e].wasActive||t.trigger("+"+e):t.obj.breakpoints[e].wasActive&&t.trigger("-"+e)})},generateStateConfig:function(e,n){var i={};return t.extend(i,e),t.iterate(t.breakpointIds,function(e){t.extend(i,n[t.breakpointIds[e]])}),i},getStateId:function(){var e="";return t.iterate(t.obj.breakpoints,function(n){var i=t.obj.breakpoints[n];i.matches()&&(e+=t.sd+i.id)}),e},poll:function(){var e="";e=t.getStateId(),""===e&&(e=t.sd),e!==t.stateId&&t.changeState(e)},_attach:null,attach:function(e){var n=t.obj.head,i=e.element;return(!i.parentNode||!i.parentNode.tagName)&&(t._attach||(t._attach=n.firstChild),n.insertBefore(i,t._attach.nextSibling),e.permanent&&(t._attach=i),!0)},attachAll:function(e){var n=[];t.iterate(e,function(t){n[e[t].priority]||(n[e[t].priority]=[]),n[e[t].priority].push(e[t])}),n.reverse(),t.iterate(n,function(e){t.iterate(n[e],function(i){t.attach(n[e][i])})})},detach:function(t){var e=t.element;return!(t.permanent||!e.parentNode||e.parentNode&&!e.parentNode.tagName)&&(e.parentNode.removeChild(e),!0)},detachAll:function(e){var n={};t.iterate(e,function(t){n[e[t].id]=!0}),t.iterate(t.obj.attachments,function(e){e in n||t.detach(t.obj.attachments[e])})},attachment:function(e){return e in t.obj.attachments?t.obj.attachments[e]:null},newAttachment:function(e,n,i,a){return t.obj.attachments[e]={id:e,element:n,priority:i,permanent:a}},init:function(){t.initMethods(),t.initVars(),t.initEvents(),t.obj.head=document.getElementsByTagName("head")[0],t.isInit=!0,t.trigger("init")},initEvents:function(){t.on("resize",function(){t.poll()}),t.on("orientationChange",function(){t.poll()}),t.DOMReady(function(){t.trigger("ready")}),window.onload&&t.on("load",window.onload),window.onload=function(){t.trigger("load")},window.onresize&&t.on("resize",window.onresize),window.onresize=function(){t.trigger("resize")},window.onorientationchange&&t.on("orientationChange",window.onorientationchange),window.onorientationchange=function(){t.trigger("orientationChange")}},initMethods:function(){document.addEventListener?!function(e,n){t.DOMReady=n()}("domready",function(){function t(t){for(r=1;t=n.shift();)t()}var e,n=[],i=document,a="DOMContentLoaded",r=/^loaded|^c/.test(i.readyState);return i.addEventListener(a,e=function(){i.removeEventListener(a,e),t()}),function(t){r?t():n.push(t)}}):!function(e,n){t.DOMReady=n()}("domready",function(t){function e(t){for(h=1;t=i.shift();)t()}var n,i=[],a=!1,r=document,o=r.documentElement,s=o.doScroll,c="DOMContentLoaded",d="addEventListener",u="onreadystatechange",l="readyState",f=s?/^loaded|^c/:/^loaded|c/,h=f.test(r[l]);return r[d]&&r[d](c,n=function(){r.removeEventListener(c,n,a),e()},a),s&&r.attachEvent(u,n=function(){/^c/.test(r[l])&&(r.detachEvent(u,n),e())}),t=s?function(e){self!=top?h?e():i.push(e):function(){try{o.doScroll("left")}catch(n){return setTimeout(function(){t(e)},50)}e()}()}:function(t){h?t():i.push(t)}}),Array.prototype.indexOf?t.indexOf=function(t,e){return t.indexOf(e)}:t.indexOf=function(t,e){if("string"==typeof t)return t.indexOf(e);var n,i,a=e?e:0;if(!this)throw new TypeError;if(i=this.length,0===i||a>=i)return-1;for(a<0&&(a=i-Math.abs(a)),n=a;n<i;n++)if(this[n]===t)return n;return-1},Array.isArray?t.isArray=function(t){return Array.isArray(t)}:t.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},Object.keys?t.iterate=function(t,e){if(!t)return[];var n,i=Object.keys(t);for(n=0;i[n]&&e(i[n],t[i[n]])!==!1;n++);}:t.iterate=function(t,e){if(!t)return[];var n;for(n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])===!1)break},window.matchMedia?t.matchesMedia=function(t){return""==t||window.matchMedia(t).matches}:window.styleMedia||window.media?t.matchesMedia=function(t){if(""==t)return!0;var e=window.styleMedia||window.media;return e.matchMedium(t||"all")}:window.getComputedStyle?t.matchesMedia=function(t){if(""==t)return!0;var e=document.createElement("style"),n=document.getElementsByTagName("script")[0],i=null;e.type="text/css",e.id="matchmediajs-test",n.parentNode.insertBefore(e,n),i="getComputedStyle"in window&&window.getComputedStyle(e,null)||e.currentStyle;var a="@media "+t+"{ #matchmediajs-test { width: 1px; } }";return e.styleSheet?e.styleSheet.cssText=a:e.textContent=a,"1px"===i.width}:t.matchesMedia=function(t){if(""==t)return!0;var e,n,i,a,r={"min-width":null,"max-width":null},o=!1;for(i=t.split(/\s+and\s+/),e=0;e<i.length;e++)n=i[e],"("==n.charAt(0)&&(n=n.substring(1,n.length-1),a=n.split(/:\s+/),2==a.length&&(r[a[0].replace(/^\s+|\s+$/g,"")]=parseInt(a[1]),o=!0));if(!o)return!1;var s=document.documentElement.clientWidth,c=document.documentElement.clientHeight;return!(null!==r["min-width"]&&s<r["min-width"]||null!==r["max-width"]&&s>r["max-width"]||null!==r["min-height"]&&c<r["min-height"]||null!==r["max-height"]&&c>r["max-height"])},navigator.userAgent.match(/MSIE ([0-9]+)/)&&RegExp.$1<9&&(t.newStyle=function(t){var e=document.createElement("span");return e.innerHTML='&nbsp;<style type="text/css">'+t+"</style>",e})},initVars:function(){var e,n,i,a=navigator.userAgent;e="other",n=0,i=[["firefox",/Firefox\/([0-9\.]+)/],["bb",/BlackBerry.+Version\/([0-9\.]+)/],["bb",/BB[0-9]+.+Version\/([0-9\.]+)/],["opera",/OPR\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)/],["edge",/Edge\/([0-9\.]+)/],["safari",/Version\/([0-9\.]+).+Safari/],["chrome",/Chrome\/([0-9\.]+)/],["ie",/MSIE ([0-9]+)/],["ie",/Trident\/.+rv:([0-9]+)/]],t.iterate(i,function(t,i){if(a.match(i[1]))return e=i[0],n=parseFloat(RegExp.$1),!1}),t.vars.browser=e,t.vars.browserVersion=n,e="other",n=0,i=[["ios",/([0-9_]+) like Mac OS X/,function(t){return t.replace("_",".").replace("_","")}],["ios",/CPU like Mac OS X/,function(t){return 0}],["wp",/Windows Phone ([0-9\.]+)/,null],["android",/Android ([0-9\.]+)/,null],["mac",/Macintosh.+Mac OS X ([0-9_]+)/,function(t){return t.replace("_",".").replace("_","")}],["windows",/Windows NT ([0-9\.]+)/,null],["bb",/BlackBerry.+Version\/([0-9\.]+)/,null],["bb",/BB[0-9]+.+Version\/([0-9\.]+)/,null]],t.iterate(i,function(t,i){if(a.match(i[1]))return e=i[0],n=parseFloat(i[2]?i[2](RegExp.$1):RegExp.$1),!1}),t.vars.os=e,t.vars.osVersion=n,t.vars.IEVersion="ie"==t.vars.browser?t.vars.browserVersion:99,t.vars.touch="wp"==t.vars.os?navigator.msMaxTouchPoints>0:!!("ontouchstart"in window),t.vars.mobile="wp"==t.vars.os||"android"==t.vars.os||"ios"==t.vars.os||"bb"==t.vars.os}};return t.init(),t}();!function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?module.exports=e():t.skel=e()}(this,function(){return skel});
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
1 +body {
2 + padding: 50px;
3 + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
4 +}
5 +
6 +a {
7 + color: #00B7FF;
8 +}
1 +var express = require("express");
2 +var router = express.Router();
3 +function makeid(length) {
4 + var result = "";
5 + var characters =
6 + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
7 + var charactersLength = characters.length;
8 + for (var i = 0; i < length; i++) {
9 + result += characters.charAt(Math.floor(Math.random() * charactersLength));
10 + }
11 + return result;
12 +}
13 +var AWS = require("aws-sdk");
14 +AWS.config.loadFromPath("./config.json");
15 +var rekognition = new AWS.Rekognition();
16 +
17 +/* GET home page. */
18 +router.get("/", function (req, res, next) {
19 + var collectionID = makeid(8);
20 + var params = {
21 + CollectionId: collectionID,
22 + };
23 + rekognition.createCollection(params, function (err, data) {
24 + if (err) console.log(err, err.stack);
25 + // an error occurred
26 + else console.log(data); // successful response
27 + });
28 + console.log(collectionID);
29 + res.render("index", {
30 + title: "AI Screensaver",
31 + error: "",
32 + collection: collectionID,
33 + });
34 +});
35 +router.post("/", function (req, res, next) {
36 + console.log(req.body.collection);
37 + res.render("index", {
38 + title: "AI Screensaver",
39 + error: "",
40 + collection: req.body.collection,
41 + });
42 +});
43 +module.exports = router;
1 +var express = require("express");
2 +var router = express.Router();
3 +var AWS = require("aws-sdk");
4 +var fs = require("fs");
5 +const path = require('path');
6 +AWS.config.loadFromPath("./config.json");
7 +const multer = require('multer');
8 +var rekognition = new AWS.Rekognition();
9 +const upload = multer({
10 + storage: multer.diskStorage({
11 + destination(req, file, cb){
12 + cb(null, 'uploads/')
13 + },
14 + filename(req, file, cb){
15 + // 확장자 추출
16 + const ext = path.extname(file.originalname);
17 + // 이름설정 (basename:확장자제외 파일명) + 현재시간 + 확장자
18 + cb(null, path.basename(file.originalname, ext) + new Date().valueOf() + ext);
19 + },
20 + }),
21 + limit: { fileSize: 5 * 1024 * 1024},
22 +});
23 +router.post("/", upload.single('img'), (req, res) => {
24 + console.log(req.file)
25 +
26 + fs.readFile(req.file.path, function (err, data) {
27 + if (err) {
28 + console.log(err);
29 + }
30 + params = {
31 + CollectionId: req.body.collection,
32 + DetectionAttributes: [],
33 + ExternalImageId: req.body.text,
34 + Image: { Bytes: data },
35 + };
36 + rekognition.indexFaces(params, function (err, data) {
37 + if (err) {
38 + console.log(err, err.stack);
39 + res.render('redirect', {error:"not registered! is there any faces on image?",collection: req.body.collection})
40 + }
41 + // an error occurred
42 + else console.log(data); // successful response
43 +
44 + fs.unlink(req.file.path, (err) => {
45 + if (err) throw err;
46 + console.log('image was deleted');
47 + });
48 + if(data.FaceRecords.length>0)
49 + res.render('redirect', {error:"registered!",collection: req.body.collection})
50 + else
51 + res.render('redirect', {error:"not registered! is there any faces on image?",collection: req.body.collection})
52 + });
53 + });
54 +});
55 +
56 +module.exports = router;
1 +<body>
2 + <h1>
3 + Action Triggered!
4 + </h1>
5 + <a href="/"> go back to home </a>
6 +</body>
...\ No newline at end of file ...\ No newline at end of file
1 +<h1><%= message %></h1>
2 +
3 +<h2><%= error.status %></h2>
4 +<!-- <pre><%= error.stack %></pre> -->
5 +<a href="/"> go back to home </a>
...@@ -64,12 +64,6 @@ ...@@ -64,12 +64,6 @@
64 <label for="type">Password (4 characters minimum):</label> 64 <label for="type">Password (4 characters minimum):</label>
65 <input type='password' name='type' id='type' minlength="4" required/> 65 <input type='password' name='type' id='type' minlength="4" required/>
66 <input type='hidden' name="collection" id='collection' value="<%= collection %>" > 66 <input type='hidden' name="collection" id='collection' value="<%= collection %>" >
67 - <!-- <select name="type" id="type" class="button alt">
68 - <option value="Desktop">바탕화면</option>
69 - <option value="Logout">로그아웃</option>
70 - <option value="NewDesktop">화면전환</option> -->
71 - </select>
72 -
73 <input type="submit" value="시작" class="button alt"> 67 <input type="submit" value="시작" class="button alt">
74 </form> 68 </form>
75 </footer> 69 </footer>
......
1 +<body>
2 +
3 +</body>
4 +<script type="text/javascript">
5 + var error = '<%= error %>';
6 +
7 + if(error!='')
8 + {
9 + alert(error);
10 + }
11 + function redirectPost(url, data) {
12 + var form = document.createElement('form');
13 + document.body.appendChild(form);
14 + form.method = 'post';
15 + form.action = url;
16 + for (var name in data) {
17 + var input = document.createElement('input');
18 + input.type = 'hidden';
19 + input.name = name;
20 + input.value = data[name];
21 + form.appendChild(input);
22 + }
23 + form.submit();
24 +}
25 +post_data = {
26 + "collection":'<%= collection %>'
27 +}
28 + // window.location.href='/'
29 + redirectPost('/',post_data)
30 + </script>
...\ No newline at end of file ...\ No newline at end of file
1 +<!-- Copyright 2019 Google LLC. All Rights Reserved.
2 +
3 +Licensed under the Apache License, Version 2.0 (the "License");
4 +you may not use this file except in compliance with the License.
5 +You may obtain a copy of the License at
6 +
7 + http://www.apache.org/licenses/LICENSE-2.0
8 +
9 +Unless required by applicable law or agreed to in writing, software
10 +distributed under the License is distributed on an "AS IS" BASIS,
11 +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 +See the License for the specific language governing permissions and
13 +limitations under the License.
14 +==============================================================================-->
15 +
16 +<style>
17 + body {
18 + margin: 25px;
19 + }
20 +
21 + #main {
22 + position: relative;
23 + margin: 50px 0;
24 + }
25 +
26 + canvas {
27 + position: absolute;
28 + top: 0;
29 + left: 0;
30 + }
31 +
32 + #description {
33 + margin-top: 20px;
34 + width: 600px;
35 + }
36 +
37 + #description-title {
38 + font-weight: bold;
39 + font-size: 18px;
40 + }
41 +</style>
42 +
43 +<body>
44 + <div id="main">
45 + <video id="video" playsinline style="
46 + -webkit-transform: scaleX(-1);
47 + transform: scaleX(-1);
48 + width: auto;
49 + height: auto;
50 + ">
51 + </video>
52 + <canvas id="output"></canvas>
53 + <div id="description">
54 + <div id="description-title">Face Detecting...</div>
55 + <input type="button" id="close_button" onclick="location.href='/';" value="종료" />
56 + </div>
57 + <video id="video" playsinline style="
58 + -webkit-transform: scaleX(-1);
59 + transform: scaleX(-1);
60 + visibility: hidden;
61 + width: auto;
62 + height: auto;
63 + ">
64 + </video>
65 + </div>
66 + <form>
67 + <input type="hidden" id="method" name="method" value=<%= method %> />
68 + <input type="hidden" id="collection" name="collection" value=<%= collection %> />
69 + </form>
70 +</body>
71 +<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
72 +<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm"></script>
73 +<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/blazeface"></script>
74 +<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
75 +<script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>
76 +<script src="https://sdk.amazonaws.com/js/aws-sdk-2.799.0.min.js"></script>
77 +<script src="javascripts/aws_setup.js"></script>
78 +<script src="javascripts/index.js"></script>