<commit_before># -*- coding: utf-8 -*-

from tqdm import tqdm
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
from requests.exceptions import HTTPError

VERSION = '0.1.3'
DEFAULT_URL = 'https://hivdb.stanford.edu/graphql'


class ResponseError(Exception):
    pass


class SierraClient(object):

    def __init__(self, url=DEFAULT_URL):
        self.url = url
        self._client = None
        self._progress = False

    def toggle_progress(self, flag='auto'):
        if flag == 'auto':
            self._progress = not self._progress
        else:
            self._progress = bool(flag)

    @property
    def client(self):
        if self._client is None:
            transport = RequestsHTTPTransport(
                self.url, use_json=True, timeout=300)
            transport.headers = {
                'Content-Type': 'application/json',
                'User-Agent': 'sierra-client (python)/{}'.format(VERSION)
            }
            self._client = Client(
                transport=transport,
                fetch_schema_from_transport=True)
        return self._client

    def execute(self, document, variable_values=None):
        try:
            return self.client.execute(
                document, variable_values=variable_values)
        except HTTPError as e:
            errors = [
                e['exception']['detailMessage']
                if 'detailMessage' in e['exception']
                else 'Unknown server error'
                for e in e.response.json()['errors']
                if 'exception' in e]
            raise ResponseError(
                'Sierra GraphQL webservice returned errors:\n - ' +
                '\n - '.join(errors))

    def get_introspection(self):
        return self.client.introspection

    def _sequence_analysis(self, sequences, query):
        result = self.execute(
            gql("""
                query sierrapy($sequences:[UnalignedSequenceInput]!) {{
                    viewer {{
                        sequenceAnalysis(sequences:$sequences) {{
                            ...F0
                        }}
                    }}
                }}
                fragment F0 on SequenceAnalysis {{
                    {query}
                }}
                """.format(query=query)),
            variable_values={"sequences": sequences})
        return result['viewer']['sequenceAnalysis']

    def _pattern_analysis(self, patterns, query, **kw):
        enable_hivalg = 'algorithms' in kw or 'customAlgorithms' in kw
        extraparams = ''
        if enable_hivalg:
            extraparams = (', $algorithms:[ASIAlgorithm], '
                           '$customAlgorithms: [CustomASIAlgorithm]')
        variables = {"patterns": patterns}
        if enable_hivalg:
            variables['algorithms'] = kw.get('algorithms')
            variables['customAlgorithms'] = kw.get('customAlgorithms')
        result = self.execute(
            gql("""
                query sierrapy($patterns:[[String]!]!{extraparams}) {{
                    viewer {{
                        patternAnalysis(patterns:$patterns) {{
                            ...F0<commit_msg>Fix a parameter naming error<commit_after># -*- coding: utf-8 -*-

from tqdm import tqdm
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
from requests.exceptions import HTTPError

VERSION = '0.1.3'
DEFAULT_URL = 'https://hivdb.stanford.edu/graphql'


class ResponseError(Exception):
    pass


class SierraClient(object):

    def __init__(self, url=DEFAULT_URL):
        self.url = url
        self._client = None
        self._progress = False

    def toggle_progress(self, flag='auto'):
        if flag == 'auto':
            self._progress = not self._progress
        else:
            self._progress = bool(flag)

    @property
    def client(self):
        if self._client is None:
            transport = RequestsHTTPTransport(
                self.url, use_json=True, timeout=300)
            transport.headers = {
                'Content-Type': 'application/json',
                'User-Agent': 'sierra-client (python)/{}'.format(VERSION)
            }
            self._client = Client(
                transport=transport,
                fetch_schema_from_transport=True)
        return self._client

    def execute(self, document, variable_values=None):
        try:
            return self.client.execute(
                document, variable_values=variable_values)
        except HTTPError as e:
            errors = [
                e['exception']['detailMessage']
                if 'detailMessage' in e['exception']
                else 'Unknown server error'
                for e in e.response.json()['errors']
                if 'exception' in e]
            raise ResponseError(
                'Sierra GraphQL webservice returned errors:\n - ' +
                '\n - '.join(errors))

    def get_introspection(self):
        return self.client.introspection

    def _sequence_analysis(self, sequences, query):
        result = self.execute(
            gql("""
                query sierrapy($sequences:[UnalignedSequenceInput]!) {{
                    viewer {{
                        sequenceAnalysis(sequences:$sequences) {{
                            ...F0
                        }}
                    }}
                }}
                fragment F0 on SequenceAnalysis {{
                    {query}
                }}
                """.format(query=query)),
            variable_values={"sequences": sequences})
        return result['viewer']['sequenceAnalysis']

    def _pattern_analysis(self, patterns, query, **kw):
        enable_hivalg = 'algorithms' in kw or 'customAlgorithms' in kw
        extraparams = ''
        if enable_hivalg:
            extraparams = (', $algorithms:[ASIAlgorithm], '
                           '$customAlgorithms: [CustomASIAlgorithm]')
        variables = {"patterns": patterns}
        if enable_hivalg:
            variables['algorithms'] = kw.get('algorithms')
            variables['customAlgorithms'] = kw.get('custom_algorithms')
        result = self.execute(
            gql("""
                query sierrapy($patterns:[[String]!]!{extraparams}) {{
                    viewer {{
                        patternAnalysis(patterns:$patterns) {{
                            ...F0
{'fraction_non_alphanumeric': 0.10648293141246477, 'fraction_numerical': 0.0031318509238960224, 'mean_word_length': 1.6892631578947368, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '340131', 'n_tokens_mistral': 1675, 'n_tokens_neox': 1579, 'n_words': 357}