{"id":23668893,"url":"https://github.com/kgruiz/pytokencounter","last_synced_at":"2025-04-10T21:10:45.516Z","repository":{"id":270164308,"uuid":"909511340","full_name":"kgruiz/PyTokenCounter","owner":"kgruiz","description":"A simple Python library for tokenizing text and counting tokens. While currently only supporting OpenAI LLMs, it helps with text processing and managing token limits in AI applications.","archived":false,"fork":false,"pushed_at":"2025-03-11T19:26:02.000Z","size":443,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-24T18:47:28.151Z","etag":null,"topics":["ai","encoding","large-language-models","llm","machine-learning","models","nlp","openai","text-processing","tiktoken","token","tokenizer"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kgruiz.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-28T23:23:45.000Z","updated_at":"2025-03-12T13:34:53.000Z","dependencies_parsed_at":"2025-02-02T00:34:37.395Z","dependency_job_id":null,"html_url":"https://github.com/kgruiz/PyTokenCounter","commit_stats":null,"previous_names":["kgruiz/tokencounter","kgruiz/pytokencounter"],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kgruiz%2FPyTokenCounter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kgruiz%2FPyTokenCounter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kgruiz%2FPyTokenCounter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kgruiz%2FPyTokenCounter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kgruiz","download_url":"https://codeload.github.com/kgruiz/PyTokenCounter/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248298316,"owners_count":21080320,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","encoding","large-language-models","llm","machine-learning","models","nlp","openai","text-processing","tiktoken","token","tokenizer"],"created_at":"2024-12-29T08:14:52.755Z","updated_at":"2025-04-10T21:10:45.500Z","avatar_url":"https://github.com/kgruiz.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PyTokenCounter\n\nPyTokenCounter is a Python library designed to simplify text tokenization and token counting. It supports various encoding schemes, with a focus on those used by **Large Language Models (LLMs)**, particularly those developed by OpenAI. Leveraging the `tiktoken` library for efficient processing, PyTokenCounter facilitates seamless integration with LLM workflows. This project is based on the [`tiktoken` library](https://github.com/openai/tiktoken) created by [OpenAI](https://github.com/openai/tiktoken).\n\n## Table of Contents\n\n- [Background](#background)\n- [Install](#install)\n- [Usage](#usage)\n  - [CLI](#cli)\n- [API](#api)\n  - [Utility Functions](#utility-functions)\n  - [String Tokenization and Counting](#string-tokenization-and-counting)\n  - [File and Directory Tokenization and Counting](#file-and-directory-tokenization-and-counting)\n  - [Token Mapping](#token-mapping)\n- [Ignored Files](#ignored-files)\n- [Maintainers](#maintainers)\n- [Acknowledgements](#acknowledgements)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Background\n\nThe development of PyTokenCounter was driven by the need for a user-friendly and efficient way to handle text tokenization in Python, particularly for applications that interact with **Large Language Models (LLMs)** like OpenAI's language models. **LLMs process text by breaking it down into tokens**, which are the fundamental units of input and output for these models. Tokenization, the process of converting text into a sequence of tokens, is a fundamental step in natural language processing and essential for optimizing interactions with LLMs.\n\nUnderstanding and managing token counts is crucial when working with LLMs because it directly impacts aspects such as **API usage costs**, **prompt length limitations**, and **response generation**. PyTokenCounter addresses these needs by providing an intuitive interface for tokenizing strings, files, and directories, as well as counting the number of tokens based on different encoding schemes. With support for various OpenAI models and their associated encodings, PyTokenCounter is versatile enough to be used in a wide range of applications involving LLMs, such as prompt engineering, cost estimation, and monitoring usage.\n\n## Install\n\nInstall PyTokenCounter using `pip`:\n\n```bash\npip install PyTokenCounter\n```\n\n## Usage\n\nHere are a few examples to get you started with PyTokenCounter, especially in the context of **LLMs**:\n\n```python\nfrom pathlib import Path\nfrom collections import OrderedDict\n\nimport PyTokenCounter as tc\nimport tiktoken\n\n# Count tokens in a string for an LLM model\nnumTokens = tc.GetNumTokenStr(\n    string=\"This is a test string.\", model=\"gpt-4o\"\n)\nprint(f\"Number of tokens: {numTokens}\")\n\n# Count tokens in a file intended for LLM processing\nfilePath = Path(\"./TestFile.txt\")\nnumTokensFile = tc.GetNumTokenFile(filePath=filePath, model=\"gpt-4o\")\nprint(f\"Number of tokens in file: {numTokensFile}\")\n\n# Count tokens in a directory of documents for batch processing with an LLM\ndirPath = Path(\"./TestDir\")\nnumTokensDir = tc.GetNumTokenDir(dirPath=dirPath, model=\"gpt-4o\", recursive=True)\nprint(f\"Number of tokens in directory: {numTokensDir}\")\n\n# Get the encoding for a specific LLM model\nencoding = tc.GetEncoding(model=\"gpt-4o\")\n\n# Tokenize a string using a specific encoding for LLM input\ntokens = tc.TokenizeStr(string=\"This is another test.\", encoding=encoding)\nprint(f\"Token IDs: {tokens}\")\n\n# Map tokens to their decoded strings\nmappedTokens = tc.MapTokens(tokens=tokens, encoding=encoding)\nprint(f\"Mapped tokens: {mappedTokens}\")\n\n# Count tokens in a string using the default model\nnumTokens = tc.GetNumTokenStr(string=\"This is a test string.\")\nprint(f\"Number of tokens: {numTokens}\")\n\n# Count tokens in a file using the default model\nfilePath = Path(\"./TestFile.txt\")\nnumTokensFile = tc.GetNumTokenFile(filePath=filePath)\nprint(f\"Number of tokens in file: {numTokensFile}\")\n\n# Tokenize a string using the default model\ntokens = tc.TokenizeStr(string=\"This is another test.\")\nprint(f\"Token IDs: {tokens}\")\n\n# Tokenize a string and map tokens to strings using the default model\nmappedTokensResult = tc.TokenizeStr(string=\"This is another test.\", mapTokens=True)\nprint(f\"Mapped tokens result: {mappedTokensResult}\")\n\n# Map tokens to their decoded strings using the default model\nmappedTokens = tc.MapTokens(tokens=tokens)\nprint(f\"Mapped tokens: {mappedTokens}\")\n\n# Tokenize a directory and get mapped tokens with counts\ndirPath = Path(\"./TestDir\")\nmappedDirTokens = tc.TokenizeDir(dirPath=dirPath, recursive=True, mapTokens=True)\nprint(f\"Mapped directory tokens: {mappedDirTokens}\")\n\n# Count tokens in a directory and get mapped counts\nmappedDirCounts = tc.GetNumTokenDir(dirPath=dirPath, recursive=True, mapTokens=True)\nprint(f\"Mapped directory counts: {mappedDirCounts}\")\n```\n\n### CLI\n\nPyTokenCounter can also be used as a command-line tool. You can use either the `tokencount` entry point or its alias `tc`. Below are examples for both:\n\n```bash\n# Tokenize a string for an LLM\ntokencount tokenize-str \"Hello, world!\" --model gpt-4o\ntc tokenize-str \"Hello, world!\" --model gpt-4o\n\n# Tokenize a string using the default model\ntokencount tokenize-str \"Hello, world!\"\ntc tokenize-str \"Hello, world!\"\n\n# Tokenize a file for an LLM\ntokencount tokenize-file TestFile.txt --model gpt-4o\ntc tokenize-file TestFile.txt --model gpt-4o\n\n# Tokenize a file using the default model\ntokencount tokenize-file TestFile.txt\ntc tokenize-file TestFile.txt\n\n# Tokenize multiple files for an LLM\ntokencount tokenize-files TestFile1.txt TestFile2.txt --model gpt-4o\ntc tokenize-files TestFile1.txt TestFile2.txt --model gpt-4o\n\n# Tokenize multiple files using the default model\ntokencount tokenize-files TestFile1.txt TestFile2.txt\ntc tokenize-files TestFile1.txt TestFile2.txt\n\n# Tokenize a directory of files for an LLM (non-recursive)\ntokencount tokenize-files MyDirectory --model gpt-4o --no-recursive\ntc tokenize-files MyDirectory --model gpt-4o --no-recursive\n\n# Tokenize a directory of files using the default model (non-recursive)\ntokencount tokenize-files MyDirectory --no-recursive\ntc tokenize-files MyDirectory --no-recursive\n\n# Tokenize a directory (alternative command) for an LLM (non-recursive)\ntokencount tokenize-dir MyDirectory --model gpt-4o --no-recursive\ntc tokenize-dir MyDirectory --model gpt-4o --no-recursive\n\n# Tokenize a directory (alternative command) using the default model (non-recursive)\ntokencount tokenize-dir MyDirectory --no-recursive\ntc tokenize-dir MyDirectory --no-recursive\n\n# Count tokens in a string for an LLM\ntokencount count-str \"This is a test string.\" --model gpt-4o\ntc count-str \"This is a test string.\" --model gpt-4o\n\n# Count tokens in a string using the default model\ntokencount count-str \"This is a test string.\"\ntc count-str \"This is a test string.\"\n\n# Count tokens in a file for an LLM\ntokencount count-file TestFile.txt --model gpt-4o\ntc count-file TestFile.txt --model gpt-4o\n\n# Count tokens in a file using the default model\ntokencount count-file TestFile.txt\ntc count-file TestFile.txt\n\n# Count tokens in multiple files for an LLM\ntokencount count-files TestFile1.txt TestFile2.txt --model gpt-4o\ntc count-files TestFile1.txt TestFile2.txt --model gpt-4o\n\n# Count tokens in multiple files using the default model\ntokencount count-files TestFile1.txt TestFile2.txt\ntc count-files TestFile1.txt TestFile2.txt\n\n# Count tokens in a directory for an LLM (non-recursive)\ntokencount count-files TestDir --model gpt-4o --no-recursive\ntc count-files TestDir --model gpt-4o --no-recursive\n\n# Count tokens in a directory using the default model (non-recursive)\ntokencount count-files TestDir --no-recursive\ntc count-files TestDir --no-recursive\n\n# Count tokens in a directory (alternative command) for an LLM (non-recursive)\ntokencount count-dir TestDir --model gpt-4o --no-recursive\ntc count-dir TestDir --model gpt-4o --no-recursive\n\n# Count tokens in a directory (alternative command) using the default model (non-recursive)\ntokencount count-dir TestDir --no-recursive\ntc count-dir TestDir --no-recursive\n\n# Get the model associated with an encoding\ntokencount get-model cl100k_base\ntc get-model cl100k_base\n\n# Get the encoding associated with a model\ntokencount get-encoding gpt-4o\ntc get-encoding gpt-4o\n\n# Map tokens to strings for an LLM\ntokencount map-tokens 123,456,789 --model gpt-4o\ntc map-tokens 123,456,789 --model gpt-4o\n\n# Map tokens to strings using the default model\ntokencount map-tokens 123,456,789\ntc map-tokens 123,456,789\n\n# Tokenize a string and output mapped tokens\ntokencount tokenize-str \"Hello, mapped world!\" --model gpt-4o -M\n\n# Tokenize a file and output mapped tokens\ntokencount tokenize-file TestFile.txt --model gpt-4o -M\n\n# Tokenize a directory and output mapped tokens\ntokencount tokenize-dir MyDirectory --model gpt-4o -M\n\n# Count tokens in a directory and output mapped counts\ntokencount count-dir MyDirectory --model gpt-4o -M\n\n# Include binary files\ntokencount tokenize-files MyDirectory --model gpt-4o -b\ntc tokenize-files MyDirectory --model gpt-4o -b\n\n# Include hidden files and directories\ntokencount tokenize-files MyDirectory --model gpt-4o -H\ntc tokenize-files MyDirectory --model gpt-4o -H\n\n# Combine both options: include binary files and include hidden files\ntokencount tokenize-files MyDirectory --model gpt-4o -b -H\ntc tokenize-files MyDirectory --model gpt-4o -b -H\n```\n\n**CLI Usage Details:**\n\nThe `tokencount` (or `tc`) CLI provides several subcommands for tokenizing and counting tokens in strings, files, and directories, tailored for use with **LLMs**.\n\n**Subcommands:**\n\n- `tokenize-str`: Tokenizes a provided string.\n  - `tokencount tokenize-str \"Your string here\" --model gpt-4o`\n  - `tc tokenize-str \"Your string here\" --model gpt-4o`\n- `tokenize-file`: Tokenizes the contents of a file.\n  - `tokencount tokenize-file Path/To/Your/File.txt --model gpt-4o`\n  - `tc tokenize-file Path/To/Your/File.txt --model gpt-4o`\n- `tokenize-files`: Tokenizes the contents of multiple specified files or all files within a directory.\n    - `tokencount tokenize-files Path/To/Your/File1.txt Path/To/Your/File2.txt --model gpt-4o`\n    - `tc tokenize-files Path/To/Your/File1.txt Path/To/Your/File2.txt --model gpt-4o`\n    - `tokencount tokenize-files Path/To/Your/Directory --model gpt-4o --no-recursive`\n    - `tc tokenize-files Path/To/Your/Directory --model gpt-4o --no-recursive`\n- `tokenize-dir`: Tokenizes all files within a specified directory into lists of token IDs.\n    - `tokencount tokenize-dir Path/To/Your/Directory --model gpt-4o --no-recursive`\n    - `tc tokenize-dir Path/To/Your/Directory --model gpt-4o --no-recursive`\n- `count-str`: Counts the number of tokens in a provided string.\n  - `tokencount count-str \"Your string here\" --model gpt-4o`\n  - `tc count-str \"Your string here\" --model gpt-4o`\n- `count-file`: Counts the number of tokens in a file.\n  - `tokencount count-file Path/To/Your/File.txt --model gpt-4o`\n  - `tc count-file Path/To/Your/File.txt --model gpt-4o`\n- `count-files`: Counts the number of tokens in multiple specified files or all files within a directory.\n  - `tokencount count-files Path/To/Your/File1.txt Path/To/Your/File2.txt --model gpt-4o`\n  - `tc count-files Path/To/Your/File1.txt Path/To/Your/File2.txt --model gpt-4o`\n  - `tokencount count-files Path/To/Your/Directory --model gpt-4o --no-recursive`\n  - `tc count-files Path/To/Your/Directory --model gpt-4o --no-recursive`\n- `count-dir`: Counts the total number of tokens across all files in a specified directory.\n  - `tokencount count-dir Path/To/Your/Directory --model gpt-4o --no-recursive`\n  - `tc count-dir Path/To/Your/Directory --model gpt-4o --no-recursive`\n- `get-model`: Retrieves the model name from the provided encoding.\n  - `tokencount get-model cl100k_base`\n  - `tc get-model cl100k_base`\n- `get-encoding`: Retrieves the encoding name from the provided model.\n  - `tokencount get-encoding gpt-4o`\n  - `tc get-encoding gpt-4o`\n- `map-tokens`: Maps a list of token integers to their decoded strings.\n    - `tokencount map-tokens 123,456,789 --model gpt-4o`\n    - `tc map-tokens 123,456,789 --model gpt-4o`\n\n**Options:**\n\n- `-m`, `--model`: Specifies the model to use for encoding. **Default: `gpt-4o`**\n- `-e`, `--encoding`: Specifies the encoding to use directly.\n- `-nr`, `--no-recursive`: When used with `tokenize-files`, `tokenize-dir`, `count-files`, or `count-dir` for a directory, it prevents the tool from processing subdirectories recursively.\n- `-q`, `--quiet`: When used with any of the above commands, it prevents the tool from showing progress bars and minimizes output.\n- `-M`, `--mapTokens`: When specified, the output will be in a mapped (nested) format. For tokenize commands, this outputs a nested `OrderedDict` mapping decoded strings to their token IDs. For count commands, this outputs a nested `OrderedDict` with token counts, including keys such as `\"numTokens\"` and `\"tokens\"`.\n- `-o`, `--output`: When used with any of the commands, specifies an output JSON file to save the results to.\n- `-b`, `--include-binary`: Include binary files in processing. (Default: binary files are excluded.)\n- `-H`, `--include-hidden`: Include hidden files and directories. (Default: hidden files and directories are skipped.)\n\n## API\n\nHere's a detailed look at the PyTokenCounter API, designed to integrate seamlessly with **LLM** workflows:\n\n### Utility Functions\n\n#### `GetModelMappings() -\u003e dict`\n\nRetrieves the mappings between models and their corresponding encodings, essential for selecting the correct tokenization strategy for different **LLMs**.\n\n**Returns:**\n\n- `dict`: A dictionary where keys are model names and values are their corresponding encodings.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\n\nmodelMappings = tc.GetModelMappings()\nprint(modelMappings)\n```\n\n---\n\n#### `GetValidModels() -\u003e list[str]`\n\nReturns a list of valid model names supported by PyTokenCounter, primarily focusing on **LLMs**.\n\n**Returns:**\n\n- `list[str]`: A list of valid model names.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\n\nvalidModels = tc.GetValidModels()\nprint(validModels)\n```\n\n---\n\n#### `GetValidEncodings() -\u003e list[str]`\n\nReturns a list of valid encoding names, ensuring compatibility with various **LLMs**.\n\n**Returns:**\n\n- `list[str]`: A list of valid encoding names.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\n\nvalidEncodings = tc.GetValidEncodings()\nprint(validEncodings)\n```\n\n---\n\n#### `GetModelForEncoding(encoding: tiktoken.Encoding) -\u003e list[str] | str`\n\nDetermines the model name(s) associated with a given encoding, facilitating the selection of appropriate **LLMs**.\n\n**Parameters:**\n\n- `encoding` (`tiktoken.Encoding`): The encoding to get the model for.\n\n**Returns:**\n\n- `str`: The model name or a list of models corresponding to the given encoding.\n\n**Raises:**\n\n- `ValueError`: If the encoding name is not valid.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nimport tiktoken\n\nencoding = tiktoken.get_encoding('cl100k_base')\nmodel = tc.GetModelForEncoding(encoding=encoding)\nprint(model)\n```\n\n---\n\n#### `GetModelForEncodingName(encodingName: str) -\u003e str`\n\nDetermines the model name associated with a given encoding name, facilitating the selection of appropriate **LLMs**.\n\n**Parameters:**\n\n- `encodingName` (`str`): The name of the encoding.\n\n**Returns:**\n\n- `str`: The model name or a list of models corresponding to the given encoding.\n\n**Raises:**\n\n- `ValueError`: If the encoding name is not valid.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\n\nmodelName = tc.GetModelForEncodingName(encodingName=\"cl100k_base\")\nprint(modelName)\n```\n\n---\n\n#### `GetEncodingForModel(modelName: str) -\u003e tiktoken.Encoding`\n\nRetrieves the encoding associated with a given model name, ensuring accurate tokenization for the selected **LLM**.\n\n**Parameters:**\n\n- `modelName` (`str`): The name of the model.\n\n**Returns:**\n\n- `tiktoken.Encoding`: The encoding corresponding to the given model name.\n\n**Raises:**\n\n- `ValueError`: If the model name is not valid.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\n\nencoding = tc.GetEncodingForModel(modelName=\"gpt-4o\")\nprint(encoding)\n```\n\n---\n\n#### `GetEncodingNameForModel(modelName: str) -\u003e str`\n\nRetrieves the encoding name associated with a given model name, ensuring accurate tokenization for the selected **LLM**.\n\n**Parameters:**\n\n- `modelName` (`str`): The name of the model.\n\n**Returns:**\n\n- `str`: The encoding name corresponding to the given model name.\n\n**Raises:**\n\n- `ValueError`: If the model name is not valid.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\n\nencodingName = tc.GetEncodingNameForModel(modelName=\"gpt-4o\")\nprint(encodingName)\n```\n\n---\n\n#### `GetEncoding(model: str | None = None, encodingName: str | None = None) -\u003e tiktoken.Encoding`\n\nObtains the `tiktoken` encoding based on the specified model or encoding name, tailored for **LLM** usage. If neither `model` nor `encodingName` is provided, it defaults to the encoding associated with the `\"gpt-4o\"` model.\n\n**Parameters:**\n\n- `model` (`str`, optional): The name of the model.\n- `encodingName` (`str`, optional): The name of the encoding.\n\n**Returns:**\n\n- `tiktoken.Encoding`: The `tiktoken` encoding object.\n\n**Raises:**\n\n- `ValueError`: If neither model nor encoding is provided, or if the provided model or encoding is invalid.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nimport tiktoken\n\nencoding = tc.GetEncoding(model=\"gpt-4o\")\nprint(encoding)\nencoding = tc.GetEncoding(encodingName=\"p50k_base\")\nprint(encoding)\nencoding = tc.GetEncoding()\nprint(encoding)\n```\n\n---\n\n### String Tokenization and Counting\n\n#### `TokenizeStr(string: str, model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None, quiet: bool = False, mapTokens: bool = False) -\u003e list[int] | OrderedDict[str, int]`\n\nTokenizes a string into a list of token IDs or a mapping of decoded strings to tokens, preparing text for input into an **LLM**.\n\n**Parameters:**\n\n- `string` (`str`): The string to tokenize.\n- `model` (`str`, optional): The name of the model. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding.\n- `encoding` (`tiktoken.Encoding`, optional): A `tiktoken` encoding object.\n- `quiet` (`bool`, optional): If `True`, suppresses progress updates.\n- `mapTokens` (`bool`, optional): If `True`, outputs an `OrderedDict` mapping decoded strings to their token IDs. **Default: `False`**\n\n**Returns:**\n\n- `list[int]`: A list of token IDs if `mapTokens` is `False`.\n- `OrderedDict[str, int]`: An `OrderedDict` mapping decoded strings to token IDs if `mapTokens` is `True`.\n\n**Raises:**\n\n- `ValueError`: If the provided model or encoding is invalid.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nfrom collections import OrderedDict\n\ntokens = tc.TokenizeStr(string=\"Hail to the Victors!\", model=\"gpt-4o\")\nprint(tokens)\n\ntokens = tc.TokenizeStr(string=\"Hail to the Victors!\")\nprint(tokens)\n\n\nimport tiktoken\nencoding = tiktoken.get_encoding(\"cl100k_base\")\nmappedTokens = tc.TokenizeStr(string=\"2024 National Champions\", encoding=encoding, mapTokens=True)\nprint(mappedTokens)\n\nmappedTokens = tc.TokenizeStr(string=\"2024 National Champions\", mapTokens=True)\nprint(mappedTokens)\n```\n\n---\n\n#### `GetNumTokenStr(string: str, model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None, quiet: bool = False, mapTokens: bool = False) -\u003e int | OrderedDict[str, int]`\n\nCounts the number of tokens in a string.\n\n**Parameters:**\n\n- `string` (`str`): The string to count tokens in.\n- `model` (`str`, optional): The name of the model. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding.\n- `encoding` (`tiktoken.Encoding`, optional): A `tiktoken.Encoding` object to use for tokenization.\n- `quiet` (`bool`, optional): If `True`, suppresses progress updates.\n- `mapTokens` (`bool`, optional): If `True`, outputs an `OrderedDict` mapping decoded strings to token counts (which are always 1 for strings). Primarily for consistency with other functions.  **Default: `False`**\n\n**Returns:**\n\n- `int`: The number of tokens in the string if `mapTokens` is `False`.\n- `OrderedDict[str, int]`: An `OrderedDict` mapping decoded strings to token counts if `mapTokens` is `True`.\n\n**Raises:**\n\n- `ValueError`: If the provided model or encoding is invalid.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nfrom collections import OrderedDict\nimport tiktoken\n\nnumTokens = tc.GetNumTokenStr(string=\"Hail to the Victors!\", model=\"gpt-4o\")\nprint(numTokens)\n\nnumTokens = tc.GetNumTokenStr(string=\"Hail to the Victors!\")\nprint(numTokens)\n\nnumTokens = tc.GetNumTokenStr(string=\"Corum 4 Heisman\", encoding=tiktoken.get_encoding(\"cl100k_base\"))\nprint(numTokens)\n\nnumTokens = tc.GetNumTokenStr(string=\"Corum 4 Heisman\")\nprint(numTokens)\n\nmappedCounts = tc.GetNumTokenStr(string=\"Mapped count example\", mapTokens=True)\nprint(mappedCounts)\n```\n\n---\n\n### File and Directory Tokenization and Counting\n\n#### `TokenizeFile(filePath: Path | str, model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None, quiet: bool = False, mapTokens: bool = False) -\u003e list[int] | OrderedDict[str, OrderedDict[str, int | list[int]]]`\n\nTokenizes the contents of a file into a list of token IDs or a nested `OrderedDict` structure.\n\n**Parameters:**\n\n- `filePath` (`Path | str`): The path to the file to tokenize.\n- `model` (`str`, optional): The name of the model to use for encoding. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding to use.\n- `encoding` (`tiktoken.Encoding`, optional): An existing `tiktoken.Encoding` object to use for tokenization.\n- `quiet` (`bool`, optional): If `True`, suppresses progress updates.\n- `mapTokens` (`bool`, optional): If `True`, outputs an `OrderedDict` where the key is the filename and the value is another `OrderedDict` with keys `\"tokens\"` (the list of token IDs) and `\"numTokens\"` (the total token count). If `False`, returns just the list of token IDs. **Default: `False`**\n\n**Returns:**\n\n- `list[int]`: A list of token IDs representing the tokenized file contents if `mapTokens` is `False`.\n- `OrderedDict[str, OrderedDict[str, int | list[int]]]`: An `OrderedDict` as described above if `mapTokens` is `True`.\n\n**Raises:**\n\n- `TypeError`: If the types of input parameters are incorrect.\n- `ValueError`: If the provided model or encoding is invalid.\n- `UnsupportedEncodingError`: If the file encoding is not supported.\n- `FileNotFoundError`: If the file does not exist.\n\n**Example:**\n\n```python\nfrom pathlib import Path\nimport PyTokenCounter as tc\nfrom collections import OrderedDict\nimport tiktoken\n\nfilePath = Path(\"TestFile1.txt\")\ntokens = tc.TokenizeFile(filePath=filePath, model=\"gpt-4o\")\nprint(tokens)\n\nfilePath = Path(\"TestFile1.txt\")\nmappedTokensFile = tc.TokenizeFile(filePath=filePath, model=\"gpt-4o\", mapTokens=True)\nprint(mappedTokensFile)\n\nfilePath = Path(\"TestFile1.txt\")\ntokens = tc.TokenizeFile(filePath=filePath)\nprint(tokens)\n\nimport tiktoken\nencoding = tiktoken.get_encoding(\"p50k_base\")\nfilePath = Path(\"TestFile2.txt\")\nmappedTokensFileEncoding = tc.TokenizeFile(filePath=filePath, encoding=encoding, mapTokens=True)\nprint(mappedTokensFileEncoding)\n\nfilePath = Path(\"TestFile2.txt\")\nmappedTokensFileDefault = tc.TokenizeFile(filePath=filePath, mapTokens=True)\nprint(mappedTokensFileDefault)\n```\n\n---\n\n#### `GetNumTokenFile(filePath: Path | str, model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None, quiet: bool = False, mapTokens: bool = False) -\u003e int | OrderedDict[str, int]`\n\nCounts the number of tokens in a file based on the specified model or encoding.\n\n**Parameters:**\n\n- `filePath` (`Path | str`): The path to the file to count tokens for.\n- `model` (`str`, optional): The name of the model to use for encoding. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding to use.\n- `encoding` (`tiktoken.Encoding`, optional): An existing `tiktoken.Encoding` object to use for tokenization.\n- `quiet` (`bool`, optional): If `True`, suppresses progress updates.\n- `mapTokens` (`bool`, optional): If `True`, outputs an `OrderedDict` where the key is the filename and the value is the token count. If `False`, returns just the token count as an integer. **Default: `False`**\n\n**Returns:**\n\n- `int`: The number of tokens in the file if `mapTokens` is `False`.\n- `OrderedDict[str, int]`: An `OrderedDict` mapping the filename to its token count if `mapTokens` is `True`.\n\n**Raises:**\n\n- `TypeError`: If the types of `filePath`, `model`, `encodingName`, or `encoding` are incorrect.\n- `ValueError`: If the provided `model` or `encodingName` is invalid, or if there is a mismatch between the model and encoding name, or between the provided encoding and the derived encoding.\n- `UnsupportedEncodingError`: If the file's encoding cannot be determined.\n- `FileNotFoundError`: If the file does not exist.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nfrom pathlib import Path\nfrom collections import OrderedDict\n\nfilePath = Path(\"TestFile1.txt\")\nnumTokens = tc.GetNumTokenFile(filePath=filePath, model=\"gpt-4o\")\nprint(numTokens)\n\nfilePath = Path(\"TestFile1.txt\")\nmappedNumTokensFile = tc.GetNumTokenFile(filePath=filePath, model=\"gpt-4o\", mapTokens=True)\nprint(mappedNumTokensFile)\n\nfilePath = Path(\"TestFile1.txt\")\nnumTokens = tc.GetNumTokenFile(filePath=filePath)\nprint(numTokens)\n\nfilePath = Path(\"TestFile2.txt\")\nnumTokens = tc.GetNumTokenFile(filePath=filePath, model=\"gpt-4o\")\nprint(numTokens)\n\nfilePath = Path(\"TestFile2.txt\")\nnumTokens = tc.GetNumTokenFile(filePath=filePath)\nprint(numTokens)\n\nfilePath = Path(\"TestFile2.txt\")\nmappedNumTokensFileDefault = tc.GetNumTokenFile(filePath=filePath, mapTokens=True)\nprint(mappedNumTokensFileDefault)\n```\n\n---\n\n#### `TokenizeFiles(inputPath: Path | str | list[Path | str], model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None, recursive: bool = True, quiet: bool = False, exitOnListError: bool = True, mapTokens: bool = False, excludeBinary: bool = True, includeHidden: bool = False) -\u003e list[int] | OrderedDict[str, list[int] | OrderedDict]`\n\nTokenizes multiple files or all files within a directory into lists of token IDs or a nested `OrderedDict` structure.\n\n**Parameters:**\n\n- `inputPath` (`Path | str | list[Path | str]`): The path to a file or directory, or a list of file paths to tokenize.\n- `model` (`str`, optional): The name of the model to use for encoding. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding to use.\n- `encoding` (`tiktoken.Encoding`, optional): An existing `tiktoken.Encoding` object to use for tokenization.\n- `recursive` (`bool`, optional): If `inputPath` is a directory, whether to tokenize files in subdirectories recursively. **Default: `True`**\n- `quiet` (`bool`, optional): If `True`, suppresses progress updates. **Default: `False`**\n- `exitOnListError` (`bool`, optional): If `True`, stop processing the list upon encountering an error. If `False`, skip files that cause errors. **Default: `True`**\n- `mapTokens` (`bool`, optional): If `True`, outputs a nested `OrderedDict` structure. For files, the value is an `OrderedDict` with keys `\"tokens\"` (the list of token IDs) and `\"numTokens\"` (the total token count). For directories, the output is wrapped with `\"tokens\"` and `\"numTokens\"` keys. If `False`, returns a list of token IDs for a single file, or a dictionary mapping filenames to token lists for multiple files. **Default: `False`**\n- `excludeBinary` (`bool`, optional): Excludes any binary files by skipping over them. **Default: `True`**\n- `includeHidden` (`bool`, optional): Skips over hidden files and directories, including subdirectories and files of a hidden directory. **Default: `False`**\n\n**Returns:**\n\n- `list[int] | OrderedDict[str, list[int] | OrderedDict]`:\n   - If `inputPath` is a file:\n     - If `mapTokens` is `False`, returns a list of token IDs for that file.\n     - If `mapTokens` is `True`, returns an `OrderedDict` with the structure described in the `mapTokens` parameter description.\n   - If `inputPath` is a list of files, returns a dictionary where each key is the file name and the value depends on `mapTokens`:\n     - If `mapTokens` is `False`, the value is the list of token IDs for that file.\n     - If `mapTokens` is `True`, the value is an `OrderedDict` with the structure described in the `mapTokens` parameter description, wrapped under the key `\"tokens\"`, and the total token count under the key `\"numTokens\"` at the top level.\n   - If `inputPath` is a directory:\n     - If `recursive` is `True`, returns a nested `OrderedDict` where each key is a file or subdirectory name with corresponding token lists or sub-dictionaries. If `mapTokens` is `True`, the directory output is wrapped with `\"tokens\"` and `\"numTokens\"` keys.\n     - If `recursive` is `False`, returns a dictionary with file names as keys and their token lists as values. If `mapTokens` is `True`, the directory output is wrapped with `\"tokens\"` and `\"numTokens\"` keys.\n\n**Raises:**\n\n- `TypeError`: If the types of `inputPath`, `model`, `encodingName`, `encoding`, or `recursive` are incorrect.\n- `ValueError`: If any of the provided file paths in a list are not files, or if a provided directory path is not a directory.\n- `UnsupportedEncodingError`: If any of the files to be tokenized have an unsupported encoding.\n- `RuntimeError`: If the provided `inputPath` is neither a file, a directory, nor a list.\n\n**Example:**\n\n```python\nfrom PyTokenCounter import TokenizeFiles\nfrom pathlib import Path\nfrom collections import OrderedDict\nimport tiktoken\n\ninputFiles = [\n    Path(\"TestFile1.txt\"),\n    Path(\"TestFile2.txt\"),\n]\ntokens = tc.TokenizeFiles(inputPath=inputFiles, model=\"gpt-4o\")\nprint(tokens)\n\nmappedTokensFiles = tc.TokenizeFiles(inputPath=inputFiles, model=\"gpt-4o\", mapTokens=True)\nprint(mappedTokensFiles)\n\ntokens = tc.TokenizeFiles(inputPath=inputFiles)\nprint(tokens)\n\n# Tokenizing multiple files using the default model\nmappedTokensFilesDefault = tc.TokenizeFiles(inputPath=inputFiles, mapTokens=True)\nprint(mappedTokensFilesDefault)\n\nimport tiktoken\nencoding = tiktoken.get_encoding('p50k_base')\ndirPath = Path(\"TestDir\")\nmappedDirTokensNonRecursiveEncoding = tc.TokenizeFiles(inputPath=dirPath, encoding=encoding, recursive=False, mapTokens=True)\nprint(mappedDirTokensNonRecursiveEncoding)\n\nmappedDirTokensRecursiveModel = tc.TokenizeFiles(inputPath=dirPath, model=\"gpt-4o\", recursive=True, mapTokens=True)\nprint(mappedDirTokensRecursiveModel)\n\nmappedDirTokensRecursiveDefault = tc.TokenizeFiles(inputPath=dirPath, recursive=True, mapTokens=True)\nprint(mappedDirTokensRecursiveDefault)\n\n# Tokenizing a directory using the default model\nmappedDirTokensDefaultModel = tc.TokenizeFiles(inputPath=dirPath, recursive=True, mapTokens=True)\nprint(mappedDirTokensDefaultModel)\n```\n\n---\n\n#### `GetNumTokenFiles(inputPath: Path | str | list[Path | str], model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None, recursive: bool = True, quiet: bool = False, exitOnListError: bool = True, excludeBinary: bool = True, includeHidden: bool = False, mapTokens: bool = False) -\u003e int | OrderedDict[str, int | OrderedDict]`\n\nCounts the number of tokens across multiple files or in all files within a directory, or returns a nested `OrderedDict` structure with counts.\n\n**Parameters:**\n\n- `inputPath` (`Path | str | list[Path | str]`): The path to a file or directory, or a list of file paths to count tokens for.\n- `model` (`str`, optional): The name of the model to use for encoding. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding to use.\n- `encoding` (`tiktoken.Encoding`, optional): An existing `tiktoken.Encoding` object to use for tokenization.\n- `recursive` (`bool`, optional): If `inputPath` is a directory, whether to count tokens in files in subdirectories recursively. **Default: `True`**\n- `quiet` (`bool`, optional): If `True`, suppresses progress updates. **Default: `False`**\n- `exitOnListError` (`bool`, optional): If `True`, stop processing the list upon encountering an error. If `False`, skip files that cause errors. **Default: `True`**\n- `excludeBinary` (`bool`, optional): Excludes any binary files by skipping over them. **Default: `True`**\n- `includeHidden` (`bool`, optional): Skips over hidden files and directories, including subdirectories and files of a hidden directory. **Default: `False`**\n- `mapTokens` (`bool`, optional): If `True`, outputs a nested `OrderedDict` structure. For files, the value is the token count. For directories, the output is wrapped with `\"tokens\"` and `\"numTokens\"` keys, where `\"tokens\"` contains the nested counts. If `False`, returns the total token count as an integer. **Default: `False`**\n\n**Returns:**\n\n- `int`: The total number of tokens in the specified files or directory if `mapTokens` is `False`.\n- `OrderedDict[str, int | OrderedDict]`: An `OrderedDict` mirroring the directory structure with token counts if `mapTokens` is `True`.\n\n**Raises:**\n\n- `TypeError`: If the types of `inputPath`, `model`, `encodingName`, `encoding`, or `recursive` are incorrect.\n- `ValueError`: If any of the provided file paths in a list are not files, or if a provided directory path is not a directory, or if the provided model or encoding is invalid.\n- `UnsupportedEncodingError`: If any of the files to be tokenized have an unsupported encoding.\n- `RuntimeError`: If the provided `inputPath` is neither a file, a directory, nor a list.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nfrom pathlib import Path\nfrom collections import OrderedDict\nimport tiktoken\n\ninputFiles = [\n    Path(\"TestFile1.txt\"),\n    Path(\"TestFile2.txt\"),\n]\nnumTokens = tc.GetNumTokenFiles(inputPath=inputFiles, model='gpt-4o')\nprint(numTokens)\n\nmappedNumTokensFiles = tc.GetNumTokenFiles(inputPath=inputFiles, model='gpt-4o', mapTokens=True)\nprint(mappedNumTokensFiles)\n\n\nnumTokens = tc.GetNumTokenFiles(inputPath=inputFiles)\nprint(numTokens)\n\n# Counting tokens in multiple files using the default model\nmappedNumTokensFilesDefault = tc.GetNumTokenFiles(inputPath=inputFiles, mapTokens=True)\nprint(mappedNumTokensFilesDefault)\n\n\nimport tiktoken\nencoding = tiktoken.get_encoding('p50k_base')\ndirPath = Path(\"TestDir\")\nmappedNumTokensDirNonRecursiveEncoding = tc.GetNumTokenFiles(inputPath=dirPath, encoding=encoding, recursive=False, mapTokens=True)\nprint(mappedNumTokensDirNonRecursiveEncoding)\nnumTokensDirRecursiveModel = tc.GetNumTokenFiles(inputPath=dirPath, model='gpt-4o', recursive=True)\nprint(numTokensDirRecursiveModel)\n\nmappedNumTokensDirRecursiveModel = tc.GetNumTokenFiles(inputPath=dirPath, model='gpt-4o', recursive=True, mapTokens=True)\nprint(mappedNumTokensDirRecursiveModel)\n\n\n# Counting tokens in a directory using the default model\nmappedNumTokensDirRecursiveDefault = tc.GetNumTokenFiles(inputPath=dirPath, recursive=True, mapTokens=True)\nprint(mappedNumTokensDirRecursiveDefault)\n```\n\n---\n\n#### `TokenizeDir(dirPath: Path | str, model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None, recursive: bool = True, quiet: bool = False, mapTokens: bool = False, excludeBinary: bool = True, includeHidden: bool = False) -\u003e OrderedDict[str, list[int] | OrderedDict]`\n\nTokenizes all files within a directory into a nested `OrderedDict` structure or lists of token IDs.\n\n**Parameters:**\n\n- `dirPath` (`Path | str`): The path to the directory to tokenize.\n- `model` (`str`, optional): The name of the model to use for encoding. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding to use.\n- `encoding` (`tiktoken.Encoding`, optional): An existing `tiktoken.Encoding` object to use for tokenization.\n- `recursive` (`bool`, optional): Whether to tokenize files in subdirectories recursively. **Default: `True`**\n- `quiet` (`bool`, optional): If `True`, suppresses progress updates. **Default: `False`**\n- `mapTokens` (`bool`, optional): If `True`, outputs a nested `OrderedDict` where each key is a file or subdirectory name. For files, the value is an `OrderedDict` with keys `\"tokens\"` (the list of token IDs) and `\"numTokens\"` (the total token count). For directories, the output is recursively structured. If `False`, returns a nested `OrderedDict` of token lists without the `\"numTokens\"` wrapper. **Default: `False`**\n- `excludeBinary` (`bool`, optional): Excludes any binary files by skipping over them. **Default: `True`**\n- `includeHidden` (`bool`, optional): Skips over hidden files and directories, including subdirectories and files of a hidden directory. **Default: `False`**\n\n**Returns:**\n\n- `OrderedDict[str, list[int] | OrderedDict]`: A nested `OrderedDict` where each key is a file or subdirectory name. If `mapTokens` is `True`, directory entries include `\"numTokens\"` and `\"tokens\"` keys.\n\n**Raises:**\n\n- `TypeError`: If the types of input parameters are incorrect.\n- `ValueError`: If the provided path is not a directory or if the model or encoding is invalid.\n- `UnsupportedEncodingError`: If the file's encoding cannot be determined.\n- `FileNotFoundError`: If the directory does not exist.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nfrom pathlib import Path\nfrom collections import OrderedDict\n\ndirPath = Path(\"TestDir\")\ntokenizedDir = tc.TokenizeDir(dirPath=dirPath, model=\"gpt-4o\", recursive=True)\nprint(tokenizedDir)\n\nmappedTokenizedDir = tc.TokenizeDir(dirPath=dirPath, model=\"gpt-4o\", recursive=True, mapTokens=True)\nprint(mappedTokenizedDir)\n\ntokenizedDir = tc.TokenizeDir(dirPath=dirPath, recursive=True)\nprint(tokenizedDir)\n\n# Tokenizing a directory using the default model\nmappedTokenizedDirDefault = tc.TokenizeDir(dirPath=dirPath, recursive=True, mapTokens=True)\nprint(mappedTokenizedDirDefault)\n\ntokenizedDirNonRecursiveModel = tc.TokenizeDir(dirPath=dirPath, model=\"gpt-4o\", recursive=False)\nprint(tokenizedDirNonRecursiveModel)\n\nmappedTokenizedDirNonRecursiveModel = tc.TokenizeDir(dirPath=dirPath, model=\"gpt-4o\", recursive=False, mapTokens=True)\nprint(mappedTokenizedDirNonRecursiveModel)\n\ntokenizedDirNonRecursiveDefault = tc.TokenizeDir(dirPath=dirPath, recursive=False)\nprint(tokenizedDirNonRecursiveDefault)\n\n\nmappedTokenizedDirRecursiveModel = tc.TokenizeDir(dirPath=dirPath, model=\"gpt-4o\", recursive=True, mapTokens=True)\nprint(mappedTokenizedDirRecursiveModel)\n\n# Tokenizing a directory using the default model with token mapping\nmappedTokenizedDirRecursiveDefaultModel = tc.TokenizeDir(dirPath=dirPath, recursive=True, mapTokens=True)\nprint(mappedTokenizedDirRecursiveDefaultModel)\n```\n\n---\n\n#### `GetNumTokenDir(dirPath: Path | str, model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None, recursive: bool = True, quiet: bool = False, excludeBinary: bool = True, includeHidden: bool = False, mapTokens: bool = False) -\u003e int | OrderedDict[str, int | OrderedDict]`\n\nCounts the number of tokens in all files within a directory, or returns a nested `OrderedDict` structure with counts.\n\n**Parameters:**\n\n- `dirPath` (`Path | str`): The path to the directory to count tokens for.\n- `model` (`str`, optional): The name of the model to use for encoding. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding to use.\n- `encoding` (`tiktoken.Encoding`, optional): An existing `tiktoken.Encoding` object to use for tokenization.\n- `recursive` (`bool`, optional): Whether to count tokens in subdirectories recursively. **Default: `True`**\n- `quiet` (`bool`, optional): If `True`, suppresses progress updates. **Default: `False`**\n- `excludeBinary` (`bool`, optional): Excludes any binary files by skipping over them. **Default: `True`**\n- `includeHidden` (`bool`, optional): Skips over hidden files and directories, including subdirectories and files of a hidden directory. **Default: `False`**\n- `mapTokens` (`bool`, optional): If `True`, outputs a nested `OrderedDict` structure mirroring the directory structure. For files, the value is the token count. For directories, the output is wrapped with `\"tokens\"` and `\"numTokens\"` keys, where `\"tokens\"` contains the nested counts. If `False`, returns the total token count as an integer. **Default: `False`**\n\n**Returns:**\n\n- `int`: The total number of tokens in the directory if `mapTokens` is `False`.\n- `OrderedDict[str, int | OrderedDict]`: An `OrderedDict` mirroring the directory structure with token counts if `mapTokens` is `True`.\n\n**Raises:**\n\n- `TypeError`: If the types of input parameters are incorrect.\n- `ValueError`: If the provided path is not a directory or if the model or encoding is invalid.\n- `UnsupportedEncodingError`: If the file's encoding cannot be determined.\n- `FileNotFoundError`: If the directory does not exist.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nfrom pathlib import Path\nfrom collections import OrderedDict\n\ndirPath = Path(\"TestDir\")\nnumTokensDir = tc.GetNumTokenDir(dirPath=dirPath, model=\"gpt-4o\", recursive=True)\nprint(numTokensDir)\n\nmappedNumTokensDir = tc.GetNumTokenDir(dirPath=dirPath, model=\"gpt-4o\", recursive=True, mapTokens=True)\nprint(mappedNumTokensDir)\n\n# Counting tokens in a directory using the default model\nmappedNumTokensDirDefault = tc.GetNumTokenDir(dirPath=dirPath, recursive=True, mapTokens=True)\nprint(mappedNumTokensDirDefault)\n\nnumTokensDirNonRecursiveModel = tc.GetNumTokenDir(dirPath=dirPath, model=\"gpt-4o\", recursive=False)\nprint(numTokensDirNonRecursiveModel)\n\nmappedNumTokensDirNonRecursiveModel = tc.GetNumTokenDir(dirPath=dirPath, model=\"gpt-4o\", recursive=False, mapTokens=True)\nprint(mappedNumTokensDirNonRecursiveModel)\n\nnumTokensDirNonRecursiveDefault = tc.GetNumTokenDir(dirPath=dirPath, recursive=False)\nprint(numTokensDirNonRecursiveDefault)\n```\n\n---\n\n### Token Mapping\n\n#### `MapTokens(tokens: list[int] | OrderedDict[str, list[int] | OrderedDict], model: str | None = \"gpt-4o\", encodingName: str | None = None, encoding: tiktoken.Encoding | None = None) -\u003e OrderedDict[str, str] | OrderedDict[str, OrderedDict[str, str] | OrderedDict]`\n\nMaps tokens to their corresponding decoded strings based on a specified encoding.\n\n**Parameters:**\n\n- `tokens` (`list[int] | OrderedDict[str, list[int] | OrderedDict]`): The tokens to be mapped. This can either be:\n    - A list of integer tokens to decode.\n    - An `OrderedDict` with string keys and values that are either:\n        - A list of integer tokens.\n        - Another nested `OrderedDict` with the same structure.\n- `model` (`str`, optional): The model name to use for determining the encoding. **Default: `\"gpt-4o\"`**\n- `encodingName` (`str`, optional): The name of the encoding to use.\n- `encoding` (`tiktoken.Encoding`, optional): The encoding object to use.\n\n**Returns:**\n\n- `OrderedDict[str, str] | OrderedDict[str, OrderedDict[str, str] | OrderedDict]`: A mapping of decoded strings to their corresponding integer tokens. If `tokens` is a nested structure, the result will maintain the same nested structure with decoded mappings.\n\n**Raises:**\n\n- `TypeError`: If `tokens` is not a list of integers or an `OrderedDict` of strings mapped to tokens.\n- `ValueError`: If an invalid model or encoding name is provided, or if the encoding does not match the model or encoding name.\n- `KeyError`: If a token is not in the given encoding's vocabulary.\n- `RuntimeError`: If an unexpected error occurs while validating the encoding.\n\n**Example:**\n\n```python\nimport PyTokenCounter as tc\nimport tiktoken\nfrom collections import OrderedDict\n\nencoding = tiktoken.get_encoding(\"cl100k_base\")\ntokens = [123,456,789]\nmapped = tc.MapTokens(tokens=tokens, encoding=encoding)\nprint(mapped)\n\nmapped = tc.MapTokens(tokens=tokens, encoding=encoding)\nprint(mapped)\n\n# Mapping tokens using the default model\nmapped = tc.MapTokens(tokens=tokens)\nprint(mapped)\n```\n\n---\n\n## Ignored Files\n\nWhen the functions are set to exclude binary files (default behavior), the following file extensions are ignored:\n\n| Category                        | Extensions                                                                                                                                                      |\n|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| **Image formats**               | `.png`, `.jpg`, `.jpeg`, `.gif`, `.bmp`, `.pbm`, `.webp`, `.avif`, `.tiff`, `.tif`, `.ico`, `.svgz`                                                                    |\n| **Video formats**               | `.mp4`, `.mkv`, `.mov`, `.avi`, `.wmv`, `.flv`, `.webm`, `.m4v`, `.mpeg`, `.mpg`, `.3gp`, `.3g2`                                                               |\n| **Audio formats**               | `.mp3`, `.wav`, `.flac`, `.ogg`, `.aac`, `.m4a`, `.wma`, `.aiff`, `.ape`, `.opus`                                                                               |\n| **Compressed archives**         | `.zip`, `.rar`, `.7z`, `.tar`, `.gz`, `.bz2`, `.xz`, `.lz`, `.zst`, `.cab`, `.deb`, `.rpm`, `.pkg`                                                               |\n| **Disk images**                 | `.iso`, `.dmg`, `.img`, `.vhd`, `.vmdk`                                                                                                                           |\n| **Executables \u0026 Libraries**     | `.exe`, `.msi`, `.bat`, `.dll`, `.so`, `.bin`, `.o`, `.a`, `.dylib`                                                                                             |\n| **Fonts**                       | `.ttf`, `.otf`, `.woff`, `.woff2`, `.eot`                                                                                                                         |\n| **Documents**                   | `.pdf`, `.ps`, `.eps`                                                                                                                                             |\n| **Design \u0026 Graphics**           | `.psd`, `.ai`, `.indd`, `.sketch`                                                                                                                                  |\n| **3D \u0026 CAD files**              | `.blend`, `.stl`, `.step`, `.iges`, `.fbx`, `.glb`, `.gltf`, `.3ds`, `.obj`, `.cad`                                                                             |\n| **Virtual Machines \u0026 Firmware** | `.qcow2`, `.vdi`, `.vhdx`, `.rom`, `.bin`, `.img`                                                                                                               |\n| **Miscellaneous binaries**      | `.dat`, `.pak`, `.sav`, `.nes`, `.gba`, `.nds`, `.iso`, `.jar`, `.class`, `.wasm`                                                                               |\n\nAlong with ignoring the extensions in the exclude list to quickly bypass known files that cannot be read, the code also catches decoding errors and skips files when `excludeBinary` is `True`. This approach ensures all unreadable files are handled efficiently, combining fast extension-based checks with robust decoding error handling.\n\n---\n\n## Maintainers\n\n- [Kaden Gruizenga](https://github.com/kgruiz)\n\n## Acknowledgements\n\n- This project is based on the `tiktoken` library created by [OpenAI](https://github.com/openai/tiktoken).\n\n## Contributing\n\nContributions are welcome! Feel free to [open an issue](https://github.com/kgruiz/PyTokenCounter/issues/new) or submit a pull request.\n\n## License\n\nThis project is licensed under the GNU General Public License v3.0. See the [LICENSE](LICENSE) file for more details.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkgruiz%2Fpytokencounter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkgruiz%2Fpytokencounter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkgruiz%2Fpytokencounter/lists"}