Coverage for seqbank/dfam.py: 100.00%

49 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-27 04:47 +0000

1import gzip 

2from pathlib import Path 

3from types import ModuleType 

4from typing import Any 

5import tempfile 

6import shutil 

7 

8from .exceptions import SeqBankError 

9from .io import download_file 

10from .seqbank import SeqBank 

11 

12 

13def import_h5py() -> ModuleType: 

14 """ 

15 Imports h5py, which is only needed to read Dfam's HDF5 files. 

16 

17 Returns: 

18 ModuleType: The h5py module. 

19 

20 Raises: 

21 SeqBankError: If h5py is not installed. 

22 """ 

23 try: 

24 import h5py 

25 except ImportError as err: 

26 raise SeqBankError("Reading Dfam requires h5py. Install it with: pip install 'seqbank[dfam]'") from err 

27 return h5py 

28 

29 

30def dfam_url(curated: bool = True, release: str = "current") -> str: 

31 """ 

32 Constructs the URL for the Dfam database file. 

33 

34 Args: 

35 curated (bool, optional): If True, fetches the curated-only version of the Dfam database. Defaults to True. 

36 release (str, optional): The Dfam release version. Defaults to "current". 

37 

38 Returns: 

39 str: The URL for the Dfam HDF5 file. 

40 """ 

41 curated_str = "_curatedonly" if curated else "" 

42 url = f"https://www.dfam.org/releases/{release}/families/Dfam{curated_str}.h5.gz" 

43 return url 

44 

45 

46def add_dfam(seqbank: SeqBank, local_path: Path) -> None: 

47 """ 

48 Adds sequences from a local Dfam HDF5 file to the SeqBank. 

49 

50 Args: 

51 seqbank (SeqBank): The SeqBank instance to add sequences to. 

52 local_path (Path): The path to the local Dfam HDF5 file. 

53 """ 

54 h5py = import_h5py() 

55 file = h5py.File(local_path, "r") 

56 

57 def visitor_func(name: str, node: Any) -> None: 

58 if isinstance(node, h5py.Dataset): 

59 accession = node.attrs["accession"] 

60 seq = node.attrs["consensus"] 

61 seqbank.add(seq=seq, accession=accession) 

62 

63 file["Families/DF"].visititems(visitor_func) 

64 

65 

66def download_dfam(seqbank: SeqBank, curated: bool = True, release: str = "current", force: bool = False) -> bool: 

67 """ 

68 Downloads the Dfam HDF5 file, decompresses it, and adds sequences to the SeqBank. 

69 

70 Args: 

71 seqbank (SeqBank): The SeqBank instance to which the Dfam sequences will be added. 

72 curated (bool, optional): If True, fetches the curated-only version of the Dfam database. Defaults to True. 

73 release (str, optional): The Dfam release version. Defaults to "current". 

74 force (bool, optional): If True, forces the download even if the URL has been previously processed. Defaults to False. 

75 

76 Returns: 

77 bool: True if the download and addition were successful, False otherwise. 

78 

79 Raises: 

80 SeqBankError: If h5py is not installed. This is checked before downloading. 

81 """ 

82 import_h5py() 

83 url = dfam_url(curated, release) 

84 url_key = seqbank.key_url(url) 

85 

86 if url_key in seqbank.file and not force: 

87 print(f"Already downloaded: {url}") 

88 return False 

89 

90 with tempfile.TemporaryDirectory() as tmpdirname: 

91 local_gzip_path = Path(tmpdirname) / Path(url).name 

92 try: 

93 print(f"Downloading Dfam: {url}") 

94 download_file(url, local_gzip_path) 

95 

96 # Decompress the gzipped file 

97 local_path = local_gzip_path.with_suffix("") 

98 with gzip.open(local_gzip_path, "rb") as infile, open(local_path, "wb") as outfile: 

99 shutil.copyfileobj(infile, outfile) 

100 

101 # Add sequences to SeqBank 

102 add_dfam(seqbank, local_path) 

103 

104 # Mark URL as processed 

105 seqbank.save_seen_url(url) 

106 except Exception as err: 

107 print(f"Failed to add Dfam: {url}: {err}") 

108 return False 

109 

110 return True