コンテンツにスキップ

TraceMoe

Attributes

ANIME_INFO_QUERY = '\nquery ($id: Int) {\n Media (id: $id, type: ANIME) {\n id\n idMal\n title {\n native\n romaji\n english\n }\n type\n format\n startDate {\n year\n month\n day\n }\n endDate {\n year\n month\n day\n }\n coverImage {\n large\n }\n synonyms\n isAdult\n }\n}\n' module-attribute

Classes

TraceMoe

Bases: BaseSearchEngine[TraceMoeResponse]

API Client for the TraceMoe image search engine.

Used for performing reverse image searches using TraceMoe service.

Attributes:

Name Type Description
anilist_url str

URL for TraceMoe endpoint to retrieve anime info.

base_url str

The base URL for TraceMoe searches.

me_url str

URL for TraceMoe API endpoint to retrieve user info.

size Optional[str]

Optional string indicating preview size ('s', 'm', 'l').

mute bool

A flag to mute preview video in search results.

Source code in PicImageSearch/engines/tracemoe.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class TraceMoe(BaseSearchEngine[TraceMoeResponse]):
    """API Client for the TraceMoe image search engine.

    Used for performing reverse image searches using TraceMoe service.

    Attributes:
        anilist_url (str): URL for TraceMoe endpoint to retrieve anime info.
        base_url (str): The base URL for TraceMoe searches.
        me_url (str): URL for TraceMoe API endpoint to retrieve user info.
        size (Optional[str]): Optional string indicating preview size ('s', 'm', 'l').
        mute (bool): A flag to mute preview video in search results.
    """

    def __init__(
        self,
        base_url: str = "https://trace.moe",
        base_url_api: str = "https://api.trace.moe",
        mute: bool = False,
        size: Optional[str] = None,
        **request_kwargs: Any,
    ):
        """Initializes a TraceMoe API client with specified configurations.

        Args:
            base_url (str): The base URL for TraceMoe searches.
            base_url_api (str): The base URL for TraceMoe API searches.
            mute (bool): If True, mutes preview video in search results.
            size (Optional[str]): Specifies preview video size ('s', 'm', 'l').
            **request_kwargs (Any): Additional arguments for network requests.
        """
        self.anilist_url = f"{base_url}/anilist"
        base_url = f"{base_url_api}/search"
        super().__init__(base_url, **request_kwargs)
        self.me_url = f"{base_url_api}/me"
        self.mute: bool = mute
        self.size: Optional[str] = size

    async def me(self, key: Optional[str] = None) -> TraceMoeMe:
        """Retrieves user account information and API usage statistics from TraceMoe.

        Args:
            key (Optional[str]): Optional API key for authentication. If not provided, uses anonymous access.

        Returns:
            TraceMoeMe: An object containing:
                - User's API quota information
                - Search quota limits
                - Priority status
                - API key validity status

        Note:
            Response data includes search quota reset time and remaining searches.
        """
        params = {"key": key} if key else None
        resp = await self.get(self.me_url, params=params)
        return TraceMoeMe(json_loads(resp.text))

    async def update_anime_info(
        self, item: TraceMoeItem, chinese_title: bool = True
    ) -> None:
        """Updates a TraceMoeItem with detailed anime information from AniList API.

        Args:
            item (TraceMoeItem): TraceMoeItem instance to be updated with detailed information.
            chinese_title (bool): If True, attempts to fetch Chinese title if available.

        Note:
            Updates multiple fields including:
            - MAL and AniList IDs
            - Titles (native, romaji, english, chinese)
            - Anime metadata (type, format, dates)
            - Cover image URL
            - Adult content flag
            - Alternative titles (synonyms)
        """
        variables = {"id": item.anilist}
        item.anime_info = json_loads(
            (
                await self.post(
                    url=self.anilist_url,
                    json={"query": ANIME_INFO_QUERY, "variables": variables},
                )
            )[0]
        )["data"]["Media"]
        # Update item fields with anime information
        item.idMal = item.anime_info["idMal"]
        item.title = item.anime_info["title"]
        item.title_native = item.anime_info["title"]["native"]
        item.title_romaji = item.anime_info["title"]["romaji"]
        item.title_english = item.anime_info["title"]["english"]
        item.synonyms = item.anime_info["synonyms"]
        item.isAdult = item.anime_info["isAdult"]
        item.type = item.anime_info["type"]
        item.format = item.anime_info["format"]
        item.start_date = item.anime_info["startDate"]
        item.end_date = item.anime_info["endDate"]
        item.cover_image = item.anime_info["coverImage"]["large"]
        if chinese_title:
            item.title_chinese = item.anime_info["title"].get("chinese", "")

    async def search(
        self,
        url: Optional[str] = None,
        file: Union[str, bytes, Path, None] = None,
        key: Optional[str] = None,
        anilist_id: Optional[int] = None,
        chinese_title: bool = True,
        cut_borders: bool = True,
        **kwargs: Any,
    ) -> TraceMoeResponse:
        """Performs a reverse image search for anime scenes using TraceMoe.

        This method supports two ways of searching:
            1. Search by image URL
            2. Search by uploading a local image file

        Args:
            url (Optional[str]): URL of the image to search.
            file (Union[str, bytes, Path, None]): Local image file (path string, bytes data, or Path object).
            key (Optional[str]): Optional API key for authentication and higher quotas.
            anilist_id (Optional[int]): Optional AniList ID to limit search scope.
            chinese_title (bool): If True, includes Chinese titles in results.
            cut_borders (bool): If True, removes black borders before searching.
            **kwargs (Any): Additional arguments passed to the parent class.

        Returns:
            TraceMoeResponse: Search results containing:
                - List of matching anime scenes
                - Confidence scores
                - Time stamps
                - Preview URLs
                - Detailed anime information

        Raises:
            ValueError: If neither `url` nor `file` is provided.

        Note:
            - Only one of `url` or `file` should be provided
            - Using an API key increases search quota and priority
            - Results are automatically enriched with detailed anime information
        """
        self._validate_args(url, file)

        headers = {"x-trace-key": key} if key else None
        files: Optional[dict[str, Any]] = None

        params: dict[str, Union[bool, int, str]] = {}
        if cut_borders:
            params["cutBorders"] = "true"
        if anilist_id:
            params["anilistID"] = anilist_id

        if url:
            params["url"] = url
        elif file:
            files = {"file": read_file(file)}

        resp = await self._make_request(
            method="post",
            headers=headers,
            params=params,
            files=files,
        )

        result = TraceMoeResponse(
            resp_data=json_loads(resp.text),
            resp_url=resp.url,
            mute=self.mute,
            size=self.size,
        )
        await asyncio.gather(
            *[self.update_anime_info(item, chinese_title) for item in result.raw]
        )

        return result

Attributes

anilist_url = f'{base_url}/anilist' instance-attribute
me_url = f'{base_url_api}/me' instance-attribute
mute: bool = mute instance-attribute
size: Optional[str] = size instance-attribute

Functions

__init__(base_url='https://trace.moe', base_url_api='https://api.trace.moe', mute=False, size=None, **request_kwargs)

Initializes a TraceMoe API client with specified configurations.

Parameters:

Name Type Description Default
base_url str

The base URL for TraceMoe searches.

'https://trace.moe'
base_url_api str

The base URL for TraceMoe API searches.

'https://api.trace.moe'
mute bool

If True, mutes preview video in search results.

False
size Optional[str]

Specifies preview video size ('s', 'm', 'l').

None
**request_kwargs Any

Additional arguments for network requests.

{}
Source code in PicImageSearch/engines/tracemoe.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def __init__(
    self,
    base_url: str = "https://trace.moe",
    base_url_api: str = "https://api.trace.moe",
    mute: bool = False,
    size: Optional[str] = None,
    **request_kwargs: Any,
):
    """Initializes a TraceMoe API client with specified configurations.

    Args:
        base_url (str): The base URL for TraceMoe searches.
        base_url_api (str): The base URL for TraceMoe API searches.
        mute (bool): If True, mutes preview video in search results.
        size (Optional[str]): Specifies preview video size ('s', 'm', 'l').
        **request_kwargs (Any): Additional arguments for network requests.
    """
    self.anilist_url = f"{base_url}/anilist"
    base_url = f"{base_url_api}/search"
    super().__init__(base_url, **request_kwargs)
    self.me_url = f"{base_url_api}/me"
    self.mute: bool = mute
    self.size: Optional[str] = size
me(key=None) async

Retrieves user account information and API usage statistics from TraceMoe.

Parameters:

Name Type Description Default
key Optional[str]

Optional API key for authentication. If not provided, uses anonymous access.

None

Returns:

Name Type Description
TraceMoeMe TraceMoeMe

An object containing: - User's API quota information - Search quota limits - Priority status - API key validity status

Note

Response data includes search quota reset time and remaining searches.

Source code in PicImageSearch/engines/tracemoe.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
async def me(self, key: Optional[str] = None) -> TraceMoeMe:
    """Retrieves user account information and API usage statistics from TraceMoe.

    Args:
        key (Optional[str]): Optional API key for authentication. If not provided, uses anonymous access.

    Returns:
        TraceMoeMe: An object containing:
            - User's API quota information
            - Search quota limits
            - Priority status
            - API key validity status

    Note:
        Response data includes search quota reset time and remaining searches.
    """
    params = {"key": key} if key else None
    resp = await self.get(self.me_url, params=params)
    return TraceMoeMe(json_loads(resp.text))
search(url=None, file=None, key=None, anilist_id=None, chinese_title=True, cut_borders=True, **kwargs) async

Performs a reverse image search for anime scenes using TraceMoe.

This method supports two ways of searching
  1. Search by image URL
  2. Search by uploading a local image file

Parameters:

Name Type Description Default
url Optional[str]

URL of the image to search.

None
file Union[str, bytes, Path, None]

Local image file (path string, bytes data, or Path object).

None
key Optional[str]

Optional API key for authentication and higher quotas.

