Coverage for seqbank/io.py: 100.00%

62 statements  

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

1from pathlib import Path 

2import gzip 

3import bz2 

4from Bio import SeqIO 

5import requests 

6import tempfile 

7from typing import Any, TextIO 

8 

9 

10def open_path(path: Path | str) -> TextIO: 

11 """ 

12 Opens a file, optionally decompressing it based on its extension. 

13 

14 Args: 

15 path (Path | str): The path to the file, which can be a compressed (.gz, .bz2) or uncompressed file. 

16 

17 Returns: 

18 file object: A file object opened for reading. 

19 

20 Raises: 

21 ValueError: If the file has an unsupported compression extension. 

22 """ 

23 path = Path(path) 

24 suffix = path.suffix.lower() 

25 

26 if suffix == ".gz": 

27 return gzip.open(path, "rt") 

28 

29 if suffix == ".bz2": 

30 return bz2.open(path, "rt") 

31 

32 return open(path, "rt") 

33 

34 

35def get_file_format(path: Path | str) -> str: 

36 """ 

37 Determines the sequence file format based on the file extension. 

38 

39 Supported file formats and their extensions: 

40 - FASTA: .fa, .fna, .fasta 

41 - GenBank: .genbank, .gb, .gbk 

42 - EMBL: .embl 

43 - Tab-delimited: .tab, .tsv 

44 - Nexus: .nexus, .nxs 

45 - FASTQ: .fastq, .fq 

46 

47 Args: 

48 path (Path | str): The path to the file. 

49 

50 Returns: 

51 str: The detected file format (e.g., 'fasta', 'genbank', 'embl', etc.). 

52 

53 Raises: 

54 ValueError: If the file format cannot be determined. 

55 """ 

56 path = Path(path) 

57 suffix = path.suffix.lower() 

58 

59 if suffix in [".gz", ".bz2"]: 

60 suffix = path.suffixes[-2].lower() 

61 

62 if suffix in [".fa", ".fna", ".fasta"]: 

63 return "fasta" 

64 

65 if suffix in [".genbank", ".gb", ".gbk"]: 

66 return "genbank" 

67 

68 if suffix in [".embl"]: 

69 return "embl" 

70 

71 if suffix in [".tab", ".tsv"]: 

72 return "tab" 

73 

74 if suffix in [".nexus", ".nxs"]: 

75 return "nexus" 

76 

77 if suffix in [".fastq", ".fq"]: 

78 return "fastq" 

79 

80 raise ValueError(f"Cannot determine file format of {path}.") 

81 

82 

83def seq_count(path: Path | str) -> int: 

84 """ 

85 Counts the number of sequences in a file. 

86 

87 Args: 

88 path (Path | str): The path to the file. 

89 

90 Returns: 

91 int: The total number of sequences in the file. 

92 """ 

93 file_format = get_file_format(path) 

94 with open_path(path) as f: 

95 total = sum(1 for _ in SeqIO.parse(f, file_format)) 

96 return total 

97 

98 

99def download_file(url: str, local_path: Path) -> Path: 

100 """ 

101 Downloads a file from a URL and saves it to a specified local path. 

102 

103 Args: 

104 url (str): The URL of the file to download. 

105 local_path (Path): The path where the file should be saved. 

106 

107 Returns: 

108 Path: The path to the downloaded file. 

109 

110 Raises: 

111 requests.exceptions.HTTPError: If the download fails. 

112 """ 

113 with requests.get(url, stream=True) as r: 

114 r.raise_for_status() 

115 with open(local_path, "wb") as f: 

116 for chunk in r.iter_content(chunk_size=8192): 

117 f.write(chunk) 

118 return local_path 

119 

120 

121class TemporaryDirectory(tempfile.TemporaryDirectory): 

122 """ 

123 A custom TemporaryDirectory class that can optionally create a parent directory if a prefix is provided. 

124 

125 Args: 

126 prefix (str | Path | None): Optional prefix for the temporary directory. 

127 """ 

128 

129 def __init__(self, prefix: str | Path | None = None, *args: Any, **kwargs: Any) -> None: 

130 self._created_dirs: list[Path] = [] # Track directories that were created 

131 if isinstance(prefix, Path): 

132 # Resolve path to string and ensure parent directories are created 

133 prefix.mkdir(parents=True, exist_ok=True) 

134 self._created_dirs.append(prefix) # Track created parent directories 

135 

136 # Ensure prefix ends with a "/" 

137 prefix = str(prefix.resolve().absolute()) 

138 if not prefix.endswith("/"): 

139 prefix += "/" 

140 

141 super().__init__(prefix=prefix, *args, **kwargs) # type: ignore[call-overload] 

142 

143 def cleanup(self) -> None: 

144 """ 

145 Cleans up the temporary directory and removes any created parent directories if they are empty. 

146 """ 

147 super().cleanup() 

148 for created_dir in self._created_dirs: 

149 if not any(created_dir.iterdir()): # Only remove if the directory is empty 

150 created_dir.rmdir() 

151 

152 def __enter__(self) -> Path: 

153 """ 

154 Enters the context of the temporary directory. 

155 

156 Returns: 

157 Path: The path to the temporary directory. 

158 """ 

159 return Path(super().__enter__())