|
9 | 9 | import logging |
10 | 10 | import warnings |
11 | 11 | import importlib |
| 12 | +import io |
12 | 13 | from typing import Optional |
13 | 14 |
|
14 | 15 | import hashlib |
@@ -316,18 +317,30 @@ def get_model_hash(self, model_path): |
316 | 317 | This method returns the MD5 hash of a given model file. |
317 | 318 | """ |
318 | 319 | self.logger.debug(f"Calculating hash of model file {model_path}") |
| 320 | + MB_10 = 10 * 1024 * 1024 |
319 | 321 | try: |
320 | | - # Open the model file in binary read mode |
321 | 322 | with open(model_path, "rb") as f: |
322 | | - # Move the file pointer 10MB before the end of the file |
323 | | - f.seek(-10000 * 1024, 2) |
324 | | - # Read the file from the current pointer to the end and calculate its MD5 hash |
325 | | - return hashlib.md5(f.read()).hexdigest() |
| 323 | + # Get file size |
| 324 | + f.seek(0, io.SEEK_END) |
| 325 | + file_size = f.tell() |
| 326 | + |
| 327 | + if file_size < MB_10: |
| 328 | + # If file is smaller than 10MB, hash the whole file |
| 329 | + f.seek(0, io.SEEK_SET) |
| 330 | + return hashlib.md5(f.read()).hexdigest() |
| 331 | + else: |
| 332 | + # Otherwise, hash the last 10MB |
| 333 | + f.seek(file_size - MB_10, io.SEEK_SET) |
| 334 | + return hashlib.md5(f.read()).hexdigest() |
326 | 335 | except IOError as e: |
327 | | - # If an IOError occurs (e.g., if the file is less than 10MB large), log the error |
328 | | - self.logger.error(f"IOError seeking -10MB or reading model file for hash calculation: {e}") |
329 | | - # Attempt to open the file again, read its entire content, and calculate the MD5 hash |
330 | | - return hashlib.md5(open(model_path, "rb").read()).hexdigest() |
| 336 | + # Log the error but attempt to hash the entire file as a fallback |
| 337 | + # This might still lead to lookup errors if the hash differs from UVR's expectation |
| 338 | + self.logger.error(f"IOError calculating hash for {model_path}: {e}. Falling back to hashing entire file.") |
| 339 | + try: |
| 340 | + return hashlib.md5(open(model_path, "rb").read()).hexdigest() |
| 341 | + except Exception as inner_e: |
| 342 | + self.logger.error(f"Failed to hash entire file after initial IOError: {inner_e}") |
| 343 | + raise inner_e # Re-raise the exception if the fallback also fails |
331 | 344 |
|
332 | 345 | def download_file_if_not_exists(self, url, output_path): |
333 | 346 | """ |
|
0 commit comments