None
anilist_id Optional[int]

Optional AniList ID to limit search scope.

None
chinese_title bool

If True, includes Chinese titles in results.

True
cut_borders bool

If True, removes black borders before searching.

True
**kwargs Any

Additional arguments passed to the parent class.

{}

Returns:

Name Type Description
TraceMoeResponse TraceMoeResponse

Search results containing: - List of matching anime scenes - Confidence scores - Time stamps - Preview URLs - Detailed anime information

Raises:

Type Description
ValueError

If neither url nor file is provided.

Note
  • Only one of url or file should be provided
  • Using an API key increases search quota and priority
  • Results are automatically enriched with detailed anime information
Source code in PicImageSearch/engines/tracemoe.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
async def search(
    self,
    url: Optional[str] = None,
    file: Union[str, bytes, Path, None] = None,
    key: Optional[str] = None,
    anilist_id: Optional[int] = None,
    chinese_title: bool = True,
    cut_borders: bool = True,
    **kwargs: Any,
) -> TraceMoeResponse:
    """Performs a reverse image search for anime scenes using TraceMoe.

    This method supports two ways of searching:
        1. Search by image URL
        2. Search by uploading a local image file

    Args:
        url (Optional[str]): URL of the image to search.
        file (Union[str, bytes, Path, None]): Local image file (path string, bytes data, or Path object).
        key (Optional[str]): Optional API key for authentication and higher quotas.
        anilist_id (Optional[int]): Optional AniList ID to limit search scope.
        chinese_title (bool): If True, includes Chinese titles in results.
        cut_borders (bool): If True, removes black borders before searching.
        **kwargs (Any): Additional arguments passed to the parent class.

    Returns:
        TraceMoeResponse: Search results containing:
            - List of matching anime scenes
            - Confidence scores
            - Time stamps
            - Preview URLs
            - Detailed anime information

    Raises:
        ValueError: If neither `url` nor `file` is provided.

    Note:
        - Only one of `url` or `file` should be provided
        - Using an API key increases search quota and priority
        - Results are automatically enriched with detailed anime information
    """
    self._validate_args(url, file)

    headers = {"x-trace-key": key} if key else None
    files: Optional[dict[str, Any]] = None

    params: dict[str, Union[bool, int, str]] = {}
    if cut_borders:
        params["cutBorders"] = "true"
    if anilist_id:
        params["anilistID"] = anilist_id

    if url:
        params["url"] = url
    elif file:
        files = {"file": read_file(file)}

    resp = await self._make_request(
        method="post",
        headers=headers,
        params=params,
        files=files,
    )

    result = TraceMoeResponse(
        resp_data=json_loads(resp.text),
        resp_url=resp.url,
        mute=self.mute,
        size=self.size,
    )
    await asyncio.gather(
        *[self.update_anime_info(item, chinese_title) for item in result.raw]
    )

    return result
update_anime_info(item, chinese_title=True) async

Updates a TraceMoeItem with detailed anime information from AniList API.

Parameters:

Name Type Description Default
item TraceMoeItem

TraceMoeItem instance to be updated with detailed information.

required
chinese_title bool

If True, attempts to fetch Chinese title if available.

True
Note

Updates multiple fields including: - MAL and AniList IDs - Titles (native, romaji, english, chinese) - Anime metadata (type, format, dates) - Cover image URL - Adult content flag - Alternative titles (synonyms)

Source code in PicImageSearch/engines/tracemoe.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
async def update_anime_info(
    self, item: TraceMoeItem, chinese_title: bool = True
) -> None:
    """Updates a TraceMoeItem with detailed anime information from AniList API.

    Args:
        item (TraceMoeItem): TraceMoeItem instance to be updated with detailed information.
        chinese_title (bool): If True, attempts to fetch Chinese title if available.

    Note:
        Updates multiple fields including:
        - MAL and AniList IDs
        - Titles (native, romaji, english, chinese)
        - Anime metadata (type, format, dates)
        - Cover image URL
        - Adult content flag
        - Alternative titles (synonyms)
    """
    variables = {"id": item.anilist}
    item.anime_info = json_loads(
        (
            await self.post(
                url=self.anilist_url,
                json={"query": ANIME_INFO_QUERY, "variables": variables},
            )
        )[0]
    )["data"]["Media"]
    # Update item fields with anime information
    item.idMal = item.anime_info["idMal"]
    item.title = item.anime_info["title"]
    item.title_native = item.anime_info["title"]["native"]
    item.title_romaji = item.anime_info["title"]["romaji"]
    item.title_english = item.anime_info["title"]["english"]
    item.synonyms = item.anime_info["synonyms"]
    item.isAdult = item.anime_info["isAdult"]
    item.type = item.anime_info["type"]
    item.format = item.anime_info["format"]
    item.start_date = item.anime_info["startDate"]
    item.end_date = item.anime_info["endDate"]
    item.cover_image = item.anime_info["coverImage"]["large"]
    if chinese_title:
        item.title_chinese = item.anime_info["title"].get("chinese", "")

Functions