Commit 2fbef0f4 authored by Jayamini Samaratunga's avatar Jayamini Samaratunga

smart assistant api endpoint added

parent e86bdbd9
This diff is collapsed.
This diff is collapsed.
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.8 (gym_rl)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="32">
<item index="0" class="java.lang.String" itemvalue="opencv-python" />
<item index="1" class="java.lang.String" itemvalue="cmake" />
<item index="2" class="java.lang.String" itemvalue="numpy" />
<item index="3" class="java.lang.String" itemvalue="dlib" />
<item index="4" class="java.lang.String" itemvalue="thop" />
<item index="5" class="java.lang.String" itemvalue="scikit-image" />
<item index="6" class="java.lang.String" itemvalue="opencv-contrib-python" />
<item index="7" class="java.lang.String" itemvalue="wincertstore" />
<item index="8" class="java.lang.String" itemvalue="networkx" />
<item index="9" class="java.lang.String" itemvalue="tifffile" />
<item index="10" class="java.lang.String" itemvalue="Flask-Cors" />
<item index="11" class="java.lang.String" itemvalue="PyYAML" />
<item index="12" class="java.lang.String" itemvalue="torch" />
<item index="13" class="java.lang.String" itemvalue="torchvision" />
<item index="14" class="java.lang.String" itemvalue="mysql-connector-python" />
<item index="15" class="java.lang.String" itemvalue="pandas" />
<item index="16" class="java.lang.String" itemvalue="tqdm" />
<item index="17" class="java.lang.String" itemvalue="regex" />
<item index="18" class="java.lang.String" itemvalue="mediapipe" />
<item index="19" class="java.lang.String" itemvalue="seaborn" />
<item index="20" class="java.lang.String" itemvalue="better-profanity" />
<item index="21" class="java.lang.String" itemvalue="colorama" />
<item index="22" class="java.lang.String" itemvalue="PyWavelets" />
<item index="23" class="java.lang.String" itemvalue="imutils" />
<item index="24" class="java.lang.String" itemvalue="pytz" />
<item index="25" class="java.lang.String" itemvalue="torchaudio" />
<item index="26" class="java.lang.String" itemvalue="Flask" />
<item index="27" class="java.lang.String" itemvalue="Pillow" />
<item index="28" class="java.lang.String" itemvalue="flashtext" />
<item index="29" class="java.lang.String" itemvalue="unidecode" />
<item index="30" class="java.lang.String" itemvalue="sklearn" />
<item index="31" class="java.lang.String" itemvalue="nltk" />
</list>
</value>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8 (gym_rl)" project-jdk-type="Python SDK" />
<component name="PyCharmProfessionalAdvertiser">
<option name="shown" value="true" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/RL.iml" filepath="$PROJECT_DIR$/.idea/RL.iml" />
</modules>
</component>
</project>
\ No newline at end of file
from gym import Env
from gym.spaces import Discrete, Box
import numpy as np
import random
class EmotionEnv(Env):
def __init__(self):
# Actions we can take, down, stay, up
self.action_space = Discrete(3)
# Friends array
self.observation_space = Box(low=np.array([0]), high=np.array([10]))
# Set start emotion
self.state = 3 + random.randint(-3, 3)
# Set emotion length
self.emotion_length = 60
def step(self, action):
# should take actions by human
# print('This is suggested friend id', action)
# self.state += int(input("Enter your emotional level : "))
self.state = action
# Reduce emotion length by 1 second
self.emotion_length -= 1
reward = 0
# Calculate reward
if self.state == 0:
reward = -2
elif self.state == 1:
reward = -1
elif self.state == 2:
reward = 1
elif self.state == 3:
reward = 2
elif self.state == 4:
reward = 3
elif self.state == 5:
reward = 4
# Check if emotion is done
if self.emotion_length <= 0:
done = True
else:
done = False
# self.state += random.randint(-1,1)
# Set placeholder for info
info = {}
# Return step information
return self.state, reward, done, info
def render(self):
# Implement viz
pass
def reset(self):
# Reset emotion state
self.state = 38 + random.randint(-3, 3)
# Reset emotion time
self.shower_length = 60
return self.state
from flask import Flask, request, url_for, redirect, render_template
from flask_cors import CORS
import json
import os
import EmotionEnv
from pycaret.classification import *
import numpy as np
env = EmotionEnv.EmotionEnv()
env.observation_space.sample()
state = env.reset()
done = False
score = 0
model = load_model('Logistic_Regression')
app = Flask(__name__)
CORS(app)
@app.route('/', methods=['GET', 'POST'])
def welcome():
return_str = '{ "status" : "app works" }'
return json.loads(return_str)
@app.route('/friend_suggestion', methods=['GET', 'POST'])
def friend_suggestion():
input_1 = request.form['input_1']
input_2 = request.form['input_2']
input_3 = request.form['input_3']
global score
data = np.array([['input_1', 'input_2', 'input_3'], [input_1, input_2, input_3]])
result = predict_model(model, data=pd.DataFrame(data=data[0:, 0:], index=data[0:, 0], columns=data[0, 0:])).iat[1, 3]
print(result)
action = env.action_space.sample()
n_state, reward, done, info = env.step(action)
score += int(result)
return_str = '{ "suggested_friend_id" : ' + str(action) + '}'
print(return_str)
return json.loads(return_str)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5500, debug=True)
model_checkpoint_path: "dqn_weights.h5f"
all_model_checkpoint_paths: "dqn_weights.h5f"
This diff is collapsed.
This diff is collapsed.
pip install tensorflow==2.3.0 gym keras keras-rl2 pycaret flask Flask-Cors
pip install pycaret
pip install numpy==1.18.0
import EmotionEnv
env = EmotionEnv.EmotionEnv()
env.observation_space.sample()
episodes = 10
for episode in range(1, episodes + 1):
state = env.reset()
done = False
score = 0
while not done:
# env.render()
action = env.action_space.sample()
n_state, reward, done, info = env.step(action)
score += reward
print('Episode:{} Score:{}'.format(episode, score))
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam
import EmotionEnv
from rl.agents import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory
env = EmotionEnv.EmotionEnv()
states = env.observation_space.shape
actions = env.action_space.n
def build_model(states, actions):
model = Sequential()
model.add(Dense(24, activation='relu', input_shape=states))
model.add(Dense(24, activation='relu'))
model.add(Dense(actions, activation='linear'))
return model
model = build_model(states, actions)
print(model.summary())
def build_agent(model, actions):
policy = BoltzmannQPolicy()
memory = SequentialMemory(limit=50000, window_length=1)
dqn = DQNAgent(model=model, memory=memory, policy=policy,
nb_actions=actions, nb_steps_warmup=10, target_model_update=1e-2)
return dqn
dqn = build_agent(model, actions)
dqn.compile(Adam(lr=1e-3), metrics=['mae'])
dqn.fit(env, nb_steps=50000, visualize=False, verbose=1)
scores = dqn.test(env, nb_episodes=100, visualize=False)
print(np.mean(scores.history['episode_reward']))
dqn.save_weights('dqn_weights.h5f', overwrite=True)
import EmotionEnv
env = EmotionEnv.EmotionEnv()
env.observation_space.sample()
episodes = 10
for episode in range(1, episodes + 1):
state = env.reset()
done = False
score = 0
while not done:
# env.render()
action = env.action_space.sample()
n_state, reward, done, info = env.step(action)
score += reward
print('Episode:{} Score:{}'.format(episode, score))
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment