-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathMainActivity.java
More file actions
773 lines (695 loc) · 28.3 KB
/
Copy pathMainActivity.java
File metadata and controls
773 lines (695 loc) · 28.3 KB
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
package io.github.subhamtyagi.ocr;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.progressindicator.LinearProgressIndicator;
import com.googlecode.tesseract.android.TessBaseAPI;
import com.theartofdev.edmodo.cropper.CropFileProvider;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import io.github.subhamtyagi.ocr.ocr.ImageTextReader;
import io.github.subhamtyagi.ocr.spinner.SpinnerDialog;
import io.github.subhamtyagi.ocr.utils.Constants;
import io.github.subhamtyagi.ocr.utils.CrashUtils;
import io.github.subhamtyagi.ocr.utils.LanguageUtil;
import io.github.subhamtyagi.ocr.utils.SpUtil;
import io.github.subhamtyagi.ocr.utils.Utils;
/**
* Apps MainActivity where all important works is going on
*/
public class MainActivity extends AppCompatActivity implements TessBaseAPI.ProgressNotifier {
public static final String TAG = "MainActivity";
private static final int REQUEST_CODE_SETTINGS = 797;
private static boolean isRefresh = false;
/**
* a progressDialog to show downloading Dialog
*/
private ProgressDialog mProgressDialog;
/**
* A spinner dialog shown on share menu
*/
private SpinnerDialog spinnerDialog;
private ArrayList<String> countryCodes;
private ArrayList<String> languagesNames;
private ArrayList<String> languagesCodes;
private CrashUtils crashUtils;
private ConvertImageToTextTask convertImageToTextTask;
private DownloadTrainingTask downloadTrainingTask;
private File dirBest;
private File dirStandard;
private File dirFast;
private File currentDirectory;
/**
* Our ImageTextReader Instance
*/
private ImageTextReader mImageTextReader;
/**
* TrainingDataType: i.e Best, Standard, Fast
*/
private String mTrainingDataType;
/**
* selected language on image or used for detection
*/
private String mLanguage;
/**
* Page segmentation mode
*/
private int mPageSegMode;
/**
* AlertDialog for showing when language data doesn't exists
*/
private AlertDialog dialog;
/**
* Image View
*/
private ImageView mImageView;
/**
* ProgressIndicator
*/
private LinearProgressIndicator mProgressIndicator;
/**
* SwipeRefreshLayout
*/
private SwipeRefreshLayout mSwipeRefreshLayout;
/**
* FloatingActionButton
*/
private FloatingActionButton mFloatingActionButton;
/**
* Language name to be displayed
*/
private TextView mLanguageName;
private void setLanguage() {
SpUtil.getInstance().init(this);
languagesCodes = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.key_language_entries_value)));
countryCodes = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.key_country_entries_value)));
String currentLanguage = SpUtil.getInstance().getString(Constants.CURRENT_LANGUAGE, "");
if (getApplicationContext() == null || currentLanguage.isEmpty()) {
return;
}
String currentCountry = getCountryCodeFromLanguage(currentLanguage);
LanguageUtil.changeLanguage(MainActivity.this, currentLanguage, currentCountry);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLanguage();
setContentView(R.layout.activity_main);
/*
Initialization of some application level variables
*/
SpUtil.getInstance().init(this);
crashUtils = new CrashUtils(getApplicationContext(), "");
languagesNames = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.ocr_engine_language)));
languagesCodes = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.key_ocr_engine_language_value)));
mImageView = findViewById(R.id.source_image);
mProgressIndicator = findViewById(R.id.progress_indicator);
mSwipeRefreshLayout = findViewById(R.id.swipe_to_refresh);
mFloatingActionButton = findViewById(R.id.btn_scan);
mLanguageName = findViewById(R.id.language_name1);
initDirectories();
/*
*initialize the OCR or download the training data
*/
initializeOCR(null);
/*
* check if this was initiated by shared menu if yes then get the image uri and get the text
* language will be preselected by user in settings
*/
initIntent();
initViews();
}
private void initViews() {
mFloatingActionButton.setOnClickListener(v -> {
if (isLanguageDataExists(mTrainingDataType, mLanguage)) {
if (mImageTextReader != null) {
selectImage();
} else {
initializeOCR(null);
}
} else {
downloadLanguageData(mTrainingDataType, mLanguage);
}
});
mSwipeRefreshLayout.setOnRefreshListener(() -> {
if (isLanguageDataExists(mTrainingDataType, mLanguage)) {
if (mImageTextReader != null) {
Drawable drawable = mImageView.getDrawable();
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
if (bitmap != null) {
isRefresh = true;
new ConvertImageToTextTask().execute(bitmap);
}
}
} else {
initializeOCR(null);
}
} else {
downloadLanguageData(mTrainingDataType, mLanguage);
}
mSwipeRefreshLayout.setRefreshing(false);
});
if (Utils.isPersistData()) {
Bitmap bitmap = loadBitmapFromStorage();
if (bitmap != null) {
mImageView.setImageBitmap(bitmap);
}
}
}
private void initIntent() {
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if (type.startsWith("image/")) {
Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
mImageView.setImageURI(imageUri);
showLanguageSelectionDialog(imageUri);
}
}
} else if ("screenshot".equals(action)) {
// uri
}
}
private void showLanguageSelectionDialog(Uri imageUri) {
spinnerDialog = new SpinnerDialog(MainActivity.this, languagesNames, getString(R.string.select_search_language), R.style.DialogAnimations_SmileWindow);
spinnerDialog.setShowKeyboard(false);
spinnerDialog.bindOnSpinnerListener((item, position) -> {
startOCRFromShareMenu(getResources().getStringArray(R.array.key_ocr_engine_language_value)[position], imageUri);
});
spinnerDialog.showSpinnerDialog();
View view = spinnerDialog.getView();
RadioButton radioButton1 = view.findViewById(R.id.rb_language1);
RadioButton radioButton2 = view.findViewById(R.id.rb_language2);
RadioButton radioButton3 = view.findViewById(R.id.rb_language3);
String[] la = Utils.getLast3UsedLanguage();
radioButton1.setText(getLanguageNameFromCode(la[0], false));
radioButton2.setText(getLanguageNameFromCode(la[1], false));
radioButton3.setText(getLanguageNameFromCode(la[2], false));
radioButton1.setOnClickListener(view1 -> startOCRFromShareMenu(la[0], imageUri));
radioButton2.setOnClickListener(view1 -> startOCRFromShareMenu(la[1], imageUri));
radioButton3.setOnClickListener(view1 -> startOCRFromShareMenu(la[2], imageUri));
}
private String getLanguageNameFromCode(String code, boolean multipleLanguages) {
return multipleLanguages ? code : languagesNames.get(languagesCodes.indexOf(code));
}
private String getCountryCodeFromLanguage(String mLanguage){
return countryCodes.isEmpty() ? "US" : countryCodes.get(languagesCodes.indexOf(mLanguage));
}
@Override
protected void onResume() {
super.onResume();
mLanguageName.setText(getLanguageNameFromCode(mLanguage,true));
}
public void startOCRFromShareMenu(String lang, Uri imageUri) {
if (!lang.contentEquals(mLanguage)) {
mLanguage = lang;
initializeOCR(mLanguage);
}
Utils.setLastUsedLanguage(mLanguage);
// Log.d("radio", "showLanguageSelectionDialog: " + mLanguage);
spinnerDialog.closeSpinnerDialog();
mImageView.setImageURI(imageUri);
if (isLanguageDataExists(mTrainingDataType, mLanguage)) {
CropImage.activity(imageUri).start(MainActivity.this);
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void initDirectories() {
dirBest = new File(getExternalFilesDir("best").getAbsolutePath());
dirFast = new File(getExternalFilesDir("fast").getAbsolutePath());
dirStandard = new File(getExternalFilesDir("standard").getAbsolutePath());
dirBest.mkdirs();
dirStandard.mkdirs();
dirFast.mkdirs();
currentDirectory = new File(dirBest, "tessdata");
currentDirectory.mkdirs();
currentDirectory = new File(dirStandard, "tessdata");
currentDirectory.mkdirs();
currentDirectory = new File(dirFast, "tessdata");
currentDirectory.mkdirs();
}
/**
* initialize the OCR i.e tesseract api
* if there is no training data in directory than it will ask for download
*/
private void initializeOCR(String languageFromShareImage) {
File cf;
mTrainingDataType = Utils.getTrainingDataType();
if (languageFromShareImage == null)
mLanguage = Utils.getTrainingDataLanguage();
Log.d(TAG, "initializeOCR: " + mLanguage);
mPageSegMode = Utils.getPageSegMode();
switch (mTrainingDataType) {
case "best":
currentDirectory = new File(dirBest, "tessdata");
cf = dirBest;
break;
case "standard":
cf = dirStandard;
currentDirectory = new File(dirStandard, "tessdata");
break;
default:
cf = dirFast;
currentDirectory = new File(dirFast, "tessdata");
}
if (isLanguageDataExists(mTrainingDataType, mLanguage)) {
//region Initialize image text reader
new Thread() {
@Override
public void run() {
try {
if (mImageTextReader != null) {
mImageTextReader.tearDownEverything();
}
int mEngineMode = Utils.getEngineMode();
mImageTextReader = ImageTextReader.geInstance(cf.getAbsolutePath(), mLanguage, mPageSegMode, mEngineMode, MainActivity.this::onProgressValues);
//check if current language data is valid
//if it is invalid(i.e. corrupted, half downloaded, tempered) then delete it
if (!mImageTextReader.success) {
File destf = new File(currentDirectory, String.format(Constants.LANGUAGE_CODE, mLanguage));
destf.delete();
mImageTextReader = null;
}
} catch (Exception e) {
crashUtils.logException(e);
File destf = new File(currentDirectory, String.format(Constants.LANGUAGE_CODE, mLanguage));
destf.delete();
mImageTextReader = null;
}
}
}.start();
//endregion
} else {
Log.d(TAG, "initializeOCR: language data doesn't exist " + mLanguage);
downloadLanguageData(mTrainingDataType, mLanguage);
}
}
@SuppressLint("StringFormatInvalid")
private void downloadLanguageData(final String dataType, final String lang) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
//region show confirmation dialog, On 'yes' download the training data.
String msg = String.format(getString(R.string.download_description), getLanguageNameFromCode(lang, true));
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.training_data_missing)
.setCancelable(false)
.setMessage(msg)
.setPositiveButton(R.string.yes, (dialog, which) -> {
dialog.cancel();
downloadTrainingTask = new DownloadTrainingTask();
downloadTrainingTask.execute(dataType, lang);
})
.setNegativeButton(R.string.no, (dialog, which) -> {
dialog.cancel();
if (!isLanguageDataExists(dataType, lang)) {
// show dialog to change language
}
}).create();
dialog.show();
//endregion
} else {
Toast.makeText(this, getString(R.string.you_are_not_connected_to_internet), Toast.LENGTH_SHORT).show();
//You are not connected to Internet
}
}
/**
* Check if language data exists
*
* @param dataType data type i.e best, fast, standard
* @param lang language
* @return true if language data exists
*/
private boolean isLanguageDataExists(final String dataType, final String lang) {
switch (dataType) {
case "best":
currentDirectory = new File(dirBest, "tessdata");
break;
case "standard":
currentDirectory = new File(dirStandard, "tessdata");
break;
default:
currentDirectory = new File(dirFast, "tessdata");
}
if (lang.contains("+")) {
String[] lang_codes = lang.split("\\+");
for (String code : lang_codes) {
File file = new File(currentDirectory, String.format(Constants.LANGUAGE_CODE, code));
if (!file.exists()) return false;
}
return true;
} else {
File language = new File(currentDirectory, String.format(Constants.LANGUAGE_CODE, lang));
return language.exists();
}
}
/**
* select the image when button is clicked
* using
*/
private void selectImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
/**
* Executed after onActivityResult or when used from shared menu
* <p>
* convert the image uri to bitmap
* call the appropriate AsyncTask based on Settings
*
* @param imageUri uri of selected image
*/
private void convertImageToText(Uri imageUri) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
crashUtils.logException(e);
}
mImageView.setImageURI(imageUri);
convertImageToTextTask = new ConvertImageToTextTask();
convertImageToTextTask.execute(bitmap);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SETTINGS) {
initializeOCR(null);
}
if (resultCode == RESULT_OK) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
if (isLanguageDataExists(mTrainingDataType, mLanguage)) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
convertImageToText(result.getUri());
} else initializeOCR(mLanguage);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (convertImageToTextTask != null && convertImageToTextTask.getStatus() == AsyncTask.Status.RUNNING) {
convertImageToTextTask.cancel(true);
}
if (downloadTrainingTask != null && downloadTrainingTask.getStatus() == AsyncTask.Status.RUNNING) {
downloadTrainingTask.cancel(true);
}
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
if (mProgressDialog != null) {
mProgressDialog.cancel();
mProgressDialog = null;
}
if (mImageTextReader != null) mImageTextReader.tearDownEverything();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem showHistoryItem = menu.findItem(R.id.action_history);
showHistoryItem.setVisible(Utils.isPersistData());
return true;
}
@Override
protected void onStop() {
super.onStop();
/*if (dialog != null) {
dialog.dismiss();
dialog = null;
}
if (mProgressDialog != null) {
mProgressDialog.cancel();
mProgressDialog = null;
}
if (convertImageToTextTask !=null && convertImageToTextTask.getStatus()== AsyncTask.Status.RUNNING){
convertImageToTextTask.cancel(true);
Log.d(TAG, "onDestroy: image processing canceled");
}
if (downloadTrainingTask !=null && downloadTrainingTask.getStatus()== AsyncTask.Status.RUNNING){
downloadTrainingTask.cancel(true);
}*/
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
startActivityForResult(new Intent(this, SettingsActivity.class), REQUEST_CODE_SETTINGS);
} else if (id == R.id.action_history) {
showOCRResult(Utils.getLastUsedText());
}
return super.onOptionsItemSelected(item);
}
@Override
public void onProgressValues(final TessBaseAPI.ProgressValues progressValues) {
runOnUiThread(() -> mProgressIndicator.setProgress((int) (progressValues.getPercent() * 1.46)));
}
public void saveBitmapToStorage(Bitmap bitmap) {
FileOutputStream fileOutputStream;
File dir;
File file;
try {
dir = CropFileProvider.filesDir(getApplicationContext());
file = new File(dir, "last_file.jpeg");
fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, fileOutputStream);
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
crashUtils.logException(e);
} catch (IOException e) {
e.printStackTrace();
crashUtils.logException(e);
}
}
public Bitmap loadBitmapFromStorage() {
Bitmap bitmap = null;
FileInputStream fileInputStream;
File dir;
File file;
try {
dir = CropFileProvider.filesDir(getApplicationContext());
file = new File(dir, "last_file.jpeg");
fileInputStream = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fileInputStream);
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
crashUtils.logException(e);
} catch (IOException e) {
e.printStackTrace();
crashUtils.logException(e);
}
return bitmap;
}
public void showOCRResult(String text) {
if (this.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
BottomSheetResultsFragment bottomSheetResultsFragment = BottomSheetResultsFragment.newInstance(text);
bottomSheetResultsFragment.show(getSupportFragmentManager(), "bottomSheetResultsFragment");
}
}
/**
* A Async Task to convert the image into text the return the text in String
*/
private class ConvertImageToTextTask extends AsyncTask<Bitmap, Void, String> {
@Override
protected String doInBackground(Bitmap... bitmaps) {
Bitmap bitmap = bitmaps[0];
if (!isRefresh && Utils.isPreProcessImage()) {
bitmap = Utils.preProcessBitmap(bitmap);
// bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * 1.5), (int) (bitmap.getHeight() * 1.5), true);
}
isRefresh = false;
saveBitmapToStorage(bitmap);
return mImageTextReader.getTextFromBitmap(bitmap);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressIndicator.setProgress(0);
mProgressIndicator.setVisibility(View.VISIBLE);
mImageView.animate()
.alpha(.2f)
.setDuration(450)
.start();
}
@Override
protected void onPostExecute(String text) {
mProgressIndicator.setVisibility(View.GONE);
mImageView.animate()
.alpha(1f)
.setDuration(450)
.start();
String clean_text = Html.fromHtml(text).toString().trim();
showOCRResult(clean_text);
Toast.makeText(MainActivity.this, "With Confidence:" + mImageTextReader.getAccuracy() + "%", Toast.LENGTH_SHORT).show();
Utils.putLastUsedText(clean_text);
Bitmap bitmap = loadBitmapFromStorage();
if (bitmap != null) {
mImageView.setImageBitmap(bitmap);
}
}
}
/**
* Download the training Data and save this to external storage
*/
private class DownloadTrainingTask extends AsyncTask<String, Integer, Boolean> {
String size;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setTitle(getString(R.string.downloading));
mProgressDialog.setMessage(getString(R.string.downloading_language));
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int percentage = values[0];
if (mProgressDialog != null) {
mProgressDialog.setMessage(percentage + getString(R.string.percentage_downloaded) + size);
mProgressDialog.show();
}
}
@Override
protected void onPostExecute(Boolean bool) {
if (mProgressDialog != null) {
mProgressDialog.cancel();
mProgressDialog = null;
}
initializeOCR(null);
}
@Override
protected Boolean doInBackground(String... languages) {
String dataType = languages[0];
String lang = languages[1];
boolean ret = true;
if (lang.contains("+")) {
String[] lang_codes = lang.split("\\+");
for (String code : lang_codes) {
if (!isLanguageDataExists(dataType, code)) {
ret &= downloadTraningData(dataType, code);
}
}
return ret;
} else {
return downloadTraningData(dataType, lang);
}
}
/**
* done the actual work of download
*
* @param dataType data type i.e best, fast, standard
* @param lang language
* @return true if success else false
*/
private boolean downloadTraningData(String dataType, String lang) {
boolean result = true;
String downloadURL;
String location;
switch (dataType) {
case "best":
downloadURL = String.format(Constants.TESSERACT_DATA_DOWNLOAD_URL_BEST, lang);
break;
case "standard":
downloadURL = String.format(Constants.TESSERACT_DATA_DOWNLOAD_URL_STANDARD, lang);
break;
default:
downloadURL = String.format(Constants.TESSERACT_DATA_DOWNLOAD_URL_FAST, lang);
}
URL url, base, next;
HttpURLConnection conn;
try {
while (true) {
try {
url = new URL(downloadURL);
} catch (java.net.MalformedURLException ex) {
crashUtils.logException(ex);
return false;
}
conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
switch (conn.getResponseCode()) {
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
location = conn.getHeaderField("Location");
base = new URL(downloadURL);
next = new URL(base, location); // Deal with relative URLs
downloadURL = next.toExternalForm();
continue;
}
break;
}
conn.connect();
int totalContentSize = conn.getContentLength();
size = Utils.getSize(totalContentSize);
InputStream input = new BufferedInputStream(url.openStream());
File destf = new File(currentDirectory, String.format(Constants.LANGUAGE_CODE, lang));
destf.createNewFile();
OutputStream output = new FileOutputStream(destf);
byte[] data = new byte[1024 * 6];
int count, downloaded = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
downloaded += count;
int percentage = (downloaded * 100) / totalContentSize;
publishProgress(percentage);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
result = false;
e.printStackTrace();
crashUtils.logException(e);
}
return result;
}
}
}