Coverage for bioimageio/spec/generic/_v0_3_converter.py: 24%

42 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-02-05 13:53 +0000

1import collections.abc 

2import string 

3from pathlib import Path 

4 

5import imageio 

6from loguru import logger 

7 

8from .._internal.io import ( 

9 BioimageioYamlContent, 

10 extract_file_name, 

11 interprete_file_source, 

12) 

13from ._v0_2_converter import convert_from_older_format as convert_from_older_format_v0_2 

14 

15 

16def convert_from_older_format(data: BioimageioYamlContent) -> None: 

17 """convert raw RDF data of an older format where possible""" 

18 # check if we have future format version 

19 fv = data.get("format_version", "0.2.0") 

20 if ( 

21 not isinstance(fv, str) 

22 or fv.count(".") != 2 

23 or tuple(map(int, fv.split(".")[:2])) > (0, 3) 

24 ): 

25 return 

26 

27 convert_from_older_format_v0_2(data) 

28 

29 convert_attachments(data) 

30 convert_cover_images(data) 

31 

32 _ = data.pop("download_url", None) 

33 _ = data.pop("rdf_source", None) 

34 

35 if "name" in data and isinstance(data["name"], str): 

36 data["name"] = "".join( 

37 c if c in string.ascii_letters + string.digits + "_- ()" else " " 

38 for c in data["name"] 

39 )[:128] 

40 

41 data["format_version"] = "0.3.0" 

42 

43 

44def convert_attachments(data: BioimageioYamlContent) -> None: 

45 a = data.get("attachments") 

46 if isinstance(a, collections.abc.Mapping): 

47 data["attachments"] = tuple({"source": file} for file in a.get("files", [])) # type: ignore 

48 

49 

50def convert_cover_images(data: BioimageioYamlContent) -> None: 

51 covers = data.get("covers") 

52 if not isinstance(covers, list): 

53 return 

54 

55 for i in range(len(covers)): 

56 c = covers[i] 

57 if not isinstance(c, str): 

58 continue 

59 

60 src = interprete_file_source(c) 

61 fname = extract_file_name(src) 

62 

63 if not (fname.endswith(".tif") or fname.endswith(".tiff")): 

64 continue 

65 

66 try: 

67 image = imageio.imread(c) 

68 c_path = (Path(".bioimageio_converter_cache") / fname).with_suffix(".png") 

69 imageio.imwrite(c_path, image) 

70 covers[i] = str(c_path.absolute()) 

71 except Exception as e: 

72 logger.warning("failed to convert tif cover image: {}", e)