Failed to load tensorflowjs model on cordova android



  • I’am trying to import a model treined in keras to tensorflow.
    it works fine with the command “quasar dev”, however when i run with “cordova run android” it shows the message TypeError: Failed to Fetch

    <template>
      <div>
        <div class="train-controls">
          <div class="text-center">
            <div class="text-bold">
              Vendas de Sorvetes<br />
              <img src="~assets/sorvete.png" style="height: 100px; width:100px" />
            </div>
            Temperatura em Celcius<br />
            <input
              class="field element"
              v-model="valueToPredict"
              type="number"
              placeholder="digite um inteiro"
            />
            <div class="element">{{ predictedValue }}</div>
            <button class="element button--green" v-on:click="carregar_modelo">
              Carrega Treino
            </button>
          </div>
        </div>
      </div>
    </template>
    <script>
    import * as tf from "@tensorflow/tfjs";
    
    
    export default {
      data() {
        return {
          predictedValue: "Clique em Predizer Vendas",
          valueToPredict: "",
          model: tf.sequential()
        };
      },
      mounted() {
        this.carregar_modelo();
      },
      methods: {
        async carregar_modelo() {
    
          if (this.$q.platform.is.android) {
            try {
    
    
              this.model = await tf.loadLayersModel("model/model.json");
    
            } catch (error) {
              alert(error);
            }
          } else {
            this.model = await tf.loadLayersModel("model/model.json");
          }
    
        },
        predict() {
          let valor = this.model.predict(
            tf.tensor2d([this.valueToPredict], [1, 1], "float32")
          );
    
          this.predictedValue = "R$" + Number(valor.dataSync()).toFixed(2);
        }
      }
    };
    

    ![alt text](Screenshot_2020-07-22-16-18-49-453_dis.epm.br.jpg image url)



  • if you put your code on github people can help you better.



  • I forgot to put how to solve this
    it was a problem with the fetch function on android.
    to fix it
    i instaled “npm i whatwg-fetch”

    import { fetch as fetchPolyfill } from “whatwg-fetch”;

    on mounted() function added
    window.fetch = fetchPolyfill;

    <template>
      <q-layout class="layoutHome">
          <img id="imagemSorvete" src="~assets/imagem_sorvete.jpg" />
          <q-input class="text-dark" maxlength="3" v-model="valorTemperatura" label="Temperatura em Celsius" placeholder="Digite a temperatura..." @reset="limparCampos" />
          <q-input class="text-dark" v-model="valorPreditoLucro" label="Valor do Lucro" readonly/>
    
          <div :class="$q.screen.width <= 350 ? 'layoutBotoes row' : 'layoutBotoes'">
            <q-btn id="botaoPredizerLucro" :class="$q.screen.width <= 350 ? 'col' : ''" color="primary" label="Predizer Lucro" v-on:click="predizerLucroVendas" />
            <q-btn id="botaoLimparCampos"  :class="$q.screen.width <= 350 ? 'col' : ''" color="primary" label="Limpar Campos" v-on:click="limparCampos" />
          </div>
      </q-layout>
    </template>
    <script>
    import * as tf from "@tensorflow/tfjs";
    import { fetch as fetchPolyfill } from "whatwg-fetch";
    import { Dialog } from 'quasar'
    
    export default {
      data() {
        return {
          valorPreditoLucro: "",
          valorTemperatura: "",
          model: tf.sequential()
        };
      },
      mounted() {
        try {
          window.fetch = fetchPolyfill;
          this.carregar_modelo();
        } catch (error) {
          alert(error);
        }
      },
      methods: {
        async carregar_modelo() {
          if (this.$q.platform.is.android) {
            try {
              this.model = await tf.loadLayersModel("model/model.json");
            } catch (error) {
              alert(error);
            }
          } else {
            this.model = await tf.loadLayersModel("model/model.json");
          }
        },
        predizerLucroVendas() {
    
          if(this.valorTemperatura == "") {
            this.popupTemperaturaNula();
          }
          else if(this.valorTemperatura >60 || this.valorTemperatura < -90) {
            this.popupTemperaturasInvalidas();
            this.limparCampos();
          }
          else {
            let valor = this.model.predict(
            tf.tensor2d([this.valorTemperatura], [1, 1], "float32")
          );
    
          this.valorPreditoLucro = "R$ " + Number(valor.dataSync()).toFixed(2);
          }
        },
        limparCampos() {
          this.valorTemperatura="";
          this.valorPreditoLucro="";
        },
        popupTemperaturaNula(){
          this.$q.dialog({
            title: 'Temperatura Nula',
            message: 'O campo "valor da temperatura" está nulo'
          }).onOk(() => {
            
          }).onCancel(() => {
            
          }).onDismiss(() => {
            
          })
    
          this.limparCampos();
        },
        popupTemperaturasInvalidas() {
          this.$q.dialog({
            title: 'Temperatura Inválida',
            message: 'Temperaturas maiores que 60ºC ou menores que -90ºC não são aceitas'
          }).onOk(() => {
            
          }).onCancel(() => {
            
          }).onDismiss(() => {
            
          })
    
          this.limparCampos();
        }
      }
    };
    </script>
    
    
    
    

Log in to reply