defford
/

defford commited on
Commit
a170004
·
verified ·
1 Parent(s): e6022a2

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +20 -9
handler.py CHANGED
@@ -6,7 +6,8 @@ import base64
6
 
7
  class EndpointHandler():
8
  def __init__(self, path=""):
9
- # Use the specific GLM-OCR architecture
 
10
  self.processor = AutoProcessor.from_pretrained(path, trust_remote_code=True)
11
  self.model = AutoModelForVision2Seq.from_pretrained(
12
  path,
@@ -17,17 +18,27 @@ class EndpointHandler():
17
  self.model.eval()
18
 
19
  def __call__(self, data):
20
- # Decode the image sent from Google Sheets
21
- inputs = data.pop("inputs", data)
22
- image_data = base64.b64decode(inputs)
23
- image = Image.open(io.BytesIO(image_data)).convert("RGB")
24
 
25
- # Format for GLM-OCR
26
- prompt = "Identify Date, Vendor, and list every Item with description, qty, and price. Return as JSON."
27
- inputs = self.processor(text=prompt, images=image, return_tensors="pt").to(self.model.device)
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  with torch.no_grad():
30
- generated_ids = self.model.generate(**inputs, max_new_tokens=1024)
31
 
32
  result = self.processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
 
33
  return [{"generated_text": result}]
 
6
 
7
  class EndpointHandler():
8
  def __init__(self, path=""):
9
+ # We MUST use trust_remote_code=True because the architecture
10
+ # is defined in the files you downloaded, not in the library itself.
11
  self.processor = AutoProcessor.from_pretrained(path, trust_remote_code=True)
12
  self.model = AutoModelForVision2Seq.from_pretrained(
13
  path,
 
18
  self.model.eval()
19
 
20
  def __call__(self, data):
21
+ # Handle the input format from Google Sheets
22
+ inputs_data = data.pop("inputs", data)
 
 
23
 
24
+ # If the data comes in as a string (base64)
25
+ if isinstance(inputs_data, str):
26
+ image_bytes = base64.b64decode(inputs_data)
27
+ else:
28
+ # Handle direct bytes if necessary
29
+ image_bytes = inputs_data
30
+
31
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
32
+
33
+ # The prompt that tells the AI what to look for
34
+ prompt = "Extract all line items. Return a JSON array of objects with: date, vendor, description, qty, price, total."
35
+
36
+ # Process the image and text
37
+ model_inputs = self.processor(text=prompt, images=image, return_tensors="pt").to(self.model.device)
38
 
39
  with torch.no_grad():
40
+ generated_ids = self.model.generate(**model_inputs, max_new_tokens=1024)
41
 
42
  result = self.processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
43
+
44
  return [{"generated_text": result}]