All files / src/app/imageupload imageupload.component.ts

53.11% Statements 145/273
31.3% Branches 36/115
42.5% Functions 17/40
61.04% Lines 141/231

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437                                        1x 1x 1x 2x 1x   1x 1x   1x               1x                                                     1x       1x 1x 1x 1x   1x           12x 12x       12x       12x       12x       12x 12x 12x 12x       12x       12x       12x       12x       12x         12x       12x       12x       12x       12x             1x 12x 12x 12x 74x                       1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x                                               1x 8x 4x     4x 1x     3x                 1x 3x 1x   2x 1x   1x 1x               1x 4x 4x 4x 4x 4x 8x   4x 4x   4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x       4x       4x   4x 4x 4x   4x 4x 3x 3x 3x 3x 3x 3x 3x                 1x 4x 4x 4x               3x                   3x                             3x             1x 3x 3x 3x 3x 3x 3x                       1x 1x   1x 1x 1x   1x 1x                             1x 1x             1x 1x 1x 1x 1x 1x 1x 3x                     1x                         1x                   1x               1x   1x
/**
 * File Name:       imageupload.component
 * Version Number:  v1.3
 * Author:          Tobias Bester
 * Project Name:    Ninshiki
 * Organization:    Software Sharks
 * User Manual:     Refer to https://github.com/OrishaOrrie/SoftwareSharks/blob/master/Documentation/User%20Manual.pdf
 * Update History:
 * ------------------------------------------
 * Date         Author        Description
 * 01/03/2018   Tobias        Created component
 * 03/07/2018   Tobias        Added Custom Image Upload Functionality
 * 12/09/2018   Tobias        Added model selection functionality
 * ------------------------------------------
 * Test Cases:      imageupload.component.spec.ts
 * Functional Description:
 *  Provides interface for user to select or capture an image and have the model predict the class of the
 *  object in the image.
 */
 
/**
 * @ignore
*/I
import { Component, OnInit } from '@angular/core';E
import { ModelLoaderService } from '../model/model-loader.service';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { QuoteDialogComponent } from '../quotebuilder/quote-dialog.component';
// iEmport { AngularFireStorage } from '../../../node_modules/angularfire2/storage';
 
@Component({
  selector: 'app-imageupload',
  templateUrl: './imageupload.component.html',
  styleUrls: ['./imageupload.component.css']
})
export class ImageuploadComponent implements OnInit {
 
  /**
   * Text displayed on the interface indicating what needs to be done
   */
  public instruction: String = 'Click either the File Select or Webcam Capture button';

  /**
   * Determines whether the spinner next to the Submit button should be displayed or not
   */
  public showSpinner = false;

  /**
   * Determines whether the video element should display the current webcam footage
   */
  public streaming = false;

  /**
   * The video, canvas, image, and captureButton variables are used when dynamically creating elements for webcam capture
   */
  public video = null;
  public canvas = null;
  public image = null;
  public captureButton = null;
 
  /**
   * This variable is a reference to the file that will be uploaded, either selected or captured
   */
  public imageToUpload: File = null;
 
  /**
   * Determines whether the file to upload was selected from the file explorer or captured via webcam
   */
  public uploadCapture = false;
 
  /**
   * Determines if an image is available to be uploaded
   */
  public imgAvailable = false;
 
  /**
   * Determines whether or not the Submit button should be displayed
   */
  public displayUpload: Boolean = false;
 
  /**
   * Indicates whether the model loader service has loaded a model into memory
   */
  public modelLoaded: Boolean = false;
 
  /**
   * Stores the results returned by the model loader predict method
   */
  public predictions: any;
 
  /**
   * An array used to store JSON objects related to the classes that were predicted. Includes class name, class likeliness,
   * and class catalogue links, if specified
   */
  public resultPreds = [];
 
  /**
   * The header column text displayed in the results table
   */
  public displayedColumns = ['name', 'likeliness', 'link'];
 
  /**
   * Determines whether a model is ready and whether an image has been predicted
   */
  public notReadyToPredict = true;
 
  /**
   * The text displayed on the Submit button
   */
  public modelStatus = 'Loading...';
 
  /**
   * Determines which model is to be used in the model loader service
   */
  public modelNumber = 1;
 
  /**
   * This constructor is only used to pass an instance of the HttpClient module.
   * @param http  HttpClient instance
   */
  constructor(public ml: ModelLoaderService, private dialog: MatDialog ) { }
 
  /**
   * Upon initialization of the component, the model loader service loads the model. It then queries whether
   * the model has been loaded every 500 ms and if it is, it allows predicting to take place. This timed query
   * is due to the asynchronous nature of the TensorFlowJS loadModel method
   */
  ngOnInit() {
    this.ml.loadModel();
    const modelLoaded = setInterval(() => {
      if (this.ml.modelIsReady()) {
        this.notReadyToPredict = false;
        clearInterval(modelLoaded);
        this.modelStatus = 'Submit';
      }
    }, 500);
  }
 
