File size: 4,228 Bytes
2a261b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install transformers --upgrade"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create Custom Handler for Inference Endpoints\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting handler.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile handler.py\n",
    "from typing import Dict, List, Any\n",
    "from transformers import DonutProcessor, VisionEncoderDecoderModel\n",
    "import torch\n",
    "\n",
    "\n",
    "# check for GPU\n",
    "device = 0 if torch.cuda.is_available() else -1\n",
    "\n",
    "\n",
    "class EndpointHandler:\n",
    "    def __init__(self, path=\"\"):\n",
    "        # load the model\n",
    "        self.processor = DonutProcessor.from_pretrained(path)\n",
    "        self.model = VisionEncoderDecoderModel.from_pretrained(path)\n",
    "        # move model to device\n",
    "        self.model.to(device)\n",
    "        self.decoder_input_ids = self.processor.tokenizer(\n",
    "            \"<s_cord-v2>\", add_special_tokens=False, return_tensors=\"pt\"\n",
    "        ).input_ids\n",
    "\n",
    "    def __call__(self, data: Any) -> List[List[Dict[str, float]]]:\n",
    "\n",
    "        inputs = data.pop(\"inputs\", data)\n",
    "\n",
    "\n",
    "        # preprocess the input\n",
    "        pixel_values = self.processor(inputs, return_tensors=\"pt\").pixel_values\n",
    "\n",
    "        # forward pass\n",
    "        outputs = self.model.generate(\n",
    "            pixel_values.to(device),\n",
    "            decoder_input_ids=self.decoder_input_ids.to(device),\n",
    "            max_length=self.model.decoder.config.max_position_embeddings,\n",
    "            early_stopping=True,\n",
    "            pad_token_id=self.processor.tokenizer.pad_token_id,\n",
    "            eos_token_id=self.processor.tokenizer.eos_token_id,\n",
    "            use_cache=True,\n",
    "            num_beams=1,\n",
    "            bad_words_ids=[[self.processor.tokenizer.unk_token_id]],\n",
    "            return_dict_in_generate=True,\n",
    "        )\n",
    "        # process output\n",
    "        prediction = self.processor.batch_decode(outputs.sequences)[0]\n",
    "        prediction = self.processor.token2json(prediction)\n",
    "\n",
    "        return prediction\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "test custom pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from handler import EndpointHandler\n",
    "\n",
    "my_handler = EndpointHandler(\".\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
      "To disable this warning, you can either:\n",
      "\t- Avoid using `tokenizers` before the fork if possible\n",
      "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
     ]
    }
   ],
   "source": [
    "from PIL import Image\n",
    "\n",
    "payload = {\"inputs\": Image.open(\"sample.png\").convert(\"RGB\")}\n",
    "\n",
    "my_handler(payload)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.13 ('dev': conda)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "f6dd96c16031089903d5a31ec148b80aeb0d39c32affb1a1080393235fbfa2fc"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}