|
| 1 | +UPSTREAM_PICKLE_FILE_SIGNATURES = { |
| 2 | + "a3a8d27b822072fa5c67c0651cb3c934" # distributed with dateparser==1.2.2 |
| 3 | +} |
| 4 | + |
| 5 | + |
| 6 | +def fix_dateparser() -> None: |
| 7 | + # work around the following upstream issues in dateparser==1.2.2 (which all have the same root cause): |
| 8 | + # - https://github.com/scrapinghub/dateparser/issues/1270 |
| 9 | + # - https://github.com/scrapinghub/dateparser/issues/1281 |
| 10 | + # - https://github.com/scrapinghub/dateparser/issues/1282 |
| 11 | + # |
| 12 | + # This hack can be removed if this issue is fixed upstream. |
| 13 | + # If you're removing this hack, make sure to update pyproject.toml to blacklist version 1.2.2 |
| 14 | + |
| 15 | + import importlib, hashlib |
| 16 | + from pathlib import Path |
| 17 | + |
| 18 | + spec = importlib.util.find_spec("dateparser") |
| 19 | + if spec and spec.origin: |
| 20 | + # spec.origin will be something like: |
| 21 | + # "/path/to/venv/lib/python3.9/site-packages/dateparser/__init__.py" |
| 22 | + tz_cache = Path(spec.origin).parent / "data" / "dateparser_tz_cache.pkl" |
| 23 | + if tz_cache.exists(): |
| 24 | + # if the tz_cache file matches the signature of the buggy upstream one, delete it |
| 25 | + # we dont want to delete it if it's been generated locally against our environment |
| 26 | + signature = hashlib.md5(tz_cache.read_bytes()).hexdigest() |
| 27 | + if signature in UPSTREAM_PICKLE_FILE_SIGNATURES: |
| 28 | + try: |
| 29 | + tz_cache.unlink() |
| 30 | + except Exception as e: |
| 31 | + print(f"WARNING: Unable to delete upstream dateparser cache: {str(e)}") |
| 32 | + |
| 33 | + # Test that it actually worked |
| 34 | + import dateparser |
| 35 | + |
| 36 | + if dateparser.parse("1 minute ago") is None: |
| 37 | + print( |
| 38 | + "WARNING: Buggy dateparser detected; some date expressions may fail to parse.\n" |
| 39 | + f"Please either delete the file '{str(tz_cache)}' manually or use dateparser<=1.2.1" |
| 40 | + ) |
0 commit comments