Created
May 21, 2023 12:15
-
-
Save itasyurt/e5db9e3f4da2e930a3024c33f1d60c2f to your computer and use it in GitHub Desktop.
OCRController 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.http.MediaType | |
import org.springframework.http.ResponseEntity | |
import org.springframework.validation.annotation.Validated | |
import org.springframework.web.bind.annotation.PostMapping | |
import org.springframework.web.bind.annotation.RequestBody | |
import org.springframework.web.bind.annotation.RequestMapping | |
import org.springframework.web.bind.annotation.RestController | |
import org.springframework.web.multipart.MultipartFile | |
import javax.validation.constraints.NotNull | |
@RestController | |
@RequestMapping("/api/ocr") | |
@Validated | |
class OCRController { | |
@Autowired | |
private lateinit var ocrService: OCRService | |
@PostMapping(consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) | |
fun ocr(@NotNull file: MultipartFile): ResponseEntity<String> { | |
val ocrOutput = ocrService.performOCR(file) | |
return ResponseEntity.ok(ocrOutput) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.cloud.vision.v1.AnnotateImageRequest | |
import com.google.cloud.vision.v1.Feature | |
import com.google.cloud.vision.v1.Image | |
import com.google.cloud.vision.v1.ImageAnnotatorClient | |
import com.google.cloud.vision.v1.ImageContext | |
import com.google.protobuf.ByteString | |
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.stereotype.Service | |
import org.springframework.web.multipart.MultipartFile | |
@Service | |
class OCRService { | |
@Autowired | |
private lateinit var imageAnnotatorClient: ImageAnnotatorClient | |
fun performOCR(file: MultipartFile): String { | |
val imageBytes = ByteString.copyFrom(file.bytes) | |
val image = Image.newBuilder().setContent(imageBytes).build() | |
val imageRequest = AnnotateImageRequest.newBuilder() | |
.addFeatures(Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION)) | |
.setImage(image) | |
.setImageContext(ImageContext.newBuilder().setLanguageHints("en").build()) | |
.build() | |
val response = imageAnnotatorClient.batchAnnotateImages(listOf(imageRequest)) | |
val annotation = response.responsesList[0].textAnnotationsList[0] | |
return annotation.description | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment