Skip to content

deepseek-ocr: parse model output with ast.literal_eval - #594

Open
fjvbn2003 wants to merge 1 commit into
basetenlabs:mainfrom
fjvbn2003:ocr-literal-eval
Open

fjvbn2003 wants to merge 1 commit into
basetenlabs:mainfrom
fjvbn2003:ocr-literal-eval

Conversation

@fjvbn2003

@fjvbn2003 fjvbn2003 commented Oct 29, 2026 •

Copy link
Copy Markdown

What

In deepseek-ocr/, replace eval() with ast.literal_eval() where text produced by the model is parsed:

  • model/model.py: extract_coordinates_and_label
  • visualizer.py: extract_coordinates_and_label and the geometry (Line / Circle) parsing

It is imported as from ast import literal_eval so the longest changed line stays within ruff-format's 88 columns. No other changes.

Why

The model's output depends on the input document, so it is untrusted input, and model.py runs on the serving side. These spots only need lists, tuples, numbers and strings, which literal_eval parses without evaluating expressions. Text that isn't a literal now raises ValueError and takes the existing try/except path, as malformed coordinates already do.

Testing

No model or GPU needed. I loaded extract_coordinates_and_label (both files) and the DeepSeekOCRVisualizer class from the original and the patched files into a small script (Python 3.12, Pillow 12.3) and compared them:

  • [[10, 20, 30, 40]], [10, 20, 30, 40], several boxes, floats/negatives, tuples and non-list literals return the same values as before.
  • draw_bounding_boxes produces a byte-identical image.
  • Coordinate text containing a Python expression is not evaluated; extract_coordinates_and_label returns None through its existing except branch and that box is skipped.
  • A sample geometry dict parses to the same lines, endpoints and circles.

I did not deploy the Truss or run ruff locally (checked line lengths by hand).

Prepared with help from Claude (AI), including the local test described above.

model/model.py and visualizer.py parse the <|det|>[[x1, y1, x2, y2]]<|/det|>
coordinates, and visualizer.py also the geometry dict, with eval(). That
text is produced by the model and depends on the input document, so it
should be treated as untrusted. Only Python literals are needed, and
literal_eval() parses them without evaluating expressions.

Valid coordinates parse to the same values as before. Text that is not
a literal now raises ValueError and goes through the existing error
handling.

Assisted-by: Claude <[email protected]>
@CLAassistant

CLAassistant commented Oct 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants