hyeyeon-sun

final

Showing 71 changed files with 2175 additions and 0 deletions
node_modules/
MIT License
Copyright (c) 2016 Jerry Wang (https://jw84.co)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
web: node index.js
This diff is collapsed. Click to expand it.
import tensorflow as tf
import numpy as np
import re
from collections import Counter
import sys
import math
from random import randint
import pickle
import os
import sys
sys.stdout.reconfigure(encoding='utf-8')
# This Word2Vec implementation is largely based on this paper
# https://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf
# It's a bit old, but Word2Vec is still SOTA and relatively simple, so I'm going with it
# Check out Tensorflow's documentation which is pretty good for Word2Vec
# https://www.tensorflow.org/tutorials/word2vec
wordVecDimensions = 100
batchSize = 128
numNegativeSample = 64
windowSize = 5
numIterations = 100000
# This function just takes in the conversation data and makes it
# into one huge string, and then uses a Counter to identify words
# and the number of occurences
def processDataset(filename):
openedFile = open(filename, 'r', encoding='UTF8')
allLines = openedFile.readlines()
myStr = ""
for line in allLines:
myStr += line
finalDict = Counter(myStr.split())
return myStr, finalDict
def createTrainingMatrices(dictionary, corpus):
allUniqueWords = list(dictionary.keys())
allWords = corpus.split()
numTotalWords = len(allWords)
xTrain=[]
yTrain=[]
for i in range(numTotalWords):
if i % 100000 == 0:
print ('Finished %d/%d total words' % (i, numTotalWords))
wordsAfter = allWords[i + 1:i + windowSize + 1]
wordsBefore = allWords[max(0, i - windowSize):i]
wordsAdded = wordsAfter + wordsBefore
for word in wordsAdded:
xTrain.append(allUniqueWords.index(allWords[i]))
yTrain.append(allUniqueWords.index(word))
return xTrain, yTrain
def getTrainingBatch():
num = randint(0,numTrainingExamples - batchSize - 1)
arr = xTrain[num:num + batchSize]
labels = yTrain[num:num + batchSize]
return arr, labels[:,np.newaxis]
continueWord2Vec = True
# Loading the data structures if they are present in the directory
if (os.path.isfile('Word2VecXTrain.npy') and os.path.isfile('Word2VecYTrain.npy') and os.path.isfile('wordList.txt')):
xTrain = np.load('Word2VecXTrain.npy')
yTrain = np.load('Word2VecYTrain.npy')
print ('Finished loading training matrices')
with open("wordList.txt", "rb") as fp:
wordList = pickle.load(fp)
print ('Finished loading word list')
else:
fullCorpus, datasetDictionary = processDataset(r'C:\Users\dlgpd\Desktop\20-1\oss\term-project\Learn_for_yourself\final\conversationData.txt')
print ('Finished parsing and cleaning dataset')
wordList = list(datasetDictionary.keys())
createOwnVectors = 'y'
if (createOwnVectors == 'y'):
xTrain, yTrain = createTrainingMatrices(datasetDictionary, fullCorpus)
print ('Finished creating training matrices')
np.save(r'C:\Users\dlgpd\Desktop\20-1\oss\term-project\Learn_for_yourself\final\Word2VecXTrain.npy', xTrain)
np.save(r'C:\Users\dlgpd\Desktop\20-1\oss\term-project\Learn_for_yourself\final\Word2VecYTrain.npy', yTrain)
else:
continueWord2Vec = False
with open(r"C:\Users\dlgpd\Desktop\20-1\oss\term-project\Learn_for_yourself\final\wordList.txt", "wb") as fp:
pickle.dump(wordList, fp)
// call all the required packages
var express = require('express')
var bodyParser= require('body-parser')
var multer = require('multer');
let { PythonShell } = require ( 'python-shell' )
//CREATE EXPRESS APP
var app = express();
app.use(bodyParser.urlencoded({extended: true}))
app.use('/users', express.static('uploads'))
var options = {
mode: 'text',
pythonPath: '',
pythonOptions: ['-u'],
scriptPath: '',
// args: ['value1', 'value2', 'value3'],
encoding: 'utf8'
};
//ROUTES WILL GO HERE
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, "dataset.txt")
}
})
var upload = multer({ storage: storage })
app.post('/uploadfile', upload.single('myFile'), (req, res, next) => {
const file = req.file
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send(file)
})
var upload = multer({ storage: storage })
app.get('/makebot', (req, res) => {
res.sendFile(__dirname + '/index.html');
PythonShell.run('createDataset.py', options, (err, results) => {
if (err) throw err;
console.log('results: %j', results);
});
res.send("create Data set")
PythonShell.run('Word2Vec.py', options, (err, results) => {
if (err) throw err;
console.log('results: %j', results);
});
res.send("word to vector")
PythonShell.run('Seq2Seq.py', options, (err, results) => {
if (err) throw err;
console.log('results: %j', results);
res.send("seq 2 seq")
});
})
app.listen(3000, () => console.log('Server started on port 3000'));
\ No newline at end of file
import pandas as pd
import numpy as np
import os
import re
from datetime import datetime
import sys
sys.stdout.reconfigure(encoding='utf-8')
currentPath = os.getcwd()
def getFacebookData():
print("function active")
personName = "이혜연"
personName = personName.rstrip('\r')
responseDictionary = dict()
with open(r'C:\Users\dlgpd\Desktop\20-1\oss\term-project\Learn_for_yourself\final\uploads\dataset.txt', 'r', encoding='UTF8') as fbFile:
allLines = fbFile.readlines()
myMessage, otherPersonsMessage, currentSpeaker = "","",""
for index,lines in enumerate(allLines):
rightBracket = lines.find(':') + 5
justMessage = lines[rightBracket:]
colon = justMessage.find(':')
# Find messages that I sent
if (justMessage[:colon-1] == personName):
if not myMessage:
# Want to find the first message that I send (if I send multiple
# in a row)
startMessageIndex = index - 1
myMessage += justMessage[colon + 2:]
elif myMessage:
# Now go and see what message the other person sent by looking at
# previous messages
for counter in range(startMessageIndex, 0, -1):
currentLine = allLines[counter]
rightBracket = currentLine.find(':') + 5
justMessage = currentLine[rightBracket:]
colon = justMessage.find(':')
if not currentSpeaker:
# The first speaker not named me
currentSpeaker = justMessage[:colon]
elif (currentSpeaker != justMessage[:colon] and otherPersonsMessage):
# A different person started speaking, so now I know that the
# first person's message is done
otherPersonsMessage = cleanMessage(otherPersonsMessage)
myMessage = cleanMessage(myMessage)
responseDictionary[otherPersonsMessage] = myMessage
break
otherPersonsMessage = justMessage[colon + 2:] + otherPersonsMessage
myMessage, otherPersonsMessage, currentSpeaker = "","",""
return responseDictionary
def cleanMessage(message):
# Remove new lines within message
cleanedMessage = message.replace('\n',' ').lower()
# Deal with some weird tokens
cleanedMessage = cleanedMessage.replace("\xc2\xa0", "")
# Remove punctuation
cleanedMessage = re.sub('([.,!?])','', cleanedMessage)
# Remove multiple spaces in message
cleanedMessage = re.sub(' +',' ', cleanedMessage)
return cleanedMessage
combinedDictionary = {}
combinedDictionary.update(getFacebookData())
print ('Total len of dictionary', len(combinedDictionary))
print('Saving conversation data dictionary')
np.save(r'C:\Users\dlgpd\Desktop\20-1\oss\term-project\Learn_for_yourself\final\conversationDictionary.npy', combinedDictionary)
conversationFile = open(r'C:\Users\dlgpd\Desktop\20-1\oss\term-project\Learn_for_yourself\final\conversationData.txt', 'w', encoding='UTF8')
for key, value in combinedDictionary.items():
if (not key.strip() or not value.strip()):
# If there are empty strings
continue
conversationFile.write(key.strip() + value.strip())
import numpy as np
import pickle
import tensorflow as tf
from flask import Flask, jsonify, render_template, request
import model
# Load in data structures
with open("data/wordList.txt", "rb") as fp:
wordList = pickle.load(fp)
wordList.append('<pad>')
wordList.append('<EOS>')
# Load in hyperparamters
vocabSize = len(wordList)
batchSize = 24
maxEncoderLength = 15
maxDecoderLength = 15
lstmUnits = 112
numLayersLSTM = 3
# Create placeholders
encoderInputs = [tf.placeholder(tf.int32, shape=(None,)) for i in range(maxEncoderLength)]
decoderLabels = [tf.placeholder(tf.int32, shape=(None,)) for i in range(maxDecoderLength)]
decoderInputs = [tf.placeholder(tf.int32, shape=(None,)) for i in range(maxDecoderLength)]
feedPrevious = tf.placeholder(tf.bool)
encoderLSTM = tf.nn.rnn_cell.BasicLSTMCell(lstmUnits, state_is_tuple=True)
#encoderLSTM = tf.nn.rnn_cell.MultiRNNCell([singleCell]*numLayersLSTM, state_is_tuple=True)
decoderOutputs, decoderFinalState = tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq(encoderInputs, decoderInputs, encoderLSTM,
vocabSize, vocabSize, lstmUnits, feed_previous=feedPrevious)
decoderPrediction = tf.argmax(decoderOutputs, 2)
# Start session and get graph
sess = tf.Session()
#y, variables = model.getModel(encoderInputs, decoderLabels, decoderInputs, feedPrevious)
# Load in pretrained model
saver = tf.train.Saver()
saver.restore(sess, tf.train.latest_checkpoint('models'))
zeroVector = np.zeros((1), dtype='int32')
def pred(inputString):
inputVector = model.getTestInput(inputString, wordList, maxEncoderLength)
feedDict = {encoderInputs[t]: inputVector[t] for t in range(maxEncoderLength)}
feedDict.update({decoderLabels[t]: zeroVector for t in range(maxDecoderLength)})
feedDict.update({decoderInputs[t]: zeroVector for t in range(maxDecoderLength)})
feedDict.update({feedPrevious: True})
ids = (sess.run(decoderPrediction, feed_dict=feedDict))
return model.idsToSentence(ids, wordList)
# webapp
app = Flask(__name__, template_folder='./')
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MY APP</title>
</head>
<body>
<div>
<script type ="text/javascript">
function movepage() {
location.href = "/makebot";
}
</script>
<form action="/uploadfile" enctype="multipart/form-data" method="POST">
<input type="file" name="myFile" />
<input type="submit" value="Upload a file"/>
</form>
<input type="button" value="make chatbot" onclick="movepage()"/>
</div>
</body>
</html>
\ No newline at end of file
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# database
/database.json
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
This diff could not be displayed because it is too large.
{
"name": "management",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.10.2",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000/"
}
No preview for this file type
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
import React, { Component } from 'react';
import './App.css';
import Customer from './components/Customer';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableHead from '@material-ui/core/TableHead';
import TableBody from '@material-ui/core/TableBody';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import { withStyles } from '@material-ui/core/styles';
import CircularProgress from '@material-ui/core/CircularProgress';
const styles = theme => ({
root: {
width: '100%',
marginTop: theme.spacing.unit*3,
overflowX: "auto"
},
table: {
minWidth: 1080
},
progress: {
margine: theme.spacing.unit*2
}
})
class App extends Component {
state = {
customers: "",
completed: 0
}
//모든 컴포넌트 준비 완료일 때 실행 -- react가 라이브러리이기 때문 !
componentDidMount() {
this.timer = setInterval(this.progress,20);
this.callApi()
.then(res => this.setState({customers: res}))
.catch(err => console.log(err));
}
callApi = async() => {
//local의/api/customers에 접속해 response로 받아오고 이를 body변수에 담아주겠다
const response = await fetch('/api/customers');
const body = await response.json();
return body;
}
progress = () => {
const { completed } = this.state;
this.setState({completed : completed >=100 ? 0: completed +1});
}
render() {
const { classes } = this.props;
return (
<Paper className = {classes.root}>
<Table className = {classes.table}>
<TableHead>
<TableRow>
<TableCell>번호</TableCell>
<TableCell>이미지</TableCell>
<TableCell>이름</TableCell>
<TableCell>생년월일</TableCell>
<TableCell>성별</TableCell>
<TableCell>직업</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.customers ? this.state.customers.map (c=> {
return (<Customer key={c.id} id={c.id} image={c.image} name={c.name} birthday={c.birthday} gender={c.gender} job={c.job} />)
}) :
<TableRow>
<TableCell colSpan="6" align="center">
<CircularProgress className={classes.progress} varient="determinate" value={this.state.completed}/>
</TableCell>
</TableRow>
}
</TableBody>
</Table>
</Paper>
);
}
}
export default withStyles(styles)(App);
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
import React from 'react';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
class Customer extends React.Component {
render(){
return(
<TableRow>
<TableCell>{this.props.id}</TableCell>
<TableCell><img src={this.props.image} alt="profile"/></TableCell>
<TableCell>{this.props.name}</TableCell>
<TableCell>{this.props.birthday}</TableCell>
<TableCell>{this.props.gender}</TableCell>
<TableCell>{this.props.job}</TableCell>
</TableRow>
);
}
}
export default Customer;
\ No newline at end of file
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';
This diff is collapsed. Click to expand it.
{
"name" : "management",
"version": "1.0.0",
"scripts":{
"client": "cd client && yarn start",
"server": "node server.js",
"dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
},
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4"
},
"devDependencies": {
"concurrently":"^"
}
}
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ exrended : true }));
const data = fs.readFileSync('./database.json');
const conf = JSON.parse(data);
const mysql = require('mysql');
const connection = mysql.createConnection({
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.databse
});
connection.connect();
app.get('/api/customers', (req, res) => {
connection.query(
"SELECT * FROM CUSTOMER",
(err,rows,fields) => {
res.send(rows);
}
)
})
app.listen(port, () => console.log(`Listening on port ${port}`));
\ No newline at end of file
model_checkpoint_path: "pretrained_seq2seq.ckpt-108300"
all_model_checkpoint_paths: "pretrained_seq2seq.ckpt-107900"
all_model_checkpoint_paths: "pretrained_seq2seq.ckpt-108000"
all_model_checkpoint_paths: "pretrained_seq2seq.ckpt-108100"
all_model_checkpoint_paths: "pretrained_seq2seq.ckpt-108200"
all_model_checkpoint_paths: "pretrained_seq2seq.ckpt-108300"
/* eslint-disable */
module.exports = {
"extends": "standard",
"rules": {
"semi": [2, "always"],
"indent": [2, 4],
"no-return-await": 0,
"space-before-function-paren": [2, {
"named": "never",
"anonymous": "never",
"asyncArrow": "always"
}],
"template-curly-spacing": [2, "always"]
}
};
\ No newline at end of file
# my-own-bot
like me
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
## Prerequisites
- [Node.js](https://nodejs.org) version 10.14.1 or higher
```bash
# determine node version
node --version
```
## To run the bot
- Install modules
```bash
npm install
```
- Start the bot
```bash
npm start
```
## Testing the bot using Bot Framework Emulator
[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
- Install the Bot Framework Emulator version 4.9.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
### Connect to the bot using Bot Framework Emulator
- Launch Bot Framework Emulator
- File -> Open Bot
- Enter a Bot URL of `http://localhost:3978/api/messages`
## Deploy the bot to Azure
To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions.
## Further reading
- [Bot Framework Documentation](https://docs.botframework.com)
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
- [Dialogs](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
- [Gathering Input Using Prompts](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0)
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
- [Azure Portal](https://portal.azure.com)
- [Language Understanding using LUIS](https://docs.microsoft.com/en-us/azure/cognitive-services/luis/)
- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
- [Restify](https://www.npmjs.com/package/restify)
- [dotenv](https://www.npmjs.com/package/dotenv)
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const { ActivityHandler, MessageFactory } = require('botbuilder');
class EchoBot extends ActivityHandler {
constructor() {
super();
// See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
this.onMessage(async (context, next) => {
const replyText = `Echo: ${ context.activity.text }`;
await context.sendActivity(MessageFactory.text(replyText, replyText));
// By calling next() you ensure that the next BotHandler is run.
await next();
});
this.onMembersAdded(async (context, next) => {
const membersAdded = context.activity.membersAdded;
const welcomeText = 'Hello and welcome!';
for (let cnt = 0; cnt < membersAdded.length; ++cnt) {
if (membersAdded[cnt].id !== context.activity.recipient.id) {
await context.sendActivity(MessageFactory.text(welcomeText, welcomeText));
}
}
// By calling next() you ensure that the next BotHandler is run.
await next();
});
}
}
module.exports.EchoBot = EchoBot;
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"groupLocation": {
"value": ""
},
"groupName": {
"value": ""
},
"appId": {
"value": ""
},
"appSecret": {
"value": ""
},
"botId": {
"value": ""
},
"botSku": {
"value": ""
},
"newAppServicePlanName": {
"value": ""
},
"newAppServicePlanSku": {
"value": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": 1
}
},
"newAppServicePlanLocation": {
"value": ""
},
"newWebAppName": {
"value": ""
}
}
}
\ No newline at end of file
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"appId": {
"value": ""
},
"appSecret": {
"value": ""
},
"botId": {
"value": ""
},
"botSku": {
"value": ""
},
"newAppServicePlanName": {
"value": ""
},
"newAppServicePlanSku": {
"value": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": 1
}
},
"appServicePlanLocation": {
"value": ""
},
"existingAppServicePlan": {
"value": ""
},
"newWebAppName": {
"value": ""
}
}
}
\ No newline at end of file
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"groupLocation": {
"type": "string",
"metadata": {
"description": "Specifies the location of the Resource Group."
}
},
"groupName": {
"type": "string",
"metadata": {
"description": "Specifies the name of the Resource Group."
}
},
"appId": {
"type": "string",
"metadata": {
"description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
}
},
"appSecret": {
"type": "string",
"metadata": {
"description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings."
}
},
"botId": {
"type": "string",
"metadata": {
"description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
}
},
"botSku": {
"type": "string",
"metadata": {
"description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
}
},
"newAppServicePlanName": {
"type": "string",
"metadata": {
"description": "The name of the App Service Plan."
}
},
"newAppServicePlanSku": {
"type": "object",
"defaultValue": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": 1
},
"metadata": {
"description": "The SKU of the App Service Plan. Defaults to Standard values."
}
},
"newAppServicePlanLocation": {
"type": "string",
"metadata": {
"description": "The location of the App Service Plan. Defaults to \"westus\"."
}
},
"newWebAppName": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
}
}
},
"variables": {
"appServicePlanName": "[parameters('newAppServicePlanName')]",
"resourcesLocation": "[parameters('newAppServicePlanLocation')]",
"webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
"siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
"botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"
},
"resources": [
{
"name": "[parameters('groupName')]",
"type": "Microsoft.Resources/resourceGroups",
"apiVersion": "2018-05-01",
"location": "[parameters('groupLocation')]",
"properties": {
}
},
{
"type": "Microsoft.Resources/deployments",
"apiVersion": "2018-05-01",
"name": "storageDeployment",
"resourceGroup": "[parameters('groupName')]",
"dependsOn": [
"[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
],
"properties": {
"mode": "Incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"variables": {},
"resources": [
{
"comments": "Create a new App Service Plan",
"type": "Microsoft.Web/serverfarms",
"name": "[variables('appServicePlanName')]",
"apiVersion": "2018-02-01",
"location": "[variables('resourcesLocation')]",
"sku": "[parameters('newAppServicePlanSku')]",
"properties": {
"name": "[variables('appServicePlanName')]"
}
},
{
"comments": "Create a Web App using the new App Service Plan",
"type": "Microsoft.Web/sites",
"apiVersion": "2015-08-01",
"location": "[variables('resourcesLocation')]",
"kind": "app",
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms/', variables('appServicePlanName'))]"
],
"name": "[variables('webAppName')]",
"properties": {
"name": "[variables('webAppName')]",
"serverFarmId": "[variables('appServicePlanName')]",
"siteConfig": {
"appSettings": [
{
"name": "WEBSITE_NODE_DEFAULT_VERSION",
"value": "10.14.1"
},
{
"name": "MicrosoftAppId",
"value": "[parameters('appId')]"
},
{
"name": "MicrosoftAppPassword",
"value": "[parameters('appSecret')]"
}
],
"cors": {
"allowedOrigins": [
"https://botservice.hosting.portal.azure.net",
"https://hosting.onecloud.azure-test.net/"
]
}
}
}
},
{
"apiVersion": "2017-12-01",
"type": "Microsoft.BotService/botServices",
"name": "[parameters('botId')]",
"location": "global",
"kind": "bot",
"sku": {
"name": "[parameters('botSku')]"
},
"properties": {
"name": "[parameters('botId')]",
"displayName": "[parameters('botId')]",
"endpoint": "[variables('botEndpoint')]",
"msaAppId": "[parameters('appId')]",
"developerAppInsightsApplicationId": null,
"developerAppInsightKey": null,
"publishingCredentials": null,
"storageResourceId": null
},
"dependsOn": [
"[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"
]
}
],
"outputs": {}
}
}
}
]
}
\ No newline at end of file
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"appId": {
"type": "string",
"metadata": {
"description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
}
},
"appSecret": {
"type": "string",
"metadata": {
"description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Defaults to \"\"."
}
},
"botId": {
"type": "string",
"metadata": {
"description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
}
},
"botSku": {
"defaultValue": "F0",
"type": "string",
"metadata": {
"description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
}
},
"newAppServicePlanName": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "The name of the new App Service Plan."
}
},
"newAppServicePlanSku": {
"type": "object",
"defaultValue": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": 1
},
"metadata": {
"description": "The SKU of the App Service Plan. Defaults to Standard values."
}
},
"appServicePlanLocation": {
"type": "string",
"metadata": {
"description": "The location of the App Service Plan."
}
},
"existingAppServicePlan": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "Name of the existing App Service Plan used to create the Web App for the bot."
}
},
"newWebAppName": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
}
}
},
"variables": {
"defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlan')), 'createNewAppServicePlan', parameters('existingAppServicePlan'))]",
"useExistingAppServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",
"servicePlanName": "[if(variables('useExistingAppServicePlan'), parameters('existingAppServicePlan'), parameters('newAppServicePlanName'))]",
"resourcesLocation": "[parameters('appServicePlanLocation')]",
"webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
"siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
"botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"
},
"resources": [
{
"comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.",
"type": "Microsoft.Web/serverfarms",
"condition": "[not(variables('useExistingAppServicePlan'))]",
"name": "[variables('servicePlanName')]",
"apiVersion": "2018-02-01",
"location": "[variables('resourcesLocation')]",
"sku": "[parameters('newAppServicePlanSku')]",
"properties": {
"name": "[variables('servicePlanName')]"
}
},
{
"comments": "Create a Web App using an App Service Plan",
"type": "Microsoft.Web/sites",
"apiVersion": "2015-08-01",
"location": "[variables('resourcesLocation')]",
"kind": "app",
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms/', variables('servicePlanName'))]"
],
"name": "[variables('webAppName')]",
"properties": {
"name": "[variables('webAppName')]",
"serverFarmId": "[variables('servicePlanName')]",
"siteConfig": {
"appSettings": [
{
"name": "WEBSITE_NODE_DEFAULT_VERSION",
"value": "10.14.1"
},
{
"name": "MicrosoftAppId",
"value": "[parameters('appId')]"
},
{
"name": "MicrosoftAppPassword",
"value": "[parameters('appSecret')]"
}
],
"cors": {
"allowedOrigins": [
"https://botservice.hosting.portal.azure.net",
"https://hosting.onecloud.azure-test.net/"
]
}
}
}
},
{
"apiVersion": "2017-12-01",
"type": "Microsoft.BotService/botServices",
"name": "[parameters('botId')]",
"location": "global",
"kind": "bot",
"sku": {
"name": "[parameters('botSku')]"
},
"properties": {
"name": "[parameters('botId')]",
"displayName": "[parameters('botId')]",
"endpoint": "[variables('botEndpoint')]",
"msaAppId": "[parameters('appId')]",
"developerAppInsightsApplicationId": null,
"developerAppInsightKey": null,
"publishingCredentials": null,
"storageResourceId": null
},
"dependsOn": [
"[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"
]
}
]
}
\ No newline at end of file
//This is still work in progress
/*
Please report any bugs to nicomwaks@gmail.com
i have added console.log on line 48
*/
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
app.set('port', (process.env.PORT || 5000))
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
// parse application/json
app.use(bodyParser.json())
// index
app.get('/', function (req, res) {
res.send('hello world i am a secret bot')
})
// for facebook verification
app.get('/webhook/', function (req, res) {
if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
res.send(req.query['hub.challenge'])
} else {
res.send('Error, wrong token')
}
})
// to post data
app.post('/webhook/', function (req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
if (event.message && event.message.text) {
let text = event.message.text
if (text === 'Generic'){
console.log("welcome to chatbot")
//sendGenericMessage(sender)
continue
}
sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
}
if (event.postback) {
let text = JSON.stringify(event.postback)
sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token)
continue
}
}
res.sendStatus(200)
})
// recommended to inject access tokens as environmental variables, e.g.
// const token = process.env.FB_PAGE_ACCESS_TOKEN
const token = "EAAupaHJrQWABAEqni9O28fmMkpTvq5TO9T9OdPVlEBbj7ZCodF9B8rKeChVGduhGNjxr4zSPXWZA6LKdWZBkCxkuHoYZBmgrmQsrol7RiPoeh8NgvHy60VTcAu5TxdcQdBVSaZBaJIEA8cBbJKuP84CMa8UnroXdZAqALIK8gj1VKGNY3JNvWG"
function sendTextMessage(sender, text) {
let messageData = { text:text }
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendGenericMessage(sender) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "First card",
"subtitle": "Element #1 of an hscroll",
"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
"buttons": [{
"type": "web_url",
"url": "https://www.messenger.com",
"title": "web url"
}, {
"type": "postback",
"title": "Postback",
"payload": "Payload for first element in a generic bubble",
}],
}, {
"title": "Second card",
"subtitle": "Element #2 of an hscroll",
"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
"buttons": [{
"type": "postback",
"title": "Postback",
"payload": "Payload for second element in a generic bubble",
}],
}]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
// spin spin sugar
app.listen(app.get('port'), function() {
console.log('running on port', app.get('port'))
})
This diff could not be displayed because it is too large.
{
"name": "my-own-bot",
"version": "1.0.0",
"description": "like me",
"author": "Generated using Microsoft Bot Builder Yeoman generator v4.9.0",
"license": "MIT",
"main": "index.js",
"scripts": {
"start": "node ./index.js",
"watch": "nodemon ./index.js",
"lint": "eslint .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com"
},
"dependencies": {
"botbuilder": "~4.9.0",
"dotenv": "^8.2.0",
"restify": "~8.5.1"
},
"devDependencies": {
"eslint": "^7.0.0",
"eslint-config-standard": "^14.1.1",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"nodemon": "~2.0.4"
}
}
This diff is collapsed. Click to expand it.
{
"name": "secretbots",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.0",
"express": "^4.13.4",
"request": "^2.71.0"
}
}
"use strict";
const moment = require('moment');
const process = require('process');
const async = require('async');
const express = require('express');
const AWS = require('aws-sdk');
const s3 = new AWS.S3({
region: 'us-east-1',
accessKeyId: 'ASIA265JP6JAKK4AAZFL',
secretAccessKey: 'CuomIr3gEgtwPcOWSN94mC54iIMMWfXTVSFJXDUf',
sessionToken: 'FwoGZXIvYXdzEMX//////////wEaDLD1Yk1xhWixp9ZSByK/AbDcW6LYR1EpPLNIqCteTtZtXCoIIFr7b2olxXkKyQUVQGUnf4YJVcmk8PD1/1T9O/MaJIuO0c0tAO2ir31Oa5nsc1QomKEFpAy/girMM3JML5azImFhjMKDGYahUiZWTfiP8oksDWoeEM+HjwEvWzSa5nBBoTlKxa33Gjo/15LL/oHDgN75K/fiHWAJ6Uvey0I1Lu26CjohLbEE9tQ61ymtq4GiO96DSjgSTW4gyrp5R+tn0oLH1A51oLNBfFxsKOvfxu8FMi2RufVY3HSu2JsFVyXMXkMrgDhVA5lZngj2ZW7SQx8No0vfb9zPKuHXxGKjkQY='
});
var BUCKET = 'oss-project-image-storage';
var S3UPparam = {
Bucket:BUCKET,
Key:null,
ACL:'public-read',
Body:null
};
var S3DOWNparam = {
Bucket:BUCKET,
Prefix:null
};
const multer = require('multer');
// tensorflow의 data folder에 저장할 때 multer 설정
var storage_data = multer.diskStorage({
destination: function (req, file, cb) {
var dir = req.params.directoryName;
cb(null, dataFolder + dir + '/');
},
filename: function (req, file, cb) {
cb(null, new Date().valueOf() + "_" + file.originalname);
}
});
var upload_data = multer({
storage: storage_data
});
// tensorflow의 test folder에 저장할 때 multer 설정
var storage_test = multer.diskStorage({
destination: function (req, file, cb) {
var dir = req.params.directoryName;
cb(null, testFolder);
},
filename: function (req, file, cb) {
cb(null, "test.jpg");
}
});
var upload_test = multer({
storage: storage_test
});
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const pyShell = require('python-shell');
const PORT = 8080;
const HOST = '0.0.0.0';
const app = express();
const dataFolder = './tensorflow/data/';
const testFolder = './tensorflow/test/';
app.set('view engine', 'pug');
app.set('views', './views');
app.locals.pretty = true
app.use(bodyParser.urlencoded({extended:false}));
// tensorflow 학습을 완료한 시간
var LearnTime = undefined;
// Redirect Root to Home
app.get('/', (req, res) => {
res.redirect('./home/');
});
// Main Page
app.get('/home/', (req, res) => {
// data 폴더 목록을 읽어서 home 화면에 넘겨줌
fs.readdir(dataFolder, function(error, filelist){
if(error)
console.log(error);
res.render('home', {fileList:filelist, learntime:LearnTime});
});
});
// Directory existence checking
app.post('/directory_check', (req, res) => {
var dir = req.body.directoryName; // 입력받은 새로운 directory name
// Directory exists
if(fs.existsSync(dataFolder + dir))
{
// Go back page
res.render('error_directoryAdd');
}
// Directory doesn't exist
else
{
// Make directory
fs.mkdirSync(dataFolder + dir);
console.log('Directory Create: ' + dir);
res.redirect('/home/' + dir + '/');
}
});
// Basic Directory Page
app.get('/home/:directoryName/', (req, res) => {
// 임시로 이미지 파일명 목록을 보여주는 코드
var directoryName = req.params.directoryName; // 접속한 directory name
var filelist = new Array();
var imagelist = new Array();
// read directory's file list
fs.readdirSync(dataFolder + directoryName).forEach(function(file, index){
// 확장자 추출 및 이미지 파일인지 체크
var fileType = path.extname(file);
if(fileType == ".jpg" || fileType == ".jpeg") {
filelist.push(file);
}
});
S3DOWNparam.Prefix = directoryName + '/';
s3.listObjects(S3DOWNparam, function (err, data) {
if (err)
console.log(err);
else {
data.Contents.forEach(function(image) {
imagelist.push('https://' + BUCKET + '.s3.amazonaws.com/' + image.Key.replace(' ', '+'));
});
}
res.render('directory', {directoryName:directoryName, fileList:filelist, imageList:imagelist});
});
});
// Image Upload Directory Page
app.post('/home/:directoryName/upload/', upload_data.array('userImage'), (req, res) => {
var directoryName = req.params.directoryName;
req.files.forEach(function(file) {
S3UPparam.Key = directoryName + '/' + new Date().valueOf() + "_" + file.originalname;
S3UPparam.Body = fs.createReadStream(file.path);
s3.upload(S3UPparam, function (err, result) {
if (err)
console.log(err);
});
});
res.redirect('/home/' + directoryName + '/');
});
// Modify Directory name
app.get('/home/:directoryName/modify/', (req, res) => {
var directoryName = req.params.directoryName; // 본래 directory 이름
var newName = req.query.newName; // 입력받은 수정할 이름
// exist query.newName
if (req.query.newName) {
// modify Directory name
var Path = dataFolder + directoryName;
fs.rename(Path, dataFolder + newName, function (err) {
if (err) {
console.log("Directory Rename error: " + err);
} else {
console.log("Directory Rename: " + directoryName + " -> " + newName);
}
});
s3.listObjects({Bucket:BUCKET, Prefix: directoryName + '/'}, function(err, data) {
if (data.Contents.length) {
async.each(data.Contents, function(file, cb) {
s3.copyObject({
Bucket: BUCKET,
CopySource: BUCKET + '/' + file.Key,
Key: file.Key.replace(directoryName, newName)
})
.promise()
.then(() =>
s3.deleteObject({
Bucket: BUCKET,
Key: file.Key
}).promise()
).catch ((e) => console.error(e));
});
}
s3.deleteObject({
Bucket: BUCKET,
Key: directoryName
}, function(err, data) {
if (err) console.log(err);
});
});
res.redirect('/');
}
else {
res.render('directoryModifyCheck', {directoryName:JSON.stringify(directoryName)});
}
});
// Delete Directory
app.get('/home/:directoryName/delete/', (req, res) => {
var directoryName = req.params.directoryName;
// exist query.real
if (req.query.real) {
// Remove Directory and Files
var path = dataFolder + directoryName;
fs.readdirSync(path).forEach(function(file,index){
var curPath = path + "/" + file;
fs.unlinkSync(curPath);
});
fs.rmdirSync(path);
// Remove S3 Directory and Files
s3.listObjects({Bucket:BUCKET, Prefix: directoryName + '/'}, function(err, data) {
if (data.Contents.length) {
async.each(data.Contents, function(file, cb) {
s3.deleteObject({
Bucket: BUCKET,
Key: file.Key
}, function(err, data) {
if (err) console.log(err);
});
});
}
});
console.log('Directory Delete: ' + directoryName);
res.redirect('/');
}
else {
res.render('directoryDeleteCheck', {directoryName:JSON.stringify(directoryName)});
}
});
// Image Test Page
app.post('/test', upload_test.single('TestImage'), (req, res) => {
var results = new Array();
console.log("Test Start");
process.chdir('./tensorflow/'); // move working directory
// retrain_run_inference.py로 test
pyShell.PythonShell.run('retrain_run_inference.py', null, function (err, result) {
if (err) {
console.log('Test error: '+ err);
}
else {
var strArr = result.toString().split('\n'); // result를 줄바꿈 기준으로 자름
// 결과만 results에 저장
strArr.forEach(function(str) {
if (str.indexOf('score') > -1) {
str = str.split('\\n').join('');
results = str.split(',');
for(var i = 0; i < results.length; i++){
results[i] = results[i].substring(1);
}
}
});
}
process.chdir('../'); // move working directory
console.log(results);
console.log("Test Complete");
res.render('testResult', {result:results});
});
});
// Image Learning
app.get('/imageLearning', (req, res) => {
var results = new Array();
var tmp = LearnTime;
res.redirect('/home/');
console.log("Learning Start");
process.chdir('./tensorflow/'); // move working directory
// retrain.py로 학습
LearnTime = "학습 중...";
pyShell.PythonShell.run('retrain.py', null, function (err, result) {
if (err) {
console.log('Learning error: '+ err);
LearnTime = tmp + ', error: 다시 학습 버튼을 눌러주세요';
}
else {
LearnTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 학습 완료한 시간 저장
console.log("Learning Complete");
}
});
process.chdir('../'); // move working directory
});
app.listen(PORT, HOST);
console.log('Running on http://${HOST}:${POST}');
\ No newline at end of file
This diff is collapsed. Click to expand it.
# -*- coding: utf-8 -*-
"""Inception v3 architecture 모델을 retraining한 모델을 이용해서 이미지에 대한 추론(inference)을 진행하는 예제"""
import sys
import numpy as np
import tensorflow as tf
imagePath = ''
modelFullPath = ''
labelsFullPath = ''
if (len(sys.argv) > 1):
imagePath = sys.argv[1] + '/test/test.jpg'
modelFullPath = sys.argv[1] + '/test/output_graph.pb'
labelsFullPath = sys.argv[1] + '/test/output_labels.txt'
else:
imagePath = './test/test.jpg' # 추론을 진행할 이미지 경로
modelFullPath = './test/output_graph.pb' # 읽어들일 graph 파일 경로
labelsFullPath = './test/output_labels.txt' # 읽어들일 labels 파일 경로
def create_graph():
"""저장된(saved) GraphDef 파일로부터 graph를 생성하고 saver를 반환한다."""
# 저장된(saved) graph_def.pb로부터 graph를 생성한다.
with tf.gfile.FastGFile(modelFullPath, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
def run_inference_on_image():
answer = None
if not tf.gfile.Exists(imagePath):
tf.logging.fatal('File does not exist %s', imagePath)
answer = 'File does not exist ' + imagePath
return answer
image_data = tf.gfile.FastGFile(imagePath, 'rb').read()
# 저장된(saved) GraphDef 파일로부터 graph를 생성한다.
create_graph()
with tf.Session() as sess:
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(softmax_tensor,
{'DecodeJpeg/contents:0': image_data})
predictions = np.squeeze(predictions)
top_k = predictions.argsort()[-5:][::-1] # 가장 높은 확률을 가진 5개(top 5)의 예측값(predictions)을 얻는다.
f = open(labelsFullPath, 'rb')
lines = f.readlines()
labels = [str(w).replace("\n", "") for w in lines]
for node_id in top_k:
human_string = labels[node_id]
score = predictions[node_id]
print('%s (score = %.5f)' % (human_string, score))
answer = labels[top_k[0]]
return answer
if __name__ == '__main__':
run_inference_on_image()
\ No newline at end of file
doctype html
html
head
meta(charset='utf-8')
title 파일 업로드
style
img
| display="block"
| max-width="200px"
| max-height="200px"
| width="auto"
| height="auto"
body
- var DirectoryName=directoryName;
h1=DirectoryName
br
h2 파일 업로드
form(action="./upload/" method="POST" enctype="multipart/form-data")
input(type="file", name="userImage", multiple="multiple", accept=".jpg, .jpeg")
input(type="submit", value="업로드")
br
br
ul
- var ImageList=imageList
- var filelist=fileList
- var iter=0
each Image in ImageList
div(style="margin-right:10px;")
img(src=Image)
li=filelist[iter]
- iter=iter+1
br
br
\ No newline at end of file
script.
var directoryName= !{directoryName};
confirm('모든 이미지가 삭제됩니다.\n정말 ' + directoryName + ' 분류를 삭제하시겠습니까?')
? location.href ='.?real=true' : history.back();
\ No newline at end of file
script.
var directoryName= !{directoryName};
var result = prompt('새 분류명을 입력하세요. (기존: ' + directoryName + ')');
if (result) {
location.href = '.?newName=' + result;
} else {
alert('분류명을 수정하지 않습니다.');
history.back();
}
\ No newline at end of file
script.
var msg = '이미 존재하는 분류입니다.'
alert(msg);
history.back();
\ No newline at end of file
doctype html
html
head
meta(charset='utf-8')
title 분류 리스트
body
form(action="../directory_check" method="post")
p 새로 만들 분류명:
input(name="directoryName", type="text")
input(type="submit", value="생성")
br
br
form(action="../test" method="post" enctype="multipart/form-data")
p 테스트할 이미지:
input(name="TestImage", type="file", accept=".jpg, .jpeg")
input(type="submit", value="테스트")
br
br
br
div(style="margin-right:10px; float:left;")
form(action="../imageLearning" method="get")
input(type="submit", value="이미지 학습시키기" style="font-size:24px; font-weight:bold")
- var learnTime=learntime
div(style="margin-right:30px;")
p="(최근 학습 시간: " + learnTime + ")"
br
ul
- var folderList=fileList
each folder in folderList
div(style="margin-right:30px; float:left;")
li
a(href="./"+folder+"/")=folder
div(style="margin-right:5px; float:left;")
form(action="./"+folder+"/modify/" method="get")
input(type="submit", value="수정")
div
form(action="./"+folder+"/delete/" method="get")
input(type="submit", value="삭제")
br
\ No newline at end of file
h1 결과
ol
- var Result=result
for item in Result
div(style="font-size:20px;")
li=item
div(style="font-size:10px;")
br
\ No newline at end of file
This diff is collapsed. Click to expand it.