Create handler.py
Browse files- handler.py +21 -0
handler.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class PreTrainedPipeline():
|
| 6 |
+
def __init__(self, path=""):
|
| 7 |
+
self.processor = TrOCRProcessor.from_pretrained(path)
|
| 8 |
+
self.model = VisionEncoderDecoderModel.from_pretrained(path)
|
| 9 |
+
|
| 10 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 11 |
+
image = data.pop("inputs", data)
|
| 12 |
+
|
| 13 |
+
# process image
|
| 14 |
+
pixel_values = self.processor(images=image, return_tensors="pt").pixel_values
|
| 15 |
+
|
| 16 |
+
# run prediction
|
| 17 |
+
generated_ids = self.model.generate(pixel_values)
|
| 18 |
+
|
| 19 |
+
# decode output
|
| 20 |
+
prediction = generated_text = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 21 |
+
return {"text":prediction[0]}
|