Skip to content

Commit 6cb27b8

Browse files
authored
アノテーション仕様のメッセージを取得するutil関数を追加 (#659)
* メッセージを取得する関数を作成 * 不要になった関数を削除 * 無視する * エラー * 不要なimportを削除 * ディレクトリを移動するコードを削除
1 parent 99f4e94 commit 6cb27b8

16 files changed

+105
-73
lines changed

annofabapi/api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ def _request_wrapper(
492492
"""
493493

494494
# TODO 判定条件が不明
495-
if url_path.startswith("/internal/"): # noqa: SIM108
495+
if url_path.startswith("/internal/"):
496496
url = f"{self.endpoint_url}/api{url_path}"
497497
else:
498498
url = f"{self.url_prefix}{url_path}"

annofabapi/api2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import requests
66
from requests.cookies import RequestsCookieJar
77

8-
import annofabapi.utils
8+
import annofabapi
99
from annofabapi.api import (
1010
DEFAULT_WAITING_TIME_SECONDS_WITH_429_STATUS_CODE,
1111
AnnofabApi,

annofabapi/util/__init__.py

Whitespace-only changes.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from __future__ import annotations
2+
3+
from typing import Any, Literal, Optional, Union
4+
5+
import more_itertools
6+
7+
from annofabapi.models import Lang
8+
9+
10+
def get_english_message(internationalization_message: dict[str, Any]) -> str:
11+
"""
12+
`InternalizationMessage`クラスの値から、英語メッセージを取得します。
13+
英語メッセージが見つからない場合は ``ValueError`` をスローします。
14+
15+
Notes:
16+
英語メッセージは必ず存在するはずなので、英語メッセージが見つからない場合は ``ValueError`` をスローするようにしました。
17+
18+
Args:
19+
internationalization_message: 多言語化されたメッセージ。キー ``messages`` が存在している必要があります。
20+
21+
Returns:
22+
指定した言語に対応するメッセージ。
23+
24+
Raises:
25+
ValueError: 英語メッセージが見つからない場合
26+
"""
27+
messages: list[dict[str, str]] = internationalization_message["messages"]
28+
result = more_itertools.first_true(messages, pred=lambda e: e["lang"] == Lang.EN_US.value)
29+
if result is not None:
30+
return result["message"]
31+
else:
32+
raise ValueError(f"'{internationalization_message}'に英語のメッセージは存在しません。")
33+
34+
35+
STR_LANG = Literal["en-US", "ja-JP", "vi-VN"]
36+
"""
37+
対応している ``lang`` の文字列
38+
"""
39+
40+
41+
def get_message_with_lang(internationalization_message: dict[str, Any], lang: Union[Lang, STR_LANG]) -> Optional[str]: # noqa: UP007
42+
"""
43+
`InternalizationMessage`クラスの値から、指定した ``lang`` に対応するメッセージを取得します。
44+
45+
Args:
46+
internationalization_message: 多言語化されたメッセージ。キー ``messages`` が存在している必要があります。
47+
lang: 取得したいメッセージに対応する言語コード。
48+
49+
Returns:
50+
指定した言語に対応するメッセージ。見つからない場合はNoneを返します。
51+
52+
"""
53+
messages: list[dict[str, str]] = internationalization_message["messages"]
54+
if isinstance(lang, Lang):
55+
str_lang = lang.value
56+
else:
57+
str_lang = str(lang)
58+
59+
result = more_itertools.first_true(messages, pred=lambda e: e["lang"] == str_lang)
60+
if result is not None:
61+
return result["message"]
62+
return None

annofabapi/utils.py

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
import datetime
22
import logging
3-
from typing import Any, Dict, List, Optional
3+
from typing import List, Optional
44

55
import dateutil
66
import dateutil.tz
7-
import more_itertools
87

98
from annofabapi.models import Task, TaskHistory, TaskHistoryShort, TaskPhase
109

@@ -160,25 +159,3 @@ def can_put_annotation(task: Task, my_account_id: str) -> bool:
160159
"""
161160
# ログインユーザはプロジェクトオーナであること前提
162161
return len(task["histories_by_phase"]) == 0 or task["account_id"] == my_account_id
163-
164-
165-
def get_message_for_i18n(internationalization_message: Dict[str, Any], lang: str = "en-US") -> str:
166-
"""
167-
アノテーション仕様で使われている`InternalizationMessage`クラスの値から、指定された言語のメッセージを取得する。
168-
169-
Args:
170-
internationalization_message: 多言語化されたメッセージ
171-
lang: 取得したいメッセージに対応する言語コード。`en-US`または`ja-JP`のみサポートしています。
172-
173-
Returns:
174-
指定した言語に対応するメッセージ。
175-
176-
Raises:
177-
ValueError: 引数langに対応するメッセージが見つからない場合
178-
"""
179-
messages: List[Dict[str, str]] = internationalization_message["messages"]
180-
result = more_itertools.first_true(messages, pred=lambda e: e["lang"] == lang)
181-
if result is not None:
182-
return result["message"]
183-
else:
184-
raise ValueError(f"lang='{lang}'であるメッセージは見つかりませんでした。")

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ ignore = [
9595
"ERA", # : 役立つこともあるが、コメントアウトしていないコードも警告されるので無視する
9696
"TD", # flake8-todos
9797
"FIX", # flake8-fixme
98+
"SIM108", # if-else-block-instead-of-if-exp, 三項演算子が読みにくい場合もあるので無視する
9899

99100
# 以下のルールはコードに合っていないので無効化した
100101
"RSE", # flake8-raise

tests/test_api.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
import configparser
99
import datetime
10-
import os
1110
import uuid
1211
from typing import Any
1312

@@ -16,7 +15,6 @@
1615
from more_itertools import first_true
1716

1817
import annofabapi
19-
import annofabapi.utils
2018
from annofabapi.dataclass.annotation import AnnotationV2Output, SimpleAnnotation, SingleAnnotationV2
2119
from annofabapi.dataclass.annotation_specs import AnnotationSpecsV3
2220
from annofabapi.dataclass.comment import Comment
@@ -32,8 +30,6 @@
3230
from annofabapi.wrapper import TaskFrameKey
3331
from tests.utils_for_test import WrapperForTest, create_csv_for_task
3432

35-
# プロジェクトトップに移動する
36-
os.chdir(os.path.dirname(os.path.abspath(__file__)) + "/../")
3733
inifile = configparser.ConfigParser()
3834
inifile.read("./pytest.ini", "UTF-8")
3935

tests/test_api2.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,10 @@
44
"""
55

66
import configparser
7-
import os
87

98
import annofabapi
10-
import annofabapi.utils
119
from tests.utils_for_test import WrapperForTest
1210

13-
# プロジェクトトップに移動する
14-
os.chdir(os.path.dirname(os.path.abspath(__file__)) + "/../")
1511
inifile = configparser.ConfigParser()
1612
inifile.read("./pytest.ini", "UTF-8")
1713
project_id = inifile["annofab"]["project_id"]

tests/test_local_parser.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import configparser
2-
import os
32
import zipfile
43
from pathlib import Path
54

65
import pytest
76

87
import annofabapi
98
import annofabapi.parser
10-
import annofabapi.utils
119
from annofabapi.dataclass.annotation import FullAnnotation, FullAnnotationDataPoints, SimpleAnnotation
1210
from annofabapi.exceptions import AnnotationOuterFileNotFoundError
1311
from annofabapi.parser import (
@@ -19,8 +17,6 @@
1917
SimpleAnnotationZipParserByTask,
2018
)
2119

22-
# プロジェクトトップに移動する
23-
os.chdir(os.path.dirname(os.path.abspath(__file__)) + "/../")
2420
inifile = configparser.ConfigParser()
2521
inifile.read("./pytest.ini", "UTF-8")
2622

tests/test_local_resource.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,6 @@
99
import annofabapi.exceptions
1010
from annofabapi.resource import build, build_from_env
1111

12-
# プロジェクトトップに移動する
13-
os.chdir(os.path.dirname(os.path.abspath(__file__)) + "/../")
14-
1512

1613
class TestBuild:
1714
# def test_build_from_netrc(self):

0 commit comments

Comments
 (0)