Skip to content

Commit 99cdf6d

Browse files
adbarAprilistic
andauthored
fix: numpy.float32 json dump error (#14)
Co-authored-by: Jinho Heo <[email protected]>
1 parent 0d673d7 commit 99cdf6d

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

py3langid/langid.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,15 @@ def rank_path(self, path):
284284
return path, retval
285285

286286

287+
class NumpyEncoder(json.JSONEncoder):
288+
""" Custom encoder for numpy data types """
289+
def default(self, obj):
290+
if isinstance(obj, np.float32):
291+
return float(obj) # Convert float32 to native float
292+
if isinstance(obj, np.ndarray):
293+
return obj.tolist() # Convert arrays to list
294+
return json.JSONEncoder.default(self, obj)
295+
287296
def application(environ, start_response):
288297
"""
289298
WSGI-compatible langid web service.
@@ -349,7 +358,7 @@ def application(environ, start_response):
349358

350359
headers = [('Content-type', 'text/javascript; charset=utf-8')] # HTTP Headers
351360
start_response(status, headers)
352-
return [json.dumps(response)]
361+
return [json.dumps(response, cls=NumpyEncoder).encode('utf-8')]
353362

354363

355364
def main():

0 commit comments

Comments
 (0)