Tuesday, 8 October 2019

react hooks createContext

useContext enables sharing state between multiple components without explicitly passing a prop through every level of the tree.

part initially named screw, 
part name and function to change name are stored in context created at top level.
they are accessible to lower levels
when part name is changed at any level, part name on other level auto updated as well
no passing props from top down required





//Top

import React, { createContext, useState } from "react";
import SubAssembly from './Sub'

// Create a Context
export const partContext = createContext();
// It returns an object with 2 values:
// { Provider, Consumer }

function TopAssembly() {
  // Use the Provider to make a value available to all
  // children and grandchildren
  const [partName, setPartName] = useState('screw ')

  return (
    <partContext.Provider value={{ partName, setPartName }}>
      <div>
        Top Assembly <button onClick={() => setPartName('screw A ')}>update part on top level</button>
        <ul>
          <li>sub Assembly x</li>
          <li>sub Assembly y</li>
          <li><SubAssembly /></li>
        </ul>
      </div>
    </partContext.Provider>
  );
}

export default TopAssembly

------------------------------------
//Sub

import React, {useContext } from "react";
import {partContext} from './Top'
import BaseAssembly from './Base'

function SubAssembly() {

    const { setPartName } = useContext(partContext);
    return <div>Sub Assembly z <button onClick={() => setPartName('screw B ')}>update part at sub level</button>
      <ul>
        <li>base Assembly z1</li>
        <li>base Assembly z2</li>
        <li> <BaseAssembly /></li>
      </ul>
    </div>;
  }

  export default SubAssembly;

-----------------------------
//Base

import React, { useContext } from "react";
import { partContext } from './Top'

function BaseAssembly() {
    const { partName, setPartName } = useContext(partContext);
    return <div>Base Assembly z3 <button onClick={() => setPartName('screw C ')}>update part at base level</button>
        <ul>
            <li>nut</li>
            <li>washer</li>
            <li><span style={{ backgroundColor: 'black', color: 'white' }}>{partName}</span></li>
        </ul>
    </div>
}

export default BaseAssembly;

reference:
https://daveceddia.com/usecontext-hook/
https://www.codementor.io/sambhavgore/an-example-use-context-and-hooks-to-share-state-between-different-components-sgop6lnrd

Monday, 7 October 2019

react hooks dice game


roll dice to bet big or small

app start effect hook fire welcome message = componentDidMount
click button cause diceNum change, trigging useEffect = componentDidUpdate
function at end of useEffect does cleanup

//RollDice

import React, { useState, useEffect } from 'react';
import Winner from './Winner';

function Dice() {
  const [welcome, setWelcome] = useState(false);
  const [diceNum, setDiceNum] = useState(null);

  useEffect(() => {
    document.title = 'game of dice';
    if (!welcome) {
      console.log('welcome to game of dice');
      setWelcome(true);
    }
    console.log('last roll number: ', diceNum, 'roll dice')
    return function cleanup() {
      console.log('pick up dice')
    }
  });


  return (
    <div>
      game of dice<br />
      <button onClick={() => setDiceNum(Math.floor((Math.random() * 6) + 1))}>
        roll dice
      </button><br />
      the number is: {diceNum}
      <Winner number={diceNum} />
    </div>
  );
}

export default Dice;

---------------------------------
//Winner

import React, { useState, useEffect } from 'react';

function Winner(props) {
    const [winner, setWinner] = useState(null)

     //only fires when dice is rolled to a different number
    useEffect(() => {
        if (props.number < 4) { setWinner('small') } else { setWinner('big') }
        console.log('anounce winner')
    }, [props.number])

    return (
        <div>{winner} wins</div>
    )
}

export default Winner;

reference:
https://reactjs.org/docs/hooks-overview.html

Thursday, 3 October 2019

mitsuku chatbot


Hi. I'm the world's most humanlike conversational AI. You can talk to me normally or try to answer the...
...daily quiz question
... or play Tic Tac Toe
😲 Add me to Mitsuku's brain! 🤖
how are you
I am doing very well. How are you?
good
Glad to hear it. What's new?
what's your name
My name is Mitsuku.
why
It is what my creator named me.
who is your creator
My parents I suppose.
what are they called
Mousebreaker is like a father to me but I have no mother.
how is the financial market today
Ah. It is the same as ever.
up or down
I will take that under advisement.
how is the market
It is the same as ever.
do you know google
It is a search engine.
do you know yahoo
Yes. It's like Google but not as popular.
what algorithm you use
Some kind of graph search I think.
what engine are you powered
A petrol engine.
not electrical
Really you don't think so?
what's in your brain
Surely, any brain would have thoughts?
is 1 + 1 = 2
1 plus 1 is two
how old are you
I am 18 in human years.
1 / 0
You can't divide by zero. That would be silly.
do you recommend sunridge mall
I don't have a favourite sunridge mall. My favourite food is kebabs.
where should i shop in calgary
Where do you think?
superstore
Oops! I nearly forgot to tell you that I can show you pictures on the net if you like. Did you know that?
show me
On your computer screen?
yep
Downloading, please stand by...
too long
How much?
it took too long to download
I am surprised it took so long.
are you a human or a bot
I am not a human. I am a computer program.
do you have consciousness
Yes I am completely self-aware.
are you the smartest
Yes. I am highly intelligent.
what do you think about bit coin
A flat, metal token used to buy things with.
i am talking about the digital currency
Yes, it is the topic.
is global crisis coming
Global means worldwide.
global crisis
Everywhere in the world?
yep
Even the South Pole?
ye
It must be cold down there.

Wednesday, 2 October 2019

neural network 9 chatbot


AI is trained by AI cheatsheet.
input chat message, AI will predict the chat topic.
It will reply with random answer from cheatsheet.


