File size: 2,354 Bytes
e49dc7d 8a8276e e49dc7d 86209be 26c91ca e49dc7d 1550120 47d7b51 1550120 47d7b51 1550120 47d7b51 1550120 47d7b51 e49dc7d af679a9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import torch
import re
from PIL import Image
from transformers import DonutProcessor, VisionEncoderDecoderModel
import io
import json
def model_fn(model_dir, context=None):
print("this is model_dir: ", model_dir)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
processor = DonutProcessor.from_pretrained(model_dir)
model = VisionEncoderDecoderModel.from_pretrained(model_dir)
model.to(device)
return model, processor, device
def input_fn(input_data, content_type, context=None):
"""Deserialize the input data."""
if content_type == 'application/x-image' or content_type == 'application/octet-stream':
image = Image.open(io.BytesIO(input_data))
return image
else:
raise ValueError(f"Unsupported content type: {content_type}")
def predict_fn(data, model_data, context=None):
"""Apply the model to the input data."""
model, processor, device = model_data
# Preprocess the image
pixel_values = processor(data, return_tensors="pt").pixel_values.to(device)
# Run inference
model.eval()
with torch.no_grad():
task_prompt = "<s_receipt>"
decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device)
generated_outputs = model.generate(
pixel_values,
decoder_input_ids=decoder_input_ids,
max_length=model.config.decoder.max_position_embeddings,
pad_token_id=processor.tokenizer.pad_token_id,
eos_token_id=processor.tokenizer.eos_token_id,
early_stopping=True,
bad_words_ids=[[processor.tokenizer.unk_token_id]],
return_dict_in_generate=True
)
# Decode the output
decoded_text = processor.batch_decode(generated_outputs.sequences)[0]
decoded_text = decoded_text.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
decoded_text = re.sub(r"<.*?>", "", decoded_text, count=1).strip()
prediction = {'result': decoded_text}
return prediction
def output_fn(prediction, accept):
"""Serialize the prediction output."""
if accept == 'application/json':
return json.dumps(prediction), 'application/json'
else:
raise ValueError(f"Unsupported response content type: {accept}") |