Skip to content

Commit

Permalink
Change JSON serialization to custom json.dumps (#31100)
Browse files Browse the repository at this point in the history
* Change JSON serialization to custom json.dumps to prevent escaping of "<", ">", "&", "'"

* caller has control over the order, remove sort_key=True

* Move tojson into a proper function and expose a couple of other args

---------

Co-authored-by: jun.4 <[email protected]>
Co-authored-by: Matt <[email protected]>
  • Loading branch information
3 people authored Jun 12, 2024
1 parent 1c77b3d commit 17896f6
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/transformers/tokenization_utils_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1892,8 +1892,13 @@ def _compile_jinja_template(self, chat_template):
def raise_exception(message):
raise TemplateError(message)

def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
# We override the built-in tojson filter because Jinja's default filter escapes HTML characters
# We also expose some options like custom indents and separators
return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)

jinja_env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True)
jinja_env.policies["json.dumps_kwargs"]["ensure_ascii"] = False
jinja_env.filters["tojson"] = tojson
jinja_env.globals["raise_exception"] = raise_exception
return jinja_env.from_string(chat_template)

Expand Down

0 comments on commit 17896f6

Please sign in to comment.