Skip to content

Instantly share code, notes, and snippets.

@itasyurt
Last active May 22, 2023 07:02
Show Gist options
  • Select an option

  • Save itasyurt/8f1105ea4d6b502def78a13ba9fa5239 to your computer and use it in GitHub Desktop.

Select an option

Save itasyurt/8f1105ea4d6b502def78a13ba9fa5239 to your computer and use it in GitHub Desktop.
OCRController 1
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.protobuf.ByteString
import org.springframework.beans.factory.annotation.Value
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.RequestMapping
import org.springframework.web.bind.annotation.RequestPart
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.FileInputStream
import javax.validation.constraints.NotNull
@RestController
@RequestMapping("/api/ocr")
@Validated
class OCRController {
@Value("\${google.cloud.credentials.path}")
private lateinit var credentialsPath: String
@PostMapping(consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
fun ocr(@NotNull @RequestPart("file") file: MultipartFile): ResponseEntity<String> {
val imageBytes = ByteString.copyFrom(file.bytes)
val image = Image.newBuilder().setContent(imageBytes).build()
val settings = ImageAnnotatorSettings.newBuilder()
.setCredentialsProvider { FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(FileInputStream(credentialsPath))) }
.build()
val imageAnnotatorClient = ImageAnnotatorClient.create(settings)
val imageRequest = AnnotateImageRequest.newBuilder()
.addFeatures(Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION))
.setImage(image)
.build()
val response = imageAnnotatorClient.batchAnnotateImages(listOf(imageRequest))
val annotation = response.responsesList[0].textAnnotationsList[0]
imageAnnotatorClient.close()
return ResponseEntity.ok(annotation.description)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment