1010 warnings .warn ("Blob is not available in this environment" )
1111 js_Blob = None
1212
13+ try :
14+ import PIL .Image as PILImage
15+
16+ PILImageImage = PILImage .Image
17+ except ImportError :
18+ PILImage = None # type: ignore
19+ PILImageImage = None # type: ignore
20+
1321
1422def is_url (url : str ) -> bool :
1523 # Check if the URL is valid, covering all the possible schemes.
@@ -21,11 +29,11 @@ def is_url(url: str) -> bool:
2129 return False
2230
2331
24- def as_url (data_or_file_path : Union [str , bytes ]) -> str :
32+ def as_url (data_or_file_path : Union [str , bytes , PILImageImage ]) -> str :
2533 """For example, `pipeline('zero-shot-image-classification')`
2634 requires a URL of the input image file in the browser environment.
27- This function converts a file path on Pyodide's virtual file system
28- to a URL that can be used as the input of such pipelines.
35+ This function converts an input data or a input file path on Pyodide's virtual FS
36+ into a URL that can be used as the input of such pipelines.
2937
3038 Internally, Transformers.js reads the input with this code:
3139 https://github.com/xenova/transformers.js/blob/2.6.2/src/utils/image.js#L112-L113
@@ -40,6 +48,12 @@ def as_url(data_or_file_path: Union[str, bytes]) -> str:
4048 data = f .read ()
4149 elif isinstance (data_or_file_path , bytes ):
4250 data = data_or_file_path
51+ elif PILImage and isinstance (data_or_file_path , PILImage .Image ):
52+ import io
53+
54+ with io .BytesIO () as f :
55+ data_or_file_path .save (f , format = "PNG" )
56+ data = f .getvalue ()
4357 else :
4458 raise TypeError (
4559 "data_or_file_path must be str or bytes, "
0 commit comments