### Install AioTraceMoeAPI using pip or uv Source: https://github.com/fenicu/aiotracemoeapi/blob/master/README.md Installs the AioTraceMoeAPI Python package. This can be done using either `uv` or `pip`, standard Python package managers. ```bash uv add aiotracemoeapi ``` ```bash pip install aiotracemoeapi ``` -------------------------------- ### TraceMoe Client Initialization Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Demonstrates how to initialize the TraceMoe client with and without an API token, including options for custom timeouts and using the client as a context manager. ```APIDOC ## TraceMoe Client Initialization ### Description Initialize the TraceMoe client for interacting with the trace.moe API. Supports anonymous usage, API token authentication for higher rate limits, custom timeouts, and recommended context manager usage for automatic session management. ### Method `TraceMoe(token: str | None = None, timeout: float = 60.0)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): # Basic initialization (anonymous, lower rate limits) api = TraceMoe() # With API token for higher limits (get from https://trace.moe/account) api_with_token = TraceMoe(token="your_api_token_here") # With custom timeout (default is 60 seconds) api_custom = TraceMoe(token="your_token", timeout=120.0) # Using as context manager (recommended - auto-closes session) async with TraceMoe(token="your_token") as api: result = await api.search("https://example.com/image.jpg", is_url=True) print(f"Found {len(result.result)} results") # Manual session management api = TraceMoe() try: result = await api.search("https://example.com/image.jpg", is_url=True) finally: await api.close() asyncio.run(main()) ``` ### Response #### Success Response (200) N/A (Initialization does not return a direct response) #### Response Example N/A ``` -------------------------------- ### Initialize TraceMoe Client Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Demonstrates various ways to initialize the TraceMoe client, including anonymous usage, with an API token, custom timeouts, and using it as a context manager for automatic session closure. ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): # Basic initialization (anonymous, lower rate limits) api = TraceMoe() # With API token for higher limits (get from https://trace.moe/account) api_with_token = TraceMoe(token="your_api_token_here") # With custom timeout (default is 60 seconds) api_custom = TraceMoe(token="your_token", timeout=120.0) # Using as context manager (recommended - auto-closes session) async with TraceMoe(token="your_token") as api: result = await api.search("https://example.com/image.jpg", is_url=True) print(f"Found {len(result.result)} results") # Manual session management api = TraceMoe() try: result = await api.search("https://example.com/image.jpg", is_url=True) finally: await api.close() asyncio.run(main()) ``` -------------------------------- ### Search Anime by Local File Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Demonstrates how to search for anime scenes by uploading a local image file. It also shows how to filter search results by a specific AniList ID. ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): async with TraceMoe() as api: # Search by local file path result = await api.search("screenshot.jpg") if result.result: for match in result.result[:3]: # Top 3 results print(f"Match: {match.filename}") print(f" Similarity: {match.short_similarity()}") print(f" Episode: {match.episode}") print(f" Time: {match.anime_from:.1f}s") print() # Filter results by specific AniList ID result_filtered = await api.search( "screenshot.jpg", ani_list_id=21, # Filter to specific anime (Anilist ID for "ONE PUNCH MAN") ) asyncio.run(main()) ``` -------------------------------- ### POST /search (Local File) Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Search for an anime scene by uploading a local image file. The library handles file reading asynchronously. Results can be filtered by a specific AniList ID. ```APIDOC ## POST /search (Local File) ### Description Search for an anime scene by uploading a local image file. The library handles file reading asynchronously. Results can be optionally filtered by a specific AniList ID. ### Method POST ### Endpoint `/search` ### Parameters #### Path Parameters None #### Query Parameters * **file** (file) - Required - The local image file to upload. * **ani_list_id** (integer) - Optional - Filter results to a specific AniList anime ID. #### Request Body None (File is uploaded as form-data) ### Request Example ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): async with TraceMoe() as api: # Search by local file path result = await api.search("screenshot.jpg") if result.result: for match in result.result[:3]: # Top 3 results print(f"Match: {match.filename}") print(f" Similarity: {match.short_similarity()}") print(f" Episode: {match.episode}") print(f" Time: {match.anime_from:.1f}s") print() # Filter results by specific AniList ID result_filtered = await api.search( "screenshot.jpg", ani_list_id=21, # Filter to specific anime (Anilist ID for "ONE PUNCH MAN") ) asyncio.run(main()) ``` ### Response #### Success Response (200) - **result** (list) - A list of matching anime scenes. - **best_result** (object) - The most likely match from the results. - **limits** (object) - Information about the API rate limits. #### Response Example ```json { "error": "", "id": 12345, "result": [ { "anilist": { "id": 21, "title": { "romaji": "One Punch Man", "english": "One-Punch Man", "native": "ワンパンマン" }, "is_adult": false, "mal_url": "https://myanimelist.net/anime/30276/One-Punch_Man" }, "filename": "One Punch Man - 01 (BD 1920x1080 H.265 10bit AAC) [3F34C19A].mkv", "episode": 1, "from": 119.5, "to": 125.2, "similarity": 0.952, "video": "https://tn.anime. Qualia.com/videos/12345.mp4", "image": "https://tn.anime. Qualia.com/images/12345.jpg" } ], "limits": { "current": 100, "limit": 100, "remaining": 99 } } ``` ``` -------------------------------- ### Search Anime with aiotracemoeapi and Process Response (Python) Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Demonstrates how to search for anime using an image URL with the aiotracemoeapi library and process the AnimeResponse object. It covers accessing general response data, the best search result, detailed anime information from AniList, and rate limit details. Requires the 'aiotracemoeapi' library. ```python import asyncio import datetime as dt from aiotracemoeapi import TraceMoe, AnimeResponse, AnimeSearch, AniList, RateLimit async def main(): async with TraceMoe() as api: response: AnimeResponse = await api.search( "https://example.com/screenshot.jpg", is_url=True ) # AnimeResponse properties print(f"Frame Count: {response.frame_count}") print(f"Error (if any): {response.error}") print(f"Results Count: {len(response.result)}") # Best result shortcut best: AnimeSearch = response.best_result if best: # AnimeSearch properties print(f"Filename: {best.filename}") print(f"Episode: {best.episode}" ) # Can be int, float, str, or list print(f"Raw Similarity: {best.similarity}") # 0.0 to 1.0 print(f"Formatted: {best.short_similarity()}") # "95.2%" print(f"Custom Format: {best.short_similarity('{:.2%}')}") # "95.23%" # Time range in episode start = dt.timedelta(seconds=int(best.anime_from)) end = dt.timedelta(seconds=int(best.anime_to)) print(f"Scene Time: {start} - {end}") # Preview URLs print(f"Video: {best.video}") print(f"Image: {best.image}") # AniList data (when anilist_info=True) if isinstance(best.anilist, AniList): anilist: AniList = best.anilist print(f"AniList ID: {anilist.id}") print(f"MAL ID: {anilist.id_mal}") print(f"MAL URL: {anilist.mal_url}") print(f"Title (EN): {anilist.title.english}") print(f"Title (JP): {anilist.title.romaji}") print(f"Title (Native): {anilist.title.native}") print(f"Synonyms: {anilist.synonyms}") print(f"Adult Content: {anilist.is_adult}") # Rate limit information limits: RateLimit = response.limits if limits: print(f"Requests Remaining: {limits.remaining}/{limits.limit}") print(f"Reset Timestamp: {limits.reset}") print(f"Reset DateTime: {limits.reset_datetime}") print(f"Time Until Reset: {limits.reset_timedelta}") asyncio.run(main()) ``` -------------------------------- ### POST /search (Image URL) Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Search for an anime scene by providing a URL to an image. The `is_url=True` parameter is required when passing a URL string. Supports options for border cutting and including AniList metadata. ```APIDOC ## POST /search (Image URL) ### Description Search for an anime scene by providing a URL to an image. The `is_url=True` parameter is required when passing a URL string. The library can automatically detect and remove black borders (`cut_borders`) and include detailed AniList metadata (`anilist_info`). ### Method POST ### Endpoint `/search` ### Parameters #### Path Parameters None #### Query Parameters * **url** (string) - Required - The URL of the image to search. * **is_url** (boolean) - Required - Set to `True` when providing an image URL. * **cut_borders** (boolean) - Optional - Auto-detect and remove black borders. Defaults to `True`. * **anilist_info** (boolean) - Optional - Include detailed AniList metadata. Defaults to `True`. #### Request Body None (Parameters are passed as query parameters) ### Request Example ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): async with TraceMoe() as api: # Search by image URL result = await api.search( "https://images.plurk.com/32B15UXxymfSMwKGTObY5e.jpg", is_url=True, cut_borders=True, # Auto-detect and remove black borders (default: True) anilist_info=True # Include detailed AniList metadata (default: True) ) if result.result: best = result.best_result print(f"Anime: {best.filename}") print(f"Similarity: {best.short_similarity()}") # Output: "95.2%" print(f"Episode: {best.episode}") print(f"Timestamp: {best.anime_from}s - {best.anime_to}s") print(f"Video Preview: {best.video}") print(f"Image Preview: {best.image}") # Access AniList metadata if anilist_info=True if hasattr(best.anilist, 'title'): print(f"Title (English): {best.anilist.title.english}") print(f"Title (Romaji): {best.anilist.title.romaji}") print(f"Title (Native): {best.anilist.title.native}") print(f"Is Adult: {best.anilist.is_adult}") print(f"MAL URL: {best.anilist.mal_url}") else: print("No results found") # Access rate limit information print(f"Rate Limit: {result.limits.remaining}/{result.limits.limit}") asyncio.run(main()) ``` ### Response #### Success Response (200) - **result** (list) - A list of matching anime scenes. - **best_result** (object) - The most likely match from the results. - **limits** (object) - Information about the API rate limits. #### Response Example ```json { "error": "", "id": 12345, "result": [ { "anilist": { "id": 21, "title": { "romaji": "One Punch Man", "english": "One-Punch Man", "native": "ワンパンマン" }, "is_adult": false, "mal_url": "https://myanimelist.net/anime/30276/One-Punch_Man" }, "filename": "One Punch Man - 01 (BD 1920x1080 H.265 10bit AAC) [3F34C19A].mkv", "episode": 1, "from": 119.5, "to": 125.2, "similarity": 0.952, "video": "https://tn.anime. Qualia.com/videos/12345.mp4", "image": "https://tn.anime. Qualia.com/images/12345.jpg" } ], "limits": { "current": 100, "limit": 100, "remaining": 99 } } ``` ``` -------------------------------- ### Search Anime by File Upload using AioTraceMoeAPI Source: https://github.com/fenicu/aiotracemoeapi/blob/master/README.md Searches for anime by uploading a local image file. It takes a file path as input and returns the filename and episode of the most similar anime found. Includes error handling for `FileNotFoundError`. ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): api = TraceMoe() # Search by local file path # Ensure 'image.jpg' exists in your directory try: result = await api.search("image.jpg") if result.result: print(f"Anime: {result.result[0].filename}") print(f"Episode: {result.result[0].episode}") except FileNotFoundError: print("File not found!") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Check Account Status with Python Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Check API usage limits, quota, and account information using the `/me` endpoint. This can be done anonymously or with an authenticated API token. The response includes details on quota used, total quota, priority, and concurrency limits. ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): # Anonymous user check api = TraceMoe() me = await api.me() print(f"ID: {me.id}") print(f"Priority: {me.priority}") print(f"Concurrency: {me.concurrency}") print(f"Quota: {me.quota_used}/{me.quota}") await api.close() # Authenticated user check async with TraceMoe(token="your_api_token") as api: me = await api.me() print(f"Account ID: {me.id}") print(f"Quota Used: {me.quota_used}") print(f"Quota Total: {me.quota}") print(f"Priority Level: {me.priority}") print(f"Max Concurrent Requests: {me.concurrency}") # Rate limit info from headers if me.limits: print(f"Rate Limit: {me.limits.remaining}/{me.limits.limit}") print(f"Reset Time: {me.limits.reset_datetime}") asyncio.run(main()) ``` -------------------------------- ### Search Anime by Image URL Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Searches for anime scenes using an image URL. It shows how to process the results, access detailed information like anime title, episode, timestamp, and AniList metadata, and check rate limits. ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): async with TraceMoe() as api: # Search by image URL result = await api.search( "https://images.plurk.com/32B15UXxymfSMwKGTObY5e.jpg", is_url=True, cut_borders=True, # Auto-detect and remove black borders (default: True) anilist_info=True # Include detailed AniList metadata (default: True) ) if result.result: best = result.best_result print(f"Anime: {best.filename}") print(f"Similarity: {best.short_similarity()}") # Output: "95.2%" print(f"Episode: {best.episode}") print(f"Timestamp: {best.anime_from}s - {best.anime_to}s") print(f"Video Preview: {best.video}") print(f"Image Preview: {best.image}") # Access AniList metadata if anilist_info=True if hasattr(best.anilist, 'title'): print(f"Title (English): {best.anilist.title.english}") print(f"Title (Romaji): {best.anilist.title.romaji}") print(f"Title (Native): {best.anilist.title.native}") print(f"Is Adult: {best.anilist.is_adult}") print(f"MAL URL: {best.anilist.mal_url}") else: print("No results found") # Access rate limit information print(f"Rate Limit: {result.limits.remaining}/{result.limits.limit}") asyncio.run(main()) ``` -------------------------------- ### Handle API Errors with Python Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Implement granular error handling for various TraceMoe API errors using specific exception classes provided by the library. This allows for tailored responses to issues like invalid API keys, depleted quotas, or service unavailability. ```python import asyncio from aiotracemoeapi import TraceMoe from aiotracemoeapi.exceptions import ( TraceMoeAPIError, InvalidAPIKey, SearchQuotaDepleted, ConcurrencyLimitExceeded, SearchQueueFull, InvalidImageUrl, FailedFetchImage, FailedProcessImage, TooManyRequests, PayloadTooLarge, ServiceUnavailable, ) async def main(): async with TraceMoe(token="your_token") as api: try: result = await api.search("https://example.com/image.jpg", is_url=True) print(f"Found {len(result.result)} results") except InvalidAPIKey as e: print(f"Invalid API key: {e.text}") except SearchQuotaDepleted: print("Monthly search quota exhausted. Wait for reset or upgrade.") except ConcurrencyLimitExceeded: print("Too many concurrent requests. Wait and retry.") except SearchQueueFull: print("Server busy. Try again later.") except InvalidImageUrl as e: print(f"Invalid image URL provided: {e.url}") except FailedFetchImage: print("Could not download the image from URL.") except FailedProcessImage: print("Image could not be processed (corrupt or unsupported format).") except TooManyRequests: print("Rate limit exceeded. Slow down requests.") except PayloadTooLarge: print("Image file too large. Max size is 25MB.") except ServiceUnavailable: print("Service temporarily unavailable.") except TraceMoeAPIError as e: # Catch-all for other API errors print(f"API Error: {e.text}") print(f"URL: {e.url}") asyncio.run(main()) ``` -------------------------------- ### Search Anime by BytesIO Image Data with Python Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt Search for anime using in-memory image data provided as a BytesIO object. This is useful when the image is obtained from sources like HTTP responses or PIL image objects. It requires the `httpx` library for fetching images from URLs. ```python import asyncio import io from aiotracemoeapi import TraceMoe import httpx async def main(): async with TraceMoe() as api: # Example: Search with BytesIO from downloaded image async with httpx.AsyncClient() as http: response = await http.get("https://example.com/anime-screenshot.jpg") image_data = io.BytesIO(response.content) result = await api.search(image_data) if result.best_result: best = result.best_result print(f"Found: {best.filename} (Episode {best.episode})") print(f"Similarity: {best.similarity * 100:.1f}%") asyncio.run(main()) ``` -------------------------------- ### Search Anime by URL using AioTraceMoeAPI Source: https://github.com/fenicu/aiotracemoeapi/blob/master/README.md Performs an anime search using a provided image URL. Requires `is_url=True` to indicate that the input is a URL. Returns search results including filename and similarity, or a 'No results found' message. ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): api = TraceMoe() # Search by URL # Note: is_url=True is required when passing a URL string result = await api.search("https://images.plurk.com/32B15UXxymfSMwKGTObY5e.jpg", is_url=True) if result.result: print(f"Anime: {result.result[0].filename}") print(f"Similarity: {result.result[0].similarity}") else: print("No results found.") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Identify Anime from Image Source using AioTraceMoeAPI (Python) Source: https://context7.com/fenicu/aiotracemoeapi/llms.txt This Python function uses the AioTraceMoeAPI to identify anime from a given image source, which can be a URL or a local file path. It handles potential API errors and returns detailed information about the best match found, including similarity, filename, episode, timestamp, preview links, and Anilist data if available. Dependencies include the 'aiotracemoeapi' library and 'asyncio'. ```python import asyncio import datetime as dt from aiotracemoeapi import TraceMoe, exceptions, types async def identify_anime(image_source: str, is_url: bool = False): """ Identify anime from an image source. Args: image_source: URL string or local file path is_url: Set True if image_source is a URL """ async with TraceMoe() as api: try: response = await api.search(image_source, is_url=is_url) if not response.result: return {"success": False, "error": "No matches found"} best = response.best_result result = { "success": True, "similarity": best.similarity, "similarity_formatted": best.short_similarity(), "filename": best.filename, "episode": best.episode, "timestamp": { "from": best.anime_from, "to": best.anime_to, "formatted": f"{dt.timedelta(seconds=int(best.anime_from))}" }, "preview": { "video": best.video, "image": best.image } } if isinstance(best.anilist, types.AniList): result["anilist"] = { "id": best.anilist.id, "mal_id": best.anilist.id_mal, "title": { "english": best.anilist.title.english, "romaji": best.anilist.title.romaji, "native": best.anilist.title.native }, "is_adult": best.anilist.is_adult, "mal_url": best.anilist.mal_url } return result except exceptions.SearchQueueFull: return {"success": False, "error": "Server busy, try again later"} except exceptions.SearchQuotaDepleted: return {"success": False, "error": "Search quota depleted"} except exceptions.TooManyRequests: return {"success": False, "error": "Rate limited, slow down"} except exceptions.TraceMoeAPIError as e: return {"success": False, "error": str(e.text)} async def main(): # Search by URL result = await identify_anime( "https://images.plurk.com/32B15UXxymfSMwKGTObY5e.jpg", is_url=True ) if result["success"]: print(f"Anime: {result.get('anilist', {}).get('title', {}).get('english', result['filename'])}") print(f"Episode: {result['episode']}") print(f"Similarity: {result['similarity_formatted']}") print(f"Timestamp: {result['timestamp']['formatted']}") else: print(f"Error: {result['error']}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Check Account Status with AioTraceMoeAPI Source: https://github.com/fenicu/aiotracemoeapi/blob/master/README.md Retrieves the user's API account status, including ID, priority, quota used, and total quota. An API token can be provided for potentially higher limits. The token can be obtained from the trace.moe website. ```python import asyncio from aiotracemoeapi import TraceMoe async def main(): # Initialize with your API token (optional, but recommended for higher limits) # Get your token from https://trace.moe/account api = TraceMoe(token="your_token_here") me = await api.me() print(f"ID: {me.id}") print(f"Priority: {me.priority}") print(f"Quota Used: {me.quota_used}") print(f"Quota Total: {me.quota}") if __name__ == "__main__": asyncio.run(main()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.