Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

save data to firebase #17

Open
sichrif opened this issue Feb 11, 2021 · 3 comments
Open

save data to firebase #17

sichrif opened this issue Feb 11, 2021 · 3 comments

Comments

@sichrif
Copy link

sichrif commented Feb 11, 2021

is it possible and if it is can anyone share how to do it with me

@adelanov
Copy link

adelanov commented Mar 12, 2021

the following code I modify in TFLiteObjectDetectionAPIModel.java for get data from Firebase

`........
public static SimilarityClassifier create(
final AssetManager assetManager,
final String modelFilename,
final String labelFilename,
final int inputSize,
final boolean isQuantized, DetectorActivity det)
throws IOException {

final TFLiteObjectDetectionAPIModel d = new TFLiteObjectDetectionAPIModel();


try {
  //Toast.makeText(det.getApplicationContext(), "name is null", Toast.LENGTH_LONG ).show();

  FirebaseStorage storage = FirebaseStorage.getInstance();
  StorageReference storageRef = storage.getReference();
  StorageReference test2 = storageRef.child(FileName);

  File localFile = File.createTempFile("Student", "txt");
  //File localFile = new File(det.getFilesDir(),"test2.txt");
  test2.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

      try {

        Gson gson = new Gson();
        ObjectInputStream i = new ObjectInputStream(new FileInputStream(localFile));
        //HashMap<String, Recognition> registeredl = (HashMap<String, Recognition>) i.readObject();

        Type type = new TypeToken<HashMap<String, Recognition>>(){}.getType();
        HashMap<String, Recognition> registeredl = gson.fromJson((String)i.readObject(), type);
        //HashMap<String, Recognition> registeredl = (HashMap<String, Recognition>) i.readObject();

        if (registeredl != null){
          d.registered = registeredl;
        }
        i.close();

        Toast.makeText(det.getApplicationContext(), "โหลดข้อมูลเรียบร้อย.", Toast.LENGTH_LONG ).show();
        Log.d("Clique AQUI", "Clique Aqui Adicionado " + registeredl.size());

      } catch (Exception e) {
        Log.d("Clique AQUI", "Clique Aqui erro " + e.toString());
        Toast.makeText(det.getApplicationContext(), "Exception 1" + e.getMessage(), Toast.LENGTH_LONG ).show();
      }
    }
  }).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
      Log.d("Clique AQUI", "Clique Aqui erro " + exception.toString());
      Toast.makeText(det.getApplicationContext(), "Exception 2 " + exception.getMessage(), Toast.LENGTH_LONG ).show();
    }
  });


} catch (Exception e) {

  Log.d("Clique AQUI", "Clique AQUI file created: " + e.toString());
}



String actualFilename = labelFilename.split("file:///android_asset/")[1];
InputStream labelsInput = assetManager.open(actualFilename);
BufferedReader br = new BufferedReader(new InputStreamReader(labelsInput));
String line;

.......`

to save data to firebase i modify in register method

` public void register(String name, Recognition rec,DetectorActivity det) {
registered.put(name, rec);

byte[] bytes=null;
try {

  //  file.createNewFile();
  //write the bytes in file
  {
    Gson gson = new Gson();


    File localFile = new File(det.getFilesDir(),FileName);
    FileOutputStream fileOutputStream = new FileOutputStream(localFile);

    Type type = new TypeToken<HashMap<String, Recognition>>(){}.getType();
    String toStoreObject = gson.toJson(registered,type);

    ObjectOutputStream o = new ObjectOutputStream(fileOutputStream);
    o.writeObject(toStoreObject);
    //o.writeObject(registered);

    o.close();
    /* 26 */
    fileOutputStream.close();

    Toast.makeText(det.getApplicationContext(), "save file completed.", Toast.LENGTH_LONG ).show();

    Log.d("Clique AQUI","Clique AQUI file created: " );
    ///     file.delete();
    Log.d("Clique AQUI","Clique AQUI delete " );
  }

  FirebaseStorage storage = FirebaseStorage.getInstance();
  StorageReference storageRef = storage.getReference();
  StorageReference test2 = storageRef.child(FileName);
  //test2.delete();
  //test2.putStream();

  Uri file = Uri.fromFile(new File(det.getFilesDir(),FileName));


  test2.putFile(file)
          .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
              // Get a URL to the uploaded content
              //Uri downloadUrl = taskSnapshot.get();
              Toast.makeText(det.getApplicationContext(), "Upload Completed.", Toast.LENGTH_LONG ).show();

            }
          })
          .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
              // Handle unsuccessful uploads
              // ...
              Toast.makeText(det.getApplicationContext(), "Upload Failure.", Toast.LENGTH_LONG ).show();
            }
          });

  Log.d("Clique AQUI","Clique Aqui Enviou ");



}catch (Exception e){


  Log.d("Clique AQUI","Clique AQUI file created: " + e.toString());

  //Log.d("Clique AQUI","Clique AQUI file created: " + bytes.length);
  Toast.makeText(det.getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG ).show();

}

}`

I also use Gson to deserialize 2d array

`private Pair<String, Float> findNearest(float[] emb) {

Gson gson = new Gson();

Pair<String, Float> ret = null;

for (Map.Entry<String, Recognition> entry : registered.entrySet()) {
  String name = entry.getKey();

  float distance = 0;
  try {

    // original code 
    //final float[] knownEmb = ((float[][]) entry.getValue().getExtra())[0];

    // -------------------- MODIFY --------------------------------------------------------------/
    float[][] knownEmb2d = gson.fromJson(entry.getValue().getExtra().toString(), float[][].class);
    final float[] knownEmb = knownEmb2d[0];

    for (int i = 0; i < emb.length; i++) {
      float diff = emb[i] - knownEmb[i];
      distance += diff * diff;
    }
  }
  catch (Exception e){
    //Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG ).show();
    Log.e("findNearest",e.getMessage());
  }
  distance = (float) Math.sqrt(distance);
  if (ret == null || distance < ret.second) {
    ret = new Pair<>(name, distance);
  }
}

return ret;

}`

vdo for this sample i try to face recognitions my student

https://youtu.be/Vfb8x5Jxzro

@panwarunionitc
Copy link

Brother i am getting

StorageException has occurred. Object does not exist at location. Storage FireBase
help me plz

@panwarunionitc
Copy link

i used same code as given

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants