package info.selflearner.ocr.controller; import info.selflearner.ocr.util.Excel; import info.selflearner.ocr.util.OCR; import info.selflearner.ocr.model.Passport; import net.sourceforge.tess4j.TesseractException; import org.springframework.core.io.FileSystemResource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.io.*; import java.util.ArrayList; @Controller public class ApiController { @GetMapping("/") public String index(Model model) { String ocr = (String) model.asMap().get("ocr"); model.addAttribute("ocr", ocr); return "index"; } @PostMapping("/api/files") public String files(@RequestParam("files") MultipartFile[] files, String eng, String rus, String uzb, String uzb_cyrl, String documentType, RedirectAttributes redirectAttributes) throws IOException { ArrayList ocrResults = new ArrayList<>(); ArrayList passportArrayList = new ArrayList<>(); StringBuilder languages = new StringBuilder(); if ("other".equals(documentType)) { if (eng != null) languages.append(eng).append("+"); if (rus != null) languages.append(rus).append("+"); if (uzb != null) languages.append(uzb).append("+"); if (uzb_cyrl != null) languages.append(uzb_cyrl).append("+"); languages.deleteCharAt(languages.toString().length() - 1); } for (MultipartFile file : files) { File savedFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename()); savedFile.createNewFile(); try (InputStream inputStream = file.getInputStream(); OutputStream outputStream = new FileOutputStream(savedFile)) { int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } if ("other".equals(documentType)) { ocrResults.add(OCR.perform(savedFile, languages.toString())); } else if ("passport".equals(documentType)) { passportArrayList.add(OCR.performPassport(savedFile)); } } catch (IOException | TesseractException | InterruptedException exception) { throw new RuntimeException(exception); } } if ("other".equals(documentType)) { redirectAttributes.addFlashAttribute("ocrs", ocrResults); } else if ("passport".equals(documentType)) { redirectAttributes.addFlashAttribute("passports", passportArrayList); Excel.write(passportArrayList); } return "redirect:/"; } @GetMapping("/api/passport/excel") @ResponseBody public FileSystemResource downloadPassportExcel(@RequestParam(value = "filename") String filename) { return new FileSystemResource(new File(System.getProperty("java.io.tmpdir") + "/" + filename)); } }