Skip to content

Commit

Permalink
update mathpix apiv2 to v3, improved code quality
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaliCode5019 committed May 15, 2017
1 parent 24f87e9 commit 0ef3c70
Show file tree
Hide file tree
Showing 9 changed files with 169 additions and 169 deletions.
6 changes: 2 additions & 4 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,9 @@ dependencies {
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.mixpanel.android:mixpanel-android:4.+'
compile 'com.google.android.gms:play-services:9.0.0'
compile 'com.squareup:otto:1.3.8'
compile 'org.apache.commons:commons-lang3:3.4'

compile 'com.squareup.okhttp3:okhttp:3.8.0'
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'

compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
Expand Down
1 change: 0 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />

<uses-feature android:name="android.hardware.camera" />

Expand Down
4 changes: 2 additions & 2 deletions app/src/main/assets/latex.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
<div style="text-align:center"><span id="mykatex1"></span></div>
</div>
<script>
function setResultJson(resultJson) {
katex.render(resultJson.latex, mykatex1, {displayMode: true});
function setLatex(latex) {
katex.render(latex, mykatex1, {displayMode: true});
}
</script>

Expand Down
19 changes: 9 additions & 10 deletions app/src/main/java/com/app/mathpix_sample/CameraFragment.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
Expand Down Expand Up @@ -73,7 +72,7 @@ public class CameraFragment extends Fragment {

@OnClick(R.id.nextPhoto)
void onNextPhotoClicked() {
if(mWebViewContainer.getVisibility() == View.VISIBLE) {
if (mWebViewContainer.getVisibility() == View.VISIBLE) {
mWebViewContainer.setVisibility(View.INVISIBLE);


Expand All @@ -84,7 +83,7 @@ void onNextPhotoClicked() {

@OnClick(R.id.crop_control)
void onTapCropView() {
if(mPreview != null) {
if (mPreview != null) {
try {
Log.e(TAG, "Start auto-focusing");
mPreview.autoFocus();
Expand All @@ -105,8 +104,8 @@ void onTakePhotoButtonClicked() {
public void onPictureTaken(final byte[] data, Camera camera) {
stopPreview();

Bitmap bm= ImageUtil.toBitmap(data);
if(bm.getWidth() > bm.getHeight()) {
Bitmap bm = ImageUtil.toBitmap(data);
if (bm.getWidth() > bm.getHeight()) {
bm = ImageUtil.rotate(bm, 90);
}
Log.e(TAG, "got bitmap size = " + bm.getWidth() + ", " + bm.getHeight());
Expand Down Expand Up @@ -208,7 +207,7 @@ private void startPreview() {
try {
mCamera = CameraUtil.getCameraInstance();

if(mCamera == null) {
if (mCamera == null) {
// showAlert("Can not connect to camera.");
} else {
mPreview = new CameraPreview(getContext(), mCamera);
Expand Down Expand Up @@ -243,8 +242,7 @@ private void uploadImage(Bitmap bitmap) {
startScanAnimation();


UUID deviceUID = MathpixUUID.uuid(getContext());
UploadImageTask.UploadParams params = new UploadImageTask.UploadParams(bitmap,deviceUID);
UploadImageTask.UploadParams params = new UploadImageTask.UploadParams(bitmap);
UploadImageTask task = new UploadImageTask(new UploadImageTask.ResultListener() {
@Override
public void onError(String message) {
Expand Down Expand Up @@ -273,11 +271,12 @@ private void loadLocalContent() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String js = "javascript:setResultJson(" + mLatestLatex + ")";
final String js = "javascript:setLatex('" + mLatestLatex + "')";
if (mWebView != null) {
mWebView.loadUrl(js);
}
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
Expand All @@ -296,7 +295,7 @@ public boolean shouldOverrideUrlLoading(WebView view, String url) {

}

public String localHTML(Context context){
public String localHTML(Context context) {
StringBuilder stringBuilder = new StringBuilder();
InputStream json;
try {
Expand Down
36 changes: 0 additions & 36 deletions app/src/main/java/com/app/mathpix_sample/MathpixUUID.java

This file was deleted.

180 changes: 66 additions & 114 deletions app/src/main/java/com/app/mathpix_sample/UploadImageTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,147 +2,99 @@

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;
import com.app.mathpix_sample.api.request.SingleProcessRequest;
import com.app.mathpix_sample.api.response.DetectionResult;
import com.google.gson.Gson;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UploadImageTask extends AsyncTask<UploadImageTask.UploadParams, Void, UploadImageTask.Result> {
class UploadImageTask extends AsyncTask<UploadImageTask.UploadParams, Void, UploadImageTask.Result> {

private final ResultListener listener;
private static final String FORM_BOUNDARY = "********";
private static final String DASHES = "--";
private static final String CLRF = "\r\n";
private static final String FORM_NAME = "file";
private static final String FORM_FILENAME = "image.jpg";

public UploadImageTask(ResultListener listener) {
UploadImageTask(ResultListener listener) {
this.listener = listener;
}

interface ResultListener{
void onError(String message);
void onSuccess(String url);
}

public static class UploadParams {
private Bitmap image;
private UUID deviceUID;

public UploadParams(Bitmap image, UUID deviceUID) {
this.image = image;
this.deviceUID = deviceUID;
}
}

public static class Result {
}

public static class ResultSuccessful extends Result {
private String resultURL;
protected String latex;
}

public static class ResultFailed extends Result {
private Exception exception;
public String message;
}

@Override
protected Result doInBackground(UploadParams... arr) {
UploadParams params = arr[0];
Result result;
try {
URL url = new URL(Constant.base_Url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
setupAndDoUpload(conn, params);
String response = getResponse(conn);
Log.d("Image Upload", response);
JSONObject jsonResponse = new JSONObject(response);
conn.disconnect();
ResultFailed failed = new ResultFailed();
failed.message = "Math not found";
if (jsonResponse.has("latex")){
String latex = jsonResponse.getString("latex");
if (latex.length() > 0){
ResultSuccessful successful = new ResultSuccessful();
successful.resultURL = response;
successful.latex = latex;
result = successful;
}else{
result = failed;
}
}else{
result = failed;
OkHttpClient client = new OkHttpClient();
SingleProcessRequest singleProcessRequest = new SingleProcessRequest(params.image);
MediaType JSON = MediaType.parse("application/json");
RequestBody requestBody = RequestBody.create(JSON, new Gson().toJson(singleProcessRequest));

Request request = new Request.Builder()
.url("https://api.mathpix.com/v3/latex")
.addHeader("content-type", "application/json")
.addHeader("app_id", "mathpix")
.addHeader("app_key", "139ee4b61be2e4abcfb1238d9eb99902")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
String responseString = response.body().string();
DetectionResult detectionResult = new Gson().fromJson(responseString, DetectionResult.class);
if (detectionResult != null && detectionResult.latex != null) {
result = new ResultSuccessful(detectionResult.latex);
} else if (detectionResult != null && detectionResult.error != null) {
result = new ResultFailed(detectionResult.error);
} else {
result = new ResultFailed("Math not found");
}

} catch (Exception e) {
ResultFailed failed = new ResultFailed();
failed.exception = e;
failed.message = "Failed to send to server. Check your connection and try again";
result = failed;
result = new ResultFailed("Failed to send to server. Check your connection and try again");
}
return result;
}

private void setupAndDoUpload(HttpURLConnection conn, UploadParams params) throws IOException {
conn.setRequestProperty("DeviceId", params.deviceUID.toString());
conn.setRequestProperty("app_id",Constant.app_id);
conn.setRequestProperty("app_key",Constant.app_key);
String contentType = "multipart/form-data; boundary=" + FORM_BOUNDARY;
conn.setRequestProperty("Content-Type", contentType);
DataOutputStream body = new DataOutputStream(conn.getOutputStream());
body.writeBytes(DASHES + FORM_BOUNDARY + CLRF);
String bytes = "Content-Disposition: form-data; name=\"" + FORM_NAME + "\"; filename=\"" +
FORM_FILENAME + "\"" + CLRF;
body.writeBytes(bytes);
body.writeBytes("Content-Type: image/jpeg" + CLRF + CLRF);
body.write(bitmapToBytes(params.image));
body.writeBytes(CLRF);
body.writeBytes(DASHES + FORM_BOUNDARY + DASHES + CLRF);
body.flush();
body.close();
}

// Convert to JPEG and return byte array
private byte[] bitmapToBytes(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
return baos.toByteArray();
}

private String getResponse(HttpURLConnection conn) throws IOException {
InputStream responseStream = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader =new BufferedReader(new InputStreamReader(responseStream));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
return stringBuilder.toString();
}

@Override
protected void onPostExecute(Result result) {
if (result instanceof ResultSuccessful) {
ResultSuccessful successful = (ResultSuccessful) result;
listener.onSuccess(successful.resultURL);
listener.onSuccess(successful.latex);
} else if (result instanceof ResultFailed) {
ResultFailed failed = (ResultFailed) result;
listener.onError(failed.message);
}
}

interface ResultListener {
void onError(String message);

void onSuccess(String url);
}

static class UploadParams {
private Bitmap image;

UploadParams(Bitmap image) {
this.image = image;
}
}

static class Result {
}

private static class ResultSuccessful extends Result {
String latex;

ResultSuccessful(String latex) {
this.latex = latex;
}
}

private static class ResultFailed extends Result {
String message;

ResultFailed(String message) {
this.message = message;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.app.mathpix_sample.api.request;

import android.graphics.Bitmap;
import android.util.Base64;

import com.google.gson.annotations.SerializedName;

import java.io.ByteArrayOutputStream;

public class SingleProcessRequest {
@SerializedName("url")
private String url;

public SingleProcessRequest(Bitmap bm) {
url = "data:image/jpeg;base64," + bitmapToBase64(bm);
}

public SingleProcessRequest(byte[] fileBytes) {
url = "data:image/jpeg;base64," + Base64.encodeToString(fileBytes, Base64.DEFAULT);
}

private String bitmapToBase64(Bitmap image) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, os);
return Base64.encodeToString(os.toByteArray(), Base64.DEFAULT);
}
}
Loading

0 comments on commit 0ef3c70

Please sign in to comment.