meta-sam-parser 0.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ SAM License
2
+ Last Updated: November 19, 2025
3
+
4
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein.
5
+
6
+
7
+ “SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement.
8
+
9
+ “Documentation” means the specifications, manuals and documentation accompanying
10
+ SAM Materials distributed by Meta.
11
+
12
+
13
+ “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
14
+
15
+
16
+ “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
17
+
18
+
19
+ “Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom.
20
+
21
+
22
+ “Trade Controls” means any of the following: Sanctions and applicable export and import controls.
23
+
24
+ By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement.
25
+
26
+
27
+ 1. License Rights and Redistribution.
28
+
29
+
30
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials.
31
+
32
+ b. Redistribution and Use.
33
+ i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials.
34
+
35
+
36
+ ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication.
37
+
38
+
39
+ iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.
40
+ iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials.
41
+ v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons.
42
+ 2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
43
+
44
+
45
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS.
46
+
47
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
48
+
49
+ 5. Intellectual Property.
50
+
51
+
52
+ a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
53
+
54
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials.
55
+
56
+ 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
57
+
58
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
59
+
60
+
61
+ 8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
@@ -0,0 +1,394 @@
1
+ Metadata-Version: 2.4
2
+ Name: meta-sam-parser
3
+ Version: 0.0.2
4
+ Summary: Native Python parsing primitives for the SAM 3 segmentation protocol
5
+ Project-URL: Homepage, https://github.com/meta-models/meta-sam
6
+ Project-URL: Repository, https://github.com/meta-models/meta-sam
7
+ Project-URL: Issues, https://github.com/meta-models/meta-sam/issues
8
+ Author: Meta Platforms, Inc.
9
+ License: SAM License
10
+ Last Updated: November 19, 2025
11
+
12
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein.
13
+
14
+
15
+ “SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement.
16
+
17
+ “Documentation” means the specifications, manuals and documentation accompanying
18
+ SAM Materials distributed by Meta.
19
+
20
+
21
+ “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
22
+
23
+
24
+ “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
25
+
26
+
27
+ “Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom.
28
+
29
+
30
+ “Trade Controls” means any of the following: Sanctions and applicable export and import controls.
31
+
32
+ By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement.
33
+
34
+
35
+ 1. License Rights and Redistribution.
36
+
37
+
38
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials.
39
+
40
+ b. Redistribution and Use.
41
+ i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials.
42
+
43
+
44
+ ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication.
45
+
46
+
47
+ iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.
48
+ iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials.
49
+ v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons.
50
+ 2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
51
+
52
+
53
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS.
54
+
55
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
56
+
57
+ 5. Intellectual Property.
58
+
59
+
60
+ a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
61
+
62
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials.
63
+
64
+ 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
65
+
66
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
67
+
68
+
69
+ 8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
70
+ License-File: LICENSE
71
+ Classifier: Development Status :: 3 - Alpha
72
+ Classifier: Programming Language :: Python :: 3
73
+ Classifier: Programming Language :: Python :: 3.10
74
+ Classifier: Programming Language :: Python :: 3.11
75
+ Classifier: Programming Language :: Python :: 3.12
76
+ Classifier: Programming Language :: Python :: 3.13
77
+ Classifier: Programming Language :: Python :: 3.14
78
+ Classifier: Typing :: Typed
79
+ Requires-Python: >=3.10
80
+ Provides-Extra: dev
81
+ Requires-Dist: build==1.3.0; extra == 'dev'
82
+ Requires-Dist: hatchling==1.27.0; extra == 'dev'
83
+ Requires-Dist: jsonschema==4.25.1; extra == 'dev'
84
+ Requires-Dist: mypy==1.18.2; extra == 'dev'
85
+ Requires-Dist: pytest-cov==7.0.0; extra == 'dev'
86
+ Requires-Dist: pytest==9.0.3; extra == 'dev'
87
+ Requires-Dist: ruff==0.13.1; extra == 'dev'
88
+ Description-Content-Type: text/markdown
89
+
90
+ # meta-sam-parser
91
+
92
+ `meta-sam-parser` is the dependency-free native Python implementation of the
93
+ language-neutral SAM 3 segmentation protocol in the repository root. It provides
94
+ the strict complete-mask raster, COCO RLE, and SVG path conversions, incremental image/video line parser, and async
95
+ Responses API stream adapter.
96
+
97
+ ## Install and use
98
+
99
+ Install the package from this directory with any standard Python installer:
100
+
101
+ ```sh
102
+ python -m pip install .
103
+ ```
104
+
105
+ ## Direct parser API
106
+
107
+ Import supported APIs only from the package root. Deep imports are unsupported;
108
+ underscore-prefixed modules are implementation details and may change without notice.
109
+ Format factories are zero-argument and create isolated parser state:
110
+
111
+ ```python
112
+ from meta_sam_parser import CompletedOutcome, video_segmentation_format
113
+
114
+ format_ = video_segmentation_format()
115
+ parser = format_.create_parser()
116
+
117
+ for snapshot in parser.push(
118
+ "[frame=7] object=bus box=(10,20,110,80)\n"
119
+ "[frame=7] object=bus mask=one_bit;size=5x5;data=!!!!!(QO(0lu8?\n"
120
+ ):
121
+ print(snapshot.revision, len(snapshot.records))
122
+
123
+ finished = parser.finish(CompletedOutcome())
124
+ for snapshot in finished.events:
125
+ print(snapshot.revision, len(snapshot.records))
126
+ result = finished.result
127
+ ```
128
+
129
+ `push()` accepts arbitrarily split text chunks and returns zero or one cumulative
130
+ snapshot. `finish()` parses a final unterminated line and returns immutable final
131
+ events plus a result. Pass `IncompleteOutcome(reason="response", detail=...)` for
132
+ an explicitly incomplete response or `IncompleteOutcome(reason="eof")` when the
133
+ source ends without a terminal response event.
134
+
135
+ The same formats are normally passed to `parse_responses_stream()` so the adapter
136
+ can own lane validation, source cleanup, and terminal outcomes.
137
+
138
+ ## Responses API streams
139
+
140
+ `parse_responses_stream(source, format)` accepts an async iterable of official
141
+ OpenAI Python SDK event objects, mappings with the same wire fields, or a mixture
142
+ of both. It has no runtime dependency on the OpenAI SDK. Field names stay in the
143
+ SDK/wire snake-case form (`item_id`, `output_index`, and `content_index`).
144
+
145
+ ### Iterator-first
146
+
147
+ Use the parsed stream as both an async iterable and an async context manager. The
148
+ context manager is important when the loop may exit early because Python does not
149
+ implicitly call `aclose()` on arbitrary async iterators.
150
+
151
+ ```python
152
+ from meta_sam_parser import parse_responses_stream, video_segmentation_format
153
+
154
+ async def consume(response_events):
155
+ parsed = parse_responses_stream(response_events, video_segmentation_format())
156
+ async with parsed:
157
+ async for snapshot in parsed:
158
+ print(snapshot.revision, len(snapshot.records))
159
+
160
+ result = await parsed.final_result()
161
+ return result
162
+ ```
163
+
164
+ The first iterator request selects iterator mode. Calling `final_result()` selects
165
+ final-only mode synchronously, before its returned awaitable is awaited, so it
166
+ cannot race a later iterator claim. Pulls are serialized, snapshots are produced
167
+ on demand, and repeated `final_result()` calls await the same internal terminal
168
+ future. In iterator-first mode, requesting the final result does not consume the
169
+ remaining source: iteration must still reach completion. Exit early only through
170
+ `async with` or `aclose()`, which closes the source and makes the final result
171
+ raise `ResponsesStreamAbortedError`. Requesting another iterator raises
172
+ `ResponsesStreamConsumedError`.
173
+
174
+ ### Final-only
175
+
176
+ Calling `final_result()` before requesting an iterator selects final-only mode.
177
+ The adapter drains and parses the source while suppressing intermediate snapshots:
178
+
179
+ ```python
180
+ result = await parse_responses_stream(
181
+ response_events,
182
+ video_segmentation_format(),
183
+ ).final_result()
184
+ ```
185
+
186
+ ### Early exit
187
+
188
+ Leaving an async context before a terminal response closes a created upstream
189
+ iterator once and makes `final_result()` raise `ResponsesStreamAbortedError`:
190
+
191
+ ```python
192
+ parsed = parse_responses_stream(response_events, video_segmentation_format())
193
+ async with parsed:
194
+ async for snapshot in parsed:
195
+ if snapshot.records:
196
+ break
197
+
198
+ # Raises ResponsesStreamAbortedError.
199
+ await parsed.final_result()
200
+ ```
201
+
202
+ ### Explicit ownership
203
+
204
+ Code that does not use `async with` must close the parsed stream explicitly:
205
+
206
+ ```python
207
+ parsed = parse_responses_stream(response_events, video_segmentation_format())
208
+ try:
209
+ iterator = aiter(parsed)
210
+ first_snapshot = await anext(iterator)
211
+ use(first_snapshot)
212
+ finally:
213
+ await parsed.aclose()
214
+ ```
215
+
216
+ `aclose()` is idempotent and safe while a source read is pending: it cancels and
217
+ waits for that read before closing the source owner exactly once. Both synchronous
218
+ and asynchronous close methods are supported, including closing an unstarted
219
+ source that owns transport resources. Cancellation of a pull, `final_result()`, or
220
+ `aclose()` propagates `asyncio.CancelledError` unchanged; cleanup continues on a
221
+ best-effort basis, and a later `final_result()` reports
222
+ `ResponsesStreamAbortedError` unless source cleanup itself fails. Parser and source
223
+ failures are exception-chained through `__cause__`.
224
+
225
+ ## Immutable public model
226
+
227
+ All public values are frozen, slotted dataclasses. Observable collections are
228
+ tuples. The package root exports:
229
+
230
+ - Geometry, masks, and aliases: `FrameReference`, `SegmentationMaskBounds`,
231
+ `SegmentationMask`, `SegmentationMaskIdentity`, `SegmentationMedia`,
232
+ `DiagnosticSeverity`, and `IncompleteReason`.
233
+ - Records: `SegmentationTextRecord`, `SegmentationPointRecord`,
234
+ `SegmentationBoxRecord`, `SegmentationMaskRecord`, and `SegmentationRecord`.
235
+ - Views: `SegmentationDiagnostic`, `ImageSegmentationSnapshot`,
236
+ `VideoSegmentationSnapshot`, `SegmentationSnapshot`,
237
+ `ImageSegmentationResult`, `VideoSegmentationResult`, and
238
+ `SegmentationResult`.
239
+ - Outcomes and parser contracts: `CompletedOutcome`, `IncompleteOutcome`,
240
+ `ResponseStreamOutcome`, `ParserFinish`, `ResponseFormatParser`, and
241
+ `ResponseFormat`.
242
+ - Format factories: `image_segmentation_format` and
243
+ `video_segmentation_format`.
244
+ - Stream lifecycle: `ParsedResponsesStream`, `parse_responses_stream`,
245
+ `ResponsesEvent`, `ResponsesEventLike`, `OutputTextLane`, and
246
+ `ResponseSourceOperation`.
247
+ - Errors: `ResponsesStreamError`, `ResponsesStreamConsumedError`,
248
+ `ResponsesStreamAbortedError`, `ResponsesStreamFailedError`,
249
+ `ResponsesStreamEventError`, `ResponsesStreamLaneError`,
250
+ `ResponsesStreamRefusalError`, `ResponsesStreamParserError`,
251
+ `ResponsesStreamSourceError` and `InvalidSegmentationMaskError`.
252
+ - Conversions: `decode_mask_to_raster`, `decode_mask_to_rle`,
253
+ `decode_mask_to_svg_path`, and the frozen, slotted `RLEObject`.
254
+
255
+ Fields use snake case. A mask identity is the immutable tuple of media,
256
+ `frame_index`, and `object_id`; each later accepted mask for that identity gets
257
+ the next revision.
258
+
259
+ ## Parsing behavior
260
+
261
+ The documented package grammar is the line form in the
262
+ [SAM 3 protocol](https://github.com/meta-models/meta-sam/blob/main/protocol/sam3.md).
263
+ The parser separately accepts compact box-first SAM API output as production
264
+ compatibility input and normalizes it to the same records. Its object token is an
265
+ ASCII-decimal ID retained as a string, and IDs may be multi-digit or non-contiguous.
266
+ The compact input's inclusive `x2`/`y2` coordinates become half-open `right`/`bottom`
267
+ bounds. Image API
268
+ records require frame zero and omit it from normalized records; video records retain
269
+ frame indices. Every mask is strictly decoded before insertion.
270
+
271
+ Plain text remains an ordered text record. Malformed structured-looking lines
272
+ produce diagnostics and parsing continues. `raw_output` preserves every input
273
+ character exactly. Newline, CRLF, blank-line, and final unterminated-line behavior
274
+ matches the TypeScript parser. JavaScript safe-integer, ASCII token grammar, and
275
+ observable numeric parsing boundaries are preserved explicitly.
276
+
277
+ ## Mask conversion
278
+
279
+ `decode_mask_to_raster()` strictly validates a complete `one_bit` or `lossless`
280
+ payload and returns immutable row-major `bytes` containing only `0` and `1`.
281
+ `decode_mask_to_rle()` returns exact COCO compressed RLE with `(height, width)`
282
+ size after transposing that raster to COCO column-major order.
283
+ `decode_mask_to_svg_path()` returns the polygonal `M`/`L`/`Z` path,
284
+ including multiple subpaths where needed, and returns `""` for an empty mask.
285
+ Structural checks cover supported encodings, positive JavaScript-safe dimensions
286
+ and area, packed payload shape and alphabet, prefixes, groups, tails, finalization,
287
+ and exact decoded length; the decoder imposes no project-defined area or payload
288
+ quota ceiling. Non-memory decoding failures are wrapped as
289
+ `InvalidSegmentationMaskError` with their cause, while `MemoryError` propagates
290
+ unchanged:
291
+
292
+ ```python
293
+ from meta_sam_parser import (
294
+ SegmentationMask,
295
+ decode_mask_to_raster,
296
+ decode_mask_to_rle,
297
+ decode_mask_to_svg_path,
298
+ )
299
+
300
+ mask = SegmentationMask(
301
+ encoding="one_bit",
302
+ payload="!!!!!(QO(0lu8?",
303
+ width=5,
304
+ height=5,
305
+ )
306
+ raster = decode_mask_to_raster(mask)
307
+ coco_rle = decode_mask_to_rle(mask)
308
+ svg_path = decode_mask_to_svg_path(mask)
309
+ ```
310
+
311
+ `raster` is immutable `bytes` in row-major order and contains only `0` and `1`.
312
+ `one_bit` payloads must pass a unique canonical round trip. `lossless` payloads
313
+ must use the strict packed envelope and contain enough arithmetic-coder
314
+ finalization to decode the declared raster, but they are not uniqueness-
315
+ canonicalized: trailing packed bytes and alternate unused finalization bytes may
316
+ encode the same raster and are accepted. The package does not expose a lossless
317
+ encoder or promise a canonical lossless spelling. Deep imports are implementation
318
+ details and are not supported.
319
+
320
+ ## Python support
321
+
322
+ The declared range is CPython 3.10 and newer. Python 3.10 is the floor because
323
+ the public immutable types use standard-library slotted dataclasses and the
324
+ codebase uses Python 3.10 type syntax. There is no upper bound because the
325
+ runtime is pure Python, has no dependencies, and does not use CPython internals.
326
+ CI exercises Python 3.10 through 3.14.
327
+
328
+ ## Development
329
+
330
+ Create and activate a virtual environment, then install the pinned development
331
+ toolchain:
332
+
333
+ ```sh
334
+ python -m pip install -e '.[dev]'
335
+ python -m ruff format --check .
336
+ python -m ruff check .
337
+ python -m mypy
338
+ python -m pytest
339
+ python scripts/build_artifacts.py
340
+ python scripts/audit_distribution.py
341
+ ```
342
+
343
+ The package audit verifies exact wheel and sdist allowlists, metadata, the typed
344
+ root API, archive safety, reproducible bytes, and isolated wheel and sdist
345
+ consumers. Each consumer runs `pip check`, runtime lifecycle cases, and strict
346
+ static typing against the installed distribution. The wheel consumer also
347
+ installs the official OpenAI Python SDK version pinned in
348
+ `requirements-openai.txt`, statically accepts `AsyncStream[ResponseStreamEvent]`,
349
+ and passes its attribute-object events through the installed parser while verifying
350
+ transport cleanup. OpenAI is a test-only consumer dependency and is not a runtime
351
+ package dependency.
352
+
353
+ ## Releasing
354
+
355
+ `meta-sam-parser` is published to [PyPI](https://pypi.org/project/meta-sam-parser/)
356
+ by the `release PyPI distribution` workflow
357
+ (`.github/workflows/release-pypi.yml`). A release is one commit and one tag:
358
+
359
+ 1. Bump `version` in `pyproject.toml`, run `node scripts/sync-compatibility` from
360
+ the repository root so the compatibility matrix records the new version, and
361
+ merge that change to `main`.
362
+ 2. Push the tag `meta-sam-parser@<version>` at that commit. The workflow refuses a
363
+ tag that does not match the manifest version.
364
+ 3. The workflow builds the reproducible wheel and sdist, runs the artifact and
365
+ clean-consumer audits and the cross-language conformance suite, and then waits
366
+ for approval in the `pypi` GitHub environment before uploading through PyPI
367
+ trusted publishing (OIDC) with attestations. No PyPI credential is stored in the
368
+ repository. It then creates the GitHub release for the tag.
369
+
370
+ A manual dispatch from `main` rehearses the same build and audits against
371
+ TestPyPI from the `testpypi` environment and never publishes to PyPI.
372
+
373
+ Build and audit the same artifacts locally from `python/`:
374
+
375
+ ```sh
376
+ python -m pip install -e '.[dev]'
377
+ python scripts/build_artifacts.py
378
+ python scripts/audit_distribution.py
379
+ ```
380
+
381
+ The build command replaces `dist/` with exactly one wheel and one sdist for the
382
+ version declared in `pyproject.toml`. The audit must pass against those exact
383
+ files; it does not upload, publish, or read credentials.
384
+
385
+ The Python conformance tests execute all 29 shared cases through
386
+ `parse_responses_stream()`, including stream lifecycle failures, completed and
387
+ incomplete outcomes, diagnostics, and masks. From the repository root, `node
388
+ scripts/validate-conformance` runs the same exact normalized cases in both
389
+ languages, while `node scripts/validate` runs complete validation and builds both
390
+ distributions.
391
+
392
+ ## License
393
+
394
+ `meta-sam-parser` is licensed under the [SAM License](LICENSE).