Coder Social home page Coder Social logo

Comments (5)

jamesrweb avatar jamesrweb commented on April 20, 2024 1

I refactored your sketch.js file:

import * as ml5 from "ml5";

export default function sketch(p5) {
  let video = null;
  let setLabel = null;
  let label = "test";

  function modelReady() {
    // Unchanged
  }

  function gotResults(error, results) {
    if (error) {
      console.error(error);
    } else {
      label = results[0].label;
      setLabel(label); // added here
      mobilenet.predict(gotResults);
    }
  }

  p5.setup = () => {
    // Unchanged
  };

  p5.myCustomRedrawAccordingToNewPropsHandler = function (props) {
    setLabel = props.setLabel; // set the handler hook to the variable value by reference
  };

  p5.draw = () => {
    // Unchanged
  };
}
  1. Since in your sandbox mobilenet is already global, we don't need a variable for it.
  2. Since the sketch isn't a react component we don't need to import react.
  3. Since JS can use pass by reference for functions, we can just assign the prop to a variable and use it in our sketch anywhere we like.

Does this solve your issue?

from react.

jamesrweb avatar jamesrweb commented on April 20, 2024 1

The way I did it is generally better since the way you're doing it will re-create the gotResults function each time the component is re-rendered which is very inneficient. Each function should be seperately declared in each case.

I did some more thoughtful refactoring in your sketch.js file of how I might approach things:

import * as ml5 from "ml5";

let label = "";
let mobilenet = null;
let setLabel = null;
let video = null;

const predict = callback => mobilenet.predict(callback);

function gotResults(error, results) {
  if (error) {
    console.error(error);
    return;
  }

  label = results[0].label;
  setLabel(label);
  predict(gotResults);
}

export default p5 => {
  p5.setup = () => {
    p5.createCanvas(400, 400);
    video = p5.createCapture(p5.VIDEO);
    video.hide();
    p5.background(0);
    mobilenet = ml5.imageClassifier("MobileNet", video, predict.bind(null, gotResults));
  };

  p5.myCustomRedrawAccordingToNewPropsHandler = props => {
    setLabel = props.setLabel;
  }

  p5.draw = () => {
    p5.background(0);
    p5.image(video, 0, 0);
    p5.fill(255);
    p5.textSize(32);
    p5.text(label, 10, p5.height - 20);
  };
}

Of course this code isn't perfect but it is clean and ready for you to expand upon. As an example you could add some type checks for peace of mind that things won't go wrong when the code is run. As a demonstration of that, we could change the predict function to look like so:

const predict = callback => {
  if(callback instanceof Function === false) {
    throw new Error("Argument 1 must be of type Function.");
  }

  mobilenet.predict(callback);
}

This is great because now we ensure our code is testable! Using Jest for example, we can test the predict function like so:

import { predict } from './sketch.js';

describe("predict", () => {
  it("Throws with an invalid callback", () => {
    expect(() => predict(null)).toThrow();
    expect(() => predict("")).toThrow();
    expect(() => predict(1)).toThrow();
  });

  it("predicts as expected", () => {
    const callback = (error, results) => results[0].label;
    const prediction = predict(callback);
    expect(prediction).toBe("something"); 
  })
});

Naturally more needs configured for the tests to run but this is just an idea to show you the things you could do if you chose to. Hope all of this helped somehow and if any further issues come up, just let us know!

from react.

vennsoh avatar vennsoh commented on April 20, 2024

The thing that I'm building https://codesandbox.io/s/dark-wave-dgrlg (it's a machine learning cam that will detect what the camera is seeing) You can see that the label within React is not updating but it's only updating the label in the p5 sketch.

My fix: I have done something like setInterval(setLabel, 0) in my code but that doesn't seem to be the correct pattern? Is there a better way?

from react.

vennsoh avatar vennsoh commented on April 20, 2024

Thanks @jamesrweb yes! I've figured that out (:
Solved my issue.

from react.

vennsoh avatar vennsoh commented on April 20, 2024
export default function sketch(p5) {
    function modelReady() {
        console.log("Model is ready!!!")
        mobilenet.predict(gotResults)
    }

    let gotResults = (error, results) => {}

    p5.setup = () => {
        p5.createCanvas(400, 400)
        video = p5.createCapture(p5.VIDEO)
        video.hide()
        p5.background(0)
        mobilenet = ml5.imageClassifier("MobileNet", video, modelReady)
    }

    p5.myCustomRedrawAccordingToNewPropsHandler = function (props) {
        gotResults = (error, results) => {
            if (error) {
                console.error(error)
            } else {
                label = results[0].label
                props.setLabel(label)
                mobilenet.predict(gotResults)
            }
        }
    }

    p5.draw = () => {
        p5.background(0)
        p5.image(video, 0, 0)
        p5.fill(255)
        p5.textSize(32)
        p5.text(label, 10, p5.height - 20)
    }
}

However, my solution involve putting function gotResults inside of .myCustomRedrawAccordingToNewPropsHandler Is there a preference on how to do this?

from react.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.