prasule/lib/network/tessdata.dart
2023-09-08 11:50:21 +02:00

64 lines
2.3 KiB
Dart

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_tesseract_ocr/flutter_tesseract_ocr.dart';
import 'package:prasule/main.dart';
class TessdataApi {
static final Dio _client = Dio(
BaseOptions(
validateStatus: (status) => true,
),
);
static Future<List<String>> getAvailableData() async {
var res = await _client.get(
"https://git.mnau.xyz/api/v1/repos/hernik/tessdata_best/contents",
options: Options(headers: {"Accept": "application/json"}));
if ((res.statusCode ?? 500) > 399) {
return Future.error("The server returned status code ${res.statusCode}");
}
var data = res.data;
final dataFiles = <String>[];
for (var file in data) {
if (!file["name"].endsWith(".traineddata")) continue;
dataFiles.add(file["name"].replaceAll(".traineddata", ""));
}
return dataFiles;
}
static Future<void> deleteData(String name) async {
var dataDir = Directory(await FlutterTesseractOcr.getTessdataPath());
var dataFile = File("${dataDir.path}/$name.traineddata");
if (!dataFile.existsSync()) return;
dataFile.deleteSync();
}
static Future<List<String>> getDownloadedData() async =>
Directory(await FlutterTesseractOcr.getTessdataPath())
.listSync()
.where((element) => element.path.endsWith(".traineddata"))
.map<String>((e) => e.path.split("/").last)
.toList();
static Future<void> downloadData(String isoCode,
{void Function(int, int)? callback}) async {
var file = File(
"${(await FlutterTesseractOcr.getTessdataPath())}/$isoCode.traineddata");
if (file.existsSync()) return; // TODO: maybe ask to redownload?
var res = await _client.get(
"https://git.mnau.xyz/hernik/tessdata_best/raw/branch/main/$isoCode.traineddata",
options: Options(responseType: ResponseType.bytes),
onReceiveProgress: callback);
if ((res.statusCode ?? 500) > 399) {
return Future.error("The server returned status code ${res.statusCode}");
}
try {
var writefile = file.openSync(mode: FileMode.write);
writefile.writeFromSync(res.data);
writefile.closeSync();
} catch (e) {
logger.e(e);
return Future.error("Could not complete writing file");
}
}
}