server_source.py 3.4 KB
Newer Older
W
wuzewu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#coding:utf-8
# Copyright (c) 2020  PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import platform
import requests
import sys

import paddlehub
from paddlehub.utils import utils


W
wuzewu 已提交
25 26 27 28 29 30 31 32 33
class ServerConnectionError(Exception):
    def __init__(self, url: str):
        self.url = url

    def __str__(self):
        tips = 'Can\'t connect to Hub Server: {}'.format(self.url)
        return tips


W
wuzewu 已提交
34
class ServerSource(object):
W
wuzewu 已提交
35 36 37 38 39 40 41
    '''
    PaddleHub server source

    Args:
        url(str) : Url of the server
        timeout(int) : Request timeout
    '''
W
wuzewu 已提交
42

W
wuzewu 已提交
43
    def __init__(self, url: str, timeout: int = 10):
W
wuzewu 已提交
44 45 46
        self._url = url
        self._timeout = timeout

W
wuzewu 已提交
47 48 49 50 51 52 53 54
    def search_module(self, name: str, version: str = None) -> dict:
        '''
        Search PaddleHub module

        Args:
            name(str) : PaddleHub module name
            version(str) : PaddleHub module version
        '''
W
wuzewu 已提交
55 56
        return self.search_resouce(type='module', name=name, version=version)

W
wuzewu 已提交
57 58 59 60 61 62 63 64 65
    def search_resouce(self, type: str, name: str, version: str = None) -> dict:
        '''
        Search PaddleHub Resource

        Args:
            type(str) : Resource type
            name(str) : Resource name
            version(str) : Resource version
        '''
W
wuzewu 已提交
66 67 68 69 70 71 72
        payload = {'environments': {}}

        payload['word'] = name
        payload['type'] = type
        if version:
            payload['version'] = version

W
wuzewu 已提交
73 74
        # Delay module loading to improve command line speed
        import paddle
W
wuzewu 已提交
75 76 77 78 79 80 81 82 83
        payload['environments']['hub_version'] = paddlehub.__version__
        payload['environments']['paddle_version'] = paddle.__version__
        payload['environments']['python_version'] = '.'.join(map(str, sys.version_info[0:3]))
        payload['environments']['platform_version'] = platform.version()
        payload['environments']['platform_system'] = platform.system()
        payload['environments']['platform_architecture'] = platform.architecture()
        payload['environments']['platform_type'] = platform.platform()

        api = '{}/search'.format(self._url)
W
wuzewu 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97

        try:
            result = requests.get(api, payload, timeout=self._timeout)
            result = result.json()

            if result['status'] == 0 and len(result['data']) > 0:
                for item in result['data']:
                    if name.lower() == item['name'].lower() and utils.Version(item['version']).match(version):
                        return item
            else:
                print(result)
            return None
        except requests.exceptions.ConnectionError as e:
            raise ServerConnectionError(self._url)
W
wuzewu 已提交
98 99

    @classmethod
W
wuzewu 已提交
100 101 102 103 104 105 106
    def check(cls, url: str) -> bool:
        '''
        Check if the specified url is a valid paddlehub server

        Args:
            url(str) : Url to check
        '''
W
wuzewu 已提交
107 108 109 110 111
        try:
            r = requests.get(url + '/search')
            return r.status_code == 200
        except:
            return False