- vimport React, { useState, useRef, useEffect } from "react";
- import * as tf from "@tensorflow/tfjs";
- import { detectVideo } from "../utils/detection/detect";
- import { Webcam } from "../utils/detection/webcam";
- export default function ModelLoader() {
- const [isModelLoading, setIsModelLoading] = useState({
- loading: true,
- progress: 0,
- });
- const [model, setModel] = useState({
- net: null,
- inputShape: [1, 0, 0, 3],
- });
- const [streaming, setStreaming] = useState();
- const webcam = new Webcam();
- const cameraRef = useRef(null);
- const canvasRef = useRef(null);
- // model config
- const modelName = "fire_detector";
- const classThreshold = 0.25;
- useEffect(() => {
- tf.ready().then(async () => {
- const model_url = `${[removed].origin}/${modelName}_yolov5n_web_model/model.json`;
- const yolov5 = await tf.loadGraphModel(model_url, {
- onProgress: (fraction) => {
- setIsModelLoading({
- loading: true,
- progress: fraction,
- });
- },
- });
- const dummyInput = tf.ones(yolov5.inputs[0].shape);
- const warmupResult = await yolov5.executeAsync(dummyInput);
- tf.dispose(warmupResult);
- tf.dispose(dummyInput);
- setIsModelLoading({ loading: false, progress: 1 });
- setModel({
- net: yolov5,
- inputShape: yolov5.inputs[0].shape,
- }); // set model & input shape
- console.log("Model Loaded");
- });
- }, []);
- async function handleStartWebcam() {
- if (streaming) {
- webcam.close(cameraRef.current);
- cameraRef.current.style.display = "none";
- setStreaming(null);
- return;
- }
- webcam.open(cameraRef.current);
- cameraRef.current.style.display = "block";
- setStreaming("camera");
- }
- return (
- <div className="ModelLoader">
- {isModelLoading.loading ? (
- <div>
- <h1>Loading Model</h1>
- <p>{Math.round(isModelLoading.progress * 100)}%</p>
- </div>
- ) : (
- <div className="content">
- <h1>Webcam</h1>
- <video
- autoPlay
- muted
- ref={cameraRef}
- =>
- detectVideo(
- cameraRef.current,
- model,
- classThreshold,
- canvasRef.current,
- () => alert("Fire Detected")
- )
- }
- />
- <canvas
- width={model.inputShape[1]}
- height={model.inputShape[2]}
- ref={canvasRef}
- />
- </div>
- )}
- <button >Start Detection</button>
- </div>
- );
- }