Coverage for geoparser/gazetteer/build/stages/acquire.py: 100%

102 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 18:08 +0000

1""" 

2Acquisition of gazetteer source files. 

3 

4Handles downloading remote files (with size-based caching), validating local 

5paths, extracting ZIP archives and locating the target file within extracted 

6contents or directories. 

7""" 

8 

9import shutil 

10import zipfile 

11from pathlib import Path 

12from typing import Optional 

13 

14import requests 

15 

16from geoparser.gazetteer.build.progress import advance, item 

17from geoparser.gazetteer.build.schema import SourceConfig 

18 

19# Network request timeout in seconds 

20REQUEST_TIMEOUT = 30 

21 

22# Download chunk size in bytes (8KB) 

23DOWNLOAD_CHUNK_SIZE = 8192 

24 

25 

26class Acquirer: 

27 """ 

28 Downloads and extracts gazetteer source files. 

29 

30 Remote files are cached in the downloads directory and skipped when the 

31 local copy matches the remote size. ZIP archives are extracted next to 

32 the archive, with extraction skipped when contents are up to date. Each 

33 download or extraction that actually runs shows its own item bar and 

34 advances the active stage (see :mod:`progress`) once it finishes; a 

35 cached, unzipped local file shows neither and advances nothing. 

36 """ 

37 

38 def __init__(self, downloads_directory: Path): 

39 """ 

40 Initialize the acquirer. 

41 

42 Args: 

43 downloads_directory: Directory to store downloaded files 

44 """ 

45 self.downloads_directory = downloads_directory 

46 self.downloads_directory.mkdir(parents=True, exist_ok=True) 

47 

48 def acquire(self, source_config: SourceConfig) -> Path: 

49 """ 

50 Resolve the data file for a source, downloading and extracting as needed. 

51 

52 Args: 

53 source_config: Source configuration 

54 

55 Returns: 

56 Path to the source's target file 

57 """ 

58 source_path = self._resolve_source_path(source_config) 

59 return self._resolve_file_path(source_config, source_path) 

60 

61 def cleanup(self) -> None: 

62 """Remove all downloaded files and extracted contents.""" 

63 if self.downloads_directory.exists(): 

64 shutil.rmtree(self.downloads_directory) 

65 

66 def _resolve_source_path(self, source_config: SourceConfig) -> Path: 

67 """Download the source's file or validate its local path.""" 

68 if source_config.url: 

69 return self._download_file(source_config.url) 

70 local_path = Path(source_config.path) 

71 if not local_path.exists(): 

72 raise FileNotFoundError(f"Local path does not exist: {local_path}") 

73 return local_path 

74 

75 def _download_file(self, url: str) -> Path: 

76 """Download a file unless a matching local copy already exists.""" 

77 download_path = self.downloads_directory / Path(url).name 

78 if self._should_skip_download(url, download_path): 

79 return download_path 

80 return self._stream_download(url, download_path) 

81 

82 def _should_skip_download(self, url: str, local_path: Path) -> bool: 

83 """Check if downloading can be skipped by comparing file sizes.""" 

84 if not local_path.exists(): 

85 return False 

86 try: 

87 response = requests.head(url, timeout=REQUEST_TIMEOUT) 

88 remote_size = int(response.headers.get("content-length", 0)) 

89 local_size = local_path.stat().st_size 

90 return remote_size == local_size and remote_size != 0 

91 except (requests.RequestException, ValueError): 

92 # If the HEAD request fails, proceed with the download 

93 return False 

94 

95 def _stream_download(self, url: str, download_path: Path) -> Path: 

96 """Stream a file download with progress tracking.""" 

97 with requests.get(url, stream=True, timeout=REQUEST_TIMEOUT) as response: 

98 response.raise_for_status() 

99 total_size = int(response.headers.get("content-length", 0)) 

100 

101 with open(download_path, "wb") as output_file: 

102 with item( 

103 f"Downloading {download_path.name}", total=total_size or None 

104 ) as progress_bar: 

105 for chunk in response.iter_content(chunk_size=DOWNLOAD_CHUNK_SIZE): 

106 if chunk: 

107 output_file.write(chunk) 

108 progress_bar.update(len(chunk)) 

109 advance() 

110 

111 return download_path 

112 

113 def _resolve_file_path( 

114 self, source_config: SourceConfig, source_path: Path 

115 ) -> Path: 

116 """ 

117 Locate the target file from a source path. 

118 

119 Handles directories (recursive search), ZIP archives (extraction) and 

120 raw files (name check). 

121 """ 

122 target_filename = source_config.file 

123 

124 if source_path.is_dir(): 

125 return self._find_target_file(source_path, target_filename) 

126 

127 if not zipfile.is_zipfile(source_path): 

128 if source_path.name == target_filename: 

129 return source_path 

130 raise FileNotFoundError( 

131 f"Source '{source_config.name}': file '{target_filename}' not " 

132 f"found at {source_path}" 

133 ) 

134 

135 extraction_dir = source_path.parent / source_path.stem 

136 if self._should_skip_extraction(source_path, extraction_dir, target_filename): 

137 return self._find_target_file(extraction_dir, target_filename) 

138 return self._extract_zip(source_path, extraction_dir, target_filename) 

139 

140 def _should_skip_extraction( 

141 self, archive_path: Path, extraction_dir: Path, target_filename: str 

142 ) -> bool: 

143 """Check if a previous extraction is still up to date.""" 

144 if not extraction_dir.exists(): 

145 return False 

146 

147 # Local directories are already in their final form 

148 if not archive_path.is_file(): 

149 return True 

150 

151 if extraction_dir.name == target_filename: 

152 if archive_path.stat().st_mtime <= extraction_dir.stat().st_mtime: 

153 return True 

154 

155 target_path = self._find_target_file_quiet(extraction_dir, target_filename) 

156 if target_path: 

157 if archive_path.stat().st_mtime <= target_path.stat().st_mtime: 

158 return True 

159 

160 return False 

161 

162 def _extract_zip( 

163 self, archive_path: Path, extraction_dir: Path, target_filename: str 

164 ) -> Path: 

165 """Extract a ZIP archive and locate the target file.""" 

166 if extraction_dir.exists(): 

167 shutil.rmtree(extraction_dir) 

168 extraction_dir.mkdir(exist_ok=True) 

169 

170 with zipfile.ZipFile(archive_path, "r") as zip_ref: 

171 total_size = sum(info.file_size for info in zip_ref.infolist()) 

172 with item( 

173 f"Unpacking {archive_path.name}", total=total_size or None 

174 ) as progress_bar: 

175 for zip_info in zip_ref.infolist(): 

176 zip_ref.extract(zip_info, path=extraction_dir) 

177 progress_bar.update(zip_info.file_size) 

178 advance() 

179 

180 if extraction_dir.name == target_filename: 

181 return extraction_dir 

182 return self._find_target_file(extraction_dir, target_filename) 

183 

184 def _find_target_file(self, directory: Path, filename: str) -> Path: 

185 """Find a file by name in a directory tree.""" 

186 for path in directory.glob("**/*"): 

187 if path.name == filename: 

188 return path 

189 raise FileNotFoundError(f"File '{filename}' not found in {directory}") 

190 

191 def _find_target_file_quiet( 

192 self, directory: Path, filename: str 

193 ) -> Optional[Path]: 

194 """Find a file by name, returning None if not found.""" 

195 try: 

196 return self._find_target_file(directory, filename) 

197 except FileNotFoundError: 

198 return None