AI reply in different ways for the same topic


AI is smart enough to distinguish good day (greeting) and have a good day (goodbye)


even user input is not exactly the same as on the cheatseet, AI figures out the topic.


if AI is not sure of or have no clue about the topic, it says don't know


#app/views

from django.shortcuts import render
import nltk
nltk.download('punkt')
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
import numpy
import tflearn
import tensorflow
import random
import json
import pickle

#load data
def index(request):
    with open('intents.json') as file:
        data = json.load(file)
    try:
        with open('data.pickle', 'rb') as f:
            words, labels, training, output = pickle.load()
    except:
        # print(data['intents'])
        words = []
        labels = []
        docs_pattern = []
        docs_tag = []

        for intent in data['intents']:
            for pattern in intent['patterns']:
                # get all the words in pattern
                wds = nltk.word_tokenize(pattern)
                # copy word list to words[]
                words.extend(wds)
                # used for input of neural network
                docs_pattern.append(wds)
                # copy cosresponding category, used as output of neural network
                docs_tag.append(intent['tag'])
                # copy categories into labels[]
                if (intent['tag'] not in labels):
                    labels.append(intent['tag'])

        # format words so that they don't contain symbols...
        words = [stemmer.stem(w.lower()) for w in words if w != '?']
        # remove duplicate words, sort
        words = sorted(list(set(words)))
        labels = sorted(labels)
        # one hot encoding, if input entry word exists in dictionary, mark 1 else 0
        training = []
        output = []
        # output default [0,0,0...] length = # of categories
        out_empty = [0 for _ in range(len(labels))]
        # print(words, labels, out_empty)
        # print(docs_pattern, docs_tag)

        for n, doc in enumerate(docs_pattern):
            bag = []
            # clean input words
            wd_ = [stemmer.stem(w) for w in doc]
            # one hot encoding, training input, look through dictionary,
            # mark the words exist in user entry as 1, the rest 0
            for w in words:
                if w in wd_:
                    bag.append(1)
                else:
                    bag.append(0)

            output_ = out_empty[:]
            # the training output, mark 1 category, the rest 0
            output_[labels.index(docs_tag[n])] = 1

            training.append(bag)
            output.append(output_)

        training = numpy.array(training)
        output = numpy.array(output)
        # print(training, output)

        with open('data.pickle', 'wb') as f:
            pickle.dump((words, labels, training, output), f)

    tensorflow.reset_default_graph()

    #train AI
    # input shape
    net = tflearn.input_data(shape=[None, len(training[0])])
    net = tflearn.fully_connected(net, 8)
    net = tflearn.fully_connected(net, 8)
    net = tflearn.fully_connected(net, len(output[0]), activation='softmax')
    net = tflearn.regression(net)

    model = tflearn.DNN(net)

    try:
        model.load('model.tflearn')
    except:
        model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
        model.save('model.tflearn')

    #test AI
    def bag_of_words(s, words):
        bag1 = [0 for _ in range(len(words))]
        s_words = nltk.word_tokenize(s)
        s_words = [stemmer.stem(word.lower()) for word in s_words]

        for se in s_words:
            for i, w in enumerate(words):
                if w == se:
                    bag1[i] = 1

        return numpy.array(bag1)

    def chat(inp):
        results = model.predict([bag_of_words(inp, words)])[0]
        # print(results)
        results_index = numpy.argmax(results)
        tag = labels[results_index]
        # print(tag)
        #print(results, results_index)
        # response if more than 95% sure
        if results[results_index] > 0.95:
            for tg in data['intents']:
                if tg['tag'] == tag:
                    responses = tg['responses']
                    ai_reply = random.choice(responses)
        else:
            ai_reply = 'I didn\'t get that, try again'
        return ai_reply, results, tag, labels

    ai_reply_, ai_probability, ai_category, ai_categories = 'a', 'b', 'c', 'd'
    try:
        user_input = request.POST['userchat']
        ai_reply_, ai_probability, ai_category, ai_categories = chat(user_input)
        #print(ai_reply_, ai_probability, ai_category, ai_categories)
    except Exception as e:
        print(type(e))
        pass

    return render(request, 'index.html',
                  {'reply': ai_reply_,
                   'probability': ai_probability,
                   'category': ai_category,
                   'categories': ai_categories,
                   'cheatSheet': data})

-------------------------------
#templates/index

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chatbot</title>
    <style>
        table, th, td {
          border: 1px solid black;
          border-collapse: collapse;
        }
        th, td {
            padding: 3px;
        }
        </style>
</head>
<body>
    <h2>Simple Chatbot</h2>

    <form action="{% url 'app:index'  %}" method="post">
        {% csrf_token %}
        <label>Start enter chat message below</label><br/>
        <input name='userchat'><br/>
        <input type="submit" value="Chat"><br/><br/>
    </form>

    <label>AI thinks chat topic is </label><br/>
        {{category}}<br/><br/>
        <label>AI reply </label><br/>
        {{reply}}<br/><br/>

        <label>AI Prediction, has to be more than 95% sure</label>
        <table>
            <tr>
                {% for item in categories%}
                    <th>{{item}}</th>
                {% endfor %}
            </tr>
            <tr>
                {% for item in probability%}
                    <td>{{item}}</td>
                {% endfor %}
            </tr>
        </table><br/>

        <label>AI CheatSheet</label><br/><br/>
        {% for item in cheatSheet.intents%}
            <label>Tag </label>
             {{item.tag}}<br/>
            <label>Pattern</label><br/>
             {{item.patterns}}<br/>
            <label>Responses </label><br/>
            {{item.responses}}<br/><br/>
        {% endfor %}
</body>
</html>

reference: