Alfonso Velasco commited on
Commit
f007bd6
·
1 Parent(s): c8bd4a2
Files changed (2) hide show
  1. handler.py +84 -16
  2. requirements.txt +1 -0
handler.py CHANGED
@@ -4,6 +4,8 @@ import torch
4
  from PIL import Image
5
  import io
6
  import base64
 
 
7
 
8
  class EndpointHandler():
9
  def __init__(self, path=""):
@@ -19,20 +21,8 @@ class EndpointHandler():
19
  self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
  self.model.to(self.device)
21
 
22
- def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
23
- inputs = data.pop("inputs", data)
24
-
25
- if isinstance(inputs, dict):
26
- image_data = inputs.get("image", inputs.get("inputs", ""))
27
- else:
28
- image_data = inputs
29
-
30
- if "base64," in image_data:
31
- image_data = image_data.split("base64,")[1]
32
-
33
- image_bytes = base64.b64decode(image_data)
34
- image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
35
-
36
  encoding = self.processor(
37
  image,
38
  truncation=True,
@@ -54,7 +44,85 @@ class EndpointHandler():
54
  if token not in ['[CLS]', '[SEP]', '[PAD]']:
55
  results.append({
56
  "text": token,
57
- "bbox": {"x": box[0], "y": box[1], "width": box[2] - box[0], "height": box[3] - box[1]}
 
 
 
 
 
58
  })
59
 
60
- return {"extractions": results}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  from PIL import Image
5
  import io
6
  import base64
7
+ import fitz # PyMuPDF
8
+ import tempfile
9
 
10
  class EndpointHandler():
11
  def __init__(self, path=""):
 
21
  self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
22
  self.model.to(self.device)
23
 
24
+ def process_image(self, image):
25
+ """Process a single image and return extractions"""
 
 
 
 
 
 
 
 
 
 
 
 
26
  encoding = self.processor(
27
  image,
28
  truncation=True,
 
44
  if token not in ['[CLS]', '[SEP]', '[PAD]']:
45
  results.append({
46
  "text": token,
47
+ "bbox": {
48
+ "x": box[0],
49
+ "y": box[1],
50
+ "width": box[2] - box[0],
51
+ "height": box[3] - box[1]
52
+ }
53
  })
54
 
55
+ return results
56
+
57
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
58
+ inputs = data.pop("inputs", data)
59
+
60
+ # Handle different input formats
61
+ if isinstance(inputs, dict):
62
+ # Check if it's a PDF
63
+ if "pdf" in inputs:
64
+ file_data = inputs["pdf"]
65
+ else:
66
+ file_data = inputs.get("image", inputs.get("inputs", ""))
67
+ else:
68
+ file_data = inputs
69
+
70
+ # Remove base64 prefix if present
71
+ if isinstance(file_data, str) and "base64," in file_data:
72
+ file_data = file_data.split("base64,")[1]
73
+
74
+ # Decode base64
75
+ file_bytes = base64.b64decode(file_data)
76
+
77
+ # Check if it's a PDF or image
78
+ if file_bytes.startswith(b'%PDF'):
79
+ # Process PDF
80
+ all_results = []
81
+
82
+ # Save PDF to temporary file
83
+ with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as tmp_file:
84
+ tmp_file.write(file_bytes)
85
+ tmp_file.flush()
86
+
87
+ # Open with PyMuPDF
88
+ pdf_document = fitz.open(tmp_file.name)
89
+
90
+ # Process each page
91
+ for page_num in range(len(pdf_document)):
92
+ page = pdf_document[page_num]
93
+
94
+ # Convert page to image (PIL format)
95
+ mat = fitz.Matrix(2.0, 2.0) # 2x scaling for better quality
96
+ pix = page.get_pixmap(matrix=mat)
97
+ img_data = pix.tobytes("png")
98
+ image = Image.open(io.BytesIO(img_data)).convert("RGB")
99
+
100
+ # Process the page
101
+ page_results = self.process_image(image)
102
+
103
+ # Add page context to results
104
+ all_results.append({
105
+ "page": page_num + 1,
106
+ "page_width": page.rect.width,
107
+ "page_height": page.rect.height,
108
+ "extractions": page_results
109
+ })
110
+
111
+ pdf_document.close()
112
+
113
+ # Return all pages' results
114
+ return {
115
+ "document_type": "pdf",
116
+ "total_pages": len(all_results),
117
+ "pages": all_results
118
+ }
119
+
120
+ else:
121
+ # Process as image
122
+ image = Image.open(io.BytesIO(file_bytes)).convert("RGB")
123
+ results = self.process_image(image)
124
+
125
+ return {
126
+ "document_type": "image",
127
+ "extractions": results
128
+ }
requirements.txt CHANGED
@@ -2,3 +2,4 @@ transformers>=4.35.0
2
  torch>=2.0.0
3
  pillow>=9.0.0
4
  pytesseract>=0.3.10
 
 
2
  torch>=2.0.0
3
  pillow>=9.0.0
4
  pytesseract>=0.3.10
5
+ PyMuPDF>=1.23.0