|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright The PyTorch Lightning team. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +import os |
| 16 | +import re |
| 17 | +import warnings |
| 18 | +from urllib.error import HTTPError, URLError |
| 19 | +from urllib.request import Request, urlopen |
| 20 | + |
| 21 | +from pytorch_lightning import PROJECT_ROOT, __homepage__, __version__ |
| 22 | + |
| 23 | +_PATH_BADGES = os.path.join('.', 'docs', 'source', '_images', 'badges') |
| 24 | +# badge to download |
| 25 | +_DEFAULT_BADGES = [ |
| 26 | + 'PyPI - Python Version', |
| 27 | + 'PyPI Status', |
| 28 | + 'PyPI Status', |
| 29 | + 'Conda', |
| 30 | + 'DockerHub', |
| 31 | + 'codecov', |
| 32 | + 'ReadTheDocs', |
| 33 | + 'Slack', |
| 34 | + 'Discourse status', |
| 35 | + 'license', |
| 36 | + 'Next Release' |
| 37 | +] |
| 38 | + |
| 39 | + |
| 40 | +def _load_requirements(path_dir, file_name='requirements.txt', comment_char='#'): |
| 41 | + """Load requirements from a file |
| 42 | +
|
| 43 | + >>> _load_requirements(PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE |
| 44 | + ['numpy...', 'torch...', ...] |
| 45 | + """ |
| 46 | + with open(os.path.join(path_dir, file_name), 'r') as file: |
| 47 | + lines = [ln.strip() for ln in file.readlines()] |
| 48 | + reqs = [] |
| 49 | + for ln in lines: |
| 50 | + # filer all comments |
| 51 | + if comment_char in ln: |
| 52 | + ln = ln[:ln.index(comment_char)].strip() |
| 53 | + # skip directly installed dependencies |
| 54 | + if ln.startswith('http'): |
| 55 | + continue |
| 56 | + if ln: # if requirement is not empty |
| 57 | + reqs.append(ln) |
| 58 | + return reqs |
| 59 | + |
| 60 | + |
| 61 | +def _parse_for_badge(text: str, path_badges: str = _PATH_BADGES, badge_names: list = _DEFAULT_BADGES): |
| 62 | + """ Returns the new parsed text with url change with local downloaded files |
| 63 | +
|
| 64 | + >>> _parse_for_badge('Some text here... ' # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE |
| 65 | + ... '[]' |
| 66 | + ... '(https://pypi.org/project/pytorch-lightning/) and another text later') |
| 67 | + 'Some text here... |
| 68 | + [](https://pypi.org/project/pytorch-lightning/) |
| 69 | + and another text later' |
| 70 | + >>> import shutil |
| 71 | + >>> shutil.rmtree(_PATH_BADGES) |
| 72 | + """ |
| 73 | + for line in text.split(os.linesep): |
| 74 | + search_string = r'\[\!\[(.*)]\((.*)\)]' |
| 75 | + match = re.search(search_string, line) |
| 76 | + if match is None: |
| 77 | + continue |
| 78 | + |
| 79 | + badge_name, badge_url = match.groups() |
| 80 | + # check if valid name |
| 81 | + if badge_name not in badge_names: |
| 82 | + continue |
| 83 | + |
| 84 | + # download badge |
| 85 | + saved_badge_name = _download_badge(badge_url, badge_name, path_badges) |
| 86 | + |
| 87 | + # replace url with local file path |
| 88 | + text = text.replace(f'[]', f'[]') |
| 89 | + |
| 90 | + return text |
| 91 | + |
| 92 | + |
| 93 | +def _save_file(url_badge, save, extension, headers): |
| 94 | + """function for saving the badge either in `.png` or `.svg`""" |
| 95 | + |
| 96 | + # because there are two badge with name `PyPI Status` the second one is download |
| 97 | + if 'https://pepy.tech/badge/pytorch-lightning' in url_badge: |
| 98 | + save += '_downloads' |
| 99 | + |
| 100 | + try: |
| 101 | + req = Request(url=url_badge, headers=headers) |
| 102 | + resp = urlopen(req) |
| 103 | + except URLError: |
| 104 | + warnings.warn("Error while downloading the badge", UserWarning) |
| 105 | + else: |
| 106 | + save += extension |
| 107 | + with open(save, 'wb') as download_file: |
| 108 | + download_file.write(resp.read()) |
| 109 | + |
| 110 | + |
| 111 | +def _download_badge(url_badge, badge_name, target_dir): |
| 112 | + """Download badge from url |
| 113 | +
|
| 114 | + >>> path_img = _download_badge('https://img.shields.io/pypi/pyversions/pytorch-lightning', |
| 115 | + ... 'PyPI - Python Version', '.') |
| 116 | + >>> os.path.isfile(path_img) |
| 117 | + True |
| 118 | + >>> path_img # doctest: +ELLIPSIS |
| 119 | + '...PyPI_Python_Version_badge.png' |
| 120 | + >>> os.remove(path_img) |
| 121 | + """ |
| 122 | + os.makedirs(target_dir, exist_ok=True) |
| 123 | + |
| 124 | + headers = { |
| 125 | + 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0', |
| 126 | + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/svg,*/*;q=0.8', |
| 127 | + } |
| 128 | + |
| 129 | + save_path = badge_name.replace(' - ', ' ') |
| 130 | + save_path = os.path.join(target_dir, f"{save_path.replace(' ', '_')}_badge") |
| 131 | + |
| 132 | + if "?" in url_badge and ".png" not in url_badge: |
| 133 | + _save_file(url_badge, save_path, extension='.svg', headers=headers) |
| 134 | + return save_path + '.svg' |
| 135 | + else: |
| 136 | + try: |
| 137 | + # always try to download the png versions (some url have an already png version available) |
| 138 | + _save_file(url_badge, save_path, extension='.png', headers=headers) |
| 139 | + return save_path + '.png' |
| 140 | + except HTTPError as err: |
| 141 | + if err.code == 404: |
| 142 | + # save the `.svg` |
| 143 | + url_badge = url_badge.replace('.png', '.svg') |
| 144 | + _save_file(url_badge, save_path, extension='.svg', headers=headers) |
| 145 | + return save_path + '.svg' |
| 146 | + |
| 147 | + |
| 148 | +def _load_long_description(path_dir): |
| 149 | + """Load readme as decribtion |
| 150 | +
|
| 151 | + >>> _load_long_description(PROJECT_ROOT) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE |
| 152 | + '<div align="center">...' |
| 153 | + >>> import shutil |
| 154 | + >>> shutil.rmtree(_PATH_BADGES) |
| 155 | + """ |
| 156 | + # https://github.com/PyTorchLightning/pytorch-lightning/raw/master/docs/source/_images/lightning_module/pt_to_pl.png |
| 157 | + url = os.path.join(__homepage__, 'raw', __version__, 'docs') |
| 158 | + path_readme = os.path.join(path_dir, 'README.md') |
| 159 | + text = open(path_readme, encoding='utf-8').read() |
| 160 | + # replace relative repository path to absolute link to the release |
| 161 | + text = text.replace('](docs', f']({url}') |
| 162 | + # SVG images are not readable on PyPI, so replace them with PNG |
| 163 | + text = text.replace('.svg', '.png') |
| 164 | + # download badge and replace url with local file |
| 165 | + text = _parse_for_badge(text) |
| 166 | + return text |
0 commit comments