Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[textanalytics] run pyupgrade on textanalytics #22344

Merged
merged 4 commits into from
Jan 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down Expand Up @@ -37,7 +36,7 @@ def _authentication_policy(credential):
return authentication_policy


class TextAnalyticsClientBase(object):
class TextAnalyticsClientBase:
def __init__(self, endpoint, credential, **kwargs):
http_logging_policy = HttpLoggingPolicy(**kwargs)
http_logging_policy.allowed_header_names.update(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down Expand Up @@ -32,18 +31,18 @@ class TextAnalyticsOperationResourcePolling(OperationResourcePolling):
def __init__(
self, operation_location_header="operation-location", show_stats=False
):
super(TextAnalyticsOperationResourcePolling, self).__init__(
super().__init__(
operation_location_header=operation_location_header
)
self._show_stats = show_stats
self._query_params = {"showStats": show_stats}

def get_polling_url(self):
if not self._show_stats:
return super(TextAnalyticsOperationResourcePolling, self).get_polling_url()
return super().get_polling_url()

return (
super(TextAnalyticsOperationResourcePolling, self).get_polling_url()
super().get_polling_url()
+ "?"
+ urlencode(self._query_params)
)
Expand Down Expand Up @@ -124,7 +123,7 @@ def __init__(self, *args, **kwargs):
self._doc_id_order = kwargs.pop("doc_id_order", None)
self._show_stats = kwargs.pop("show_stats", None)
self._text_analytics_client = kwargs.pop("text_analytics_client")
super(AnalyzeHealthcareEntitiesLROPollingMethod, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

@property
def _current_body(self):
Expand Down Expand Up @@ -273,7 +272,7 @@ def __init__(self, *args, **kwargs):
self._doc_id_order = kwargs.pop("doc_id_order", None)
self._task_id_order = kwargs.pop("task_id_order", None)
self._show_stats = kwargs.pop("show_stats", None)
super(AnalyzeActionsLROPollingMethod, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

@property
def _current_body(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# coding=utf-8 pylint: disable=too-many-lines
# pylint: disable=too-many-lines
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down Expand Up @@ -1199,7 +1199,7 @@ def __getattr__(self, attr):
)
)
raise AttributeError(
"'DocumentError' object has no attribute '{}'".format(attr)
f"'DocumentError' object has no attribute '{attr}'"
)

@classmethod
Expand Down Expand Up @@ -1239,7 +1239,7 @@ class DetectLanguageInput(LanguageInput):
"""

def __init__(self, **kwargs):
super(DetectLanguageInput, self).__init__(**kwargs)
super().__init__(**kwargs)
self.id = kwargs.get("id", None)
self.text = kwargs.get("text", None)
self.country_hint = kwargs.get("country_hint", None)
Expand Down Expand Up @@ -1390,7 +1390,7 @@ class TextDocumentInput(DictMixin, MultiLanguageInput):
"""

def __init__(self, **kwargs):
super(TextDocumentInput, self).__init__(**kwargs)
super().__init__(**kwargs)
self.id = kwargs.get("id", None)
self.text = kwargs.get("text", None)
self.language = kwargs.get("language", None)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand All @@ -14,7 +13,7 @@ class TextAnalyticsResponseHookPolicy(SansIOHTTPPolicy):
def __init__(self, **kwargs):
self._response_callback = kwargs.get("raw_response_hook")
self._is_lro = None
super(TextAnalyticsResponseHookPolicy, self).__init__()
super().__init__()

def on_request(self, request):
self._response_callback = request.context.options.pop(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------


import six
from ._generated.models import (
EntitiesTask,
PiiTask,
Expand Down Expand Up @@ -35,13 +33,13 @@ def _validate_input(documents, hint, whole_input_hint):
if not documents:
raise ValueError("Input documents can not be empty or None")

if isinstance(documents, six.string_types):
if isinstance(documents, str):
raise TypeError("Input documents cannot be a string.")

if isinstance(documents, dict):
raise TypeError("Input documents cannot be a dict")

if not all(isinstance(x, six.string_types) for x in documents):
if not all(isinstance(x, str) for x in documents):
if not all(
isinstance(x, (dict, TextDocumentInput, DetectLanguageInput))
for x in documents
Expand All @@ -52,7 +50,7 @@ def _validate_input(documents, hint, whole_input_hint):

request_batch = []
for idx, doc in enumerate(documents):
if isinstance(doc, six.string_types):
if isinstance(doc, str):
if hint == "country_hint" and whole_input_hint.lower() == "none":
whole_input_hint = ""
document = {"id": str(idx), hint: whole_input_hint, "text": doc}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down Expand Up @@ -46,11 +45,11 @@ class CSODataV4Format(ODataV4Format):
def __init__(self, odata_error):
try:
if odata_error["error"]["innererror"]:
super(CSODataV4Format, self).__init__(
super().__init__(
odata_error["error"]["innererror"]
)
except KeyError:
super(CSODataV4Format, self).__init__(odata_error)
super().__init__(odata_error)


def process_http_response_error(error):
Expand Down Expand Up @@ -367,22 +366,22 @@ def get_task_from_pointer(task_type): # pylint: disable=too-many-return-stateme
def resolve_action_pointer(pointer):
import re
pointer_union = "|".join(value for value in ActionPointerKind)
found = re.search(r"#/tasks/({})/\d+".format(pointer_union), pointer)
found = re.search(fr"#/tasks/({pointer_union})/\d+", pointer)
if found:
index = int(pointer[-1])
task = pointer.split("#/tasks/")[1].split("/")[0]
property_name = get_task_from_pointer(task)
return property_name, index
raise ValueError(
"Unexpected response from service - action pointer '{}' is not a valid action pointer.".format(pointer)
f"Unexpected response from service - action pointer '{pointer}' is not a valid action pointer."
)


def get_ordered_errors(tasks_obj, task_name, doc_id_order):
# throw exception if error missing a target
missing_target = any([error for error in tasks_obj.errors if error.target is None])
if missing_target:
message = "".join(["({}) {}".format(err.code, err.message) for err in tasks_obj.errors])
message = "".join([f"({err.code}) {err.message}" for err in tasks_obj.errors])
raise HttpResponseError(message=message)

# create a DocumentError per input doc with the action error details
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down Expand Up @@ -118,7 +117,7 @@ class TextAnalyticsClient(TextAnalyticsClientBase):

def __init__(self, endpoint, credential, **kwargs):
# type: (str, Union[AzureKeyCredential, TokenCredential], Any) -> None
super(TextAnalyticsClient, self).__init__(
super().__init__(
endpoint=endpoint, credential=credential, **kwargs
)
self._api_version = kwargs.get("api_version", DEFAULT_API_VERSION)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------

from ._version import VERSION

USER_AGENT = "ai-textanalytics/{}".format(VERSION)
USER_AGENT = f"ai-textanalytics/{VERSION}"
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down Expand Up @@ -28,7 +27,7 @@ def _authentication_policy(credential):
return authentication_policy


class AsyncTextAnalyticsClientBase(object):
class AsyncTextAnalyticsClientBase:
def __init__(self, endpoint, credential, **kwargs):
http_logging_policy = HttpLoggingPolicy(**kwargs)
http_logging_policy.allowed_header_names.update(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down Expand Up @@ -96,7 +95,7 @@ def __init__(self, *args, **kwargs):
self._text_analytics_client = kwargs.pop("text_analytics_client")
self._doc_id_order = kwargs.pop("doc_id_order", None)
self._show_stats = kwargs.pop("show_stats", None)
super(AsyncAnalyzeHealthcareEntitiesLROPollingMethod, self).__init__(
super().__init__(
*args, **kwargs
)

Expand Down Expand Up @@ -242,7 +241,7 @@ def __init__(self, *args, **kwargs):
self._doc_id_order = kwargs.pop("doc_id_order", None)
self._task_id_order = kwargs.pop("task_id_order", None)
self._show_stats = kwargs.pop("show_stats", None)
super(AsyncAnalyzeActionsLROPollingMethod, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

@property
def _current_body(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Expand Down Expand Up @@ -116,7 +115,7 @@ def __init__( # type: ignore
credential: Union["AzureKeyCredential", "AsyncTokenCredential"],
**kwargs: Any,
) -> None:
super(TextAnalyticsClient, self).__init__(
super().__init__(
endpoint=endpoint, credential=credential, **kwargs
)
self._api_version = kwargs.get("api_version", DEFAULT_API_VERSION)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding: utf-8

# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
Expand Down Expand Up @@ -47,10 +45,10 @@ async def sample_alternative_document_input():

for idx, doc in enumerate(result):
if not doc.is_error:
print("Document text: {}".format(documents[idx]))
print("Language detected: {}".format(doc.primary_language.name))
print("ISO6391 name: {}".format(doc.primary_language.iso6391_name))
print("Confidence score: {}\n".format(doc.primary_language.confidence_score))
print(f"Document text: {documents[idx]}")
print(f"Language detected: {doc.primary_language.name}")
print(f"ISO6391 name: {doc.primary_language.iso6391_name}")
print(f"Confidence score: {doc.primary_language.confidence_score}\n")
if doc.is_error:
print(doc.id, doc.error)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# coding: utf-8

# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
Expand Down Expand Up @@ -84,7 +82,7 @@ async def sample_analyze_async():
document_results.append(page)

for doc, action_results in zip(documents, document_results):
print("\nDocument text: {}".format(doc))
print(f"\nDocument text: {doc}")
recognize_entities_result = action_results[0]
print("...Results of Recognize Entities Action:")
if recognize_entities_result.is_error:
Expand All @@ -93,10 +91,10 @@ async def sample_analyze_async():
))
else:
for entity in recognize_entities_result.entities:
print("......Entity: {}".format(entity.text))
print(".........Category: {}".format(entity.category))
print(".........Confidence Score: {}".format(entity.confidence_score))
print(".........Offset: {}".format(entity.offset))
print(f"......Entity: {entity.text}")
print(f".........Category: {entity.category}")
print(f".........Confidence Score: {entity.confidence_score}")
print(f".........Offset: {entity.offset}")

recognize_pii_entities_result = action_results[1]
print("...Results of Recognize PII Entities action:")
Expand All @@ -106,9 +104,9 @@ async def sample_analyze_async():
))
else:
for entity in recognize_pii_entities_result.entities:
print("......Entity: {}".format(entity.text))
print(".........Category: {}".format(entity.category))
print(".........Confidence Score: {}".format(entity.confidence_score))
print(f"......Entity: {entity.text}")
print(f".........Category: {entity.category}")
print(f".........Confidence Score: {entity.confidence_score}")

extract_key_phrases_result = action_results[2]
print("...Results of Extract Key Phrases action:")
Expand All @@ -117,7 +115,7 @@ async def sample_analyze_async():
extract_key_phrases_result.code, extract_key_phrases_result.message
))
else:
print("......Key Phrases: {}".format(extract_key_phrases_result.key_phrases))
print(f"......Key Phrases: {extract_key_phrases_result.key_phrases}")

recognize_linked_entities_result = action_results[3]
print("...Results of Recognize Linked Entities action:")
Expand All @@ -127,17 +125,17 @@ async def sample_analyze_async():
))
else:
for linked_entity in recognize_linked_entities_result.entities:
print("......Entity name: {}".format(linked_entity.name))
print(".........Data source: {}".format(linked_entity.data_source))
print(".........Data source language: {}".format(linked_entity.language))
print(".........Data source entity ID: {}".format(linked_entity.data_source_entity_id))
print(".........Data source URL: {}".format(linked_entity.url))
print(f"......Entity name: {linked_entity.name}")
print(f".........Data source: {linked_entity.data_source}")
print(f".........Data source language: {linked_entity.language}")
print(f".........Data source entity ID: {linked_entity.data_source_entity_id}")
print(f".........Data source URL: {linked_entity.url}")
print(".........Document matches:")
for match in linked_entity.matches:
print("............Match text: {}".format(match.text))
print("............Confidence Score: {}".format(match.confidence_score))
print("............Offset: {}".format(match.offset))
print("............Length: {}".format(match.length))
print(f"............Match text: {match.text}")
print(f"............Confidence Score: {match.confidence_score}")
print(f"............Offset: {match.offset}")
print(f"............Length: {match.length}")

analyze_sentiment_result = action_results[4]
print("...Results of Analyze Sentiment action:")
Expand All @@ -146,7 +144,7 @@ async def sample_analyze_async():
analyze_sentiment_result.code, analyze_sentiment_result.message
))
else:
print("......Overall sentiment: {}".format(analyze_sentiment_result.sentiment))
print(f"......Overall sentiment: {analyze_sentiment_result.sentiment}")
print("......Scores: positive={}; neutral={}; negative={} \n".format(
analyze_sentiment_result.confidence_scores.positive,
analyze_sentiment_result.confidence_scores.neutral,
Expand All @@ -162,4 +160,3 @@ async def main():

if __name__ == '__main__':
asyncio.run(main())

Loading