|
| 1 | +"""This module is designed to identify and download the medcat-scripts. |
| 2 | +
|
| 3 | +It will link the current setup (i.e medcat version) into account and |
| 4 | +subsequently identify and download the medcat-scripts based on the most |
| 5 | +recent applicable tag. So if you've got medcat==2.2.0, it might grab |
| 6 | +medcat-scripts/v2.2.3 for instance. |
| 7 | +""" |
| 8 | +import importlib.metadata |
| 9 | +import tempfile |
| 10 | +import zipfile |
| 11 | +from pathlib import Path |
| 12 | +import requests |
| 13 | +import logging |
| 14 | + |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +GITHUB_REPO = "CogStack/cogstack-nlp" |
| 20 | +SCRIPTS_PATH = "medcat-scripts/" |
| 21 | +DOWNLOAD_URL_TEMPLATE = ( |
| 22 | + f"https://api.github.com/repos/{GITHUB_REPO}/zipball/{{tag}}" |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +def _get_medcat_version() -> str: |
| 27 | + """Return the installed MedCAT version as 'major.minor'.""" |
| 28 | + version = importlib.metadata.version("medcat") |
| 29 | + major, minor, *_ = version.split(".") |
| 30 | + return f"{major}.{minor}" |
| 31 | + |
| 32 | + |
| 33 | +def _find_latest_scripts_tag(major_minor: str) -> str: |
| 34 | + """Query for the newest medcat-scripts tag matching 'v{major_minor}.*'.""" |
| 35 | + url = f"https://api.github.com/repos/{GITHUB_REPO}/tags" |
| 36 | + tags = requests.get(url, timeout=15).json() |
| 37 | + |
| 38 | + matching = [ |
| 39 | + t["name"] |
| 40 | + for t in tags |
| 41 | + if t["name"].startswith(f"medcat-scripts/v{major_minor}.") |
| 42 | + or t["name"].startswith(f"v{major_minor}.") |
| 43 | + ] |
| 44 | + if not matching: |
| 45 | + raise RuntimeError( |
| 46 | + f"No medcat-scripts tags found for MedCAT {major_minor}.x") |
| 47 | + |
| 48 | + # Tags are returned newest first by GitHub |
| 49 | + return matching[0] |
| 50 | + |
| 51 | + |
| 52 | +def fetch_scripts(destination: str | Path = ".") -> Path: |
| 53 | + """Download the latest compatible medcat-scripts folder into. |
| 54 | +
|
| 55 | + Args: |
| 56 | + destination (str | Path): The destination path. Defaults to ".". |
| 57 | +
|
| 58 | + Returns: |
| 59 | + Path: The path of the scripts. |
| 60 | + """ |
| 61 | + dest = Path(destination).expanduser().resolve() |
| 62 | + dest.mkdir(parents=True, exist_ok=True) |
| 63 | + |
| 64 | + version = _get_medcat_version() |
| 65 | + tag = _find_latest_scripts_tag(version) |
| 66 | + |
| 67 | + logger.info("Fetching scripts for MedCAT %s → tag %s}", |
| 68 | + version, tag) |
| 69 | + |
| 70 | + # Download the GitHub auto-generated zipball |
| 71 | + zip_url = DOWNLOAD_URL_TEMPLATE.format(tag=tag) |
| 72 | + with requests.get(zip_url, stream=True, timeout=30) as r: |
| 73 | + r.raise_for_status() |
| 74 | + with tempfile.NamedTemporaryFile(delete=False) as tmp: |
| 75 | + for chunk in r.iter_content(chunk_size=8192): |
| 76 | + tmp.write(chunk) |
| 77 | + zip_path = Path(tmp.name) |
| 78 | + |
| 79 | + # Extract only medcat-scripts/ from the archive |
| 80 | + with zipfile.ZipFile(zip_path) as zf: |
| 81 | + for m in zf.namelist(): |
| 82 | + if f"/{SCRIPTS_PATH}" not in m: |
| 83 | + continue |
| 84 | + # skip repo-hash prefix |
| 85 | + target = dest / Path(*Path(m).parts[2:]) |
| 86 | + if m.endswith("/"): |
| 87 | + target.mkdir(parents=True, exist_ok=True) |
| 88 | + else: |
| 89 | + with open(target, "wb") as f: |
| 90 | + f.write(zf.read(m)) |
| 91 | + |
| 92 | + logger.info("Scripts extracted to: %s", dest) |
| 93 | + return dest |
| 94 | + |
| 95 | + |
| 96 | +def main(destination: str = ".", |
| 97 | + log_level: int | str = logging.INFO): |
| 98 | + logger.setLevel(log_level) |
| 99 | + if not logger.handlers: |
| 100 | + logger.addHandler(logging.StreamHandler()) |
| 101 | + fetch_scripts(destination) |
0 commit comments