  /**
   *  This function is triggered by the user selecting an image from the file explorer. It displays the selected
   *  image in the 'preview' element. This image element is added dynamically and is only done if there is an actual
   *  file selected. The selected image is also set as the file to be uploaded.
   */
  madeChange() {
    const uploadedFile = document.querySelector('input');
    const preview = document.querySelector('.preview');
 
    this.uploadCapture = false;
    this.imageToUpload = null;
    this.streaming = false;
    this.updateInstruction();
 
    while (pIreview.firstChild) {
      preview.removeChild(preview.firstChild);
    }

    if (uploadedFile.files.length === 0) {
      const newP = document.createElement('p');
      newP.textContent = 'No files currently selected';
      newP.style.setProperty('color', 'lightgray');
 
      preview.appendChild(newP);
 
      this.imgAvailable = false;
      this.imageToUpload = null;
      this.updateInstruction();
    } else {
      const newP = document.createElement('p');
      const fileSize = this.formattedFileSize(uploadedFile.files[0].size);
      newP.textContent = 'Name: ' + uploadedFile.files[0].name + ' Size: ' + fileSize;
      newP.style.setProperty('color', 'lightgray');
      newP.style.setProperty('margin', 'auto');
      newP.style.setProperty('font-family', '"Lato", Arial, Helvetica, sans-serif');
 
      coEnst image = document.createElement('img');
      image.src = window.URL.createObjectURL(uploadedFile.files[0]);
      image.style.setProperty('height', '200px');
      this.image = image;
 
      preview.appendChild(newP);
      preview.appendChild(image);
 
      this.uploadCapture = false;
      this.imgAvailable = true;
      this.imageToUpload = uploadedFile.files[0];
      this.updateInstruction();
    }
  }

  /**
   * This function updates the instruction <p> element to display contextual information.
   */
  updateInstruction() {
    if (this.imgAvailable === false) {
      this.instruction = 'Click either the File Select or Webcam Capture button';
    } else {
      if (this.uploadCapture === false) {
        this.instruction = 'Click Submit to submit the selected image';
      } else {
        this.instruction = 'Click Capture to take a screenshot and then click Submit to submit the captured image';
      }
    }
  }
 
/**
 * This function formats the size value of the selected file from bytes to a readable string.
 * @param size  This is the size in bytes of the selected file from madeChange().
 * @returns     Returns the size in bytes, KB, or MB depending on the value of size.
 */
  formattedFileSize (size) {
    if (size < 1024) {
      return size + ' bytes';
    }
    if (size < 1024 * 1024) {
      return ( (size / 1024).toFixed(2) + 'KB' );
    }
    if (size > 1024 * 1024) {
      return ( (size / (1024 * 1024)).toFixed(2) + 'MB');
    }
 
  }
 
  /**
   * This function handles everything to do with the webcam capture option. It is called when the webcam button is clicked
   * and creates and maintains webcam footage in a video element. Allows the user to capture an image from the webcam
   * recording to upload.
   */
  captureImage() {
    const preview = document.querySelector('.preview');
    this.imgAvailable = false;
    thisE.displayUpload = false;
    this.updateInstruction();
 
    while (preview.firstChild) {
      preview.removeChild(preview.firstChild);
    }
 
    this.imageToUpload = null;
    this.uploadCapture = true;
 
    // Video element
    this.video = document.createElement('video');
    this.video.textContent = 'Video stream not available';
    this.video.style.setProperty('float', 'left');
    this.video.style.setProperty('text-align', 'center');
 
    // Capture button element
    this.captureButton = document.createElement('button');
    this.captureButton.textContent = 'CAPTURE';
    this.captureButton.style.setProperty('padding', '16px 32px');
    this.captureButton.style.setProperty('border', '3px lightgray solid');
    this.captureButton.style.setProperty('color', 'lightgray');
    this.captureButton.style.setProperty('background-color', 'rgba(5,5,5,0)');
    this.captureButton.style.setProperty('font-family', '"Lato", Arial, Helvetica, sans-serif');
    this.captureButton.style.setProperty('margin-left', '20px');
    this.captureButton.onmouseover = function() {
      this.style.setProperty('cursor', 'pointer');
      this.style.setProperty('background-color', 'rgb(33, 74, 95)');
    };
    this.captureButton.onmouseleave = function() {
      this.style.setProperty('cursor', 'default');
      this.style.setProperty('background-color', 'rgba(5,5,5,0)');
    };

    const br = document.createElement('br');

    // Canvas element that draws screenshot
    this.canvas = document.createElement('canvas');
    this.canvas.style.setProperty('display', 'none');
    this.canvas.style.setProperty('float', 'right');
 
    // Image element displaying saved screenshot
    this.image = document.createElement('img');
 
    this.startup(this.video, this.canvas, this.image, this.captureButton);
 
    preview.appendChild(this.video);
    preview.appendChild(this.canvas);
    preview.appendChild(this.image);
    preview.appendChild(br);
    preview.appendChild(this.captureButton);
 
    this.imgAvailable = true;
    this.updateInstruction();
  }
 
