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> getAvailableData() async { var res = await _client.get( "https://git.mnau.xyz/api/v1/repos/hernik/tessdata_fast/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 = []; for (var file in data) { if (!file["name"].endsWith(".traineddata")) continue; dataFiles.add(file["name"].replaceAll(".traineddata", "")); } return dataFiles; } static Future deleteData(String name) async { var dataDir = Directory(await FlutterTesseractOcr.getTessdataPath()); if (!dataDir.existsSync()) { dataDir.createSync(); } var dataFile = File("${dataDir.path}/$name.traineddata"); if (!dataFile.existsSync()) return; dataFile.deleteSync(); } static Future> getDownloadedData() async { var tessDir = Directory(await FlutterTesseractOcr.getTessdataPath()); if (!tessDir.existsSync()) { tessDir.createSync(); } return tessDir .listSync() .where((element) => element.path.endsWith(".traineddata")) .map((e) => e.path.split("/").last) .toList(); } static Future downloadData(String isoCode, {void Function(int, int)? callback}) async { var tessDir = Directory(await FlutterTesseractOcr.getTessdataPath()); if (!tessDir.existsSync()) { tessDir.createSync(); } var file = File("${tessDir.path}/$isoCode.traineddata"); if (file.existsSync()) return; // TODO: maybe ask to redownload? var res = await _client.get( "https://git.mnau.xyz/hernik/tessdata_fast/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"); } } }