Skip to content
This repository has been archived by the owner on Dec 17, 2020. It is now read-only.

Commit

Permalink
Browse files Browse the repository at this point in the history
Build v1.0
  • Loading branch information
ShivamGoyal1899 committed Mar 23, 2019
1 parent e490dfe commit 8fd91c7
Show file tree
Hide file tree
Showing 23 changed files with 517 additions and 13 deletions.
1 change: 1 addition & 0 deletions app/build.gradle
Expand Up @@ -25,4 +25,5 @@ dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}
3 changes: 3 additions & 0 deletions app/src/main/AndroidManifest.xml
Expand Up @@ -2,6 +2,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tk.shivamgoyal.affekt">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
Expand Down
Binary file added app/src/main/ic_launcher-web.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
210 changes: 209 additions & 1 deletion app/src/main/java/tk/shivamgoyal/affekt/MainActivity.java
@@ -1,13 +1,221 @@
package tk.shivamgoyal.affekt;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.net.URI;

import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.client.utils.URIBuilder;
import cz.msebera.android.httpclient.entity.ByteArrayEntity;
import cz.msebera.android.httpclient.impl.client.HttpClients;
import cz.msebera.android.httpclient.util.EntityUtils;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;

public class MainActivity extends AppCompatActivity {


private ImageView imageView; // variable to hold the image view in our activity_main.xml
private TextView resultText; // variable to hold the text view in our activity_main.xml
private static final int RESULT_LOAD_IMAGE = 100;
private static final int REQUEST_PERMISSION_CODE = 200;




@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


// initiate our image view and text view
imageView = (ImageView) findViewById(R.id.imageView);
resultText = (TextView) findViewById(R.id.resultText);
}


// when the "GET EMOTION" Button is clicked this function is called
public void getEmotion(View view) {
// run the GetEmotionCall class in the background
GetEmotionCall emotionCall = new GetEmotionCall(imageView);
emotionCall.execute();
}


// when the "GET IMAGE" Button is clicked this function is called
public void getImage(View view) {
// check if user has given us permission to access the gallery
if(checkPermission()) {
Intent choosePhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePhotoIntent, RESULT_LOAD_IMAGE);
}
else {
requestPermission();
}
}
}


// This function gets the selected picture from the gallery and shows it on the image view
protected void onActivityResult(int requestCode, int resultCode, Intent data) {


// get the photo URI from the gallery, find the file path from URI and send the file path to ConfirmPhoto
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {


Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
// a string variable which will store the path to the image in the gallery
String picturePath= cursor.getString(columnIndex);
((Cursor) cursor).close();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
imageView.setImageBitmap(bitmap);
}
}


// convert image to base 64 so that we can send the image to Emotion API
public byte[] toBase64(ImageView imgPreview) {
Bitmap bm = ((BitmapDrawable) imgPreview.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
return baos.toByteArray();
}




// if permission is not given we get permission
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
}




public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}


// asynchronous class which makes the API call in the background
private class GetEmotionCall extends AsyncTask<Void, Void, String> {


private final ImageView img;


GetEmotionCall(ImageView img) {
this.img = img;
}


// this function is called before the API call is made
@Override
protected void onPreExecute() {
super.onPreExecute();
resultText.setText("Getting results...");
}


// this function is called when the API call is made
@Override
protected String doInBackground(Void... params) {
HttpClient httpclient = HttpClients.createDefault();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);


try {
URIBuilder builder = new URIBuilder("https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect");


URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/octet-stream");
request.setHeader("Ocp-Apim-Subscription-Key", "0365c14f89e5425c879836362113bca4");


// Request body.The parameter of setEntity converts the image to base64
request.setEntity(new ByteArrayEntity(toBase64(img)));


// getting a response and assigning it to the string res
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity);


return res;


}
catch (Exception e){
return "null";
}


}


// this function is called when we get a result from the API call
@Override
protected void onPostExecute(String result) {
JSONArray jsonArray = null;
try {
// convert the string to JSONArray
jsonArray = new JSONArray(result);
String emotions = "";
// get the scores object from the results
for(int i = 0;i<jsonArray.length();i++) {
JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
JSONObject scores = jsonObject.getJSONObject("scores");
double max = 0;
String emotion = "";
for (int j = 0; j < scores.names().length(); j++) {
if (scores.getDouble(scores.names().getString(j)) > max) {
max = scores.getDouble(scores.names().getString(j));
emotion = scores.names().getString(j);
}
}
emotions += emotion + "\n";
}
resultText.setText(emotions);


} catch (JSONException e) {
resultText.setText("No emotion detected. Try again later.");
}
}
}

}
105 changes: 100 additions & 5 deletions app/src/main/res/layout/activity_main.xml
@@ -1,18 +1,113 @@
<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
tools:context="tk.shivamgoyal.affekt.MainActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">

<TextView

<ImageView
android:id="@+id/imageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="3dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="2dp"
android:layout_marginBottom="12dp"
app:layout_constraintBottom_toTopOf="@+id/getEmotion"
app:layout_constraintLeft_toLeftOf="@+id/getImage"
app:layout_constraintRight_toRightOf="@+id/getEmotion"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@mipmap/ic_launcher"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1" />


<Button
android:id="@+id/getImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginStart="60dp"
android:layout_marginTop="12dp"
android:onClick="getImage"
android:text="Get Image"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1" />


<Button
android:id="@+id/getEmotion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="60dp"
android:layout_marginBottom="37dp"
android:onClick="getEmotion"
android:text="Get Emotion"
app:layout_constraintBottom_toTopOf="@+id/resultText"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
tools:layout_constraintBottom_creator="1"
tools:layout_constraintRight_creator="1" />


<TextView
android:id="@+id/resultText"
android:layout_width="0dp"
android:layout_height="136dp"
android:layout_marginStart="18dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="24dp"
android:ems="10"
android:text=""
android:textAlignment="viewStart"
android:textAppearance="@style/TextAppearance.AppCompat.Widget.PopupMenu.Large"
android:textSize="18sp"
android:typeface="normal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="@+id/getImage"
app:layout_constraintRight_toRightOf="parent"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1" />


<TextView
android:id="@+id/textView"
android:layout_width="84dp"
android:layout_height="26dp"
android:layout_marginLeft="16dp"
android:ems="10"
android:text="Result:"
android:textAlignment="viewStart"
android:textAppearance="@style/TextAppearance.AppCompat.Widget.PopupMenu.Large"
android:textSize="18sp"
android:typeface="normal"
app:layout_constraintBaseline_toBaselineOf="@+id/resultText"
app:layout_constraintLeft_toLeftOf="parent"
tools:layout_constraintBaseline_creator="1"
tools:layout_constraintLeft_creator="1" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="8dp"
android:text="Hand Crafted with ♥ in India by Shivam Goyal"
android:textAppearance="@style/TextAppearance.AppCompat.Widget.Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/resultText" />


</android.support.constraint.ConstraintLayout>

0 comments on commit 8fd91c7

Please sign in to comment.