abhishekgahlot commited on
Commit
244ab32
·
verified ·
1 Parent(s): bddaf1a

OpenJev 1.1: full card, figures, helper and licence files

Browse files
Files changed (1) hide show
  1. helper/compat.py +61 -23
helper/compat.py CHANGED
@@ -17,7 +17,7 @@ changes. Added here:
17
  connection on these).
18
  Run exactly like shim.py, from the same folder (or with PYTHONPATH=<the helper's folder>): VLLM=http://localhost:8000/v1 python compat.py --port 8765
19
  NOT YET CHECKED ON A GPU: the default-instruction prompt and the image mapping are shapes the model was neither trained nor measured on."""
20
- import argparse, base64, email, email.policy, gzip, io, json, os, time
21
 
22
  import shim as S
23
 
@@ -25,7 +25,7 @@ DEFAULT_INSTRUCTIONS = {"choice": "Which option is correct?", "score": "Rate the
25
  RELEASE_DATE = os.environ.get("SHIM_RELEASE_DATE") or time.strftime("%Y-%m-%d") # the hosted schema requires a date; ours is unknown to the server
26
  MAX_BODY = 32 * 1024 * 1024 # the hosted limit, for the body as sent and after decompression (docs.typesafe.ai/api/errors.md)
27
  WINDOW_LOG_MAX = 25 # zstd frames may ask for a window of at most 32 MiB, the largest a body within MAX_BODY needs
28
- MAX_PARTS, MAX_PART_HEADER = 2, 8192 # a multipart body is the JSON part and at most one image; each part's header block stays short
29
 
30
 
31
  class ApiError(Exception):
@@ -48,11 +48,25 @@ def zstd_reader(raw):
48
  return zstandard.ZstdDecompressor(max_window_size=1 << WINDOW_LOG_MAX).stream_reader(io.BytesIO(raw), read_across_frames=True)
49
 
50
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def inflate(raw, enc, limit=None):
52
- """one gzip or zstd layer → at most limit + 1 bytes (limit: MAX_BODY), read in 1 MiB steps: a bomb stops at the limit"""
53
  limit = MAX_BODY if limit is None else limit
 
 
54
  out, n = [], 0
55
- with zstd_reader(raw) if enc == "zstd" else gzip.GzipFile(fileobj=io.BytesIO(raw)) as reader:
56
  while n <= limit and (chunk := reader.read(min(1 << 20, limit + 1 - n))):
57
  out.append(chunk)
58
  n += len(chunk)
@@ -78,33 +92,55 @@ def decode(raw, encoding):
78
 
79
 
80
  def split_multipart(data, content_type):
81
- """multipart/form-data (RFC 7578) → (the first part, `request`, as JSON bytes; {name: bytes} of the other parts)"""
82
- check_parts(data, content_type)
83
- msg = email.message_from_bytes(b"Content-Type: " + content_type.encode("latin-1") + b"\r\n\r\n" + data, policy=email.policy.HTTP)
84
- parts = [(p.get_param("name", header="content-disposition"), p.get_payload(decode=True)) for p in msg.iter_parts()]
 
 
 
 
 
 
85
  names = [n for n, _ in parts]
86
  if not names or names[0] != "request" or not all(names) or len(set(names)) < len(names):
87
  raise ApiError(400, "a multipart body is the JSON as its first part, named request, then one uniquely named part per image")
88
- return parts[0][1] or b"", dict(parts[1:])
89
 
90
 
91
- def check_parts(data, content_type):
92
- """a linear pass before parsing: at most MAX_PARTS parts, each header block under MAX_PART_HEADER bytes"""
93
- boundary = email.message_from_bytes(b"Content-Type: " + content_type.encode("latin-1") + b"\r\n\r\n").get_param("boundary")
94
- if not boundary:
95
- raise ApiError(400, "a multipart body needs a boundary in its Content-Type")
96
- parts = data.split(b"--" + boundary.encode("latin-1"))[1:-1]
97
- if len(parts) > MAX_PARTS:
98
- raise ApiError(400, f"a multipart body has at most {MAX_PARTS} parts: the JSON and one image")
99
- if any(not 0 <= p.find(b"\r\n\r\n") <= MAX_PART_HEADER for p in parts):
100
- raise ApiError(400, f"each multipart part needs a header block under {MAX_PART_HEADER} bytes")
 
 
 
 
 
 
 
 
101
 
102
 
103
  def uses(v, ref):
104
- """how often `ref` occurs in the strings of v; object keys are not searched, as on the hosted API"""
105
- if isinstance(v, str):
106
- return v.count(ref)
107
- return sum(uses(x, ref) for x in (v.values() if isinstance(v, dict) else v)) if isinstance(v, (dict, list)) else 0
 
 
 
 
 
 
 
 
108
 
109
 
110
  def one_image(body, files):
@@ -187,6 +223,8 @@ class H(S.H):
187
  one_image(body, files)
188
  except ApiError as e:
189
  return self.fail(e.code, e.message)
 
 
190
  except ValueError as e:
191
  return self.fail(400, f"malformed JSON body: {str(e)[:120]}")
192
  self.model, qs = body.get("model"), body.get("questions")
 
17
  connection on these).
18
  Run exactly like shim.py, from the same folder (or with PYTHONPATH=<the helper's folder>): VLLM=http://localhost:8000/v1 python compat.py --port 8765
19
  NOT YET CHECKED ON A GPU: the default-instruction prompt and the image mapping are shapes the model was neither trained nor measured on."""
20
+ import argparse, base64, email.message, email.parser, email.policy, io, json, os, time, zlib
21
 
22
  import shim as S
23
 
 
25
  RELEASE_DATE = os.environ.get("SHIM_RELEASE_DATE") or time.strftime("%Y-%m-%d") # the hosted schema requires a date; ours is unknown to the server
26
  MAX_BODY = 32 * 1024 * 1024 # the hosted limit, for the body as sent and after decompression (docs.typesafe.ai/api/errors.md)
27
  WINDOW_LOG_MAX = 25 # zstd frames may ask for a window of at most 32 MiB, the largest a body within MAX_BODY needs
28
+ MAX_PARTS, MAX_PART_HEADER = 2, 8192 # a multipart body is the JSON part and at most one image; each part's header block, in bytes
29
 
30
 
31
  class ApiError(Exception):
 
48
  return zstandard.ZstdDecompressor(max_window_size=1 << WINDOW_LOG_MAX).stream_reader(io.BytesIO(raw), read_across_frames=True)
49
 
50
 
51
+ def gunzip(raw, limit):
52
+ """one gzip member → at most limit + 1 bytes. A second member is refused: members cost a Python loop each, and 32 MiB of empty
53
+ ones would keep the helper busy for half a minute (HTTP clients send one)"""
54
+ inflater = zlib.decompressobj(zlib.MAX_WBITS | 16) # gzip framing
55
+ data = inflater.decompress(raw, limit + 1)
56
+ if len(data) <= limit and not inflater.eof:
57
+ raise ValueError("truncated gzip stream")
58
+ if len(data) <= limit and inflater.unused_data:
59
+ raise ValueError("more than one gzip member")
60
+ return data
61
+
62
+
63
  def inflate(raw, enc, limit=None):
64
+ """one gzip or zstd layer → at most limit + 1 bytes (limit: MAX_BODY): a bomb stops at the limit"""
65
  limit = MAX_BODY if limit is None else limit
66
+ if enc != "zstd":
67
+ return gunzip(raw, limit)
68
  out, n = [], 0
69
+ with zstd_reader(raw) as reader:
70
  while n <= limit and (chunk := reader.read(min(1 << 20, limit + 1 - n))):
71
  out.append(chunk)
72
  n += len(chunk)
 
92
 
93
 
94
  def split_multipart(data, content_type):
95
+ """multipart/form-data (RFC 7578) → (the first part, `request`, as JSON bytes; {name: bytes} of the other parts). Parts are
96
+ counted and split on the boundary in linear time; only their header blocks, at most MAX_PART_HEADER bytes each, are parsed"""
97
+ delimiter = b"--" + multipart_boundary(content_type)
98
+ if data.count(delimiter) > MAX_PARTS + 1: # each part opens with the delimiter, and one more closes the body
99
+ raise ApiError(400, f"a multipart body has at most {MAX_PARTS} parts: the JSON and one image")
100
+ pieces = data.split(delimiter)[1:] # what comes before the first delimiter is a preamble
101
+ end = next((i for i, piece in enumerate(pieces) if piece.startswith(b"--")), None)
102
+ if end is None:
103
+ raise ApiError(400, "the multipart body does not end with its closing boundary")
104
+ parts = [read_part(piece) for piece in pieces[:end]]
105
  names = [n for n, _ in parts]
106
  if not names or names[0] != "request" or not all(names) or len(set(names)) < len(names):
107
  raise ApiError(400, "a multipart body is the JSON as its first part, named request, then one uniquely named part per image")
108
+ return parts[0][1], dict(parts[1:])
109
 
110
 
111
+ def multipart_boundary(content_type):
112
+ """the boundary of a multipart Content-Type: 1 to 70 characters (RFC 2046)"""
113
+ header = email.message.Message()
114
+ header["content-type"] = content_type
115
+ boundary = header.get_param("boundary")
116
+ if not isinstance(boundary, str) or not 0 < len(boundary) <= 70:
117
+ raise ApiError(400, "a multipart body needs a boundary of 1 to 70 characters in its Content-Type")
118
+ return boundary.encode("latin-1")
119
+
120
+
121
+ def read_part(piece):
122
+ """one part as it sits between two boundaries → (its form-data name, its content)"""
123
+ piece = piece.lstrip(b" \t") # transport padding after the boundary
124
+ end = piece.find(b"\r\n\r\n", 0, 2 + MAX_PART_HEADER + 4) # the blank line after the header block
125
+ if not piece.startswith(b"\r\n") or end < 0 or not piece.endswith(b"\r\n"):
126
+ raise ApiError(400, f"a multipart part is a line break, at most {MAX_PART_HEADER} bytes of headers, a blank line, its content and a line break")
127
+ headers = email.parser.BytesHeaderParser(policy=email.policy.HTTP).parsebytes(piece[2:end])
128
+ return headers.get_param("name", header="content-disposition"), piece[end + 4:-2]
129
 
130
 
131
  def uses(v, ref):
132
+ """how often `ref` occurs in the strings of v; object keys are not searched, as on the hosted API. Walked with a stack: the
133
+ JSON parser accepts nesting deeper than Python's recursion limit"""
134
+ count, todo = 0, [v]
135
+ while todo:
136
+ x = todo.pop()
137
+ if isinstance(x, str):
138
+ count += x.count(ref)
139
+ elif isinstance(x, dict):
140
+ todo.extend(x.values())
141
+ elif isinstance(x, list):
142
+ todo.extend(x)
143
+ return count
144
 
145
 
146
  def one_image(body, files):
 
223
  one_image(body, files)
224
  except ApiError as e:
225
  return self.fail(e.code, e.message)
226
+ except RecursionError:
227
+ return self.fail(400, "malformed JSON body: nested too deeply")
228
  except ValueError as e:
229
  return self.fail(400, f"malformed JSON body: {str(e)[:120]}")
230
  self.model, qs = body.get("model"), body.get("questions")