  /**
   * This function carries out the process of displaying the webcam footage and saving captured images.
   * @param video   the video element that displays the webcam footage
   * @param canvas  the canvas element that draws the capture webcam image upon clicking Capture
   * @param image   the image element that displays the image drawn by the canvas
   * @param captureButton   the button element that allows the user to capture the webcam footage
   */
  startup(video, canvas, image, captureButton) {
    const width = 320;
    let height = 0;
    navigator.mediaDevices.getUserMedia({video: true})
      .then(function(stream) {
        video.srcObject = stream;
        video.play();
      })
      .catch(function(err) {
        console.log('An error has occured! ' + err);
      });
 
    video.addEventListener('canplay', function(ev) {
      if (!this.streaming) {
        height = video.videoHeight / (video.videoWidth / width);
        video.setAttribute('width', width);
        video.setAttribute('height', height);
        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);
        this.streaming = true;
      }
    }, false);

    captureButton.onclick = function() {
      const context = canvas.getContext('2d');
      let data = null;
      if (width && height) {
        this.uploadCapture = true;
        canvas.width = width;
        canvas.height = height;
        context.drawImage(video, 0, 0, width, height);

        data = canvas.toDataURL('image/png');
        image.src = data;
 
      } else {
        // this.clearPhoto(canvas, image);
      }
    };
 
    this.clearPhoto(canvas, image);
  }
 
  /**
   * This function makes the canvas white if no image has been captured yet.
   * @param canvas Same as the startup function
   * @param image Same as the startup function
   */
  clearPhoto(canvas, image) {
    const context3 = canvas.getContext('2d');
    context3.fillStyle = 'rgb(207, 207, 207)';
    context3.fillRect(0, 0, canvas.width, canvas.height);
 
    const dataF = canvas.toDataURL('image/png');
    image.setAttribute('src', dataF);
 
    this.imgAvailable = false;
  }
 
  /**
   * This function is required for the browser to make use of the device's webcam.
   */
  // hasGetUserMedia() {
  //   return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
  // }
 
  /**
   * Called when the Submit button is clicked. Calls the model loader service's predictImage method,
   * then maps the predictions and fills the resultPreds array, so that the results table is updated
   */
  predictImage() {

    // Spinner is not displayed due to async issues or not being able to figure it out
    const updateStatus = (txt) => {
      this.modelStatus = txt;
      this.showSpinner = true;
    };
 
    updateStatus('Predicting...');
    this.ml.predictImage(this.image)
    .then((predictions) => {
      this.showSpinner = false;
      this.resultPreds = this.ml.mapPredictions(predictions);
      this.modelStatus = 'Submit';
      if (this.ml.modelHasLinks()) {
        this.displayedColumns = ['name', 'likeliness', 'link', 'quote'];
      } else {
        this.displayedColumns = ['name', 'likeliness'];
      }
 
      const el = document.querySelector('.result-card');
      el.scrollIntoView({behavior: 'smooth'});
    })
    .catch((error) => {
      console.error('Error: ' + error);
      this.showSpinner = false;
    });
 
  }
 
  /**I
   * Called when the select element is changed. The model loader service methods are called to change the
   * selected model and load it into memory
   */
  changeSelectedModel() {
    this.ml.changeModel(this.modelNumber);
    this.notReadyToPredict = true;
    this.modelStatus = 'Loading...';
    this.ml.loadModel();
    const modelLoaded = setInterval(() => {
      if (this.ml.modelIsReady()) {
        this.notReadyToPredict = false;
        clearInterval(modelLoaded);
        this.modelStatus = 'Submit';
      }
    }, 500);
  }

  /**
   * Called when clicking on a predicted item. Handles the addition of quotes
   * @param elName Corresponds with the results table element clicked
   */
  openQuoteDialog(elName) {
    const dialogConfig = new MatDialogConfig();

    dialogConfig.autoFocus = true;
    dialogConfig.data = {
      name: elName
    };
    dialogConfig.minHeight = '250px';
    dialogConfig.minHeight = '300px';
 
    this.dialog.open(QuoteDialogComponent, dialogConfig);
  }
 
  /**
   * This function scrolls up to the Image Submit section of the page
   */
  async reloadPage() {
    const el = document.querySelector('.upload-card__instruction');
    el.scrollIntoView({behavior: 'smooth'});
  }
 
}